http.go 6.1 KB

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