v2ray-core/proxy/http/server.go

317 lines
8.5 KiB
Go
Raw Normal View History

2015-10-28 11:13:27 +00:00
package http
import (
2017-02-15 21:51:01 +00:00
"bufio"
2017-01-14 23:57:06 +00:00
"context"
2017-10-28 12:25:22 +00:00
"encoding/base64"
2015-12-15 15:00:47 +00:00
"io"
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"
2017-01-31 11:42:05 +00:00
"time"
2015-10-28 11:13:27 +00:00
"v2ray.com/core"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common"
2016-12-09 12:17:34 +00:00
"v2ray.com/core/common/buf"
2016-12-04 08:10:47 +00:00
"v2ray.com/core/common/errors"
2017-12-19 20:28:12 +00:00
"v2ray.com/core/common/log"
"v2ray.com/core/common/net"
http_proto "v2ray.com/core/common/protocol/http"
2016-12-29 23:32:20 +00:00
"v2ray.com/core/common/signal"
2016-08-20 18:55:45 +00:00
"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 {
config *ServerConfig
v *core.Instance
2015-10-28 11:13:27 +00:00
}
2016-12-22 12:54:11 +00:00
// NewServer creates a new HTTP inbound handler.
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
2017-01-06 14:32:36 +00:00
s := &Server{
config: config,
v: core.FromContext(ctx),
2015-10-28 11:13:27 +00:00
}
if s.v == nil {
return nil, newError("V is not in context.")
}
return s, nil
2015-10-28 11:13:27 +00:00
}
func (s *Server) policy() core.Policy {
config := s.config
p := s.v.PolicyManager().ForLevel(config.UserLevel)
if config.Timeout > 0 && config.UserLevel == 0 {
p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second
}
return p
}
func (*Server) Network() net.NetworkList {
return net.NetworkList{
Network: []net.Network{net.Network_TCP},
2017-01-14 23:57:06 +00:00
}
}
func parseHost(rawHost string, defaultPort net.Port) (net.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 {
return net.Destination{}, err
2015-12-14 23:53:40 +00:00
}
2017-11-03 12:03:51 +00:00
} else if len(rawPort) > 0 {
2015-12-15 15:00:47 +00:00
intPort, err := strconv.Atoi(rawPort)
if err != nil {
return net.Destination{}, err
2015-12-15 15:00:47 +00:00
}
port = net.Port(intPort)
2015-12-14 16:26:29 +00:00
}
2015-12-15 15:00:47 +00:00
return net.TCPDestination(net.ParseAddress(host), port), nil
2015-12-14 16:26:29 +00:00
}
2017-04-11 22:21:46 +00:00
func isTimeout(err error) bool {
2017-11-16 11:01:42 +00:00
nerr, ok := errors.Cause(err).(net.Error)
2017-04-11 22:21:46 +00:00
return ok && nerr.Timeout()
}
2017-10-28 12:25:22 +00:00
func parseBasicAuth(auth string) (username, password string, ok bool) {
const prefix = "Basic "
if !strings.HasPrefix(auth, prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
2017-11-24 22:24:12 +00:00
type readerOnly struct {
io.Reader
}
func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher core.Dispatcher) error {
2017-11-24 22:24:12 +00:00
reader := bufio.NewReaderSize(readerOnly{conn}, buf.Size)
Start:
conn.SetReadDeadline(time.Now().Add(s.policy().Timeouts.Handshake))
request, err := http.ReadRequest(reader)
if err != nil {
trace := newError("failed to read http request").Base(err)
2017-04-11 22:21:46 +00:00
if errors.Cause(err) != io.EOF && !isTimeout(errors.Cause(err)) {
trace.AtWarning()
2016-06-03 18:21:46 +00:00
}
return trace
}
2017-10-26 19:44:13 +00:00
2017-12-05 22:49:16 +00:00
if len(s.config.Accounts) > 0 {
2017-10-28 12:25:22 +00:00
user, pass, ok := parseBasicAuth(request.Header.Get("Proxy-Authorization"))
2017-12-02 09:07:42 +00:00
if !ok || !s.config.HasAccount(user, pass) {
2017-12-05 22:49:16 +00:00
_, err := conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"proxy\"\r\n\r\n"))
2017-10-26 19:44:13 +00:00
return err
}
}
2017-12-19 20:28:12 +00:00
newError("request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]").WriteToLog()
conn.SetReadDeadline(time.Time{})
2017-01-31 15:49:59 +00:00
defaultPort := net.Port(80)
if strings.ToLower(request.URL.Scheme) == "https" {
defaultPort = net.Port(443)
}
host := request.Host
if len(host) == 0 {
host = request.URL.Host
}
dest, err := parseHost(host, defaultPort)
if err != nil {
2017-04-08 23:43:25 +00:00
return newError("malformed proxy host: ", host).AtWarning().Base(err)
}
2017-12-19 20:28:12 +00:00
log.Record(&log.AccessMessage{
From: conn.RemoteAddr(),
To: request.URL,
Status: log.AccessAccepted,
})
if strings.ToUpper(request.Method) == "CONNECT" {
return s.handleConnect(ctx, request, reader, conn, dest, dispatcher)
2015-12-16 14:52:40 +00:00
}
keepAlive := (strings.TrimSpace(strings.ToLower(request.Header.Get("Proxy-Connection"))) == "keep-alive")
2017-11-17 19:54:24 +00:00
err = s.handlePlainHTTP(ctx, request, conn, dest, dispatcher)
if err == errWaitAnother {
if keepAlive {
goto Start
}
err = nil
}
return err
2015-12-16 14:52:40 +00:00
}
2015-12-15 21:13:09 +00:00
func (s *Server) handleConnect(ctx context.Context, request *http.Request, reader *bufio.Reader, conn internet.Connection, dest net.Destination, dispatcher core.Dispatcher) error {
2017-11-17 19:54:24 +00:00
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
2017-04-18 11:30:26 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return newError("failed to write back OK response").Base(err)
2016-12-22 12:54:11 +00:00
}
2015-12-15 15:00:47 +00:00
2017-11-14 23:36:14 +00:00
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, s.policy().Timeouts.ConnectionIdle)
ray, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return err
}
2015-12-15 15:00:47 +00:00
2017-11-17 19:54:24 +00:00
if reader.Buffered() > 0 {
payload := buf.New()
common.Must(payload.Reset(func(b []byte) (int, error) {
2017-11-26 14:13:33 +00:00
return reader.Read(b[:reader.Buffered()])
2017-11-17 19:54:24 +00:00
}))
if err := ray.InboundInput().WriteMultiBuffer(buf.NewMultiBufferValue(payload)); err != nil {
return err
}
2017-11-17 19:58:46 +00:00
reader = nil
2017-11-17 19:54:24 +00:00
}
2016-12-29 23:32:20 +00:00
requestDone := signal.ExecuteAsync(func() error {
defer ray.InboundInput().Close()
defer timer.SetTimeout(s.policy().Timeouts.DownlinkOnly)
2015-12-15 15:00:47 +00:00
2017-11-17 19:54:24 +00:00
v2reader := buf.NewReader(conn)
2017-11-17 20:02:32 +00:00
return buf.Copy(v2reader, ray.InboundInput(), buf.UpdateActivity(timer))
2016-12-29 23:32:20 +00:00
})
2015-12-15 15:00:47 +00:00
2016-12-29 23:32:20 +00:00
responseDone := signal.ExecuteAsync(func() error {
2017-11-17 19:54:24 +00:00
v2writer := buf.NewWriter(conn)
2017-04-27 20:30:48 +00:00
if err := buf.Copy(ray.InboundOutput(), v2writer, buf.UpdateActivity(timer)); err != nil {
2016-12-29 23:32:20 +00:00
return err
2016-11-21 23:17:49 +00:00
}
timer.SetTimeout(s.policy().Timeouts.UplinkOnly)
2016-12-29 23:32:20 +00:00
return nil
})
if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
2017-01-10 13:22:42 +00:00
ray.InboundInput().CloseError()
ray.InboundOutput().CloseError()
2017-04-08 23:43:25 +00:00
return newError("connection ends").Base(err)
2017-01-10 13:22:42 +00:00
}
return nil
}
2015-12-15 15:00:47 +00:00
var errWaitAnother = newError("keep alive")
2016-06-01 22:57:08 +00:00
func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, writer io.Writer, dest net.Destination, dispatcher core.Dispatcher) error {
2017-11-05 21:13:15 +00:00
if !s.config.AllowTransparent && len(request.URL.Host) <= 0 {
// RFC 2068 (HTTP/1.1) requires URL to be absolute URL in HTTP proxy.
response := &http.Response{
Status: "Bad Request",
StatusCode: 400,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: http.Header(make(map[string][]string)),
Body: nil,
ContentLength: 0,
Close: true,
}
response.Header.Set("Proxy-Connection", "close")
response.Header.Set("Connection", "close")
return response.Write(writer)
}
2017-11-05 21:13:15 +00:00
if len(request.URL.Host) > 0 {
request.Host = request.URL.Host
}
http_proto.RemoveHopByHopHeaders(request.Header)
// Prevent UA from being set to golang's default ones
if len(request.Header.Get("User-Agent")) == 0 {
request.Header.Set("User-Agent", "")
}
ray, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return err
}
2016-12-29 23:51:39 +00:00
input := ray.InboundInput()
output := ray.InboundOutput()
2017-01-28 22:34:55 +00:00
defer input.Close()
2016-12-29 23:51:39 +00:00
var result error = errWaitAnother
2016-12-29 23:32:20 +00:00
requestDone := signal.ExecuteAsync(func() error {
request.Header.Set("Connection", "close")
2017-11-09 21:33:15 +00:00
requestWriter := buf.NewBufferedWriter(ray.InboundInput())
2017-11-15 10:23:25 +00:00
common.Must(requestWriter.SetBuffered(false))
if err := request.Write(requestWriter); err != nil {
return newError("failed to write whole request").Base(err).AtWarning()
}
return nil
2016-12-29 23:32:20 +00:00
})
responseDone := signal.ExecuteAsync(func() error {
2017-11-20 10:27:33 +00:00
responseReader := bufio.NewReaderSize(buf.NewBufferedReader(ray.InboundOutput()), buf.Size)
response, err := http.ReadResponse(responseReader, request)
if err == nil {
http_proto.RemoveHopByHopHeaders(response.Header)
if response.ContentLength >= 0 {
response.Header.Set("Proxy-Connection", "keep-alive")
response.Header.Set("Connection", "keep-alive")
response.Header.Set("Keep-Alive", "timeout=4")
response.Close = false
} else {
response.Close = true
result = nil
}
} else {
2017-12-19 20:28:12 +00:00
newError("failed to read response from ", request.Host).Base(err).AtWarning().WriteToLog()
response = &http.Response{
Status: "Service Unavailable",
StatusCode: 503,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: http.Header(make(map[string][]string)),
Body: nil,
ContentLength: 0,
Close: true,
}
response.Header.Set("Connection", "close")
response.Header.Set("Proxy-Connection", "close")
}
2017-04-17 20:35:20 +00:00
if err := response.Write(writer); err != nil {
return newError("failed to write response").Base(err).AtWarning()
}
2016-12-29 23:32:20 +00:00
return nil
})
if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
2017-01-10 13:22:42 +00:00
input.CloseError()
output.CloseError()
2017-04-08 23:43:25 +00:00
return newError("connection ends").Base(err)
2016-12-29 23:32:20 +00:00
}
return result
2015-10-28 11:13:27 +00:00
}
2016-05-07 12:08:27 +00: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 12:08:27 +00:00
}