1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-10 18:00:43 +00:00
v2fly/proxy/http/server.go

299 lines
7.8 KiB
Go
Raw Normal View History

2015-10-28 11:13:27 +00:00
package http
import (
2015-12-15 15:00:47 +00:00
"io"
2015-10-28 11:13:27 +00:00
"net"
2015-12-14 16:26:29 +00:00
"net/http"
2015-12-14 23:53:40 +00:00
"strconv"
2015-12-14 16:26:29 +00:00
"strings"
2015-12-15 15:00:47 +00:00
"sync"
2015-10-28 11:13:27 +00:00
2016-08-20 18:55:45 +00:00
"v2ray.com/core/app"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/common"
2016-12-09 12:17:34 +00:00
"v2ray.com/core/common/buf"
"v2ray.com/core/common/bufio"
2016-12-04 08:10:47 +00:00
"v2ray.com/core/common/errors"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/log"
v2net "v2ray.com/core/common/net"
2016-12-15 10:51:09 +00:00
"v2ray.com/core/common/serial"
2016-12-29 23:32:20 +00:00
"v2ray.com/core/common/signal"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/proxy"
"v2ray.com/core/transport/internet"
2015-10-28 11:13:27 +00:00
)
2016-05-29 14:46:31 +00:00
// Server is a HTTP proxy server.
type Server struct {
sync.Mutex
2016-01-31 16:01:28 +00:00
accepting bool
packetDispatcher dispatcher.PacketDispatcher
2016-08-25 19:55:49 +00:00
config *ServerConfig
2016-06-14 20:54:08 +00:00
tcpListener *internet.TCPHub
2016-06-04 12:25:13 +00:00
meta *proxy.InboundHandlerMeta
2015-10-28 11:13:27 +00:00
}
2016-12-22 12:54:11 +00:00
// NewServer creates a new HTTP inbound handler.
2017-01-06 14:32:36 +00:00
func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandlerMeta) *Server {
s := &Server{
config: config,
meta: meta,
2015-10-28 11:13:27 +00:00
}
2017-01-06 14:32:36 +00:00
space.OnInitialize(func() error {
s.packetDispatcher = dispatcher.FromSpace(space)
if s.packetDispatcher == nil {
return errors.New("HTTP|Server: Dispatcher not found in space.")
}
return nil
})
return s
2015-10-28 11:13:27 +00:00
}
2016-12-22 12:54:11 +00:00
// Port implements InboundHandler.Port().
2016-11-27 20:39:09 +00:00
func (v *Server) Port() v2net.Port {
return v.meta.Port
2016-01-19 22:41:40 +00:00
}
2016-12-22 12:54:11 +00:00
// Close implements InboundHandler.Close().
2016-11-27 20:39:09 +00:00
func (v *Server) Close() {
v.accepting = false
if v.tcpListener != nil {
v.Lock()
v.tcpListener.Close()
v.tcpListener = nil
v.Unlock()
}
}
2016-12-22 12:54:11 +00:00
// Start implements InboundHandler.Start().
2016-11-27 20:39:09 +00:00
func (v *Server) Start() error {
if v.accepting {
2016-06-03 22:38:22 +00:00
return nil
2016-01-19 22:41:40 +00:00
}
2016-11-27 20:39:09 +00:00
tcpListener, err := internet.ListenTCP(v.meta.Address, v.meta.Port, v.handleConnection, v.meta.StreamSettings)
2015-12-14 23:53:40 +00:00
if err != nil {
2016-11-27 20:39:09 +00:00
log.Error("HTTP: Failed listen on ", v.meta.Address, ":", v.meta.Port, ": ", err)
2015-12-14 23:53:40 +00:00
return err
2015-10-28 11:13:27 +00:00
}
2016-11-27 20:39:09 +00:00
v.Lock()
v.tcpListener = tcpListener
v.Unlock()
v.accepting = true
2015-12-14 23:53:40 +00:00
return nil
2015-12-14 16:26:29 +00:00
}
2015-12-16 22:53:38 +00:00
func parseHost(rawHost string, defaultPort v2net.Port) (v2net.Destination, error) {
2015-12-15 15:00:47 +00:00
port := defaultPort
2015-12-14 23:53:40 +00:00
host, rawPort, err := net.SplitHostPort(rawHost)
if err != nil {
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
host = rawHost
} else {
2016-09-20 09:53:05 +00:00
return v2net.Destination{}, err
2015-12-14 23:53:40 +00:00
}
2015-12-15 15:00:47 +00:00
} else {
intPort, err := strconv.Atoi(rawPort)
if err != nil {
2016-09-20 09:53:05 +00:00
return v2net.Destination{}, err
2015-12-15 15:00:47 +00:00
}
port = v2net.Port(intPort)
2015-12-14 16:26:29 +00:00
}
2015-12-15 15:00:47 +00:00
2015-12-14 23:53:40 +00:00
if ip := net.ParseIP(host); ip != nil {
2015-12-16 22:53:38 +00:00
return v2net.TCPDestination(v2net.IPAddress(ip), port), nil
2015-12-14 23:53:40 +00:00
}
2015-12-16 22:53:38 +00:00
return v2net.TCPDestination(v2net.DomainAddress(host), port), nil
2015-12-14 16:26:29 +00:00
}
2016-11-27 20:39:09 +00:00
func (v *Server) handleConnection(conn internet.Connection) {
2015-12-15 15:00:47 +00:00
defer conn.Close()
2017-01-03 13:53:59 +00:00
conn.SetReusable(false)
2016-11-27 20:39:09 +00:00
timedReader := v2net.NewTimeOutReader(v.config.Timeout, conn)
2016-12-09 12:17:34 +00:00
reader := bufio.OriginalReaderSize(timedReader, 2048)
request, err := http.ReadRequest(reader)
if err != nil {
2016-12-04 08:10:47 +00:00
if errors.Cause(err) != io.EOF {
2016-06-03 18:21:46 +00:00
log.Warning("HTTP: Failed to read http request: ", err)
}
return
}
2016-06-01 22:57:08 +00:00
log.Info("HTTP: Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
defaultPort := v2net.Port(80)
if strings.ToLower(request.URL.Scheme) == "https" {
defaultPort = v2net.Port(443)
}
host := request.Host
if len(host) == 0 {
host = request.URL.Host
}
dest, err := parseHost(host, defaultPort)
if err != nil {
2016-06-01 22:57:08 +00:00
log.Warning("HTTP: Malformed proxy host (", host, "): ", err)
2016-01-11 11:35:28 +00:00
return
}
2016-06-05 13:02:15 +00:00
log.Access(conn.RemoteAddr(), request.URL, log.AccessAccepted, "")
2016-08-14 15:08:01 +00:00
session := &proxy.SessionInfo{
2016-08-14 21:20:23 +00:00
Source: v2net.DestinationFromAddr(conn.RemoteAddr()),
2016-08-14 15:08:01 +00:00
Destination: dest,
2016-11-27 20:39:09 +00:00
Inbound: v.meta,
2016-08-14 15:08:01 +00:00
}
if strings.ToUpper(request.Method) == "CONNECT" {
2016-11-27 20:39:09 +00:00
v.handleConnect(request, session, reader, conn)
} else {
2016-11-27 20:39:09 +00:00
v.handlePlainHTTP(request, session, reader, conn)
2015-12-16 14:52:40 +00:00
}
}
2015-12-15 21:13:09 +00:00
2016-11-27 20:39:09 +00:00
func (v *Server) handleConnect(request *http.Request, session *proxy.SessionInfo, reader io.Reader, writer io.Writer) {
2015-12-16 14:52:40 +00:00
response := &http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: http.Header(make(map[string][]string)),
Body: nil,
ContentLength: 0,
Close: false,
}
2016-12-22 12:54:11 +00:00
if err := response.Write(writer); err != nil {
log.Warning("HTTP|Server: failed to write back OK response: ", err)
return
}
2015-12-15 15:00:47 +00:00
2016-11-27 20:39:09 +00:00
ray := v.packetDispatcher.DispatchToOutbound(session)
2015-12-15 15:00:47 +00:00
2016-12-29 23:32:20 +00:00
requestDone := signal.ExecuteAsync(func() error {
defer ray.InboundInput().Close()
2015-12-15 15:00:47 +00:00
2016-12-29 23:32:20 +00:00
v2reader := buf.NewReader(reader)
2016-12-09 12:17:34 +00:00
if err := buf.PipeUntilEOF(v2reader, ray.InboundInput()); err != nil {
2016-12-29 23:32:20 +00:00
return err
2016-11-21 23:17:49 +00:00
}
2016-12-29 23:32:20 +00:00
return nil
})
2015-12-15 15:00:47 +00:00
2016-12-29 23:32:20 +00:00
responseDone := signal.ExecuteAsync(func() error {
v2writer := buf.NewWriter(writer)
2016-12-09 12:17:34 +00:00
if err := buf.PipeUntilEOF(ray.InboundOutput(), v2writer); err != nil {
2016-12-29 23:32:20 +00:00
return err
2016-11-21 23:17:49 +00:00
}
2016-12-29 23:32:20 +00:00
return nil
})
2017-01-10 13:22:42 +00:00
if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
log.Info("HTTP|Server: Connection ends with: ", err)
ray.InboundInput().CloseError()
ray.InboundOutput().CloseError()
}
}
2015-12-15 15:00:47 +00:00
2016-02-20 22:27:06 +00:00
// @VisibleForTesting
func StripHopByHopHeaders(request *http.Request) {
// Strip hop-by-hop header basaed on RFC:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
request.Header.Del("Proxy-Connection")
request.Header.Del("Proxy-Authenticate")
request.Header.Del("Proxy-Authorization")
request.Header.Del("TE")
request.Header.Del("Trailers")
request.Header.Del("Transfer-Encoding")
request.Header.Del("Upgrade")
// TODO: support keep-alive
connections := request.Header.Get("Connection")
request.Header.Set("Connection", "close")
if len(connections) == 0 {
return
}
for _, h := range strings.Split(connections, ",") {
request.Header.Del(strings.TrimSpace(h))
}
}
2016-11-27 20:39:09 +00:00
func (v *Server) GenerateResponse(statusCode int, status string) *http.Response {
2016-06-01 22:57:08 +00:00
hdr := http.Header(make(map[string][]string))
hdr.Set("Connection", "close")
return &http.Response{
Status: status,
StatusCode: statusCode,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: hdr,
Body: nil,
ContentLength: 0,
2016-12-27 23:58:53 +00:00
Close: true,
2016-06-01 22:57:08 +00:00
}
}
2016-12-09 12:17:34 +00:00
func (v *Server) handlePlainHTTP(request *http.Request, session *proxy.SessionInfo, reader io.Reader, writer io.Writer) {
if len(request.URL.Host) <= 0 {
2016-11-27 20:39:09 +00:00
response := v.GenerateResponse(400, "Bad Request")
2016-07-16 11:22:34 +00:00
response.Write(writer)
return
}
request.Host = request.URL.Host
2016-02-20 22:27:06 +00:00
StripHopByHopHeaders(request)
2016-11-27 20:39:09 +00:00
ray := v.packetDispatcher.DispatchToOutbound(session)
2016-12-29 23:51:39 +00:00
input := ray.InboundInput()
output := ray.InboundOutput()
2016-12-29 23:32:20 +00:00
requestDone := signal.ExecuteAsync(func() error {
2016-12-29 23:51:39 +00:00
defer input.Close()
2016-12-29 23:32:20 +00:00
2016-12-09 12:17:34 +00:00
requestWriter := bufio.NewWriter(buf.NewBytesWriter(ray.InboundInput()))
err := request.Write(requestWriter)
if err != nil {
2016-12-29 23:32:20 +00:00
return err
}
2016-12-29 23:32:20 +00:00
if err := requestWriter.Flush(); err != nil {
return err
}
return nil
})
responseDone := signal.ExecuteAsync(func() error {
2016-12-09 12:17:34 +00:00
responseReader := bufio.OriginalReader(buf.NewBytesReader(ray.InboundOutput()))
response, err := http.ReadResponse(responseReader, request)
if err != nil {
log.Warning("HTTP: Failed to read response: ", err)
2016-11-27 20:39:09 +00:00
response = v.GenerateResponse(503, "Service Unavailable")
}
2016-12-09 12:17:34 +00:00
responseWriter := bufio.NewWriter(writer)
2016-12-29 23:32:20 +00:00
if err := response.Write(responseWriter); err != nil {
return err
}
if err := responseWriter.Flush(); err != nil {
return err
}
2016-12-29 23:32:20 +00:00
return nil
})
if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
log.Info("HTTP|Server: Connecton ending with ", err)
2017-01-10 13:22:42 +00:00
input.CloseError()
output.CloseError()
2016-12-29 23:32:20 +00:00
}
2015-10-28 11:13:27 +00:00
}
2016-05-07 12:08:27 +00:00
2016-12-22 12:54:11 +00:00
// ServerFactory is a InboundHandlerFactory.
2016-06-14 20:54:08 +00:00
type ServerFactory struct{}
2016-12-22 12:54:11 +00:00
// Create implements InboundHandlerFactory.Create().
2016-11-27 20:39:09 +00:00
func (v *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
2017-01-06 14:32:36 +00:00
return NewServer(rawConfig.(*ServerConfig), space, meta), nil
2016-06-14 20:54:08 +00:00
}
2016-05-07 12:08:27 +00:00
func init() {
2016-12-27 23:53:29 +00:00
common.Must(proxy.RegisterInboundHandlerCreator(serial.GetMessageType(new(ServerConfig)), new(ServerFactory)))
2016-05-07 12:08:27 +00:00
}