httpProxy.go 7.1 KB

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