httpProxy.go 7.5 KB

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