httpProxy.go 14 KB

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