httpProxy.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. "io"
  23. "log"
  24. "net"
  25. "net/http"
  26. "strings"
  27. "sync"
  28. "unicode"
  29. )
  30. // HttpProxy is a HTTP server that relays HTTP requests through
  31. // the tunnel SSH client.
  32. type HttpProxy struct {
  33. tunnel *Tunnel
  34. failureSignal chan bool
  35. listener net.Listener
  36. waitGroup *sync.WaitGroup
  37. httpRelay *http.Transport
  38. }
  39. // NewHttpProxy initializes and runs a new HTTP proxy server.
  40. func NewHttpProxy(tunnel *Tunnel, failureSignal chan bool) (proxy *HttpProxy, err error) {
  41. listener, err := net.Listen("tcp", "127.0.0.1:0")
  42. if err != nil {
  43. return nil, err
  44. }
  45. tunneledDialer := func(_, targetAddress string) (conn net.Conn, err error) {
  46. return tunnel.sshClient.Dial("tcp", targetAddress)
  47. }
  48. // Copy default transport for its timeout values
  49. transport := new(http.Transport)
  50. *transport = *http.DefaultTransport.(*http.Transport)
  51. transport.Dial = tunneledDialer
  52. transport.Proxy = nil
  53. proxy = &HttpProxy{
  54. tunnel: tunnel,
  55. failureSignal: failureSignal,
  56. listener: listener,
  57. waitGroup: new(sync.WaitGroup),
  58. httpRelay: transport,
  59. }
  60. proxy.waitGroup.Add(1)
  61. go proxy.serveHttpRequests()
  62. log.Printf("local HTTP proxy running at address %s", proxy.listener.Addr().String())
  63. return proxy, nil
  64. }
  65. // Close terminates the HTTP server.
  66. func (proxy *HttpProxy) Close() {
  67. proxy.listener.Close()
  68. proxy.waitGroup.Wait()
  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. func (proxy *HttpProxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  82. if request.Method == "CONNECT" {
  83. hijacker, _ := responseWriter.(http.Hijacker)
  84. conn, _, err := hijacker.Hijack()
  85. if err != nil {
  86. log.Print(ContextError(err))
  87. http.Error(responseWriter, "", http.StatusInternalServerError)
  88. return
  89. }
  90. go func() {
  91. err := httpConnectHandler(proxy.tunnel, conn, request.URL.Host)
  92. if err != nil {
  93. log.Printf("%s", err)
  94. }
  95. }()
  96. return
  97. }
  98. if !request.URL.IsAbs() {
  99. log.Print(ContextError(errors.New("no domain in request URL")))
  100. http.Error(responseWriter, "", http.StatusInternalServerError)
  101. return
  102. }
  103. // Transform request struct before using as input to relayed request:
  104. // Scheme: must be lower case.
  105. // RequestURI: cleared as docs state "It is an error to set this
  106. // field in an HTTP client request".
  107. // Accept-Encoding: removed to allow Go's RoundTripper to do its own
  108. // encoding.
  109. // Connection (and the bogus Proxy-Connection): inputs to the proxy
  110. // only and not to be passed along.
  111. request.URL.Scheme = strings.Map(unicode.ToLower, request.URL.Scheme)
  112. request.RequestURI = ""
  113. request.Header.Del("Accept-Encoding")
  114. request.Header.Del("Proxy-Connection")
  115. request.Header.Del("Connection")
  116. // Relay the HTTP request and get the response
  117. response, err := proxy.httpRelay.RoundTrip(request)
  118. if err != nil {
  119. log.Print(ContextError(err))
  120. http.Error(responseWriter, "", http.StatusInternalServerError)
  121. return
  122. }
  123. defer response.Body.Close()
  124. // Relay the remote response headers (first removing any proxy server headers)
  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. log.Print(ContextError(err))
  138. http.Error(responseWriter, "", http.StatusInternalServerError)
  139. return
  140. }
  141. }
  142. func httpConnectHandler(tunnel *Tunnel, localHttpConn net.Conn, target string) (err error) {
  143. defer localHttpConn.Close()
  144. remoteSshForward, err := tunnel.sshClient.Dial("tcp", target)
  145. if err != nil {
  146. return ContextError(err)
  147. }
  148. defer remoteSshForward.Close()
  149. _, err = localHttpConn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  150. if err != nil {
  151. return ContextError(err)
  152. }
  153. relayPortForward(localHttpConn, remoteSshForward)
  154. return nil
  155. }
  156. func (proxy *HttpProxy) serveHttpRequests() {
  157. defer proxy.listener.Close()
  158. defer proxy.waitGroup.Done()
  159. httpServer := &http.Server{
  160. Handler: proxy,
  161. ReadTimeout: HTTP_PROXY_READ_TIMEOUT,
  162. WriteTimeout: HTTP_PROXY_WRITE_TIMEOUT,
  163. }
  164. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  165. err := httpServer.Serve(proxy.listener)
  166. if err != nil {
  167. select {
  168. case proxy.failureSignal <- true:
  169. default:
  170. }
  171. log.Printf("HTTP proxy server error: %s", err)
  172. return
  173. }
  174. log.Printf("HTTP proxy stopped")
  175. }