blob: 41596198787026ae0189ac195d5889800670a983 [file] [log] [blame]
khenaidoo5fc5cea2021-08-11 17:39:16 -04001/*
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
19package transport
20
21import (
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
33const proxyAuthHeaderKey = "Proxy-Authorization"
34
35var (
36 // The following variable will be overwritten in the tests.
37 httpProxyFromEnvironment = http.ProxyFromEnvironment
38)
39
khenaidoo257f3192021-12-15 16:46:37 -050040func mapAddress(address string) (*url.URL, error) {
khenaidoo5fc5cea2021-08-11 17:39:16 -040041 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.
59type bufConn struct {
60 net.Conn
61 r io.Reader
62}
63
64func (c *bufConn) Read(b []byte) (int, error) {
65 return c.r.Read(b)
66}
67
68func basicAuth(username, password string) string {
69 auth := username + ":" + password
70 return base64.StdEncoding.EncodeToString([]byte(auth))
71}
72
73func 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.
115func proxyDial(ctx context.Context, addr string, grpcUA string) (conn net.Conn, err error) {
116 newAddr := addr
khenaidoo257f3192021-12-15 16:46:37 -0500117 proxyURL, err := mapAddress(addr)
khenaidoo5fc5cea2021-08-11 17:39:16 -0400118 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
136func 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}