http.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. v2io.Pipe(v2io.NewAdaptiveReader(input), ray.InboundInput())
  141. ray.InboundInput().Close()
  142. wg.Done()
  143. }()
  144. go func() {
  145. v2io.Pipe(ray.InboundOutput(), v2io.NewAdaptiveWriter(output))
  146. ray.InboundOutput().Release()
  147. wg.Done()
  148. }()
  149. }
  150. // @VisibleForTesting
  151. func StripHopByHopHeaders(request *http.Request) {
  152. // Strip hop-by-hop header basaed on RFC:
  153. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
  154. // https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
  155. request.Header.Del("Proxy-Connection")
  156. request.Header.Del("Proxy-Authenticate")
  157. request.Header.Del("Proxy-Authorization")
  158. request.Header.Del("TE")
  159. request.Header.Del("Trailers")
  160. request.Header.Del("Transfer-Encoding")
  161. request.Header.Del("Upgrade")
  162. // TODO: support keep-alive
  163. connections := request.Header.Get("Connection")
  164. request.Header.Set("Connection", "close")
  165. if len(connections) == 0 {
  166. return
  167. }
  168. for _, h := range strings.Split(connections, ",") {
  169. request.Header.Del(strings.TrimSpace(h))
  170. }
  171. }
  172. func (this *HttpProxyServer) handlePlainHTTP(request *http.Request, dest v2net.Destination, reader *bufio.Reader, writer io.Writer) {
  173. if len(request.URL.Host) <= 0 {
  174. hdr := http.Header(make(map[string][]string))
  175. hdr.Set("Connection", "close")
  176. response := &http.Response{
  177. Status: "400 Bad Request",
  178. StatusCode: 400,
  179. Proto: "HTTP/1.1",
  180. ProtoMajor: 1,
  181. ProtoMinor: 1,
  182. Header: hdr,
  183. Body: nil,
  184. ContentLength: 0,
  185. Close: false,
  186. }
  187. buffer := alloc.NewSmallBuffer().Clear()
  188. response.Write(buffer)
  189. writer.Write(buffer.Value)
  190. buffer.Release()
  191. return
  192. }
  193. request.Host = request.URL.Host
  194. StripHopByHopHeaders(request)
  195. requestBuffer := alloc.NewBuffer().Clear() // Don't release this buffer as it is passed into a Packet.
  196. request.Write(requestBuffer)
  197. log.Debug("Request to remote:\n", serial.BytesLiteral(requestBuffer.Value))
  198. packet := v2net.NewPacket(dest, requestBuffer, true)
  199. ray := this.packetDispatcher.DispatchToOutbound(packet)
  200. defer ray.InboundInput().Close()
  201. var wg sync.WaitGroup
  202. wg.Add(1)
  203. go func() {
  204. defer wg.Done()
  205. responseReader := bufio.NewReader(NewChanReader(ray.InboundOutput()))
  206. response, err := http.ReadResponse(responseReader, request)
  207. if err != nil {
  208. return
  209. }
  210. responseBuffer := alloc.NewBuffer().Clear()
  211. defer responseBuffer.Release()
  212. response.Write(responseBuffer)
  213. writer.Write(responseBuffer.Value)
  214. response.Body.Close()
  215. }()
  216. wg.Wait()
  217. }