server.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package http
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/base64"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "v2ray.com/core/app"
  12. "v2ray.com/core/app/dispatcher"
  13. "v2ray.com/core/app/log"
  14. "v2ray.com/core/app/policy"
  15. "v2ray.com/core/common"
  16. "v2ray.com/core/common/buf"
  17. "v2ray.com/core/common/errors"
  18. "v2ray.com/core/common/net"
  19. "v2ray.com/core/common/signal"
  20. "v2ray.com/core/transport/internet"
  21. )
  22. // Server is a HTTP proxy server.
  23. type Server struct {
  24. config *ServerConfig
  25. policy policy.Policy
  26. }
  27. // NewServer creates a new HTTP inbound handler.
  28. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
  29. space := app.SpaceFromContext(ctx)
  30. if space == nil {
  31. return nil, newError("no space in context.")
  32. }
  33. s := &Server{
  34. config: config,
  35. }
  36. space.On(app.SpaceInitializing, func(interface{}) error {
  37. pm := policy.FromSpace(space)
  38. if pm == nil {
  39. return newError("Policy not found in space.")
  40. }
  41. s.policy = pm.GetPolicy(config.UserLevel)
  42. if config.Timeout > 0 && config.UserLevel == 0 {
  43. s.policy.Timeout.ConnectionIdle.Value = config.Timeout
  44. }
  45. return nil
  46. })
  47. return s, nil
  48. }
  49. func (*Server) Network() net.NetworkList {
  50. return net.NetworkList{
  51. Network: []net.Network{net.Network_TCP},
  52. }
  53. }
  54. func parseHost(rawHost string, defaultPort net.Port) (net.Destination, error) {
  55. port := defaultPort
  56. host, rawPort, err := net.SplitHostPort(rawHost)
  57. if err != nil {
  58. if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
  59. host = rawHost
  60. } else {
  61. return net.Destination{}, err
  62. }
  63. } else if len(rawPort) > 0 {
  64. intPort, err := strconv.Atoi(rawPort)
  65. if err != nil {
  66. return net.Destination{}, err
  67. }
  68. port = net.Port(intPort)
  69. }
  70. return net.TCPDestination(net.ParseAddress(host), port), nil
  71. }
  72. func isTimeout(err error) bool {
  73. nerr, ok := errors.Cause(err).(net.Error)
  74. return ok && nerr.Timeout()
  75. }
  76. func parseBasicAuth(auth string) (username, password string, ok bool) {
  77. const prefix = "Basic "
  78. if !strings.HasPrefix(auth, prefix) {
  79. return
  80. }
  81. c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
  82. if err != nil {
  83. return
  84. }
  85. cs := string(c)
  86. s := strings.IndexByte(cs, ':')
  87. if s < 0 {
  88. return
  89. }
  90. return cs[:s], cs[s+1:], true
  91. }
  92. type readerOnly struct {
  93. io.Reader
  94. }
  95. func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher dispatcher.Interface) error {
  96. reader := bufio.NewReaderSize(readerOnly{conn}, buf.Size)
  97. Start:
  98. conn.SetReadDeadline(time.Now().Add(s.policy.Timeout.Handshake.Duration()))
  99. request, err := http.ReadRequest(reader)
  100. if err != nil {
  101. trace := newError("failed to read http request").Base(err)
  102. if errors.Cause(err) != io.EOF && !isTimeout(errors.Cause(err)) {
  103. trace.AtWarning()
  104. }
  105. return trace
  106. }
  107. if len(s.config.Accounts) > 0 {
  108. user, pass, ok := parseBasicAuth(request.Header.Get("Proxy-Authorization"))
  109. if !ok || !s.config.HasAccount(user, pass) {
  110. _, err := conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\n" +
  111. "Proxy-Authenticate: Basic realm=\"V2Ray\"\r\n\r\n"))
  112. return err
  113. }
  114. }
  115. log.Trace(newError("request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]"))
  116. conn.SetReadDeadline(time.Time{})
  117. defaultPort := net.Port(80)
  118. if strings.ToLower(request.URL.Scheme) == "https" {
  119. defaultPort = net.Port(443)
  120. }
  121. host := request.Host
  122. if len(host) == 0 {
  123. host = request.URL.Host
  124. }
  125. dest, err := parseHost(host, defaultPort)
  126. if err != nil {
  127. return newError("malformed proxy host: ", host).AtWarning().Base(err)
  128. }
  129. log.Access(conn.RemoteAddr(), request.URL, log.AccessAccepted, "")
  130. if strings.ToUpper(request.Method) == "CONNECT" {
  131. return s.handleConnect(ctx, request, reader, conn, dest, dispatcher)
  132. }
  133. keepAlive := (strings.TrimSpace(strings.ToLower(request.Header.Get("Proxy-Connection"))) == "keep-alive")
  134. err = s.handlePlainHTTP(ctx, request, conn, dest, dispatcher)
  135. if err == errWaitAnother {
  136. if keepAlive {
  137. goto Start
  138. }
  139. err = nil
  140. }
  141. return err
  142. }
  143. func (s *Server) handleConnect(ctx context.Context, request *http.Request, reader *bufio.Reader, conn internet.Connection, dest net.Destination, dispatcher dispatcher.Interface) error {
  144. _, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
  145. if err != nil {
  146. return newError("failed to write back OK response").Base(err)
  147. }
  148. ctx, cancel := context.WithCancel(ctx)
  149. timer := signal.CancelAfterInactivity(ctx, cancel, s.policy.Timeout.ConnectionIdle.Duration())
  150. ray, err := dispatcher.Dispatch(ctx, dest)
  151. if err != nil {
  152. return err
  153. }
  154. if reader.Buffered() > 0 {
  155. payload := buf.New()
  156. common.Must(payload.Reset(func(b []byte) (int, error) {
  157. return reader.Read(b[:reader.Buffered()])
  158. }))
  159. if err := ray.InboundInput().WriteMultiBuffer(buf.NewMultiBufferValue(payload)); err != nil {
  160. return err
  161. }
  162. reader = nil
  163. }
  164. requestDone := signal.ExecuteAsync(func() error {
  165. defer ray.InboundInput().Close()
  166. defer timer.SetTimeout(s.policy.Timeout.DownlinkOnly.Duration())
  167. v2reader := buf.NewReader(conn)
  168. return buf.Copy(v2reader, ray.InboundInput(), buf.UpdateActivity(timer))
  169. })
  170. responseDone := signal.ExecuteAsync(func() error {
  171. v2writer := buf.NewWriter(conn)
  172. if err := buf.Copy(ray.InboundOutput(), v2writer, buf.UpdateActivity(timer)); err != nil {
  173. return err
  174. }
  175. timer.SetTimeout(s.policy.Timeout.UplinkOnly.Duration())
  176. return nil
  177. })
  178. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  179. ray.InboundInput().CloseError()
  180. ray.InboundOutput().CloseError()
  181. return newError("connection ends").Base(err)
  182. }
  183. return nil
  184. }
  185. // @VisibleForTesting
  186. func StripHopByHopHeaders(header http.Header) {
  187. // Strip hop-by-hop header basaed on RFC:
  188. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
  189. // https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
  190. header.Del("Proxy-Connection")
  191. header.Del("Proxy-Authenticate")
  192. header.Del("Proxy-Authorization")
  193. header.Del("TE")
  194. header.Del("Trailers")
  195. header.Del("Transfer-Encoding")
  196. header.Del("Upgrade")
  197. connections := header.Get("Connection")
  198. header.Del("Connection")
  199. if len(connections) == 0 {
  200. return
  201. }
  202. for _, h := range strings.Split(connections, ",") {
  203. header.Del(strings.TrimSpace(h))
  204. }
  205. // Prevent UA from being set to golang's default ones
  206. if len(header.Get("User-Agent")) == 0 {
  207. header.Set("User-Agent", "")
  208. }
  209. }
  210. var errWaitAnother = newError("keep alive")
  211. func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, writer io.Writer, dest net.Destination, dispatcher dispatcher.Interface) error {
  212. if !s.config.AllowTransparent && len(request.URL.Host) <= 0 {
  213. // RFC 2068 (HTTP/1.1) requires URL to be absolute URL in HTTP proxy.
  214. response := &http.Response{
  215. Status: "Bad Request",
  216. StatusCode: 400,
  217. Proto: "HTTP/1.1",
  218. ProtoMajor: 1,
  219. ProtoMinor: 1,
  220. Header: http.Header(make(map[string][]string)),
  221. Body: nil,
  222. ContentLength: 0,
  223. Close: true,
  224. }
  225. response.Header.Set("Proxy-Connection", "close")
  226. response.Header.Set("Connection", "close")
  227. return response.Write(writer)
  228. }
  229. if len(request.URL.Host) > 0 {
  230. request.Host = request.URL.Host
  231. }
  232. StripHopByHopHeaders(request.Header)
  233. ray, err := dispatcher.Dispatch(ctx, dest)
  234. if err != nil {
  235. return err
  236. }
  237. input := ray.InboundInput()
  238. output := ray.InboundOutput()
  239. defer input.Close()
  240. var result error = errWaitAnother
  241. requestDone := signal.ExecuteAsync(func() error {
  242. request.Header.Set("Connection", "close")
  243. requestWriter := buf.NewBufferedWriter(ray.InboundInput())
  244. common.Must(requestWriter.SetBuffered(false))
  245. if err := request.Write(requestWriter); err != nil {
  246. return newError("failed to write whole request").Base(err).AtWarning()
  247. }
  248. return nil
  249. })
  250. responseDone := signal.ExecuteAsync(func() error {
  251. responseReader := bufio.NewReaderSize(buf.NewBufferedReader(ray.InboundOutput()), buf.Size)
  252. response, err := http.ReadResponse(responseReader, request)
  253. if err == nil {
  254. StripHopByHopHeaders(response.Header)
  255. if response.ContentLength >= 0 {
  256. response.Header.Set("Proxy-Connection", "keep-alive")
  257. response.Header.Set("Connection", "keep-alive")
  258. response.Header.Set("Keep-Alive", "timeout=4")
  259. response.Close = false
  260. } else {
  261. response.Close = true
  262. result = nil
  263. }
  264. } else {
  265. log.Trace(newError("failed to read response from ", request.Host).Base(err).AtWarning())
  266. response = &http.Response{
  267. Status: "Service Unavailable",
  268. StatusCode: 503,
  269. Proto: "HTTP/1.1",
  270. ProtoMajor: 1,
  271. ProtoMinor: 1,
  272. Header: http.Header(make(map[string][]string)),
  273. Body: nil,
  274. ContentLength: 0,
  275. Close: true,
  276. }
  277. response.Header.Set("Connection", "close")
  278. response.Header.Set("Proxy-Connection", "close")
  279. }
  280. if err := response.Write(writer); err != nil {
  281. return newError("failed to write response").Base(err).AtWarning()
  282. }
  283. return nil
  284. })
  285. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  286. input.CloseError()
  287. output.CloseError()
  288. return newError("connection ends").Base(err)
  289. }
  290. return result
  291. }
  292. func init() {
  293. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  294. return NewServer(ctx, config.(*ServerConfig))
  295. }))
  296. }