Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

232 рядки
5.5 KiB

  1. // +build !race
  2. /*
  3. *
  4. * Copyright 2017 gRPC authors.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. */
  19. package grpc
  20. import (
  21. "bufio"
  22. "context"
  23. "encoding/base64"
  24. "fmt"
  25. "io"
  26. "net"
  27. "net/http"
  28. "net/url"
  29. "testing"
  30. "time"
  31. )
  32. const (
  33. envTestAddr = "1.2.3.4:8080"
  34. envProxyAddr = "2.3.4.5:7687"
  35. )
  36. // overwriteAndRestore overwrite function httpProxyFromEnvironment and
  37. // returns a function to restore the default values.
  38. func overwrite(hpfe func(req *http.Request) (*url.URL, error)) func() {
  39. backHPFE := httpProxyFromEnvironment
  40. httpProxyFromEnvironment = hpfe
  41. return func() {
  42. httpProxyFromEnvironment = backHPFE
  43. }
  44. }
  45. type proxyServer struct {
  46. t *testing.T
  47. lis net.Listener
  48. in net.Conn
  49. out net.Conn
  50. requestCheck func(*http.Request) error
  51. }
  52. func (p *proxyServer) run() {
  53. in, err := p.lis.Accept()
  54. if err != nil {
  55. return
  56. }
  57. p.in = in
  58. req, err := http.ReadRequest(bufio.NewReader(in))
  59. if err != nil {
  60. p.t.Errorf("failed to read CONNECT req: %v", err)
  61. return
  62. }
  63. if err := p.requestCheck(req); err != nil {
  64. resp := http.Response{StatusCode: http.StatusMethodNotAllowed}
  65. resp.Write(p.in)
  66. p.in.Close()
  67. p.t.Errorf("get wrong CONNECT req: %+v, error: %v", req, err)
  68. return
  69. }
  70. out, err := net.Dial("tcp", req.URL.Host)
  71. if err != nil {
  72. p.t.Errorf("failed to dial to server: %v", err)
  73. return
  74. }
  75. resp := http.Response{StatusCode: http.StatusOK, Proto: "HTTP/1.0"}
  76. resp.Write(p.in)
  77. p.out = out
  78. go io.Copy(p.in, p.out)
  79. go io.Copy(p.out, p.in)
  80. }
  81. func (p *proxyServer) stop() {
  82. p.lis.Close()
  83. if p.in != nil {
  84. p.in.Close()
  85. }
  86. if p.out != nil {
  87. p.out.Close()
  88. }
  89. }
  90. func testHTTPConnect(t *testing.T, proxyURLModify func(*url.URL) *url.URL, proxyReqCheck func(*http.Request) error) {
  91. plis, err := net.Listen("tcp", "localhost:0")
  92. if err != nil {
  93. t.Fatalf("failed to listen: %v", err)
  94. }
  95. p := &proxyServer{
  96. t: t,
  97. lis: plis,
  98. requestCheck: proxyReqCheck,
  99. }
  100. go p.run()
  101. defer p.stop()
  102. blis, err := net.Listen("tcp", "localhost:0")
  103. if err != nil {
  104. t.Fatalf("failed to listen: %v", err)
  105. }
  106. msg := []byte{4, 3, 5, 2}
  107. recvBuf := make([]byte, len(msg))
  108. done := make(chan struct{})
  109. go func() {
  110. in, err := blis.Accept()
  111. if err != nil {
  112. t.Errorf("failed to accept: %v", err)
  113. return
  114. }
  115. defer in.Close()
  116. in.Read(recvBuf)
  117. close(done)
  118. }()
  119. // Overwrite the function in the test and restore them in defer.
  120. hpfe := func(req *http.Request) (*url.URL, error) {
  121. return proxyURLModify(&url.URL{Host: plis.Addr().String()}), nil
  122. }
  123. defer overwrite(hpfe)()
  124. // Dial to proxy server.
  125. dialer := newProxyDialer(func(ctx context.Context, addr string) (net.Conn, error) {
  126. if deadline, ok := ctx.Deadline(); ok {
  127. return net.DialTimeout("tcp", addr, time.Until(deadline))
  128. }
  129. return net.Dial("tcp", addr)
  130. })
  131. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  132. defer cancel()
  133. c, err := dialer(ctx, blis.Addr().String())
  134. if err != nil {
  135. t.Fatalf("http connect Dial failed: %v", err)
  136. }
  137. defer c.Close()
  138. // Send msg on the connection.
  139. c.Write(msg)
  140. <-done
  141. // Check received msg.
  142. if string(recvBuf) != string(msg) {
  143. t.Fatalf("received msg: %v, want %v", recvBuf, msg)
  144. }
  145. }
  146. func (s) TestHTTPConnect(t *testing.T) {
  147. testHTTPConnect(t,
  148. func(in *url.URL) *url.URL {
  149. return in
  150. },
  151. func(req *http.Request) error {
  152. if req.Method != http.MethodConnect {
  153. return fmt.Errorf("unexpected Method %q, want %q", req.Method, http.MethodConnect)
  154. }
  155. if req.UserAgent() != grpcUA {
  156. return fmt.Errorf("unexpect user agent %q, want %q", req.UserAgent(), grpcUA)
  157. }
  158. return nil
  159. },
  160. )
  161. }
  162. func (s) TestHTTPConnectBasicAuth(t *testing.T) {
  163. const (
  164. user = "notAUser"
  165. password = "notAPassword"
  166. )
  167. testHTTPConnect(t,
  168. func(in *url.URL) *url.URL {
  169. in.User = url.UserPassword(user, password)
  170. return in
  171. },
  172. func(req *http.Request) error {
  173. if req.Method != http.MethodConnect {
  174. return fmt.Errorf("unexpected Method %q, want %q", req.Method, http.MethodConnect)
  175. }
  176. if req.UserAgent() != grpcUA {
  177. return fmt.Errorf("unexpect user agent %q, want %q", req.UserAgent(), grpcUA)
  178. }
  179. wantProxyAuthStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+password))
  180. if got := req.Header.Get(proxyAuthHeaderKey); got != wantProxyAuthStr {
  181. gotDecoded, _ := base64.StdEncoding.DecodeString(got)
  182. wantDecoded, _ := base64.StdEncoding.DecodeString(wantProxyAuthStr)
  183. return fmt.Errorf("unexpected auth %q (%q), want %q (%q)", got, gotDecoded, wantProxyAuthStr, wantDecoded)
  184. }
  185. return nil
  186. },
  187. )
  188. }
  189. func (s) TestMapAddressEnv(t *testing.T) {
  190. // Overwrite the function in the test and restore them in defer.
  191. hpfe := func(req *http.Request) (*url.URL, error) {
  192. if req.URL.Host == envTestAddr {
  193. return &url.URL{
  194. Scheme: "https",
  195. Host: envProxyAddr,
  196. }, nil
  197. }
  198. return nil, nil
  199. }
  200. defer overwrite(hpfe)()
  201. // envTestAddr should be handled by ProxyFromEnvironment.
  202. got, err := mapAddress(context.Background(), envTestAddr)
  203. if err != nil {
  204. t.Error(err)
  205. }
  206. if got.Host != envProxyAddr {
  207. t.Errorf("want %v, got %v", envProxyAddr, got)
  208. }
  209. }