server.go 6.9 KB

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