http.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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/transport/ray"
  16. )
  17. type HttpProxyServer struct {
  18. sync.Mutex
  19. accepting bool
  20. space app.Space
  21. config *Config
  22. tcpListener *net.TCPListener
  23. }
  24. func NewHttpProxyServer(space app.Space, config *Config) *HttpProxyServer {
  25. return &HttpProxyServer{
  26. space: space,
  27. config: config,
  28. }
  29. }
  30. func (this *HttpProxyServer) Close() {
  31. this.accepting = false
  32. if this.tcpListener != nil {
  33. this.tcpListener.Close()
  34. this.Lock()
  35. this.tcpListener = nil
  36. this.Unlock()
  37. }
  38. }
  39. func (this *HttpProxyServer) Listen(port v2net.Port) error {
  40. tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
  41. Port: int(port.Value()),
  42. IP: []byte{0, 0, 0, 0},
  43. })
  44. if err != nil {
  45. return err
  46. }
  47. this.Lock()
  48. this.tcpListener = tcpListener
  49. this.Unlock()
  50. this.accepting = true
  51. go this.accept()
  52. return nil
  53. }
  54. func (this *HttpProxyServer) accept() {
  55. for this.accepting {
  56. retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  57. this.Lock()
  58. defer this.Unlock()
  59. if !this.accepting {
  60. return nil
  61. }
  62. tcpConn, err := this.tcpListener.AcceptTCP()
  63. if err != nil {
  64. log.Error("Failed to accept HTTP connection: %v", err)
  65. return err
  66. }
  67. go this.handleConnection(tcpConn)
  68. return nil
  69. })
  70. }
  71. }
  72. func parseHost(rawHost string, defaultPort v2net.Port) (v2net.Destination, error) {
  73. port := defaultPort
  74. host, rawPort, err := net.SplitHostPort(rawHost)
  75. if err != nil {
  76. if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
  77. host = rawHost
  78. } else {
  79. return nil, err
  80. }
  81. } else {
  82. intPort, err := strconv.Atoi(rawPort)
  83. if err != nil {
  84. return nil, err
  85. }
  86. port = v2net.Port(intPort)
  87. }
  88. if ip := net.ParseIP(host); ip != nil {
  89. return v2net.TCPDestination(v2net.IPAddress(ip), port), nil
  90. }
  91. return v2net.TCPDestination(v2net.DomainAddress(host), port), nil
  92. }
  93. func (this *HttpProxyServer) handleConnection(conn *net.TCPConn) {
  94. defer conn.Close()
  95. reader := bufio.NewReader(conn)
  96. request, err := http.ReadRequest(reader)
  97. if err != nil {
  98. log.Warning("Failed to read http request: %v", err)
  99. return
  100. }
  101. log.Info("Request to Method [%s] Host [%s] with URL [%s]", request.Method, request.Host, request.URL.String())
  102. defaultPort := v2net.Port(80)
  103. if strings.ToLower(request.URL.Scheme) == "https" {
  104. defaultPort = v2net.Port(443)
  105. }
  106. host := request.Host
  107. if len(host) == 0 {
  108. host = request.URL.Host
  109. }
  110. dest, err := parseHost(host, defaultPort)
  111. if err != nil {
  112. log.Warning("Malformed proxy host (%s): %v", host, err)
  113. return
  114. }
  115. if strings.ToUpper(request.Method) == "CONNECT" {
  116. this.handleConnect(request, dest, reader, conn)
  117. } else {
  118. this.handlePlainHTTP(request, dest, reader, conn)
  119. }
  120. }
  121. func (this *HttpProxyServer) handleConnect(request *http.Request, destination v2net.Destination, reader io.Reader, writer io.Writer) {
  122. response := &http.Response{
  123. Status: "200 OK",
  124. StatusCode: 200,
  125. Proto: "HTTP/1.1",
  126. ProtoMajor: 1,
  127. ProtoMinor: 1,
  128. Header: http.Header(make(map[string][]string)),
  129. Body: nil,
  130. ContentLength: 0,
  131. Close: false,
  132. }
  133. buffer := alloc.NewSmallBuffer().Clear()
  134. response.Write(buffer)
  135. writer.Write(buffer.Value)
  136. buffer.Release()
  137. packet := v2net.NewPacket(destination, nil, true)
  138. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  139. this.transport(reader, writer, ray)
  140. }
  141. func (this *HttpProxyServer) transport(input io.Reader, output io.Writer, ray ray.InboundRay) {
  142. var wg sync.WaitGroup
  143. wg.Add(2)
  144. defer wg.Wait()
  145. go func() {
  146. v2net.ReaderToChan(ray.InboundInput(), input)
  147. close(ray.InboundInput())
  148. wg.Done()
  149. }()
  150. go func() {
  151. v2net.ChanToWriter(output, ray.InboundOutput())
  152. wg.Done()
  153. }()
  154. }
  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%s", string(requestBuffer.Value))
  202. packet := v2net.NewPacket(dest, requestBuffer, true)
  203. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  204. defer close(ray.InboundInput())
  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. }