http.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package http
  2. import (
  3. "bufio"
  4. "crypto/tls"
  5. "io"
  6. "net"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "github.com/v2ray/v2ray-core/app/dispatcher"
  12. "github.com/v2ray/v2ray-core/common/alloc"
  13. v2io "github.com/v2ray/v2ray-core/common/io"
  14. "github.com/v2ray/v2ray-core/common/log"
  15. v2net "github.com/v2ray/v2ray-core/common/net"
  16. "github.com/v2ray/v2ray-core/common/serial"
  17. "github.com/v2ray/v2ray-core/proxy"
  18. "github.com/v2ray/v2ray-core/transport/hub"
  19. "github.com/v2ray/v2ray-core/transport/ray"
  20. )
  21. type HttpProxyServer struct {
  22. sync.Mutex
  23. accepting bool
  24. packetDispatcher dispatcher.PacketDispatcher
  25. config *Config
  26. tcpListener *hub.TCPHub
  27. listeningPort v2net.Port
  28. }
  29. func NewHttpProxyServer(config *Config, packetDispatcher dispatcher.PacketDispatcher) *HttpProxyServer {
  30. return &HttpProxyServer{
  31. packetDispatcher: packetDispatcher,
  32. config: config,
  33. }
  34. }
  35. func (this *HttpProxyServer) Port() v2net.Port {
  36. return this.listeningPort
  37. }
  38. func (this *HttpProxyServer) Close() {
  39. this.accepting = false
  40. if this.tcpListener != nil {
  41. this.Lock()
  42. this.tcpListener.Close()
  43. this.tcpListener = nil
  44. this.Unlock()
  45. }
  46. }
  47. func (this *HttpProxyServer) Listen(port v2net.Port) error {
  48. if this.accepting {
  49. if this.listeningPort == port {
  50. return nil
  51. } else {
  52. return proxy.ErrorAlreadyListening
  53. }
  54. }
  55. this.listeningPort = port
  56. var tlsConfig *tls.Config = nil
  57. if this.config.TlsConfig != nil {
  58. tlsConfig = this.config.TlsConfig.GetConfig()
  59. }
  60. tcpListener, err := hub.ListenTCP(port, this.handleConnection, tlsConfig)
  61. if err != nil {
  62. log.Error("Http: Failed listen on port ", port, ": ", err)
  63. return err
  64. }
  65. this.Lock()
  66. this.tcpListener = tcpListener
  67. this.Unlock()
  68. this.accepting = true
  69. return nil
  70. }
  71. func parseHost(rawHost string, defaultPort v2net.Port) (v2net.Destination, error) {
  72. port := defaultPort
  73. host, rawPort, err := net.SplitHostPort(rawHost)
  74. if err != nil {
  75. if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
  76. host = rawHost
  77. } else {
  78. return nil, err
  79. }
  80. } else {
  81. intPort, err := strconv.Atoi(rawPort)
  82. if err != nil {
  83. return nil, err
  84. }
  85. port = v2net.Port(intPort)
  86. }
  87. if ip := net.ParseIP(host); ip != nil {
  88. return v2net.TCPDestination(v2net.IPAddress(ip), port), nil
  89. }
  90. return v2net.TCPDestination(v2net.DomainAddress(host), port), nil
  91. }
  92. func (this *HttpProxyServer) handleConnection(conn *hub.Connection) {
  93. defer conn.Close()
  94. reader := bufio.NewReader(conn)
  95. request, err := http.ReadRequest(reader)
  96. if err != nil {
  97. log.Warning("Failed to read http request: ", err)
  98. return
  99. }
  100. log.Info("Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
  101. defaultPort := v2net.Port(80)
  102. if strings.ToLower(request.URL.Scheme) == "https" {
  103. defaultPort = v2net.Port(443)
  104. }
  105. host := request.Host
  106. if len(host) == 0 {
  107. host = request.URL.Host
  108. }
  109. dest, err := parseHost(host, defaultPort)
  110. if err != nil {
  111. log.Warning("Malformed proxy host (", host, "): ", err)
  112. return
  113. }
  114. if strings.ToUpper(request.Method) == "CONNECT" {
  115. this.handleConnect(request, dest, reader, conn)
  116. } else {
  117. this.handlePlainHTTP(request, dest, reader, conn)
  118. }
  119. }
  120. func (this *HttpProxyServer) handleConnect(request *http.Request, destination v2net.Destination, reader io.Reader, writer io.Writer) {
  121. response := &http.Response{
  122. Status: "200 OK",
  123. StatusCode: 200,
  124. Proto: "HTTP/1.1",
  125. ProtoMajor: 1,
  126. ProtoMinor: 1,
  127. Header: http.Header(make(map[string][]string)),
  128. Body: nil,
  129. ContentLength: 0,
  130. Close: false,
  131. }
  132. buffer := alloc.NewSmallBuffer().Clear()
  133. response.Write(buffer)
  134. writer.Write(buffer.Value)
  135. buffer.Release()
  136. ray := this.packetDispatcher.DispatchToOutbound(destination)
  137. this.transport(reader, writer, ray)
  138. }
  139. func (this *HttpProxyServer) transport(input io.Reader, output io.Writer, ray ray.InboundRay) {
  140. var wg sync.WaitGroup
  141. wg.Add(2)
  142. defer wg.Wait()
  143. go func() {
  144. v2reader := v2io.NewAdaptiveReader(input)
  145. defer v2reader.Release()
  146. v2io.Pipe(v2reader, ray.InboundInput())
  147. ray.InboundInput().Close()
  148. wg.Done()
  149. }()
  150. go func() {
  151. v2writer := v2io.NewAdaptiveWriter(output)
  152. defer v2writer.Release()
  153. v2io.Pipe(ray.InboundOutput(), v2writer)
  154. ray.InboundOutput().Release()
  155. wg.Done()
  156. }()
  157. }
  158. // @VisibleForTesting
  159. func StripHopByHopHeaders(request *http.Request) {
  160. // Strip hop-by-hop header basaed on RFC:
  161. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
  162. // https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
  163. request.Header.Del("Proxy-Connection")
  164. request.Header.Del("Proxy-Authenticate")
  165. request.Header.Del("Proxy-Authorization")
  166. request.Header.Del("TE")
  167. request.Header.Del("Trailers")
  168. request.Header.Del("Transfer-Encoding")
  169. request.Header.Del("Upgrade")
  170. // TODO: support keep-alive
  171. connections := request.Header.Get("Connection")
  172. request.Header.Set("Connection", "close")
  173. if len(connections) == 0 {
  174. return
  175. }
  176. for _, h := range strings.Split(connections, ",") {
  177. request.Header.Del(strings.TrimSpace(h))
  178. }
  179. }
  180. func (this *HttpProxyServer) handlePlainHTTP(request *http.Request, dest v2net.Destination, reader *bufio.Reader, writer io.Writer) {
  181. if len(request.URL.Host) <= 0 {
  182. hdr := http.Header(make(map[string][]string))
  183. hdr.Set("Connection", "close")
  184. response := &http.Response{
  185. Status: "400 Bad Request",
  186. StatusCode: 400,
  187. Proto: "HTTP/1.1",
  188. ProtoMajor: 1,
  189. ProtoMinor: 1,
  190. Header: hdr,
  191. Body: nil,
  192. ContentLength: 0,
  193. Close: false,
  194. }
  195. buffer := alloc.NewSmallBuffer().Clear()
  196. response.Write(buffer)
  197. writer.Write(buffer.Value)
  198. buffer.Release()
  199. return
  200. }
  201. request.Host = request.URL.Host
  202. StripHopByHopHeaders(request)
  203. requestBuffer := alloc.NewBuffer().Clear() // Don't release this buffer as it is passed into a Packet.
  204. request.Write(requestBuffer)
  205. log.Debug("Request to remote:\n", serial.BytesLiteral(requestBuffer.Value))
  206. ray := this.packetDispatcher.DispatchToOutbound(dest)
  207. ray.InboundInput().Write(requestBuffer)
  208. defer ray.InboundInput().Close()
  209. var wg sync.WaitGroup
  210. wg.Add(1)
  211. go func() {
  212. defer wg.Done()
  213. responseReader := bufio.NewReader(NewChanReader(ray.InboundOutput()))
  214. response, err := http.ReadResponse(responseReader, request)
  215. if err != nil {
  216. return
  217. }
  218. responseBuffer := alloc.NewBuffer().Clear()
  219. defer responseBuffer.Release()
  220. response.Write(responseBuffer)
  221. writer.Write(responseBuffer.Value)
  222. response.Body.Close()
  223. }()
  224. wg.Wait()
  225. }