http.go 6.2 KB

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