proxy_http.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  55. "golang.org/x/net/proxy"
  56. )
  57. // httpProxy is a HTTP connect proxy.
  58. type httpProxy struct {
  59. hostPort string
  60. username string
  61. password string
  62. forward proxy.Dialer
  63. customHeaders http.Header
  64. }
  65. func newHTTP(uri *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
  66. hp := new(httpProxy)
  67. hp.hostPort = uri.Host
  68. hp.forward = forward
  69. if uri.User != nil {
  70. hp.username = uri.User.Username()
  71. hp.password, _ = uri.User.Password()
  72. }
  73. if upstreamProxyConfig, ok := forward.(*UpstreamProxyConfig); ok {
  74. hp.customHeaders = upstreamProxyConfig.CustomHeaders
  75. }
  76. return hp, nil
  77. }
  78. func (hp *httpProxy) Dial(network, addr string) (net.Conn, error) {
  79. // Dial and create the http client connection.
  80. pc := &proxyConn{
  81. authState: HTTP_AUTH_STATE_UNCHALLENGED,
  82. dialFn: hp.forward.Dial,
  83. proxyAddr: hp.hostPort,
  84. customHeaders: hp.customHeaders,
  85. }
  86. err := pc.makeNewClientConn()
  87. if err != nil {
  88. // Already wrapped in proxyError
  89. return nil, err
  90. }
  91. handshakeLoop:
  92. for {
  93. err := pc.handshake(addr, hp.username, hp.password)
  94. if err != nil {
  95. // Already wrapped in proxyError
  96. return nil, err
  97. }
  98. switch pc.authState {
  99. case HTTP_AUTH_STATE_SUCCESS:
  100. pc.hijackedConn, pc.staleReader = pc.httpClientConn.Hijack()
  101. return pc, nil
  102. case HTTP_AUTH_STATE_CHALLENGED:
  103. continue
  104. default:
  105. break handshakeLoop
  106. }
  107. }
  108. return nil, proxyError(fmt.Errorf("unknown handshake error in state %v", pc.authState))
  109. }
  110. type proxyConn struct {
  111. dialFn DialFunc
  112. proxyAddr string
  113. customHeaders http.Header
  114. httpClientConn *httputil.ClientConn //lint:ignore SA1019 httputil.ClientConn used for client-side hijack
  115. hijackedConn net.Conn
  116. staleReader *bufio.Reader
  117. authResponse *http.Response
  118. authState HttpAuthState
  119. authenticator HttpAuthenticator
  120. }
  121. func (pc *proxyConn) handshake(addr, username, password string) error {
  122. // HACK: prefix addr of the form 'hostname:port' with a 'http' scheme
  123. // so it could be parsed by url.Parse
  124. reqURL, err := common.SafeParseURL("http://" + addr)
  125. if err != nil {
  126. pc.httpClientConn.Close()
  127. pc.authState = HTTP_AUTH_STATE_FAILURE
  128. return proxyError(fmt.Errorf("failed to parse proxy address: %v", err))
  129. }
  130. reqURL.Scheme = ""
  131. req, err := http.NewRequest("CONNECT", reqURL.String(), nil)
  132. if err != nil {
  133. pc.httpClientConn.Close()
  134. pc.authState = HTTP_AUTH_STATE_FAILURE
  135. return proxyError(fmt.Errorf("create proxy request: %v", err))
  136. }
  137. req.Close = false
  138. req.Header.Set("User-Agent", "")
  139. for k, s := range pc.customHeaders {
  140. // handle special Host header case
  141. if k == "Host" {
  142. if len(s) > 0 {
  143. // hack around 'CONNECT' special case:
  144. // https://golang.org/src/net/http/request.go#L476
  145. // using URL.Opaque, see URL.RequestURI() https://golang.org/src/net/url/url.go#L915
  146. req.URL.Opaque = req.Host
  147. req.URL.Path = " "
  148. req.Host = s[0]
  149. }
  150. } else {
  151. req.Header[k] = s
  152. }
  153. }
  154. if pc.authState == HTTP_AUTH_STATE_CHALLENGED {
  155. err := pc.authenticator.Authenticate(req, pc.authResponse)
  156. if err != nil {
  157. pc.authState = HTTP_AUTH_STATE_FAILURE
  158. // Already wrapped in proxyError
  159. return err
  160. }
  161. }
  162. resp, err := pc.httpClientConn.Do(req)
  163. //lint:ignore SA1019 httputil.ClientConn used for client-side hijack
  164. errPersistEOF := httputil.ErrPersistEOF
  165. if err != nil && err != 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 == 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. headers := resp.Header[http.CanonicalHeaderKey("proxy-connection")]
  203. for _, header := range headers {
  204. if header == "close" {
  205. // The server has signaled that it will close the
  206. // connection. Create a new ClientConn and continue the
  207. // handshake.
  208. err = pc.makeNewClientConn()
  209. if err != nil {
  210. // Already wrapped in proxyError
  211. return err
  212. }
  213. break
  214. }
  215. }
  216. return nil
  217. }
  218. pc.authState = HTTP_AUTH_STATE_FAILURE
  219. return proxyError(fmt.Errorf("handshake error: %v, response status: %s", err, resp.Status))
  220. }
  221. func (pc *proxyConn) makeNewClientConn() error {
  222. c, err := pc.dialFn("tcp", pc.proxyAddr)
  223. if pc.httpClientConn != nil {
  224. pc.httpClientConn.Close()
  225. }
  226. if err != nil {
  227. return proxyError(fmt.Errorf("makeNewClientConn: %v", err))
  228. }
  229. //lint:ignore SA1019 httputil.ClientConn used for client-side hijack
  230. pc.httpClientConn = httputil.NewClientConn(c, nil)
  231. return nil
  232. }
  233. func (pc *proxyConn) Read(b []byte) (int, error) {
  234. if pc.staleReader != nil {
  235. if pc.staleReader.Buffered() > 0 {
  236. return pc.staleReader.Read(b)
  237. }
  238. pc.staleReader = nil
  239. }
  240. return pc.hijackedConn.Read(b)
  241. }
  242. func (pc *proxyConn) Write(b []byte) (int, error) {
  243. return pc.hijackedConn.Write(b)
  244. }
  245. func (pc *proxyConn) Close() error {
  246. return pc.hijackedConn.Close()
  247. }
  248. func (pc *proxyConn) LocalAddr() net.Addr {
  249. return pc.hijackedConn.LocalAddr()
  250. }
  251. // RemoteAddr returns the network address of the proxy that
  252. // the proxyConn is connected to.
  253. func (pc *proxyConn) RemoteAddr() net.Addr {
  254. // Note: returning nil here can crash "tls".
  255. return pc.hijackedConn.RemoteAddr()
  256. }
  257. func (pc *proxyConn) SetDeadline(t time.Time) error {
  258. return proxyError(fmt.Errorf("not supported"))
  259. }
  260. func (pc *proxyConn) SetReadDeadline(t time.Time) error {
  261. return proxyError(fmt.Errorf("not supported"))
  262. }
  263. func (pc *proxyConn) SetWriteDeadline(t time.Time) error {
  264. return proxyError(fmt.Errorf("not supported"))
  265. }
  266. func init() {
  267. proxy.RegisterDialerType("http", newHTTP)
  268. }