http.go 6.0 KB

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