http.go 6.5 KB

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