server.go 9.1 KB

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