httpProxy.go 14 KB

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