server.go 6.8 KB

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