http.go 5.5 KB

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