http.go 4.6 KB

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