http.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. if !this.accepting {
  56. return nil
  57. }
  58. this.Lock()
  59. defer this.Unlock()
  60. if this.tcpListener != nil {
  61. tcpConn, err := this.tcpListener.AcceptTCP()
  62. if err != nil {
  63. log.Error("Failed to accept HTTP connection: %v", err)
  64. return err
  65. }
  66. go this.handleConnection(tcpConn)
  67. }
  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. return
  99. }
  100. log.Info("Request to Method [%s] Host [%s] with URL [%s]", request.Method, request.Host, request.URL.String())
  101. defaultPort := v2net.Port(80)
  102. if strings.ToLower(request.URL.Scheme) == "https" {
  103. defaultPort = v2net.Port(443)
  104. }
  105. host := request.Host
  106. if len(host) == 0 {
  107. host = request.URL.Host
  108. }
  109. dest, err := parseHost(host, defaultPort)
  110. if err != nil {
  111. log.Warning("Malformed proxy host (%s): %v", host, err)
  112. }
  113. if strings.ToUpper(request.Method) == "CONNECT" {
  114. this.handleConnect(request, dest, reader, conn)
  115. } else {
  116. this.handlePlainHTTP(request, dest, reader, conn)
  117. }
  118. }
  119. func (this *HttpProxyServer) handleConnect(request *http.Request, destination v2net.Destination, reader io.Reader, writer io.Writer) {
  120. response := &http.Response{
  121. Status: "200 OK",
  122. StatusCode: 200,
  123. Proto: "HTTP/1.1",
  124. ProtoMajor: 1,
  125. ProtoMinor: 1,
  126. Header: http.Header(make(map[string][]string)),
  127. Body: nil,
  128. ContentLength: 0,
  129. Close: false,
  130. }
  131. buffer := alloc.NewSmallBuffer().Clear()
  132. response.Write(buffer)
  133. writer.Write(buffer.Value)
  134. buffer.Release()
  135. packet := v2net.NewPacket(destination, nil, true)
  136. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  137. this.transport(reader, writer, ray)
  138. }
  139. func (this *HttpProxyServer) transport(input io.Reader, output io.Writer, ray ray.InboundRay) {
  140. var wg sync.WaitGroup
  141. wg.Add(2)
  142. defer wg.Wait()
  143. go func() {
  144. v2net.ReaderToChan(ray.InboundInput(), input)
  145. close(ray.InboundInput())
  146. wg.Done()
  147. }()
  148. go func() {
  149. v2net.ChanToWriter(output, ray.InboundOutput())
  150. wg.Done()
  151. }()
  152. }
  153. func stripHopByHopHeaders(request *http.Request) {
  154. // Strip hop-by-hop header basaed on RFC:
  155. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
  156. // https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
  157. request.Header.Del("Proxy-Connection")
  158. request.Header.Del("Proxy-Authenticate")
  159. request.Header.Del("Proxy-Authorization")
  160. request.Header.Del("TE")
  161. request.Header.Del("Trailers")
  162. request.Header.Del("Transfer-Encoding")
  163. request.Header.Del("Upgrade")
  164. // TODO: support keep-alive
  165. connections := request.Header.Get("Connection")
  166. request.Header.Set("Connection", "close")
  167. if len(connections) == 0 {
  168. return
  169. }
  170. for _, h := range strings.Split(connections, ",") {
  171. request.Header.Del(strings.TrimSpace(h))
  172. }
  173. }
  174. func (this *HttpProxyServer) handlePlainHTTP(request *http.Request, dest v2net.Destination, reader *bufio.Reader, writer io.Writer) {
  175. if len(request.URL.Host) <= 0 {
  176. hdr := http.Header(make(map[string][]string))
  177. hdr.Set("Connection", "close")
  178. response := &http.Response{
  179. Status: "400 Bad Request",
  180. StatusCode: 400,
  181. Proto: "HTTP/1.1",
  182. ProtoMajor: 1,
  183. ProtoMinor: 1,
  184. Header: hdr,
  185. Body: nil,
  186. ContentLength: 0,
  187. Close: false,
  188. }
  189. buffer := alloc.NewSmallBuffer().Clear()
  190. response.Write(buffer)
  191. writer.Write(buffer.Value)
  192. buffer.Release()
  193. return
  194. }
  195. request.Host = request.URL.Host
  196. stripHopByHopHeaders(request)
  197. requestBuffer := alloc.NewBuffer().Clear()
  198. request.Write(requestBuffer)
  199. log.Info("Request to remote:\n%s", string(requestBuffer.Value))
  200. packet := v2net.NewPacket(dest, requestBuffer, true)
  201. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  202. defer close(ray.InboundInput())
  203. var wg sync.WaitGroup
  204. wg.Add(1)
  205. go func() {
  206. defer wg.Done()
  207. responseReader := bufio.NewReader(NewChanReader(ray.InboundOutput()))
  208. responseBuffer := alloc.NewBuffer()
  209. defer responseBuffer.Release()
  210. response, err := http.ReadResponse(responseReader, request)
  211. if err != nil {
  212. return
  213. }
  214. responseBuffer.Clear()
  215. response.Write(responseBuffer)
  216. writer.Write(responseBuffer.Value)
  217. response.Body.Close()
  218. }()
  219. wg.Wait()
  220. }