http.go 6.0 KB

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