httpProxy.go 14 KB

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