proxy.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. /*
  2. *
  3. * Copyright 2017, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. package grpc
  34. import (
  35. "bufio"
  36. "errors"
  37. "fmt"
  38. "io"
  39. "net"
  40. "net/http"
  41. "net/http/httputil"
  42. "net/url"
  43. "golang.org/x/net/context"
  44. )
  45. var (
  46. // errDisabled indicates that proxy is disabled for the address.
  47. errDisabled = errors.New("proxy is disabled for the address")
  48. // The following variable will be overwritten in the tests.
  49. httpProxyFromEnvironment = http.ProxyFromEnvironment
  50. )
  51. func mapAddress(ctx context.Context, address string) (string, error) {
  52. req := &http.Request{
  53. URL: &url.URL{
  54. Scheme: "https",
  55. Host: address,
  56. },
  57. }
  58. url, err := httpProxyFromEnvironment(req)
  59. if err != nil {
  60. return "", err
  61. }
  62. if url == nil {
  63. return "", errDisabled
  64. }
  65. return url.Host, nil
  66. }
  67. // To read a response from a net.Conn, http.ReadResponse() takes a bufio.Reader.
  68. // It's possible that this reader reads more than what's need for the response and stores
  69. // those bytes in the buffer.
  70. // bufConn wraps the original net.Conn and the bufio.Reader to make sure we don't lose the
  71. // bytes in the buffer.
  72. type bufConn struct {
  73. net.Conn
  74. r io.Reader
  75. }
  76. func (c *bufConn) Read(b []byte) (int, error) {
  77. return c.r.Read(b)
  78. }
  79. func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, addr string) (_ net.Conn, err error) {
  80. defer func() {
  81. if err != nil {
  82. conn.Close()
  83. }
  84. }()
  85. req := (&http.Request{
  86. Method: http.MethodConnect,
  87. URL: &url.URL{Host: addr},
  88. Header: map[string][]string{"User-Agent": {grpcUA}},
  89. })
  90. if err := sendHTTPRequest(ctx, req, conn); err != nil {
  91. return nil, fmt.Errorf("failed to write the HTTP request: %v", err)
  92. }
  93. r := bufio.NewReader(conn)
  94. resp, err := http.ReadResponse(r, req)
  95. if err != nil {
  96. return nil, fmt.Errorf("reading server HTTP response: %v", err)
  97. }
  98. defer resp.Body.Close()
  99. if resp.StatusCode != http.StatusOK {
  100. dump, err := httputil.DumpResponse(resp, true)
  101. if err != nil {
  102. return nil, fmt.Errorf("failed to do connect handshake, status code: %s", resp.Status)
  103. }
  104. return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump)
  105. }
  106. return &bufConn{Conn: conn, r: r}, nil
  107. }
  108. // newProxyDialer returns a dialer that connects to proxy first if necessary.
  109. // The returned dialer checks if a proxy is necessary, dial to the proxy with the
  110. // provided dialer, does HTTP CONNECT handshake and returns the connection.
  111. func newProxyDialer(dialer func(context.Context, string) (net.Conn, error)) func(context.Context, string) (net.Conn, error) {
  112. return func(ctx context.Context, addr string) (conn net.Conn, err error) {
  113. var skipHandshake bool
  114. newAddr, err := mapAddress(ctx, addr)
  115. if err != nil {
  116. if err != errDisabled {
  117. return nil, err
  118. }
  119. skipHandshake = true
  120. newAddr = addr
  121. }
  122. conn, err = dialer(ctx, newAddr)
  123. if err != nil {
  124. return
  125. }
  126. if !skipHandshake {
  127. conn, err = doHTTPConnectHandshake(ctx, conn, addr)
  128. }
  129. return
  130. }
  131. }