httpProxy.go 14 KB

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