httpProxy.go 14 KB

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