httpProxy.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. "sync"
  27. )
  28. // HttpProxy is a HTTP server that relays HTTP requests through
  29. // the tunnel SSH client.
  30. type HttpProxy struct {
  31. tunneler Tunneler
  32. listener net.Listener
  33. serveWaitGroup *sync.WaitGroup
  34. httpRelay *http.Transport
  35. openConns *Conns
  36. stopListeningBroadcast chan struct{}
  37. }
  38. // NewHttpProxy initializes and runs a new HTTP proxy server.
  39. func NewHttpProxy(config *Config, tunneler Tunneler) (proxy *HttpProxy, err error) {
  40. listener, err := net.Listen(
  41. "tcp", fmt.Sprintf("127.0.0.1:%d", config.LocalHttpProxyPort))
  42. if err != nil {
  43. if IsAddressInUseError(err) {
  44. NoticeHttpProxyPortInUse(config.LocalHttpProxyPort)
  45. }
  46. return nil, ContextError(err)
  47. }
  48. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  49. // downstreamConn is not set in this case, as there is not a fixed
  50. // association between a downstream client connection and a particular
  51. // tunnel.
  52. // TODO: connect timeout?
  53. return tunneler.Dial(addr, false, nil)
  54. }
  55. // TODO: also use http.Client, with its Timeout field?
  56. transport := &http.Transport{
  57. Dial: tunneledDialer,
  58. MaxIdleConnsPerHost: HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST,
  59. ResponseHeaderTimeout: HTTP_PROXY_ORIGIN_SERVER_TIMEOUT,
  60. }
  61. proxy = &HttpProxy{
  62. tunneler: tunneler,
  63. listener: listener,
  64. serveWaitGroup: new(sync.WaitGroup),
  65. httpRelay: transport,
  66. openConns: new(Conns),
  67. stopListeningBroadcast: make(chan struct{}),
  68. }
  69. proxy.serveWaitGroup.Add(1)
  70. go proxy.serve()
  71. NoticeListeningHttpProxyPort(proxy.listener.Addr().(*net.TCPAddr).Port)
  72. return proxy, nil
  73. }
  74. // Close terminates the HTTP server.
  75. func (proxy *HttpProxy) Close() {
  76. close(proxy.stopListeningBroadcast)
  77. proxy.listener.Close()
  78. proxy.serveWaitGroup.Wait()
  79. // Close local->proxy persistent connections
  80. proxy.openConns.CloseAll()
  81. // Close idle proxy->origin persistent connections
  82. // TODO: also close active connections
  83. proxy.httpRelay.CloseIdleConnections()
  84. }
  85. // ServeHTTP receives HTTP requests and proxies them. CONNECT requests
  86. // are hijacked and all data is relayed. Other HTTP requests are proxied
  87. // with explicit round trips. In both cases, the tunnel is used for proxied
  88. // traffic.
  89. //
  90. // Implementation is based on:
  91. //
  92. // https://github.com/justmao945/mallory
  93. // Copyright (c) 2014 JianjunMao
  94. // The MIT License (MIT)
  95. //
  96. // https://golang.org/src/pkg/net/http/httputil/reverseproxy.go
  97. // Copyright 2011 The Go Authors. All rights reserved.
  98. // Use of this source code is governed by a BSD-style
  99. // license that can be found in the LICENSE file.
  100. //
  101. func (proxy *HttpProxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  102. if request.Method == "CONNECT" {
  103. hijacker, _ := responseWriter.(http.Hijacker)
  104. conn, _, err := hijacker.Hijack()
  105. if err != nil {
  106. NoticeAlert("%s", ContextError(err))
  107. http.Error(responseWriter, "", http.StatusInternalServerError)
  108. return
  109. }
  110. go func() {
  111. err := proxy.httpConnectHandler(conn, request.URL.Host)
  112. if err != nil {
  113. NoticeAlert("%s", ContextError(err))
  114. }
  115. }()
  116. return
  117. }
  118. if !request.URL.IsAbs() {
  119. NoticeAlert("%s", ContextError(errors.New("no domain in request URL")))
  120. http.Error(responseWriter, "", http.StatusInternalServerError)
  121. return
  122. }
  123. // Transform request struct before using as input to relayed request
  124. request.Close = false
  125. request.RequestURI = ""
  126. for _, key := range hopHeaders {
  127. request.Header.Del(key)
  128. }
  129. // Relay the HTTP request and get the response
  130. response, err := proxy.httpRelay.RoundTrip(request)
  131. if err != nil {
  132. NoticeAlert("%s", ContextError(err))
  133. forceClose(responseWriter)
  134. return
  135. }
  136. defer response.Body.Close()
  137. // Relay the remote response headers
  138. for _, key := range hopHeaders {
  139. response.Header.Del(key)
  140. }
  141. for key, _ := range responseWriter.Header() {
  142. responseWriter.Header().Del(key)
  143. }
  144. for key, values := range response.Header {
  145. for _, value := range values {
  146. responseWriter.Header().Add(key, value)
  147. }
  148. }
  149. // Relay the response code and body
  150. responseWriter.WriteHeader(response.StatusCode)
  151. _, err = io.Copy(responseWriter, response.Body)
  152. if err != nil {
  153. NoticeAlert("%s", ContextError(err))
  154. forceClose(responseWriter)
  155. return
  156. }
  157. }
  158. // forceClose hijacks and closes persistent connections. This is used
  159. // to ensure local persistent connections into the HTTP proxy are closed
  160. // when ServeHTTP encounters an error.
  161. func forceClose(responseWriter http.ResponseWriter) {
  162. hijacker, _ := responseWriter.(http.Hijacker)
  163. conn, _, err := hijacker.Hijack()
  164. if err == nil {
  165. conn.Close()
  166. }
  167. }
  168. // From https://golang.org/src/pkg/net/http/httputil/reverseproxy.go:
  169. // Hop-by-hop headers. These are removed when sent to the backend.
  170. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  171. var hopHeaders = []string{
  172. "Connection",
  173. "Keep-Alive",
  174. "Proxy-Authenticate",
  175. "Proxy-Authorization",
  176. "Proxy-Connection", // see: http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/web-proxy-connection-header.html
  177. "Te", // canonicalized version of "TE"
  178. "Trailers",
  179. "Transfer-Encoding",
  180. "Upgrade",
  181. }
  182. func (proxy *HttpProxy) httpConnectHandler(localConn net.Conn, target string) (err error) {
  183. defer localConn.Close()
  184. defer proxy.openConns.Remove(localConn)
  185. proxy.openConns.Add(localConn)
  186. // Setting downstreamConn so localConn.Close() will be called when remoteConn.Close() is called.
  187. // This ensures that the downstream client (e.g., web browser) doesn't keep waiting on the
  188. // open connection for data which will never arrive.
  189. remoteConn, err := proxy.tunneler.Dial(target, false, localConn)
  190. if err != nil {
  191. return ContextError(err)
  192. }
  193. defer remoteConn.Close()
  194. _, err = localConn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  195. if err != nil {
  196. return ContextError(err)
  197. }
  198. Relay(localConn, remoteConn)
  199. return nil
  200. }
  201. // httpConnStateCallback is called by http.Server when the state of a local->proxy
  202. // connection changes. Open connections are tracked so that all local->proxy persistent
  203. // connections can be closed by HttpProxy.Close()
  204. // TODO: if the HttpProxy is decoupled from a single Tunnel instance and
  205. // instead uses the "current" Tunnel, it may not be necessary to close
  206. // local persistent connections when the tunnel reconnects.
  207. func (proxy *HttpProxy) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  208. switch connState {
  209. case http.StateNew:
  210. proxy.openConns.Add(conn)
  211. case http.StateActive, http.StateIdle:
  212. // No action
  213. case http.StateHijacked, http.StateClosed:
  214. proxy.openConns.Remove(conn)
  215. }
  216. }
  217. func (proxy *HttpProxy) serve() {
  218. defer proxy.listener.Close()
  219. defer proxy.serveWaitGroup.Done()
  220. httpServer := &http.Server{
  221. Handler: proxy,
  222. ConnState: proxy.httpConnStateCallback,
  223. }
  224. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  225. err := httpServer.Serve(proxy.listener)
  226. // Can't check for the exact error that Close() will cause in Accept(),
  227. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  228. // explicit stop signal to stop gracefully.
  229. select {
  230. case <-proxy.stopListeningBroadcast:
  231. default:
  232. if err != nil {
  233. proxy.tunneler.SignalComponentFailure()
  234. NoticeAlert("%s", ContextError(err))
  235. }
  236. }
  237. NoticeInfo("HTTP proxy stopped")
  238. }