httpProxy.go 7.5 KB

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