httpProxy.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. failureSignal chan bool
  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, failureSignal chan bool) (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. failureSignal: failureSignal,
  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. }
  69. // ServeHTTP receives HTTP requests and proxies them. CONNECT requests
  70. // are hijacked and all data is relayed. Other HTTP requests are proxied
  71. // with explicit round trips. In both cases, the tunnel is used for proxied
  72. // traffic.
  73. //
  74. // Implementation is based on:
  75. //
  76. // https://github.com/justmao945/mallory
  77. // Copyright (c) 2014 JianjunMao
  78. // The MIT License (MIT)
  79. //
  80. // https://golang.org/src/pkg/net/http/httputil/reverseproxy.go
  81. // Copyright 2011 The Go Authors. All rights reserved.
  82. // Use of this source code is governed by a BSD-style
  83. // license that can be found in the LICENSE file.
  84. //
  85. func (proxy *HttpProxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  86. if request.Method == "CONNECT" {
  87. hijacker, _ := responseWriter.(http.Hijacker)
  88. conn, _, err := hijacker.Hijack()
  89. if err != nil {
  90. Notice(NOTICE_ALERT, "%s", ContextError(err))
  91. http.Error(responseWriter, "", http.StatusInternalServerError)
  92. return
  93. }
  94. go func() {
  95. err := httpConnectHandler(proxy.tunnel, conn, request.URL.Host)
  96. if err != nil {
  97. Notice(NOTICE_ALERT, "%s", ContextError(err))
  98. }
  99. }()
  100. return
  101. }
  102. if !request.URL.IsAbs() {
  103. Notice(NOTICE_ALERT, "%s", ContextError(errors.New("no domain in request URL")))
  104. http.Error(responseWriter, "", http.StatusInternalServerError)
  105. return
  106. }
  107. // Transform request struct before using as input to relayed request
  108. request.Close = false
  109. request.RequestURI = ""
  110. for _, key := range hopHeaders {
  111. request.Header.Del(key)
  112. }
  113. // Relay the HTTP request and get the response
  114. response, err := proxy.httpRelay.RoundTrip(request)
  115. if err != nil {
  116. Notice(NOTICE_ALERT, "%s", ContextError(err))
  117. http.Error(responseWriter, "", http.StatusInternalServerError)
  118. return
  119. }
  120. defer response.Body.Close()
  121. // Relay the remote response headers
  122. for _, key := range hopHeaders {
  123. response.Header.Del(key)
  124. }
  125. for key, _ := range responseWriter.Header() {
  126. responseWriter.Header().Del(key)
  127. }
  128. for key, values := range response.Header {
  129. for _, value := range values {
  130. responseWriter.Header().Add(key, value)
  131. }
  132. }
  133. // Relay the response code and body
  134. responseWriter.WriteHeader(response.StatusCode)
  135. _, err = io.Copy(responseWriter, response.Body)
  136. if err != nil {
  137. Notice(NOTICE_ALERT, "%s", ContextError(err))
  138. http.Error(responseWriter, "", http.StatusInternalServerError)
  139. return
  140. }
  141. }
  142. // Hop-by-hop headers. These are removed when sent to the backend.
  143. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  144. var hopHeaders = []string{
  145. "Connection",
  146. "Keep-Alive",
  147. "Proxy-Authenticate",
  148. "Proxy-Authorization",
  149. "Te", // canonicalized version of "TE"
  150. "Trailers",
  151. "Transfer-Encoding",
  152. "Upgrade",
  153. }
  154. func httpConnectHandler(tunnel *Tunnel, localHttpConn net.Conn, target string) (err error) {
  155. defer localHttpConn.Close()
  156. remoteSshForward, err := tunnel.sshClient.Dial("tcp", target)
  157. if err != nil {
  158. return ContextError(err)
  159. }
  160. defer remoteSshForward.Close()
  161. _, err = localHttpConn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  162. if err != nil {
  163. return ContextError(err)
  164. }
  165. relayPortForward(localHttpConn, remoteSshForward)
  166. return nil
  167. }
  168. func (proxy *HttpProxy) serveHttpRequests() {
  169. defer proxy.listener.Close()
  170. defer proxy.waitGroup.Done()
  171. httpServer := &http.Server{
  172. Handler: proxy,
  173. }
  174. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  175. err := httpServer.Serve(proxy.listener)
  176. if err != nil {
  177. select {
  178. case proxy.failureSignal <- true:
  179. default:
  180. }
  181. Notice(NOTICE_ALERT, "%s", ContextError(err))
  182. return
  183. }
  184. Notice(NOTICE_HTTP_PROXY, "HTTP proxy stopped")
  185. }