http.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. package http
  2. import (
  3. "bufio"
  4. "io"
  5. "net"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/v2ray/v2ray-core/app"
  12. "github.com/v2ray/v2ray-core/common/alloc"
  13. "github.com/v2ray/v2ray-core/common/log"
  14. v2net "github.com/v2ray/v2ray-core/common/net"
  15. "github.com/v2ray/v2ray-core/transport/ray"
  16. )
  17. type HttpProxyServer struct {
  18. accepting bool
  19. space app.Space
  20. config Config
  21. }
  22. func NewHttpProxyServer(space app.Space, config Config) *HttpProxyServer {
  23. return &HttpProxyServer{
  24. space: space,
  25. config: config,
  26. }
  27. }
  28. func (this *HttpProxyServer) Listen(port v2net.Port) error {
  29. tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
  30. Port: int(port.Value()),
  31. IP: []byte{0, 0, 0, 0},
  32. })
  33. if err != nil {
  34. return err
  35. }
  36. go this.accept(tcpListener)
  37. return nil
  38. }
  39. func (this *HttpProxyServer) accept(listener *net.TCPListener) {
  40. this.accepting = true
  41. for this.accepting {
  42. tcpConn, err := listener.AcceptTCP()
  43. if err != nil {
  44. log.Error("Failed to accept HTTP connection: %v", err)
  45. continue
  46. }
  47. go this.handleConnection(tcpConn)
  48. }
  49. }
  50. func parseHost(rawHost string, defaultPort v2net.Port) (v2net.Address, error) {
  51. port := defaultPort
  52. host, rawPort, err := net.SplitHostPort(rawHost)
  53. if err != nil {
  54. if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
  55. host = rawHost
  56. } else {
  57. return nil, err
  58. }
  59. } else {
  60. intPort, err := strconv.Atoi(rawPort)
  61. if err != nil {
  62. return nil, err
  63. }
  64. port = v2net.Port(intPort)
  65. }
  66. if ip := net.ParseIP(host); ip != nil {
  67. return v2net.IPAddress(ip, port), nil
  68. }
  69. return v2net.DomainAddress(host, port), nil
  70. }
  71. func (this *HttpProxyServer) handleConnection(conn *net.TCPConn) {
  72. defer conn.Close()
  73. reader := bufio.NewReader(conn)
  74. for true {
  75. request, err := http.ReadRequest(reader)
  76. if err != nil {
  77. break
  78. }
  79. this.handleRequest(request, reader, conn)
  80. }
  81. }
  82. func (this *HttpProxyServer) handleRequest(request *http.Request, reader io.Reader, writer io.Writer) {
  83. log.Info("Request to Method [%s] Host [%s] with URL [%s]", request.Method, request.Host, request.URL.String())
  84. defaultPort := v2net.Port(80)
  85. if strings.ToLower(request.URL.Scheme) == "https" {
  86. defaultPort = v2net.Port(443)
  87. }
  88. if strings.ToUpper(request.Method) == "CONNECT" {
  89. address, err := parseHost(request.Host, defaultPort)
  90. if err != nil {
  91. log.Warning("Malformed proxy host: %v", err)
  92. return
  93. }
  94. response := &http.Response{
  95. Status: "200 OK",
  96. StatusCode: 200,
  97. Proto: "HTTP/1.1",
  98. ProtoMajor: 1,
  99. ProtoMinor: 1,
  100. Header: http.Header(make(map[string][]string)),
  101. Body: nil,
  102. ContentLength: 0,
  103. Close: false,
  104. }
  105. buffer := alloc.NewSmallBuffer().Clear()
  106. response.Write(buffer)
  107. writer.Write(buffer.Value)
  108. packet := v2net.NewPacket(v2net.NewTCPDestination(address), nil, true)
  109. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  110. this.transport(reader, writer, ray)
  111. } else if len(request.URL.Host) > 0 {
  112. address, err := parseHost(request.URL.Host, defaultPort)
  113. if err != nil {
  114. log.Warning("Malformed proxy host: %v", err)
  115. return
  116. }
  117. request.Host = request.URL.Host
  118. request.Header.Set("Connection", "keep-alive")
  119. request.Header.Del("Proxy-Connection")
  120. buffer := alloc.NewBuffer().Clear()
  121. request.Write(buffer)
  122. log.Info("Request to remote: %s", string(buffer.Value))
  123. packet := v2net.NewPacket(v2net.NewTCPDestination(address), buffer, true)
  124. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  125. defer close(ray.InboundInput())
  126. responseReader := bufio.NewReader(NewChanReader(ray.InboundOutput()))
  127. response, err := http.ReadResponse(responseReader, request)
  128. if err != nil {
  129. return
  130. }
  131. responseBuffer := alloc.NewBuffer().Clear()
  132. defer responseBuffer.Release()
  133. response.Write(responseBuffer)
  134. writer.Write(responseBuffer.Value)
  135. } else {
  136. response := &http.Response{
  137. Status: "400 Bad Request",
  138. StatusCode: 400,
  139. Proto: "HTTP/1.1",
  140. ProtoMajor: 1,
  141. ProtoMinor: 1,
  142. Header: http.Header(make(map[string][]string)),
  143. Body: nil,
  144. ContentLength: 0,
  145. Close: false,
  146. }
  147. buffer := alloc.NewSmallBuffer().Clear()
  148. response.Write(buffer)
  149. writer.Write(buffer.Value)
  150. }
  151. }
  152. func (this *HttpProxyServer) transport(input io.Reader, output io.Writer, ray ray.InboundRay) {
  153. var inputFinish, outputFinish sync.Mutex
  154. outputFinish.Lock()
  155. if input != nil {
  156. inputFinish.Lock()
  157. go func() {
  158. v2net.ReaderToChan(ray.InboundInput(), input)
  159. inputFinish.Unlock()
  160. }()
  161. } else {
  162. // TODO: We can not close write so quickly, as some HTTP server will stop responding if so.
  163. }
  164. go func() {
  165. v2net.ChanToWriter(output, ray.InboundOutput())
  166. outputFinish.Unlock()
  167. }()
  168. inputFinish.Lock()
  169. go func() {
  170. <-time.After(10 * time.Second)
  171. close(ray.InboundInput())
  172. }()
  173. outputFinish.Lock()
  174. }