httpProxy.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. tunnel *Tunnel
  32. stoppedSignal chan struct{}
  33. listener net.Listener
  34. waitGroup *sync.WaitGroup
  35. httpRelay *http.Transport
  36. }
  37. // NewHttpProxy initializes and runs a new HTTP proxy server.
  38. func NewHttpProxy(listenPort int, tunnel *Tunnel, stoppedSignal chan struct{}) (proxy *HttpProxy, err error) {
  39. listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", listenPort))
  40. if err != nil {
  41. return nil, err
  42. }
  43. tunnelledDialer := func(_, targetAddress string) (conn net.Conn, err error) {
  44. // TODO: connect timeout?
  45. return tunnel.sshClient.Dial("tcp", targetAddress)
  46. }
  47. transport := &http.Transport{
  48. Dial: tunnelledDialer,
  49. MaxIdleConnsPerHost: HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST,
  50. ResponseHeaderTimeout: HTTP_PROXY_ORIGIN_SERVER_TIMEOUT,
  51. }
  52. proxy = &HttpProxy{
  53. tunnel: tunnel,
  54. stoppedSignal: stoppedSignal,
  55. listener: listener,
  56. waitGroup: new(sync.WaitGroup),
  57. httpRelay: transport,
  58. }
  59. proxy.waitGroup.Add(1)
  60. go proxy.serveHttpRequests()
  61. Notice(NOTICE_HTTP_PROXY, "local HTTP proxy running at address %s", proxy.listener.Addr().String())
  62. return proxy, nil
  63. }
  64. // Close terminates the HTTP server.
  65. func (proxy *HttpProxy) Close() {
  66. proxy.listener.Close()
  67. proxy.waitGroup.Wait()
  68. proxy.httpRelay.CloseIdleConnections()
  69. }
  70. // ServeHTTP receives HTTP requests and proxies them. CONNECT requests
  71. // are hijacked and all data is relayed. Other HTTP requests are proxied
  72. // with explicit round trips. In both cases, the tunnel is used for proxied
  73. // traffic.
  74. //
  75. // Implementation is based on:
  76. //
  77. // https://github.com/justmao945/mallory
  78. // Copyright (c) 2014 JianjunMao
  79. // The MIT License (MIT)
  80. //
  81. // https://golang.org/src/pkg/net/http/httputil/reverseproxy.go
  82. // Copyright 2011 The Go Authors. All rights reserved.
  83. // Use of this source code is governed by a BSD-style
  84. // license that can be found in the LICENSE file.
  85. //
  86. func (proxy *HttpProxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  87. if request.Method == "CONNECT" {
  88. hijacker, _ := responseWriter.(http.Hijacker)
  89. conn, _, err := hijacker.Hijack()
  90. if err != nil {
  91. Notice(NOTICE_ALERT, "%s", ContextError(err))
  92. http.Error(responseWriter, "", http.StatusInternalServerError)
  93. return
  94. }
  95. go func() {
  96. err := httpConnectHandler(proxy.tunnel, conn, request.URL.Host)
  97. if err != nil {
  98. Notice(NOTICE_ALERT, "%s", ContextError(err))
  99. }
  100. }()
  101. return
  102. }
  103. if !request.URL.IsAbs() {
  104. Notice(NOTICE_ALERT, "%s", ContextError(errors.New("no domain in request URL")))
  105. http.Error(responseWriter, "", http.StatusInternalServerError)
  106. return
  107. }
  108. // Transform request struct before using as input to relayed request
  109. request.Close = false
  110. request.RequestURI = ""
  111. for _, key := range hopHeaders {
  112. request.Header.Del(key)
  113. }
  114. // Relay the HTTP request and get the response
  115. response, err := proxy.httpRelay.RoundTrip(request)
  116. if err != nil {
  117. Notice(NOTICE_ALERT, "%s", ContextError(err))
  118. http.Error(responseWriter, "", http.StatusInternalServerError)
  119. return
  120. }
  121. defer response.Body.Close()
  122. // Relay the remote response headers
  123. for _, key := range hopHeaders {
  124. response.Header.Del(key)
  125. }
  126. for key, _ := range responseWriter.Header() {
  127. responseWriter.Header().Del(key)
  128. }
  129. for key, values := range response.Header {
  130. for _, value := range values {
  131. responseWriter.Header().Add(key, value)
  132. }
  133. }
  134. // Relay the response code and body
  135. responseWriter.WriteHeader(response.StatusCode)
  136. _, err = io.Copy(responseWriter, response.Body)
  137. if err != nil {
  138. Notice(NOTICE_ALERT, "%s", ContextError(err))
  139. http.Error(responseWriter, "", http.StatusInternalServerError)
  140. return
  141. }
  142. }
  143. // From // https://golang.org/src/pkg/net/http/httputil/reverseproxy.go:
  144. // Hop-by-hop headers. These are removed when sent to the backend.
  145. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  146. var hopHeaders = []string{
  147. "Connection",
  148. "Keep-Alive",
  149. "Proxy-Authenticate",
  150. "Proxy-Authorization",
  151. "Proxy-Connection", // see: http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/web-proxy-connection-header.html
  152. "Te", // canonicalized version of "TE"
  153. "Trailers",
  154. "Transfer-Encoding",
  155. "Upgrade",
  156. }
  157. func httpConnectHandler(tunnel *Tunnel, localHttpConn net.Conn, target string) (err error) {
  158. defer localHttpConn.Close()
  159. remoteSshForward, err := tunnel.sshClient.Dial("tcp", target)
  160. if err != nil {
  161. return ContextError(err)
  162. }
  163. defer remoteSshForward.Close()
  164. _, err = localHttpConn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  165. if err != nil {
  166. return ContextError(err)
  167. }
  168. relayPortForward(localHttpConn, remoteSshForward)
  169. return nil
  170. }
  171. func (proxy *HttpProxy) serveHttpRequests() {
  172. defer proxy.listener.Close()
  173. defer proxy.waitGroup.Done()
  174. httpServer := &http.Server{
  175. Handler: proxy,
  176. }
  177. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  178. err := httpServer.Serve(proxy.listener)
  179. if err != nil {
  180. select {
  181. case proxy.stoppedSignal <- *new(struct{}):
  182. default:
  183. }
  184. Notice(NOTICE_ALERT, "%s", ContextError(err))
  185. return
  186. }
  187. Notice(NOTICE_HTTP_PROXY, "HTTP proxy stopped")
  188. }