proxy.go 3.7 KB

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