1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-16 09:26:21 -05:00
v2fly/proxy/http/server.go

267 lines
7.1 KiB
Go
Raw Normal View History

2015-10-28 07:13:27 -04:00
package http
import (
2017-02-15 16:51:01 -05:00
"bufio"
2017-01-14 18:57:06 -05:00
"context"
2015-12-15 10:00:47 -05:00
"io"
2015-10-28 07:13:27 -04:00
"net"
2015-12-14 11:26:29 -05:00
"net/http"
2017-01-31 06:42:05 -05:00
"runtime"
2015-12-14 18:53:40 -05:00
"strconv"
2015-12-14 11:26:29 -05:00
"strings"
2017-01-31 06:42:05 -05:00
"time"
2015-10-28 07:13:27 -04:00
2016-08-20 14:55:45 -04:00
"v2ray.com/core/app"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/log"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common"
2016-12-09 07:17:34 -05:00
"v2ray.com/core/common/buf"
2016-12-04 03:10:47 -05:00
"v2ray.com/core/common/errors"
2016-08-20 14:55:45 -04:00
v2net "v2ray.com/core/common/net"
2016-12-29 18:32:20 -05:00
"v2ray.com/core/common/signal"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/transport/internet"
2015-10-28 07:13:27 -04:00
)
2016-05-29 10:46:31 -04:00
// Server is a HTTP proxy server.
type Server struct {
config *ServerConfig
2015-10-28 07:13:27 -04:00
}
2016-12-22 07:54:11 -05:00
// NewServer creates a new HTTP inbound handler.
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, errors.New("HTTP|Server: No space in context.")
}
2017-01-06 09:32:36 -05:00
s := &Server{
config: config,
2015-10-28 07:13:27 -04:00
}
return s, nil
2015-10-28 07:13:27 -04:00
}
func (*Server) Network() v2net.NetworkList {
2017-01-14 18:57:06 -05:00
return v2net.NetworkList{
Network: []v2net.Network{v2net.Network_TCP},
}
}
2015-12-16 17:53:38 -05:00
func parseHost(rawHost string, defaultPort v2net.Port) (v2net.Destination, error) {
2015-12-15 10:00:47 -05:00
port := defaultPort
2015-12-14 18:53:40 -05: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 05:53:05 -04:00
return v2net.Destination{}, err
2015-12-14 18:53:40 -05:00
}
2015-12-15 10:00:47 -05:00
} else {
intPort, err := strconv.Atoi(rawPort)
if err != nil {
2016-09-20 05:53:05 -04:00
return v2net.Destination{}, err
2015-12-15 10:00:47 -05:00
}
port = v2net.Port(intPort)
2015-12-14 11:26:29 -05:00
}
2015-12-15 10:00:47 -05:00
2015-12-14 18:53:40 -05:00
if ip := net.ParseIP(host); ip != nil {
2015-12-16 17:53:38 -05:00
return v2net.TCPDestination(v2net.IPAddress(ip), port), nil
2015-12-14 18:53:40 -05:00
}
2015-12-16 17:53:38 -05:00
return v2net.TCPDestination(v2net.DomainAddress(host), port), nil
2015-12-14 11:26:29 -05:00
}
func (s *Server) Process(ctx context.Context, network v2net.Network, conn internet.Connection, dispatcher dispatcher.Interface) error {
2017-01-03 08:53:59 -05:00
conn.SetReusable(false)
2017-01-31 10:49:59 -05:00
conn.SetReadDeadline(time.Now().Add(time.Second * 8))
2017-02-15 16:51:01 -05:00
reader := bufio.NewReaderSize(conn, 2048)
request, err := http.ReadRequest(reader)
if err != nil {
2016-12-04 03:10:47 -05:00
if errors.Cause(err) != io.EOF {
2016-06-03 14:21:46 -04:00
log.Warning("HTTP: Failed to read http request: ", err)
}
return err
}
2016-06-01 18:57:08 -04:00
log.Info("HTTP: Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
2017-01-31 10:49:59 -05:00
conn.SetReadDeadline(time.Time{})
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 18:57:08 -04:00
log.Warning("HTTP: Malformed proxy host (", host, "): ", err)
return err
}
2016-06-05 09:02:15 -04:00
log.Access(conn.RemoteAddr(), request.URL, log.AccessAccepted, "")
if strings.ToUpper(request.Method) == "CONNECT" {
return s.handleConnect(ctx, request, reader, conn, dest, dispatcher)
} else {
return s.handlePlainHTTP(ctx, request, reader, conn, dest, dispatcher)
2015-12-16 09:52:40 -05:00
}
}
2015-12-15 16:13:09 -05:00
func (s *Server) handleConnect(ctx context.Context, request *http.Request, reader io.Reader, writer io.Writer, dest v2net.Destination, dispatcher dispatcher.Interface) error {
2015-12-16 09:52:40 -05: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 07:54:11 -05:00
if err := response.Write(writer); err != nil {
2017-02-21 16:15:20 -05:00
return errors.Base(err).Message("HTTP|Server: Failed to write back OK response.")
2016-12-22 07:54:11 -05:00
}
2015-12-15 10:00:47 -05:00
2017-01-31 06:42:05 -05:00
ctx, cancel := context.WithCancel(ctx)
2017-01-31 10:49:59 -05:00
timeout := time.Second * time.Duration(s.config.Timeout)
if timeout == 0 {
timeout = time.Minute * 2
}
timer := signal.CancelAfterInactivity(ctx, cancel, timeout)
ray, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return err
}
2015-12-15 10:00:47 -05:00
2016-12-29 18:32:20 -05:00
requestDone := signal.ExecuteAsync(func() error {
defer ray.InboundInput().Close()
2015-12-15 10:00:47 -05:00
2016-12-29 18:32:20 -05:00
v2reader := buf.NewReader(reader)
2017-01-31 06:42:05 -05:00
if err := buf.PipeUntilEOF(timer, v2reader, ray.InboundInput()); err != nil {
2016-12-29 18:32:20 -05:00
return err
2016-11-21 18:17:49 -05:00
}
2016-12-29 18:32:20 -05:00
return nil
})
2015-12-15 10:00:47 -05:00
2016-12-29 18:32:20 -05:00
responseDone := signal.ExecuteAsync(func() error {
v2writer := buf.NewWriter(writer)
2017-01-31 06:42:05 -05:00
if err := buf.PipeUntilEOF(timer, ray.InboundOutput(), v2writer); err != nil {
2016-12-29 18:32:20 -05:00
return err
2016-11-21 18:17:49 -05:00
}
2016-12-29 18:32:20 -05:00
return nil
})
if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
2017-01-10 08:22:42 -05:00
ray.InboundInput().CloseError()
ray.InboundOutput().CloseError()
2017-02-21 16:15:20 -05:00
return errors.Base(err).Message("HTTP|Server: Connection ends.")
2017-01-10 08:22:42 -05:00
}
2017-01-31 06:42:05 -05:00
runtime.KeepAlive(timer)
return nil
}
2015-12-15 10:00:47 -05:00
2016-02-20 17:27:06 -05: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))
}
}
func generateResponse(statusCode int, status string) *http.Response {
2016-06-01 18:57:08 -04: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 18:58:53 -05:00
Close: true,
2016-06-01 18:57:08 -04:00
}
}
func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, reader io.Reader, writer io.Writer, dest v2net.Destination, dispatcher dispatcher.Interface) error {
if len(request.URL.Host) <= 0 {
response := generateResponse(400, "Bad Request")
return response.Write(writer)
}
request.Host = request.URL.Host
2016-02-20 17:27:06 -05:00
StripHopByHopHeaders(request)
ray, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return err
}
2016-12-29 18:51:39 -05:00
input := ray.InboundInput()
output := ray.InboundOutput()
2017-01-28 17:34:55 -05:00
defer input.Close()
2016-12-29 18:51:39 -05:00
2016-12-29 18:32:20 -05:00
requestDone := signal.ExecuteAsync(func() error {
2017-02-15 16:51:01 -05:00
requestWriter := buf.NewBufferedWriter(buf.ToBytesWriter(ray.InboundInput()))
err := request.Write(requestWriter)
if err != nil {
2016-12-29 18:32:20 -05:00
return err
}
2016-12-29 18:32:20 -05:00
if err := requestWriter.Flush(); err != nil {
return err
}
return nil
})
responseDone := signal.ExecuteAsync(func() error {
2017-02-15 16:51:01 -05:00
responseReader := bufio.NewReader(buf.ToBytesReader(ray.InboundOutput()))
response, err := http.ReadResponse(responseReader, request)
if err != nil {
log.Warning("HTTP: Failed to read response: ", err)
response = generateResponse(503, "Service Unavailable")
}
2017-02-15 16:51:01 -05:00
responseWriter := buf.NewBufferedWriter(writer)
2016-12-29 18:32:20 -05:00
if err := response.Write(responseWriter); err != nil {
return err
}
if err := responseWriter.Flush(); err != nil {
return err
}
2016-12-29 18:32:20 -05:00
return nil
})
if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
2017-01-10 08:22:42 -05:00
input.CloseError()
output.CloseError()
2017-02-21 16:15:20 -05:00
return errors.Base(err).Message("HTTP|Server: Connection ends.")
2016-12-29 18:32:20 -05:00
}
return nil
2015-10-28 07:13:27 -04:00
}
2016-05-07 08:08:27 -04:00
func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewServer(ctx, config.(*ServerConfig))
}))
2016-05-07 08:08:27 -04:00
}