proxy.go (3748B)
1 /* 2 * 3 * Copyright 2017 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 package transport 20 21 import ( 22 "bufio" 23 "context" 24 "encoding/base64" 25 "fmt" 26 "io" 27 "net" 28 "net/http" 29 "net/http/httputil" 30 "net/url" 31 ) 32 33 const proxyAuthHeaderKey = "Proxy-Authorization" 34 35 var ( 36 // The following variable will be overwritten in the tests. 37 httpProxyFromEnvironment = http.ProxyFromEnvironment 38 ) 39 40 func mapAddress(address string) (*url.URL, error) { 41 req := &http.Request{ 42 URL: &url.URL{ 43 Scheme: "https", 44 Host: address, 45 }, 46 } 47 url, err := httpProxyFromEnvironment(req) 48 if err != nil { 49 return nil, err 50 } 51 return url, nil 52 } 53 54 // To read a response from a net.Conn, http.ReadResponse() takes a bufio.Reader. 55 // It's possible that this reader reads more than what's need for the response and stores 56 // those bytes in the buffer. 57 // bufConn wraps the original net.Conn and the bufio.Reader to make sure we don't lose the 58 // bytes in the buffer. 59 type bufConn struct { 60 net.Conn 61 r io.Reader 62 } 63 64 func (c *bufConn) Read(b []byte) (int, error) { 65 return c.r.Read(b) 66 } 67 68 func basicAuth(username, password string) string { 69 auth := username + ":" + password 70 return base64.StdEncoding.EncodeToString([]byte(auth)) 71 } 72 73 func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, backendAddr string, proxyURL *url.URL, grpcUA string) (_ net.Conn, err error) { 74 defer func() { 75 if err != nil { 76 conn.Close() 77 } 78 }() 79 80 req := &http.Request{ 81 Method: http.MethodConnect, 82 URL: &url.URL{Host: backendAddr}, 83 Header: map[string][]string{"User-Agent": {grpcUA}}, 84 } 85 if t := proxyURL.User; t != nil { 86 u := t.Username() 87 p, _ := t.Password() 88 req.Header.Add(proxyAuthHeaderKey, "Basic "+basicAuth(u, p)) 89 } 90 91 if err := sendHTTPRequest(ctx, req, conn); err != nil { 92 return nil, fmt.Errorf("failed to write the HTTP request: %v", err) 93 } 94 95 r := bufio.NewReader(conn) 96 resp, err := http.ReadResponse(r, req) 97 if err != nil { 98 return nil, fmt.Errorf("reading server HTTP response: %v", err) 99 } 100 defer resp.Body.Close() 101 if resp.StatusCode != http.StatusOK { 102 dump, err := httputil.DumpResponse(resp, true) 103 if err != nil { 104 return nil, fmt.Errorf("failed to do connect handshake, status code: %s", resp.Status) 105 } 106 return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump) 107 } 108 109 return &bufConn{Conn: conn, r: r}, nil 110 } 111 112 // proxyDial dials, connecting to a proxy first if necessary. Checks if a proxy 113 // is necessary, dials, does the HTTP CONNECT handshake, and returns the 114 // connection. 115 func proxyDial(ctx context.Context, addr string, grpcUA string) (conn net.Conn, err error) { 116 newAddr := addr 117 proxyURL, err := mapAddress(addr) 118 if err != nil { 119 return nil, err 120 } 121 if proxyURL != nil { 122 newAddr = proxyURL.Host 123 } 124 125 conn, err = (&net.Dialer{}).DialContext(ctx, "tcp", newAddr) 126 if err != nil { 127 return 128 } 129 if proxyURL != nil { 130 // proxy is disabled if proxyURL is nil. 131 conn, err = doHTTPConnectHandshake(ctx, conn, addr, proxyURL, grpcUA) 132 } 133 return 134 } 135 136 func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { 137 req = req.WithContext(ctx) 138 if err := req.Write(conn); err != nil { 139 return fmt.Errorf("failed to write the HTTP request: %v", err) 140 } 141 return nil 142 }