http.go 6.0 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"
  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.tcpListener = tcpListener
  48. this.accepting = true
  49. go this.accept()
  50. return nil
  51. }
  52. func (this *HttpProxyServer) accept() {
  53. for this.accepting {
  54. retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  55. this.Lock()
  56. defer this.Unlock()
  57. if !this.accepting {
  58. return nil
  59. }
  60. tcpConn, err := this.tcpListener.AcceptTCP()
  61. if err != nil {
  62. log.Error("Failed to accept HTTP connection: %v", err)
  63. return err
  64. }
  65. go this.handleConnection(tcpConn)
  66. return nil
  67. })
  68. }
  69. }
  70. func parseHost(rawHost string, defaultPort v2net.Port) (v2net.Destination, error) {
  71. port := defaultPort
  72. host, rawPort, err := net.SplitHostPort(rawHost)
  73. if err != nil {
  74. if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
  75. host = rawHost
  76. } else {
  77. return nil, err
  78. }
  79. } else {
  80. intPort, err := strconv.Atoi(rawPort)
  81. if err != nil {
  82. return nil, err
  83. }
  84. port = v2net.Port(intPort)
  85. }
  86. if ip := net.ParseIP(host); ip != nil {
  87. return v2net.TCPDestination(v2net.IPAddress(ip), port), nil
  88. }
  89. return v2net.TCPDestination(v2net.DomainAddress(host), port), nil
  90. }
  91. func (this *HttpProxyServer) handleConnection(conn *net.TCPConn) {
  92. defer conn.Close()
  93. reader := bufio.NewReader(conn)
  94. request, err := http.ReadRequest(reader)
  95. if err != nil {
  96. return
  97. }
  98. log.Info("Request to Method [%s] Host [%s] with URL [%s]", request.Method, request.Host, request.URL.String())
  99. defaultPort := v2net.Port(80)
  100. if strings.ToLower(request.URL.Scheme) == "https" {
  101. defaultPort = v2net.Port(443)
  102. }
  103. host := request.Host
  104. if len(host) == 0 {
  105. host = request.URL.Host
  106. }
  107. dest, err := parseHost(host, defaultPort)
  108. if err != nil {
  109. log.Warning("Malformed proxy host (%s): %v", host, err)
  110. }
  111. if strings.ToUpper(request.Method) == "CONNECT" {
  112. this.handleConnect(request, dest, reader, conn)
  113. } else {
  114. this.handlePlainHTTP(request, dest, reader, conn)
  115. }
  116. }
  117. func (this *HttpProxyServer) handleConnect(request *http.Request, destination v2net.Destination, reader io.Reader, writer io.Writer) {
  118. response := &http.Response{
  119. Status: "200 OK",
  120. StatusCode: 200,
  121. Proto: "HTTP/1.1",
  122. ProtoMajor: 1,
  123. ProtoMinor: 1,
  124. Header: http.Header(make(map[string][]string)),
  125. Body: nil,
  126. ContentLength: 0,
  127. Close: false,
  128. }
  129. buffer := alloc.NewSmallBuffer().Clear()
  130. response.Write(buffer)
  131. writer.Write(buffer.Value)
  132. buffer.Release()
  133. packet := v2net.NewPacket(destination, nil, true)
  134. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  135. this.transport(reader, writer, ray)
  136. }
  137. func (this *HttpProxyServer) transport(input io.Reader, output io.Writer, ray ray.InboundRay) {
  138. var wg sync.WaitGroup
  139. wg.Add(2)
  140. defer wg.Wait()
  141. go func() {
  142. v2net.ReaderToChan(ray.InboundInput(), input)
  143. close(ray.InboundInput())
  144. wg.Done()
  145. }()
  146. go func() {
  147. v2net.ChanToWriter(output, ray.InboundOutput())
  148. wg.Done()
  149. }()
  150. }
  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()
  196. request.Write(requestBuffer)
  197. log.Info("Request to remote:\n%s", string(requestBuffer.Value))
  198. packet := v2net.NewPacket(dest, requestBuffer, true)
  199. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  200. defer close(ray.InboundInput())
  201. var wg sync.WaitGroup
  202. wg.Add(1)
  203. go func() {
  204. defer wg.Done()
  205. responseReader := bufio.NewReader(NewChanReader(ray.InboundOutput()))
  206. responseBuffer := alloc.NewBuffer()
  207. defer responseBuffer.Release()
  208. response, err := http.ReadResponse(responseReader, request)
  209. if err != nil {
  210. return
  211. }
  212. responseBuffer.Clear()
  213. response.Write(responseBuffer)
  214. writer.Write(responseBuffer.Value)
  215. response.Body.Close()
  216. }()
  217. wg.Wait()
  218. }