proxy_http.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. "golang.org/x/net/proxy"
  50. "net"
  51. "net/http"
  52. "net/http/httputil"
  53. "net/url"
  54. "time"
  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. }
  63. func newHTTP(uri *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
  64. hp := new(httpProxy)
  65. hp.hostPort = uri.Host
  66. hp.forward = forward
  67. if uri.User != nil {
  68. hp.username = uri.User.Username()
  69. hp.password, _ = uri.User.Password()
  70. }
  71. return hp, nil
  72. }
  73. func (hp *httpProxy) Dial(network, addr string) (net.Conn, error) {
  74. // Dial and create the http client connection.
  75. pc := &proxyConn{
  76. authState: HTTP_AUTH_STATE_UNCHALLENGED,
  77. dialFn: hp.forward.Dial,
  78. proxyAddr: hp.hostPort,
  79. }
  80. err := pc.makeNewClientConn()
  81. if err != nil {
  82. //Already wrapped in proxyError
  83. return nil, err
  84. }
  85. handshakeLoop:
  86. for {
  87. err := pc.handshake(addr, hp.username, hp.password)
  88. if err != nil {
  89. //already wrapped in proxyError
  90. return nil, err
  91. }
  92. switch pc.authState {
  93. case HTTP_AUTH_STATE_SUCCESS:
  94. pc.hijackedConn, pc.staleReader = pc.httpClientConn.Hijack()
  95. return pc, nil
  96. case HTTP_AUTH_STATE_FAILURE:
  97. //err already wrapped in proxyError
  98. return nil, err
  99. case HTTP_AUTH_STATE_CHALLENGED:
  100. continue
  101. default:
  102. break handshakeLoop
  103. }
  104. }
  105. return nil, proxyError(fmt.Errorf("Unknown handshake error"))
  106. }
  107. type proxyConn struct {
  108. dialFn DialFunc
  109. proxyAddr string
  110. httpClientConn *httputil.ClientConn
  111. hijackedConn net.Conn
  112. staleReader *bufio.Reader
  113. authResponse *http.Response
  114. authState HttpAuthState
  115. authenticator HttpAuthenticator
  116. }
  117. func (pc *proxyConn) handshake(addr, username, password string) error {
  118. // HACK: prefix addr of the form 'hostname:port' with a 'http' scheme
  119. // so it could be parsed by url.Parse
  120. reqURL, err := url.Parse("http://" + addr)
  121. if err != nil {
  122. pc.httpClientConn.Close()
  123. pc.authState = HTTP_AUTH_STATE_FAILURE
  124. return proxyError(fmt.Errorf("Failed to parse proxy address: %v", err))
  125. }
  126. reqURL.Scheme = ""
  127. req, err := http.NewRequest("CONNECT", reqURL.String(), nil)
  128. if err != nil {
  129. pc.httpClientConn.Close()
  130. pc.authState = HTTP_AUTH_STATE_FAILURE
  131. return proxyError(fmt.Errorf("Create proxy request: %v", err))
  132. }
  133. req.Close = false
  134. req.Header.Set("User-Agent", "")
  135. if pc.authState == HTTP_AUTH_STATE_CHALLENGED {
  136. err := pc.authenticator.Authenticate(req, pc.authResponse)
  137. if err != nil {
  138. pc.authState = HTTP_AUTH_STATE_FAILURE
  139. //Already wrapped in proxyError
  140. return err
  141. }
  142. }
  143. resp, err := pc.httpClientConn.Do(req)
  144. if err != nil && err != httputil.ErrPersistEOF {
  145. pc.httpClientConn.Close()
  146. pc.authState = HTTP_AUTH_STATE_FAILURE
  147. return proxyError(fmt.Errorf("making proxy request: %v", err))
  148. }
  149. if resp.StatusCode == 200 {
  150. pc.authState = HTTP_AUTH_STATE_SUCCESS
  151. return nil
  152. }
  153. if resp.StatusCode == 407 {
  154. if pc.authState == HTTP_AUTH_STATE_UNCHALLENGED {
  155. var auth_err error = nil
  156. pc.authenticator, auth_err = NewHttpAuthenticator(resp, username, password)
  157. if auth_err != nil {
  158. pc.httpClientConn.Close()
  159. pc.authState = HTTP_AUTH_STATE_FAILURE
  160. //Already wrapped in proxyError
  161. return auth_err
  162. }
  163. }
  164. pc.authState = HTTP_AUTH_STATE_CHALLENGED
  165. pc.authResponse = resp
  166. if username == "" {
  167. pc.httpClientConn.Close()
  168. pc.authState = HTTP_AUTH_STATE_FAILURE
  169. return proxyError(fmt.Errorf("No username credentials provided for proxy auth"))
  170. }
  171. if err == httputil.ErrPersistEOF {
  172. // the server may send Connection: close,
  173. // at this point we just going to create a new
  174. // ClientConn and continue the handshake
  175. err = pc.makeNewClientConn()
  176. if err != nil {
  177. //Already wrapped in proxyError
  178. return err
  179. }
  180. }
  181. return nil
  182. }
  183. pc.authState = HTTP_AUTH_STATE_FAILURE
  184. return proxyError(fmt.Errorf("Handshake error: %v, response status: %s", err, resp.Status))
  185. }
  186. func (pc *proxyConn) makeNewClientConn() error {
  187. c, err := pc.dialFn("tcp", pc.proxyAddr)
  188. if pc.httpClientConn != nil {
  189. pc.httpClientConn.Close()
  190. }
  191. if err != nil {
  192. return proxyError(fmt.Errorf("makeNewClientConn: %v", err))
  193. }
  194. pc.httpClientConn = httputil.NewClientConn(c, nil)
  195. return nil
  196. }
  197. func (pc *proxyConn) Read(b []byte) (int, error) {
  198. if pc.staleReader != nil {
  199. if pc.staleReader.Buffered() > 0 {
  200. return pc.staleReader.Read(b)
  201. }
  202. pc.staleReader = nil
  203. }
  204. return pc.hijackedConn.Read(b)
  205. }
  206. func (pc *proxyConn) Write(b []byte) (int, error) {
  207. return pc.hijackedConn.Write(b)
  208. }
  209. func (pc *proxyConn) Close() error {
  210. return pc.hijackedConn.Close()
  211. }
  212. func (pc *proxyConn) LocalAddr() net.Addr {
  213. return nil
  214. }
  215. func (pc *proxyConn) RemoteAddr() net.Addr {
  216. return nil
  217. }
  218. func (pc *proxyConn) SetDeadline(t time.Time) error {
  219. return proxyError(fmt.Errorf("not supported"))
  220. }
  221. func (pc *proxyConn) SetReadDeadline(t time.Time) error {
  222. return proxyError(fmt.Errorf("not supported"))
  223. }
  224. func (pc *proxyConn) SetWriteDeadline(t time.Time) error {
  225. return proxyError(fmt.Errorf("not supported"))
  226. }
  227. func init() {
  228. proxy.RegisterDialerType("http", newHTTP)
  229. }