3 * Copyright 2017 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
34 const proxyAuthHeaderKey = "Proxy-Authorization"
37 // errDisabled indicates that proxy is disabled for the address.
38 errDisabled = errors.New("proxy is disabled for the address")
39 // The following variable will be overwritten in the tests.
40 httpProxyFromEnvironment = http.ProxyFromEnvironment
43 func mapAddress(ctx context.Context, address string) (*url.URL, error) {
50 url, err := httpProxyFromEnvironment(req)
55 return nil, errDisabled
60 // To read a response from a net.Conn, http.ReadResponse() takes a bufio.Reader.
61 // It's possible that this reader reads more than what's need for the response and stores
62 // those bytes in the buffer.
63 // bufConn wraps the original net.Conn and the bufio.Reader to make sure we don't lose the
64 // bytes in the buffer.
70 func (c *bufConn) Read(b []byte) (int, error) {
74 func basicAuth(username, password string) string {
75 auth := username + ":" + password
76 return base64.StdEncoding.EncodeToString([]byte(auth))
79 func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, backendAddr string, proxyURL *url.URL) (_ net.Conn, err error) {
87 Method: http.MethodConnect,
88 URL: &url.URL{Host: backendAddr},
89 Header: map[string][]string{"User-Agent": {grpcUA}},
91 if t := proxyURL.User; t != nil {
94 req.Header.Add(proxyAuthHeaderKey, "Basic "+basicAuth(u, p))
97 if err := sendHTTPRequest(ctx, req, conn); err != nil {
98 return nil, fmt.Errorf("failed to write the HTTP request: %v", err)
101 r := bufio.NewReader(conn)
102 resp, err := http.ReadResponse(r, req)
104 return nil, fmt.Errorf("reading server HTTP response: %v", err)
106 defer resp.Body.Close()
107 if resp.StatusCode != http.StatusOK {
108 dump, err := httputil.DumpResponse(resp, true)
110 return nil, fmt.Errorf("failed to do connect handshake, status code: %s", resp.Status)
112 return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump)
115 return &bufConn{Conn: conn, r: r}, nil
118 // newProxyDialer returns a dialer that connects to proxy first if necessary.
119 // The returned dialer checks if a proxy is necessary, dial to the proxy with the
120 // provided dialer, does HTTP CONNECT handshake and returns the connection.
121 func newProxyDialer(dialer func(context.Context, string) (net.Conn, error)) func(context.Context, string) (net.Conn, error) {
122 return func(ctx context.Context, addr string) (conn net.Conn, err error) {
124 proxyURL, err := mapAddress(ctx, addr)
126 if err != errDisabled {
131 newAddr = proxyURL.Host
134 conn, err = dialer(ctx, newAddr)
139 // proxy is disabled if proxyURL is nil.
140 conn, err = doHTTPConnectHandshake(ctx, conn, addr, proxyURL)
146 func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error {
147 req = req.WithContext(ctx)
148 if err := req.Write(conn); err != nil {
149 return fmt.Errorf("failed to write the HTTP request: %v", err)