httpProxy.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. * Copyright (c) 2016, 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. package psiphon
  20. import (
  21. "errors"
  22. "fmt"
  23. "io"
  24. "net"
  25. "net/http"
  26. "net/url"
  27. "strings"
  28. "sync"
  29. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. )
  32. // HttpProxy is a HTTP server that relays HTTP requests through the Psiphon tunnel.
  33. // It includes support for HTTP CONNECT.
  34. //
  35. // This proxy also offers a "URL proxy" mode that relays requests for HTTP or HTTPS
  36. // or URLs specified in the proxy request path. This mode relays either through the
  37. // Psiphon tunnel, or directly.
  38. //
  39. // An example use case for tunneled URL proxy relays is to craft proxied URLs to pass to
  40. // components that don't support HTTP or SOCKS proxy settings. For example, the
  41. // Android Media Player (http://developer.android.com/reference/android/media/MediaPlayer.html).
  42. // To make the Media Player use the Psiphon tunnel, construct a URL such as:
  43. // "http://127.0.0.1:<proxy-port>/tunneled/<origin media URL>"; and pass this to the player.
  44. // The <origin media URL> must be escaped in such a way that it can be used inside a URL query.
  45. // TODO: add ICY protocol to support certain streaming media (e.g., https://gist.github.com/tulskiy/1008126)
  46. //
  47. // An example use case for direct, untunneled, relaying is to make use of Go's TLS
  48. // stack for HTTPS requests in cases where the native TLS stack is lacking (e.g.,
  49. // WinHTTP on Windows XP). The URL for direct relaying is:
  50. // "http://127.0.0.1:<proxy-port>/direct/<origin URL>".
  51. // Again, the <origin URL> must be escaped in such a way that it can be used inside a URL query.
  52. //
  53. // Origin URLs must include the scheme prefix ("http://" or "https://") and must be
  54. // URL encoded.
  55. //
  56. type HttpProxy struct {
  57. tunneler Tunneler
  58. listener net.Listener
  59. serveWaitGroup *sync.WaitGroup
  60. httpProxyTunneledRelay *http.Transport
  61. urlProxyTunneledRelay *http.Transport
  62. urlProxyTunneledClient *http.Client
  63. urlProxyDirectRelay *http.Transport
  64. urlProxyDirectClient *http.Client
  65. openConns *common.Conns
  66. stopListeningBroadcast chan struct{}
  67. }
  68. var _HTTP_PROXY_TYPE = "HTTP"
  69. // NewHttpProxy initializes and runs a new HTTP proxy server.
  70. func NewHttpProxy(
  71. config *Config,
  72. untunneledDialConfig *DialConfig,
  73. tunneler Tunneler,
  74. listenIP string) (proxy *HttpProxy, err error) {
  75. listener, err := net.Listen(
  76. "tcp", fmt.Sprintf("%s:%d", listenIP, config.LocalHttpProxyPort))
  77. if err != nil {
  78. if IsAddressInUseError(err) {
  79. NoticeHttpProxyPortInUse(config.LocalHttpProxyPort)
  80. }
  81. return nil, common.ContextError(err)
  82. }
  83. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  84. // downstreamConn is not set in this case, as there is not a fixed
  85. // association between a downstream client connection and a particular
  86. // tunnel.
  87. // TODO: connect timeout?
  88. return tunneler.Dial(addr, false, nil)
  89. }
  90. directDialer := func(_, addr string) (conn net.Conn, err error) {
  91. return DialTCP(addr, untunneledDialConfig)
  92. }
  93. responseHeaderTimeout := time.Duration(*config.HttpProxyOriginServerTimeoutSeconds) * time.Second
  94. // TODO: could HTTP proxy share a tunneled transport with URL proxy?
  95. // For now, keeping them distinct just to be conservative.
  96. httpProxyTunneledRelay := &http.Transport{
  97. Dial: tunneledDialer,
  98. MaxIdleConnsPerHost: HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST,
  99. ResponseHeaderTimeout: responseHeaderTimeout,
  100. }
  101. // Note: URL proxy relays use http.Client for upstream requests, so
  102. // redirects will be followed. HTTP proxy should not follow redirects
  103. // and simply uses http.Transport directly.
  104. urlProxyTunneledRelay := &http.Transport{
  105. Dial: tunneledDialer,
  106. MaxIdleConnsPerHost: HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST,
  107. ResponseHeaderTimeout: responseHeaderTimeout,
  108. }
  109. urlProxyTunneledClient := &http.Client{
  110. Transport: urlProxyTunneledRelay,
  111. Jar: nil, // TODO: cookie support for URL proxy?
  112. // Leaving original value in the note below:
  113. // Note: don't use this timeout -- it interrupts downloads of large response bodies
  114. //Timeout: HTTP_PROXY_ORIGIN_SERVER_TIMEOUT,
  115. }
  116. urlProxyDirectRelay := &http.Transport{
  117. Dial: directDialer,
  118. MaxIdleConnsPerHost: HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST,
  119. ResponseHeaderTimeout: responseHeaderTimeout,
  120. }
  121. urlProxyDirectClient := &http.Client{
  122. Transport: urlProxyDirectRelay,
  123. Jar: nil,
  124. }
  125. proxy = &HttpProxy{
  126. tunneler: tunneler,
  127. listener: listener,
  128. serveWaitGroup: new(sync.WaitGroup),
  129. httpProxyTunneledRelay: httpProxyTunneledRelay,
  130. urlProxyTunneledRelay: urlProxyTunneledRelay,
  131. urlProxyTunneledClient: urlProxyTunneledClient,
  132. urlProxyDirectRelay: urlProxyDirectRelay,
  133. urlProxyDirectClient: urlProxyDirectClient,
  134. openConns: new(common.Conns),
  135. stopListeningBroadcast: make(chan struct{}),
  136. }
  137. proxy.serveWaitGroup.Add(1)
  138. go proxy.serve()
  139. // TODO: NoticeListeningHttpProxyPort is emitted after net.Listen
  140. // but before go proxy.server() and httpServer.Serve(), and this
  141. // appears to cause client connections to the HTTP proxy to fail
  142. // (in controller_test.go, only when a tunnel is established very quickly
  143. // and NoticeTunnels is emitted and the client makes a request -- all
  144. // before the proxy.server() goroutine runs).
  145. // This condition doesn't arise in Go 1.4, just in Go tip (pre-1.5).
  146. // Note that httpServer.Serve() blocks so the fix can't be to emit
  147. // NoticeListeningHttpProxyPort after that call.
  148. // Also, check the listen backlog queue length -- shouldn't it be possible
  149. // to enqueue pending connections between net.Listen() and httpServer.Serve()?
  150. NoticeListeningHttpProxyPort(proxy.listener.Addr().(*net.TCPAddr).Port)
  151. return proxy, nil
  152. }
  153. // Close terminates the HTTP server.
  154. func (proxy *HttpProxy) Close() {
  155. close(proxy.stopListeningBroadcast)
  156. proxy.listener.Close()
  157. proxy.serveWaitGroup.Wait()
  158. // Close local->proxy persistent connections
  159. proxy.openConns.CloseAll()
  160. // Close idle proxy->origin persistent connections
  161. // TODO: also close active connections
  162. proxy.httpProxyTunneledRelay.CloseIdleConnections()
  163. proxy.urlProxyTunneledRelay.CloseIdleConnections()
  164. proxy.urlProxyDirectRelay.CloseIdleConnections()
  165. }
  166. // ServeHTTP receives HTTP requests and proxies them. CONNECT requests
  167. // are hijacked and all data is relayed. Other HTTP requests are proxied
  168. // with explicit round trips. In both cases, the tunnel is used for proxied
  169. // traffic.
  170. //
  171. // Implementation is based on:
  172. //
  173. // https://github.com/justmao945/mallory
  174. // Copyright (c) 2014 JianjunMao
  175. // The MIT License (MIT)
  176. //
  177. // https://golang.org/src/pkg/net/http/httputil/reverseproxy.go
  178. // Copyright 2011 The Go Authors. All rights reserved.
  179. // Use of this source code is governed by a BSD-style
  180. // license that can be found in the LICENSE file.
  181. //
  182. func (proxy *HttpProxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  183. if request.Method == "CONNECT" {
  184. hijacker, _ := responseWriter.(http.Hijacker)
  185. conn, _, err := hijacker.Hijack()
  186. if err != nil {
  187. NoticeAlert("%s", common.ContextError(err))
  188. http.Error(responseWriter, "", http.StatusInternalServerError)
  189. return
  190. }
  191. go func() {
  192. err := proxy.httpConnectHandler(conn, request.URL.Host)
  193. if err != nil {
  194. NoticeAlert("%s", common.ContextError(err))
  195. }
  196. }()
  197. } else if request.URL.IsAbs() {
  198. proxy.httpProxyHandler(responseWriter, request)
  199. } else {
  200. proxy.urlProxyHandler(responseWriter, request)
  201. }
  202. }
  203. func (proxy *HttpProxy) httpConnectHandler(localConn net.Conn, target string) (err error) {
  204. defer localConn.Close()
  205. defer proxy.openConns.Remove(localConn)
  206. proxy.openConns.Add(localConn)
  207. // Setting downstreamConn so localConn.Close() will be called when remoteConn.Close() is called.
  208. // This ensures that the downstream client (e.g., web browser) doesn't keep waiting on the
  209. // open connection for data which will never arrive.
  210. remoteConn, err := proxy.tunneler.Dial(target, false, localConn)
  211. if err != nil {
  212. return common.ContextError(err)
  213. }
  214. defer remoteConn.Close()
  215. _, err = localConn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  216. if err != nil {
  217. return common.ContextError(err)
  218. }
  219. LocalProxyRelay(_HTTP_PROXY_TYPE, localConn, remoteConn)
  220. return nil
  221. }
  222. func (proxy *HttpProxy) httpProxyHandler(responseWriter http.ResponseWriter, request *http.Request) {
  223. relayHttpRequest(nil, proxy.httpProxyTunneledRelay, request, responseWriter)
  224. }
  225. const (
  226. URL_PROXY_TUNNELED_REQUEST_PATH = "/tunneled/"
  227. URL_PROXY_DIRECT_REQUEST_PATH = "/direct/"
  228. )
  229. func (proxy *HttpProxy) urlProxyHandler(responseWriter http.ResponseWriter, request *http.Request) {
  230. var client *http.Client
  231. var originUrl string
  232. var err error
  233. // Request URL should be "/tunneled/<origin URL>" or "/direct/<origin URL>" and the
  234. // origin URL must be URL encoded.
  235. switch {
  236. case strings.HasPrefix(request.URL.RawPath, URL_PROXY_TUNNELED_REQUEST_PATH):
  237. originUrl, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_TUNNELED_REQUEST_PATH):])
  238. client = proxy.urlProxyTunneledClient
  239. case strings.HasPrefix(request.URL.RawPath, URL_PROXY_DIRECT_REQUEST_PATH):
  240. originUrl, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_DIRECT_REQUEST_PATH):])
  241. client = proxy.urlProxyDirectClient
  242. default:
  243. err = errors.New("missing origin URL")
  244. }
  245. if err != nil {
  246. NoticeAlert("%s", common.ContextError(FilterUrlError(err)))
  247. forceClose(responseWriter)
  248. return
  249. }
  250. // Origin URL must be well-formed, absolute, and have a scheme of "http" or "https"
  251. url, err := url.ParseRequestURI(originUrl)
  252. if err != nil {
  253. NoticeAlert("%s", common.ContextError(FilterUrlError(err)))
  254. forceClose(responseWriter)
  255. return
  256. }
  257. if !url.IsAbs() || (url.Scheme != "http" && url.Scheme != "https") {
  258. NoticeAlert("invalid origin URL")
  259. forceClose(responseWriter)
  260. return
  261. }
  262. // Transform received request to directly reference the origin URL
  263. request.Host = url.Host
  264. request.URL = url
  265. relayHttpRequest(client, nil, request, responseWriter)
  266. }
  267. func relayHttpRequest(
  268. client *http.Client,
  269. transport *http.Transport,
  270. request *http.Request,
  271. responseWriter http.ResponseWriter) {
  272. // Transform received request struct before using as input to relayed request
  273. request.Close = false
  274. request.RequestURI = ""
  275. for _, key := range hopHeaders {
  276. request.Header.Del(key)
  277. }
  278. // Relay the HTTP request and get the response. Use a client when supplied,
  279. // otherwise a transport. A client handles cookies and redirects, and a
  280. // transport does not.
  281. var response *http.Response
  282. var err error
  283. if client != nil {
  284. response, err = client.Do(request)
  285. } else {
  286. response, err = transport.RoundTrip(request)
  287. }
  288. if err != nil {
  289. NoticeAlert("%s", common.ContextError(FilterUrlError(err)))
  290. forceClose(responseWriter)
  291. return
  292. }
  293. defer response.Body.Close()
  294. // Relay the remote response headers
  295. for _, key := range hopHeaders {
  296. response.Header.Del(key)
  297. }
  298. for key, _ := range responseWriter.Header() {
  299. responseWriter.Header().Del(key)
  300. }
  301. for key, values := range response.Header {
  302. for _, value := range values {
  303. responseWriter.Header().Add(key, value)
  304. }
  305. }
  306. // Relay the response code and body
  307. responseWriter.WriteHeader(response.StatusCode)
  308. _, err = io.Copy(responseWriter, response.Body)
  309. if err != nil {
  310. NoticeAlert("%s", common.ContextError(err))
  311. forceClose(responseWriter)
  312. return
  313. }
  314. }
  315. // forceClose hijacks and closes persistent connections. This is used
  316. // to ensure local persistent connections into the HTTP proxy are closed
  317. // when ServeHTTP encounters an error.
  318. func forceClose(responseWriter http.ResponseWriter) {
  319. hijacker, _ := responseWriter.(http.Hijacker)
  320. conn, _, err := hijacker.Hijack()
  321. if err == nil {
  322. conn.Close()
  323. }
  324. }
  325. // From https://golang.org/src/pkg/net/http/httputil/reverseproxy.go:
  326. // Hop-by-hop headers. These are removed when sent to the backend.
  327. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  328. var hopHeaders = []string{
  329. "Connection",
  330. "Keep-Alive",
  331. "Proxy-Authenticate",
  332. "Proxy-Authorization",
  333. "Proxy-Connection", // see: http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/web-proxy-connection-header.html
  334. "Te", // canonicalized version of "TE"
  335. "Trailers",
  336. "Transfer-Encoding",
  337. "Upgrade",
  338. }
  339. // httpConnStateCallback is called by http.Server when the state of a local->proxy
  340. // connection changes. Open connections are tracked so that all local->proxy persistent
  341. // connections can be closed by HttpProxy.Close()
  342. // TODO: if the HttpProxy is decoupled from a single Tunnel instance and
  343. // instead uses the "current" Tunnel, it may not be necessary to close
  344. // local persistent connections when the tunnel reconnects.
  345. func (proxy *HttpProxy) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  346. switch connState {
  347. case http.StateNew:
  348. proxy.openConns.Add(conn)
  349. case http.StateActive, http.StateIdle:
  350. // No action
  351. case http.StateHijacked, http.StateClosed:
  352. proxy.openConns.Remove(conn)
  353. }
  354. }
  355. func (proxy *HttpProxy) serve() {
  356. defer proxy.listener.Close()
  357. defer proxy.serveWaitGroup.Done()
  358. httpServer := &http.Server{
  359. Handler: proxy,
  360. ConnState: proxy.httpConnStateCallback,
  361. }
  362. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  363. err := httpServer.Serve(proxy.listener)
  364. // Can't check for the exact error that Close() will cause in Accept(),
  365. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  366. // explicit stop signal to stop gracefully.
  367. select {
  368. case <-proxy.stopListeningBroadcast:
  369. default:
  370. if err != nil {
  371. proxy.tunneler.SignalComponentFailure()
  372. NoticeLocalProxyError(_HTTP_PROXY_TYPE, common.ContextError(err))
  373. }
  374. }
  375. NoticeInfo("HTTP proxy stopped")
  376. }