server.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. listeningAddress v2net.Address
  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(address v2net.Address, port v2net.Port) error {
  50. if this.accepting {
  51. if this.listeningPort == port && this.listeningAddress.Equals(address) {
  52. return nil
  53. } else {
  54. return proxy.ErrorAlreadyListening
  55. }
  56. }
  57. this.listeningPort = port
  58. this.listeningAddress = address
  59. var tlsConfig *tls.Config = nil
  60. if this.config.TlsConfig != nil {
  61. tlsConfig = this.config.TlsConfig.GetConfig()
  62. }
  63. tcpListener, err := hub.ListenTCP(address, port, this.handleConnection, tlsConfig)
  64. if err != nil {
  65. log.Error("Http: Failed listen on port ", port, ": ", err)
  66. return err
  67. }
  68. this.Lock()
  69. this.tcpListener = tcpListener
  70. this.Unlock()
  71. this.accepting = true
  72. return nil
  73. }
  74. func parseHost(rawHost string, defaultPort v2net.Port) (v2net.Destination, error) {
  75. port := defaultPort
  76. host, rawPort, err := net.SplitHostPort(rawHost)
  77. if err != nil {
  78. if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
  79. host = rawHost
  80. } else {
  81. return nil, err
  82. }
  83. } else {
  84. intPort, err := strconv.Atoi(rawPort)
  85. if err != nil {
  86. return nil, err
  87. }
  88. port = v2net.Port(intPort)
  89. }
  90. if ip := net.ParseIP(host); ip != nil {
  91. return v2net.TCPDestination(v2net.IPAddress(ip), port), nil
  92. }
  93. return v2net.TCPDestination(v2net.DomainAddress(host), port), nil
  94. }
  95. func (this *HttpProxyServer) handleConnection(conn *hub.Connection) {
  96. defer conn.Close()
  97. reader := bufio.NewReader(conn)
  98. request, err := http.ReadRequest(reader)
  99. if err != nil {
  100. log.Warning("Failed to read http request: ", err)
  101. return
  102. }
  103. log.Info("Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
  104. defaultPort := v2net.Port(80)
  105. if strings.ToLower(request.URL.Scheme) == "https" {
  106. defaultPort = v2net.Port(443)
  107. }
  108. host := request.Host
  109. if len(host) == 0 {
  110. host = request.URL.Host
  111. }
  112. dest, err := parseHost(host, defaultPort)
  113. if err != nil {
  114. log.Warning("Malformed proxy host (", host, "): ", err)
  115. return
  116. }
  117. if strings.ToUpper(request.Method) == "CONNECT" {
  118. this.handleConnect(request, dest, reader, conn)
  119. } else {
  120. this.handlePlainHTTP(request, dest, reader, conn)
  121. }
  122. }
  123. func (this *HttpProxyServer) handleConnect(request *http.Request, destination v2net.Destination, reader io.Reader, writer io.Writer) {
  124. response := &http.Response{
  125. Status: "200 OK",
  126. StatusCode: 200,
  127. Proto: "HTTP/1.1",
  128. ProtoMajor: 1,
  129. ProtoMinor: 1,
  130. Header: http.Header(make(map[string][]string)),
  131. Body: nil,
  132. ContentLength: 0,
  133. Close: false,
  134. }
  135. buffer := alloc.NewSmallBuffer().Clear()
  136. response.Write(buffer)
  137. writer.Write(buffer.Value)
  138. buffer.Release()
  139. ray := this.packetDispatcher.DispatchToOutbound(destination)
  140. this.transport(reader, writer, ray)
  141. }
  142. func (this *HttpProxyServer) transport(input io.Reader, output io.Writer, ray ray.InboundRay) {
  143. var wg sync.WaitGroup
  144. wg.Add(2)
  145. defer wg.Wait()
  146. go func() {
  147. v2reader := v2io.NewAdaptiveReader(input)
  148. defer v2reader.Release()
  149. v2io.Pipe(v2reader, ray.InboundInput())
  150. ray.InboundInput().Close()
  151. wg.Done()
  152. }()
  153. go func() {
  154. v2writer := v2io.NewAdaptiveWriter(output)
  155. defer v2writer.Release()
  156. v2io.Pipe(ray.InboundOutput(), v2writer)
  157. ray.InboundOutput().Release()
  158. wg.Done()
  159. }()
  160. }
  161. // @VisibleForTesting
  162. func StripHopByHopHeaders(request *http.Request) {
  163. // Strip hop-by-hop header basaed on RFC:
  164. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
  165. // https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
  166. request.Header.Del("Proxy-Connection")
  167. request.Header.Del("Proxy-Authenticate")
  168. request.Header.Del("Proxy-Authorization")
  169. request.Header.Del("TE")
  170. request.Header.Del("Trailers")
  171. request.Header.Del("Transfer-Encoding")
  172. request.Header.Del("Upgrade")
  173. // TODO: support keep-alive
  174. connections := request.Header.Get("Connection")
  175. request.Header.Set("Connection", "close")
  176. if len(connections) == 0 {
  177. return
  178. }
  179. for _, h := range strings.Split(connections, ",") {
  180. request.Header.Del(strings.TrimSpace(h))
  181. }
  182. }
  183. func (this *HttpProxyServer) handlePlainHTTP(request *http.Request, dest v2net.Destination, reader *bufio.Reader, writer io.Writer) {
  184. if len(request.URL.Host) <= 0 {
  185. hdr := http.Header(make(map[string][]string))
  186. hdr.Set("Connection", "close")
  187. response := &http.Response{
  188. Status: "400 Bad Request",
  189. StatusCode: 400,
  190. Proto: "HTTP/1.1",
  191. ProtoMajor: 1,
  192. ProtoMinor: 1,
  193. Header: hdr,
  194. Body: nil,
  195. ContentLength: 0,
  196. Close: false,
  197. }
  198. buffer := alloc.NewSmallBuffer().Clear()
  199. response.Write(buffer)
  200. writer.Write(buffer.Value)
  201. buffer.Release()
  202. return
  203. }
  204. request.Host = request.URL.Host
  205. StripHopByHopHeaders(request)
  206. ray := this.packetDispatcher.DispatchToOutbound(dest)
  207. defer ray.InboundInput().Close()
  208. defer ray.InboundOutput().Release()
  209. var finish sync.WaitGroup
  210. finish.Add(1)
  211. go func() {
  212. defer finish.Done()
  213. requestWriter := v2io.NewBufferedWriter(v2io.NewChainWriter(ray.InboundInput()))
  214. err := request.Write(requestWriter)
  215. if err != nil {
  216. log.Warning("HTTP: Failed to write request: ", err)
  217. return
  218. }
  219. requestWriter.Flush()
  220. }()
  221. finish.Add(1)
  222. go func() {
  223. defer finish.Done()
  224. responseReader := bufio.NewReader(v2io.NewChanReader(ray.InboundOutput()))
  225. response, err := http.ReadResponse(responseReader, request)
  226. if err != nil {
  227. log.Warning("HTTP: Failed to read response: ", err)
  228. return
  229. }
  230. responseWriter := v2io.NewBufferedWriter(writer)
  231. err = response.Write(responseWriter)
  232. if err != nil {
  233. log.Warning("HTTP: Failed to write response: ", err)
  234. return
  235. }
  236. responseWriter.Flush()
  237. }()
  238. finish.Wait()
  239. }
  240. func init() {
  241. internal.MustRegisterInboundHandlerCreator("http",
  242. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  243. if !space.HasApp(dispatcher.APP_ID) {
  244. return nil, internal.ErrorBadConfiguration
  245. }
  246. return NewHttpProxyServer(
  247. rawConfig.(*Config),
  248. space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)), nil
  249. })
  250. }