proxy.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. package transport
  19. import (
  20. "bufio"
  21. "context"
  22. "encoding/base64"
  23. "fmt"
  24. "io"
  25. "net"
  26. "net/http"
  27. "net/http/httputil"
  28. "net/url"
  29. )
  30. const proxyAuthHeaderKey = "Proxy-Authorization"
  31. var (
  32. // The following variable will be overwritten in the tests.
  33. httpProxyFromEnvironment = http.ProxyFromEnvironment
  34. )
  35. func mapAddress(address string) (*url.URL, error) {
  36. req := &http.Request{
  37. URL: &url.URL{
  38. Scheme: "https",
  39. Host: address,
  40. },
  41. }
  42. url, err := httpProxyFromEnvironment(req)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return url, nil
  47. }
  48. // To read a response from a net.Conn, http.ReadResponse() takes a bufio.Reader.
  49. // It's possible that this reader reads more than what's need for the response and stores
  50. // those bytes in the buffer.
  51. // bufConn wraps the original net.Conn and the bufio.Reader to make sure we don't lose the
  52. // bytes in the buffer.
  53. type bufConn struct {
  54. net.Conn
  55. r io.Reader
  56. }
  57. func (c *bufConn) Read(b []byte) (int, error) {
  58. return c.r.Read(b)
  59. }
  60. func basicAuth(username, password string) string {
  61. auth := username + ":" + password
  62. return base64.StdEncoding.EncodeToString([]byte(auth))
  63. }
  64. func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, backendAddr string, proxyURL *url.URL, grpcUA string) (_ net.Conn, err error) {
  65. defer func() {
  66. if err != nil {
  67. conn.Close()
  68. }
  69. }()
  70. req := &http.Request{
  71. Method: http.MethodConnect,
  72. URL: &url.URL{Host: backendAddr},
  73. Header: map[string][]string{"User-Agent": {grpcUA}},
  74. }
  75. if t := proxyURL.User; t != nil {
  76. u := t.Username()
  77. p, _ := t.Password()
  78. req.Header.Add(proxyAuthHeaderKey, "Basic "+basicAuth(u, p))
  79. }
  80. if err := sendHTTPRequest(ctx, req, conn); err != nil {
  81. return nil, fmt.Errorf("failed to write the HTTP request: %v", err)
  82. }
  83. r := bufio.NewReader(conn)
  84. resp, err := http.ReadResponse(r, req)
  85. if err != nil {
  86. return nil, fmt.Errorf("reading server HTTP response: %v", err)
  87. }
  88. defer resp.Body.Close()
  89. if resp.StatusCode != http.StatusOK {
  90. dump, err := httputil.DumpResponse(resp, true)
  91. if err != nil {
  92. return nil, fmt.Errorf("failed to do connect handshake, status code: %s", resp.Status)
  93. }
  94. return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump)
  95. }
  96. return &bufConn{Conn: conn, r: r}, nil
  97. }
  98. // proxyDial dials, connecting to a proxy first if necessary. Checks if a proxy
  99. // is necessary, dials, does the HTTP CONNECT handshake, and returns the
  100. // connection.
  101. func proxyDial(ctx context.Context, addr string, grpcUA string) (conn net.Conn, err error) {
  102. newAddr := addr
  103. proxyURL, err := mapAddress(addr)
  104. if err != nil {
  105. return nil, err
  106. }
  107. if proxyURL != nil {
  108. newAddr = proxyURL.Host
  109. }
  110. conn, err = (&net.Dialer{}).DialContext(ctx, "tcp", newAddr)
  111. if err != nil {
  112. return
  113. }
  114. if proxyURL != nil {
  115. // proxy is disabled if proxyURL is nil.
  116. conn, err = doHTTPConnectHandshake(ctx, conn, addr, proxyURL, grpcUA)
  117. }
  118. return
  119. }
  120. func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error {
  121. req = req.WithContext(ctx)
  122. if err := req.Write(conn); err != nil {
  123. return fmt.Errorf("failed to write the HTTP request: %v", err)
  124. }
  125. return nil
  126. }