proxy_http.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. /*
  20. * Copyright (c) 2014, Yawning Angel <yawning at torproject dot org>
  21. * All rights reserved.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions are met:
  25. *
  26. * * Redistributions of source code must retain the above copyright notice,
  27. * this list of conditions and the following disclaimer.
  28. *
  29. * * Redistributions in binary form must reproduce the above copyright notice,
  30. * this list of conditions and the following disclaimer in the documentation
  31. * and/or other materials provided with the distribution.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  34. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  35. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  37. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  38. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  39. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  40. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  41. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  43. * POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package upstreamproxy
  46. import (
  47. "bufio"
  48. "fmt"
  49. "net"
  50. "net/http"
  51. "net/http/httputil"
  52. "net/url"
  53. "time"
  54. "golang.org/x/net/proxy"
  55. )
  56. // httpProxy is a HTTP connect proxy.
  57. type httpProxy struct {
  58. hostPort string
  59. username string
  60. password string
  61. forward proxy.Dialer
  62. customHeaders http.Header
  63. }
  64. func newHTTP(uri *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
  65. hp := new(httpProxy)
  66. hp.hostPort = uri.Host
  67. hp.forward = forward
  68. if uri.User != nil {
  69. hp.username = uri.User.Username()
  70. hp.password, _ = uri.User.Password()
  71. }
  72. if upstreamProxyConfig, ok := forward.(*UpstreamProxyConfig); ok {
  73. hp.customHeaders = upstreamProxyConfig.CustomHeaders
  74. }
  75. return hp, nil
  76. }
  77. func (hp *httpProxy) Dial(network, addr string) (net.Conn, error) {
  78. // Dial and create the http client connection.
  79. pc := &proxyConn{
  80. authState: HTTP_AUTH_STATE_UNCHALLENGED,
  81. dialFn: hp.forward.Dial,
  82. proxyAddr: hp.hostPort,
  83. customHeaders: hp.customHeaders,
  84. }
  85. err := pc.makeNewClientConn()
  86. if err != nil {
  87. // Already wrapped in proxyError
  88. return nil, err
  89. }
  90. handshakeLoop:
  91. for {
  92. err := pc.handshake(addr, hp.username, hp.password)
  93. if err != nil {
  94. // Already wrapped in proxyError
  95. return nil, err
  96. }
  97. switch pc.authState {
  98. case HTTP_AUTH_STATE_SUCCESS:
  99. pc.hijackedConn, pc.staleReader = pc.httpClientConn.Hijack()
  100. return pc, nil
  101. case HTTP_AUTH_STATE_CHALLENGED:
  102. continue
  103. default:
  104. break handshakeLoop
  105. }
  106. }
  107. return nil, proxyError(fmt.Errorf("unknown handshake error in state %v", pc.authState))
  108. }
  109. type proxyConn struct {
  110. dialFn DialFunc
  111. proxyAddr string
  112. customHeaders http.Header
  113. httpClientConn *httputil.ClientConn //lint:ignore SA1019 httputil.ClientConn used for client-side hijack
  114. hijackedConn net.Conn
  115. staleReader *bufio.Reader
  116. authResponse *http.Response
  117. authState HttpAuthState
  118. authenticator HttpAuthenticator
  119. }
  120. func (pc *proxyConn) handshake(addr, username, password string) error {
  121. // HACK: prefix addr of the form 'hostname:port' with a 'http' scheme
  122. // so it could be parsed by url.Parse
  123. reqURL, err := url.Parse("http://" + addr)
  124. if err != nil {
  125. pc.httpClientConn.Close()
  126. pc.authState = HTTP_AUTH_STATE_FAILURE
  127. return proxyError(fmt.Errorf("failed to parse proxy address: %v", err))
  128. }
  129. reqURL.Scheme = ""
  130. req, err := http.NewRequest("CONNECT", reqURL.String(), nil)
  131. if err != nil {
  132. pc.httpClientConn.Close()
  133. pc.authState = HTTP_AUTH_STATE_FAILURE
  134. return proxyError(fmt.Errorf("create proxy request: %v", err))
  135. }
  136. req.Close = false
  137. req.Header.Set("User-Agent", "")
  138. for k, s := range pc.customHeaders {
  139. // handle special Host header case
  140. if k == "Host" {
  141. if len(s) > 0 {
  142. // hack around 'CONNECT' special case:
  143. // https://golang.org/src/net/http/request.go#L476
  144. // using URL.Opaque, see URL.RequestURI() https://golang.org/src/net/url/url.go#L915
  145. req.URL.Opaque = req.Host
  146. req.URL.Path = " "
  147. req.Host = s[0]
  148. }
  149. } else {
  150. req.Header[k] = s
  151. }
  152. }
  153. if pc.authState == HTTP_AUTH_STATE_CHALLENGED {
  154. err := pc.authenticator.Authenticate(req, pc.authResponse)
  155. if err != nil {
  156. pc.authState = HTTP_AUTH_STATE_FAILURE
  157. // Already wrapped in proxyError
  158. return err
  159. }
  160. }
  161. resp, err := pc.httpClientConn.Do(req)
  162. //lint:ignore SA1019 httputil.ClientConn used for client-side hijack
  163. errPersistEOF := httputil.ErrPersistEOF
  164. if err != nil && err != errPersistEOF {
  165. pc.httpClientConn.Close()
  166. pc.authState = HTTP_AUTH_STATE_FAILURE
  167. return proxyError(fmt.Errorf("making proxy request: %v", err))
  168. }
  169. if resp.StatusCode == 200 {
  170. pc.authState = HTTP_AUTH_STATE_SUCCESS
  171. return nil
  172. }
  173. if resp.StatusCode == 407 {
  174. if pc.authState == HTTP_AUTH_STATE_UNCHALLENGED {
  175. var authErr error
  176. pc.authenticator, authErr = NewHttpAuthenticator(resp, username, password)
  177. if authErr != nil {
  178. pc.httpClientConn.Close()
  179. pc.authState = HTTP_AUTH_STATE_FAILURE
  180. // Already wrapped in proxyError
  181. return authErr
  182. }
  183. }
  184. pc.authState = HTTP_AUTH_STATE_CHALLENGED
  185. pc.authResponse = resp
  186. if username == "" {
  187. pc.httpClientConn.Close()
  188. pc.authState = HTTP_AUTH_STATE_FAILURE
  189. return proxyError(fmt.Errorf("ho username credentials provided for proxy auth"))
  190. }
  191. if err == errPersistEOF {
  192. // The server may send Connection: close,
  193. // at this point we just going to create a new
  194. // ClientConn and continue the handshake
  195. err = pc.makeNewClientConn()
  196. if err != nil {
  197. // Already wrapped in proxyError
  198. return err
  199. }
  200. }
  201. return nil
  202. }
  203. pc.authState = HTTP_AUTH_STATE_FAILURE
  204. return proxyError(fmt.Errorf("handshake error: %v, response status: %s", err, resp.Status))
  205. }
  206. func (pc *proxyConn) makeNewClientConn() error {
  207. c, err := pc.dialFn("tcp", pc.proxyAddr)
  208. if pc.httpClientConn != nil {
  209. pc.httpClientConn.Close()
  210. }
  211. if err != nil {
  212. return proxyError(fmt.Errorf("makeNewClientConn: %v", err))
  213. }
  214. //lint:ignore SA1019 httputil.ClientConn used for client-side hijack
  215. pc.httpClientConn = httputil.NewClientConn(c, nil)
  216. return nil
  217. }
  218. func (pc *proxyConn) Read(b []byte) (int, error) {
  219. if pc.staleReader != nil {
  220. if pc.staleReader.Buffered() > 0 {
  221. return pc.staleReader.Read(b)
  222. }
  223. pc.staleReader = nil
  224. }
  225. return pc.hijackedConn.Read(b)
  226. }
  227. func (pc *proxyConn) Write(b []byte) (int, error) {
  228. return pc.hijackedConn.Write(b)
  229. }
  230. func (pc *proxyConn) Close() error {
  231. return pc.hijackedConn.Close()
  232. }
  233. func (pc *proxyConn) LocalAddr() net.Addr {
  234. return pc.hijackedConn.LocalAddr()
  235. }
  236. // RemoteAddr returns the network address of the proxy that
  237. // the proxyConn is connected to.
  238. func (pc *proxyConn) RemoteAddr() net.Addr {
  239. // Note: returning nil here can crash "tls".
  240. return pc.hijackedConn.RemoteAddr()
  241. }
  242. func (pc *proxyConn) SetDeadline(t time.Time) error {
  243. return proxyError(fmt.Errorf("not supported"))
  244. }
  245. func (pc *proxyConn) SetReadDeadline(t time.Time) error {
  246. return proxyError(fmt.Errorf("not supported"))
  247. }
  248. func (pc *proxyConn) SetWriteDeadline(t time.Time) error {
  249. return proxyError(fmt.Errorf("not supported"))
  250. }
  251. func init() {
  252. proxy.RegisterDialerType("http", newHTTP)
  253. }