httpProxy.go 12 KB

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