proxy_http.go 7.9 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_FAILURE:
  102. //err already wrapped in proxyError
  103. return nil, err
  104. case HTTP_AUTH_STATE_CHALLENGED:
  105. continue
  106. default:
  107. break handshakeLoop
  108. }
  109. }
  110. return nil, proxyError(fmt.Errorf("Unknown handshake error"))
  111. }
  112. type proxyConn struct {
  113. dialFn DialFunc
  114. proxyAddr string
  115. customHeaders http.Header
  116. httpClientConn *httputil.ClientConn
  117. hijackedConn net.Conn
  118. staleReader *bufio.Reader
  119. authResponse *http.Response
  120. authState HttpAuthState
  121. authenticator HttpAuthenticator
  122. }
  123. func (pc *proxyConn) handshake(addr, username, password string) error {
  124. // HACK: prefix addr of the form 'hostname:port' with a 'http' scheme
  125. // so it could be parsed by url.Parse
  126. reqURL, err := url.Parse("http://" + addr)
  127. if err != nil {
  128. pc.httpClientConn.Close()
  129. pc.authState = HTTP_AUTH_STATE_FAILURE
  130. return proxyError(fmt.Errorf("Failed to parse proxy address: %v", err))
  131. }
  132. reqURL.Scheme = ""
  133. req, err := http.NewRequest("CONNECT", reqURL.String(), nil)
  134. if err != nil {
  135. pc.httpClientConn.Close()
  136. pc.authState = HTTP_AUTH_STATE_FAILURE
  137. return proxyError(fmt.Errorf("Create proxy request: %v", err))
  138. }
  139. req.Close = false
  140. req.Header.Set("User-Agent", "")
  141. for k, s := range pc.customHeaders {
  142. // handle special Host header case
  143. if k == "Host" {
  144. if len(s) > 0 {
  145. // hack around 'CONNECT' special case:
  146. // https://golang.org/src/net/http/request.go#L476
  147. // using URL.Opaque, see URL.RequestURI() https://golang.org/src/net/url/url.go#L915
  148. req.URL.Opaque = req.Host
  149. req.URL.Path = " "
  150. req.Host = s[0]
  151. }
  152. } else {
  153. req.Header[k] = s
  154. }
  155. }
  156. if pc.authState == HTTP_AUTH_STATE_CHALLENGED {
  157. err := pc.authenticator.Authenticate(req, pc.authResponse)
  158. if err != nil {
  159. pc.authState = HTTP_AUTH_STATE_FAILURE
  160. //Already wrapped in proxyError
  161. return err
  162. }
  163. }
  164. resp, err := pc.httpClientConn.Do(req)
  165. if err != nil && err != httputil.ErrPersistEOF {
  166. pc.httpClientConn.Close()
  167. pc.authState = HTTP_AUTH_STATE_FAILURE
  168. return proxyError(fmt.Errorf("making proxy request: %v", err))
  169. }
  170. if resp.StatusCode == 200 {
  171. pc.authState = HTTP_AUTH_STATE_SUCCESS
  172. return nil
  173. }
  174. if resp.StatusCode == 407 {
  175. if pc.authState == HTTP_AUTH_STATE_UNCHALLENGED {
  176. var authErr error
  177. pc.authenticator, authErr = NewHttpAuthenticator(resp, username, password)
  178. if authErr != nil {
  179. pc.httpClientConn.Close()
  180. pc.authState = HTTP_AUTH_STATE_FAILURE
  181. //Already wrapped in proxyError
  182. return authErr
  183. }
  184. }
  185. pc.authState = HTTP_AUTH_STATE_CHALLENGED
  186. pc.authResponse = resp
  187. if username == "" {
  188. pc.httpClientConn.Close()
  189. pc.authState = HTTP_AUTH_STATE_FAILURE
  190. return proxyError(fmt.Errorf("No username credentials provided for proxy auth"))
  191. }
  192. if err == httputil.ErrPersistEOF {
  193. // the server may send Connection: close,
  194. // at this point we just going to create a new
  195. // ClientConn and continue the handshake
  196. err = pc.makeNewClientConn()
  197. if err != nil {
  198. //Already wrapped in proxyError
  199. return err
  200. }
  201. }
  202. return nil
  203. }
  204. pc.authState = HTTP_AUTH_STATE_FAILURE
  205. return proxyError(fmt.Errorf("Handshake error: %v, response status: %s", err, resp.Status))
  206. }
  207. func (pc *proxyConn) makeNewClientConn() error {
  208. c, err := pc.dialFn("tcp", pc.proxyAddr)
  209. if pc.httpClientConn != nil {
  210. pc.httpClientConn.Close()
  211. }
  212. if err != nil {
  213. return proxyError(fmt.Errorf("makeNewClientConn: %v", err))
  214. }
  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. }