http.go 6.4 KB

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