server.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. // Server is a HTTP proxy server.
  23. type Server struct {
  24. sync.Mutex
  25. accepting bool
  26. packetDispatcher dispatcher.PacketDispatcher
  27. config *Config
  28. tcpListener *hub.TCPHub
  29. meta *proxy.InboundHandlerMeta
  30. }
  31. func NewServer(config *Config, packetDispatcher dispatcher.PacketDispatcher, meta *proxy.InboundHandlerMeta) *Server {
  32. return &Server{
  33. packetDispatcher: packetDispatcher,
  34. config: config,
  35. meta: meta,
  36. }
  37. }
  38. func (this *Server) Port() v2net.Port {
  39. return this.meta.Port
  40. }
  41. func (this *Server) Close() {
  42. this.accepting = false
  43. if this.tcpListener != nil {
  44. this.Lock()
  45. this.tcpListener.Close()
  46. this.tcpListener = nil
  47. this.Unlock()
  48. }
  49. }
  50. func (this *Server) Start() error {
  51. if this.accepting {
  52. return nil
  53. }
  54. var tlsConfig *tls.Config
  55. if this.config.TLSConfig != nil {
  56. tlsConfig = this.config.TLSConfig.GetConfig()
  57. }
  58. tcpListener, err := hub.ListenTCP(this.meta.Address, this.meta.Port, this.handleConnection, tlsConfig)
  59. if err != nil {
  60. log.Error("HTTP: Failed listen on ", this.meta.Address, ":", this.meta.Port, ": ", err)
  61. return err
  62. }
  63. this.Lock()
  64. this.tcpListener = tcpListener
  65. this.Unlock()
  66. this.accepting = true
  67. return nil
  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 *Server) handleConnection(conn *hub.Connection) {
  91. defer conn.Close()
  92. reader := bufio.NewReader(conn)
  93. request, err := http.ReadRequest(reader)
  94. if err != nil {
  95. if err != io.EOF {
  96. log.Warning("HTTP: Failed to read http request: ", err)
  97. }
  98. return
  99. }
  100. log.Info("HTTP: Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
  101. defaultPort := v2net.Port(80)
  102. if strings.ToLower(request.URL.Scheme) == "https" {
  103. defaultPort = v2net.Port(443)
  104. }
  105. host := request.Host
  106. if len(host) == 0 {
  107. host = request.URL.Host
  108. }
  109. dest, err := parseHost(host, defaultPort)
  110. if err != nil {
  111. log.Warning("HTTP: Malformed proxy host (", host, "): ", err)
  112. return
  113. }
  114. if strings.ToUpper(request.Method) == "CONNECT" {
  115. this.handleConnect(request, dest, reader, conn)
  116. } else {
  117. this.handlePlainHTTP(request, dest, reader, conn)
  118. }
  119. }
  120. func (this *Server) handleConnect(request *http.Request, destination v2net.Destination, reader io.Reader, writer io.Writer) {
  121. response := &http.Response{
  122. Status: "200 OK",
  123. StatusCode: 200,
  124. Proto: "HTTP/1.1",
  125. ProtoMajor: 1,
  126. ProtoMinor: 1,
  127. Header: http.Header(make(map[string][]string)),
  128. Body: nil,
  129. ContentLength: 0,
  130. Close: false,
  131. }
  132. buffer := alloc.NewSmallBuffer().Clear()
  133. response.Write(buffer)
  134. writer.Write(buffer.Value)
  135. buffer.Release()
  136. ray := this.packetDispatcher.DispatchToOutbound(destination)
  137. this.transport(reader, writer, ray)
  138. }
  139. func (this *Server) transport(input io.Reader, output io.Writer, ray ray.InboundRay) {
  140. var wg sync.WaitGroup
  141. wg.Add(2)
  142. defer wg.Wait()
  143. go func() {
  144. v2reader := v2io.NewAdaptiveReader(input)
  145. defer v2reader.Release()
  146. v2io.Pipe(v2reader, ray.InboundInput())
  147. ray.InboundInput().Close()
  148. wg.Done()
  149. }()
  150. go func() {
  151. v2writer := v2io.NewAdaptiveWriter(output)
  152. defer v2writer.Release()
  153. v2io.Pipe(ray.InboundOutput(), v2writer)
  154. ray.InboundOutput().Release()
  155. wg.Done()
  156. }()
  157. }
  158. // @VisibleForTesting
  159. func StripHopByHopHeaders(request *http.Request) {
  160. // Strip hop-by-hop header basaed on RFC:
  161. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
  162. // https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
  163. request.Header.Del("Proxy-Connection")
  164. request.Header.Del("Proxy-Authenticate")
  165. request.Header.Del("Proxy-Authorization")
  166. request.Header.Del("TE")
  167. request.Header.Del("Trailers")
  168. request.Header.Del("Transfer-Encoding")
  169. request.Header.Del("Upgrade")
  170. // TODO: support keep-alive
  171. connections := request.Header.Get("Connection")
  172. request.Header.Set("Connection", "close")
  173. if len(connections) == 0 {
  174. return
  175. }
  176. for _, h := range strings.Split(connections, ",") {
  177. request.Header.Del(strings.TrimSpace(h))
  178. }
  179. }
  180. func (this *Server) GenerateResponse(statusCode int, status string) *http.Response {
  181. hdr := http.Header(make(map[string][]string))
  182. hdr.Set("Connection", "close")
  183. return &http.Response{
  184. Status: status,
  185. StatusCode: statusCode,
  186. Proto: "HTTP/1.1",
  187. ProtoMajor: 1,
  188. ProtoMinor: 1,
  189. Header: hdr,
  190. Body: nil,
  191. ContentLength: 0,
  192. Close: false,
  193. }
  194. }
  195. func (this *Server) handlePlainHTTP(request *http.Request, dest v2net.Destination, reader *bufio.Reader, writer io.Writer) {
  196. if len(request.URL.Host) <= 0 {
  197. response := this.GenerateResponse(400, "Bad Request")
  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. response = this.GenerateResponse(503, "Service Unavailable")
  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{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  243. if !space.HasApp(dispatcher.APP_ID) {
  244. return nil, internal.ErrorBadConfiguration
  245. }
  246. return NewServer(
  247. rawConfig.(*Config),
  248. space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  249. meta), nil
  250. })
  251. }