1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 01:57:12 -05:00
v2fly/proxy/vless/inbound/inbound.go

452 lines
14 KiB
Go
Raw Normal View History

2020-07-28 11:00:23 -04:00
package inbound
2021-02-16 15:31:50 -05:00
//go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
2020-07-28 11:00:23 -04:00
import (
"context"
"io"
"strconv"
"time"
2021-02-16 15:31:50 -05:00
core "github.com/v2fly/v2ray-core/v4"
"github.com/v2fly/v2ray-core/v4/common"
"github.com/v2fly/v2ray-core/v4/common/buf"
"github.com/v2fly/v2ray-core/v4/common/errors"
"github.com/v2fly/v2ray-core/v4/common/log"
"github.com/v2fly/v2ray-core/v4/common/net"
"github.com/v2fly/v2ray-core/v4/common/protocol"
"github.com/v2fly/v2ray-core/v4/common/retry"
2021-09-05 10:59:42 -04:00
"github.com/v2fly/v2ray-core/v4/common/serial"
2021-02-16 15:31:50 -05:00
"github.com/v2fly/v2ray-core/v4/common/session"
"github.com/v2fly/v2ray-core/v4/common/signal"
"github.com/v2fly/v2ray-core/v4/common/task"
"github.com/v2fly/v2ray-core/v4/features/dns"
feature_inbound "github.com/v2fly/v2ray-core/v4/features/inbound"
"github.com/v2fly/v2ray-core/v4/features/policy"
"github.com/v2fly/v2ray-core/v4/features/routing"
"github.com/v2fly/v2ray-core/v4/proxy/vless"
"github.com/v2fly/v2ray-core/v4/proxy/vless/encoding"
"github.com/v2fly/v2ray-core/v4/transport/internet"
"github.com/v2fly/v2ray-core/v4/transport/internet/tls"
2020-07-28 11:00:23 -04:00
)
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
var dc dns.Client
if err := core.RequireFeatures(ctx, func(d dns.Client) error {
dc = d
return nil
}); err != nil {
return nil, err
}
return New(ctx, config.(*Config), dc)
}))
2021-09-05 10:59:42 -04:00
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedServer := config.(*SimplifiedConfig)
fullConfig := &Config{
Clients: func() (users []*protocol.User) {
for _, v := range simplifiedServer.Users {
account := &vless.Account{Id: v}
users = append(users, &protocol.User{
Account: serial.ToTypedMessage(account),
})
}
return
}(),
Decryption: "none",
2021-09-05 10:59:42 -04:00
}
return common.CreateObject(ctx, fullConfig)
2021-09-05 10:59:42 -04:00
}))
2020-07-28 11:00:23 -04:00
}
// Handler is an inbound connection handler that handles messages in VLess protocol.
type Handler struct {
inboundHandlerManager feature_inbound.Manager
policyManager policy.Manager
validator *vless.Validator
dns dns.Client
2020-08-28 03:51:09 -04:00
fallbacks map[string]map[string]*Fallback // or nil
// regexps map[string]*regexp.Regexp // or nil
2020-07-28 11:00:23 -04:00
}
// New creates a new VLess inbound handler.
func New(ctx context.Context, config *Config, dc dns.Client) (*Handler, error) {
v := core.MustFromContext(ctx)
handler := &Handler{
inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
validator: new(vless.Validator),
dns: dc,
}
2020-08-28 03:51:09 -04:00
for _, user := range config.Clients {
2020-07-28 11:00:23 -04:00
u, err := user.ToMemoryUser()
if err != nil {
return nil, newError("failed to get VLESS user").Base(err).AtError()
}
if err := handler.AddUser(ctx, u); err != nil {
return nil, newError("failed to initiate user").Base(err).AtError()
}
}
2020-08-28 03:51:09 -04:00
if config.Fallbacks != nil {
handler.fallbacks = make(map[string]map[string]*Fallback)
// handler.regexps = make(map[string]*regexp.Regexp)
2020-08-28 03:51:09 -04:00
for _, fb := range config.Fallbacks {
if handler.fallbacks[fb.Alpn] == nil {
handler.fallbacks[fb.Alpn] = make(map[string]*Fallback)
}
handler.fallbacks[fb.Alpn][fb.Path] = fb
/*
if fb.Path != "" {
if r, err := regexp.Compile(fb.Path); err != nil {
return nil, newError("invalid path regexp").Base(err).AtError()
} else {
handler.regexps[fb.Path] = r
}
}
*/
}
if handler.fallbacks[""] != nil {
for alpn, pfb := range handler.fallbacks {
if alpn != "" { // && alpn != "h2" {
for path, fb := range handler.fallbacks[""] {
if pfb[path] == nil {
pfb[path] = fb
}
}
}
}
}
2020-08-03 02:13:26 -04:00
}
2020-07-28 11:00:23 -04:00
return handler, nil
}
// Close implements common.Closable.Close().
func (h *Handler) Close() error {
return errors.Combine(common.Close(h.validator))
}
// AddUser implements proxy.UserManager.AddUser().
func (h *Handler) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
return h.validator.Add(u)
}
// RemoveUser implements proxy.UserManager.RemoveUser().
func (h *Handler) RemoveUser(ctx context.Context, e string) error {
return h.validator.Del(e)
}
// Network implements proxy.Inbound.Network().
func (*Handler) Network() []net.Network {
2020-10-29 03:30:38 -04:00
return []net.Network{net.Network_TCP, net.Network_UNIX}
2020-07-28 11:00:23 -04:00
}
// Process implements proxy.Inbound.Process().
func (h *Handler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher routing.Dispatcher) error {
2020-08-28 03:51:09 -04:00
sid := session.ExportIDToError(ctx)
2020-11-12 03:45:03 -05:00
2020-09-23 21:59:14 -04:00
iConn := connection
2020-11-12 03:45:03 -05:00
statConn, ok := iConn.(*internet.StatCouterConnection)
if ok {
2020-09-23 21:59:14 -04:00
iConn = statConn.Connection
}
2020-07-28 11:00:23 -04:00
sessionPolicy := h.policyManager.ForLevel(0)
if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
return newError("unable to set read deadline").Base(err).AtWarning()
}
first := buf.New()
2020-10-04 06:51:29 -04:00
defer first.Release()
2020-07-28 11:00:23 -04:00
2020-10-04 06:51:29 -04:00
firstLen, _ := first.ReadFrom(connection)
2020-08-28 03:51:09 -04:00
newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid)
2020-07-28 11:00:23 -04:00
reader := &buf.BufferedReader{
Reader: buf.NewReader(connection),
Buffer: buf.MultiBuffer{first},
}
var request *protocol.RequestHeader
var requestAddons *encoding.Addons
var err error
2020-08-28 03:51:09 -04:00
apfb := h.fallbacks
2020-10-04 06:51:29 -04:00
isfb := apfb != nil
2020-08-04 09:08:35 -04:00
2020-08-28 03:51:09 -04:00
if isfb && firstLen < 18 {
2020-07-28 11:00:23 -04:00
err = newError("fallback directly")
} else {
request, requestAddons, isfb, err = encoding.DecodeRequestHeader(isfb, first, reader, h.validator)
2020-07-28 11:00:23 -04:00
}
if err != nil {
2020-08-28 03:51:09 -04:00
if isfb {
if err := connection.SetReadDeadline(time.Time{}); err != nil {
newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
}
newError("fallback starts").Base(err).AtInfo().WriteToLog(sid)
alpn := ""
if len(apfb) > 1 || apfb[""] == nil {
2020-08-04 09:08:35 -04:00
if tlsConn, ok := iConn.(*tls.Conn); ok {
2020-08-28 03:51:09 -04:00
alpn = tlsConn.ConnectionState().NegotiatedProtocol
newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
2020-09-23 21:59:14 -04:00
}
if apfb[alpn] == nil {
alpn = ""
2020-08-04 09:08:35 -04:00
}
}
2020-08-28 03:51:09 -04:00
pfb := apfb[alpn]
if pfb == nil {
return newError(`failed to find the default "alpn" config`).AtWarning()
}
2020-08-04 09:08:35 -04:00
2020-08-28 03:51:09 -04:00
path := ""
if len(pfb) > 1 || pfb[""] == nil {
/*
if lines := bytes.Split(firstBytes, []byte{'\r', '\n'}); len(lines) > 1 {
if s := bytes.Split(lines[0], []byte{' '}); len(s) == 3 {
if len(s[0]) < 8 && len(s[1]) > 0 && len(s[2]) == 8 {
newError("realPath = " + string(s[1])).AtInfo().WriteToLog(sid)
for _, fb := range pfb {
if fb.Path != "" && h.regexps[fb.Path].Match(s[1]) {
path = fb.Path
break
}
}
}
}
}
*/
2020-10-02 23:23:24 -04:00
if firstLen >= 18 && first.Byte(4) != '*' { // not h2c
2020-08-28 03:51:09 -04:00
firstBytes := first.Bytes()
2020-10-02 23:23:24 -04:00
for i := 4; i <= 8; i++ { // 5 -> 9
2020-08-28 03:51:09 -04:00
if firstBytes[i] == '/' && firstBytes[i-1] == ' ' {
search := len(firstBytes)
if search > 64 {
2020-10-02 23:23:24 -04:00
search = 64 // up to about 60
2020-08-28 03:51:09 -04:00
}
for j := i + 1; j < search; j++ {
k := firstBytes[j]
if k == '\r' || k == '\n' { // avoid logging \r or \n
break
}
if k == ' ' {
path = string(firstBytes[i:j])
newError("realPath = " + path).AtInfo().WriteToLog(sid)
if pfb[path] == nil {
path = ""
}
break
}
}
break
}
}
}
}
fb := pfb[path]
if fb == nil {
return newError(`failed to find the default "path" config`).AtWarning()
2020-08-03 02:13:26 -04:00
}
2020-07-28 11:00:23 -04:00
2020-08-28 03:51:09 -04:00
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
2020-07-28 11:00:23 -04:00
var conn net.Conn
if err := retry.ExponentialBackoff(5, 100).On(func() error {
var dialer net.Dialer
2020-08-28 03:51:09 -04:00
conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest)
2020-07-28 11:00:23 -04:00
if err != nil {
return err
}
return nil
}); err != nil {
2020-09-07 04:39:53 -04:00
return newError("failed to dial to " + fb.Dest).Base(err).AtWarning()
2020-07-28 11:00:23 -04:00
}
defer conn.Close()
2020-07-28 11:00:23 -04:00
serverReader := buf.NewReader(conn)
serverWriter := buf.NewWriter(conn)
postRequest := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
2020-08-28 03:51:09 -04:00
if fb.Xver != 0 {
2020-08-03 02:13:26 -04:00
remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String())
if err != nil {
return err
}
localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String())
if err != nil {
return err
}
ipv4 := true
for i := 0; i < len(remoteAddr); i++ {
if remoteAddr[i] == ':' {
ipv4 = false
break
}
}
pro := buf.New()
2020-09-10 11:58:38 -04:00
defer pro.Release()
2020-08-28 03:51:09 -04:00
switch fb.Xver {
2020-08-03 02:13:26 -04:00
case 1:
if ipv4 {
pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
} else {
pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
}
2020-08-03 02:13:26 -04:00
case 2:
pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A\x21")) // signature + v2 + PROXY
if ipv4 {
pro.Write([]byte("\x11\x00\x0C")) // AF_INET + STREAM + 12 bytes
pro.Write(net.ParseIP(remoteAddr).To4())
pro.Write(net.ParseIP(localAddr).To4())
} else {
pro.Write([]byte("\x21\x00\x24")) // AF_INET6 + STREAM + 36 bytes
pro.Write(net.ParseIP(remoteAddr).To16())
pro.Write(net.ParseIP(localAddr).To16())
}
2020-09-23 21:59:14 -04:00
p1, _ := strconv.ParseUint(remotePort, 10, 16)
p2, _ := strconv.ParseUint(localPort, 10, 16)
pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)})
2020-08-03 02:13:26 -04:00
}
if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil {
2020-08-28 03:51:09 -04:00
return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
2020-08-03 02:13:26 -04:00
}
}
2020-07-28 11:00:23 -04:00
if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
2020-08-28 03:51:09 -04:00
return newError("failed to fallback request payload").Base(err).AtInfo()
2020-07-28 11:00:23 -04:00
}
return nil
}
2020-08-28 03:51:09 -04:00
writer := buf.NewWriter(connection)
2020-07-28 11:00:23 -04:00
getResponse := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil {
2020-08-28 03:51:09 -04:00
return newError("failed to deliver response payload").Base(err).AtInfo()
2020-07-28 11:00:23 -04:00
}
return nil
}
if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil {
common.Interrupt(serverReader)
common.Interrupt(serverWriter)
return newError("fallback ends").Base(err).AtInfo()
}
return nil
}
if errors.Cause(err) != io.EOF {
log.Record(&log.AccessMessage{
From: connection.RemoteAddr(),
To: "",
Status: log.AccessRejected,
Reason: err,
})
2020-10-13 00:53:34 -04:00
err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo()
2020-07-28 11:00:23 -04:00
}
return err
}
if err := connection.SetReadDeadline(time.Time{}); err != nil {
newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
}
2020-08-28 03:51:09 -04:00
newError("received request for ", request.Destination()).AtInfo().WriteToLog(sid)
2020-07-28 11:00:23 -04:00
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
}
inbound.User = request.User
responseAddons := &encoding.Addons{}
2020-09-23 21:59:14 -04:00
2020-08-28 03:51:09 -04:00
if request.Command != protocol.RequestCommandMux {
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: connection.RemoteAddr(),
To: request.Destination(),
Status: log.AccessAccepted,
Reason: "",
Email: request.User.Email,
})
}
2020-07-28 11:00:23 -04:00
2020-08-28 03:51:09 -04:00
sessionPolicy = h.policyManager.ForLevel(request.User.Level)
2020-07-28 11:00:23 -04:00
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
2020-08-28 03:51:09 -04:00
2020-07-28 11:00:23 -04:00
link, err := dispatcher.Dispatch(ctx, request.Destination())
if err != nil {
return newError("failed to dispatch request to ", request.Destination()).Base(err).AtWarning()
}
2020-09-23 21:59:14 -04:00
serverReader := link.Reader // .(*pipe.Reader)
serverWriter := link.Writer // .(*pipe.Writer)
2020-07-28 11:00:23 -04:00
postRequest := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
// default: clientReader := reader
clientReader := encoding.DecodeBodyAddons(reader, request, requestAddons)
// from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBufer
if err := buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer)); err != nil {
2020-07-28 11:00:23 -04:00
return newError("failed to transfer request payload").Base(err).AtInfo()
}
return nil
}
getResponse := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil {
return newError("failed to encode response header").Base(err).AtWarning()
}
// default: clientWriter := bufferWriter
clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, responseAddons)
{
multiBuffer, err := serverReader.ReadMultiBuffer()
if err != nil {
return err // ...
}
if err := clientWriter.WriteMultiBuffer(multiBuffer); err != nil {
return err // ...
}
}
// Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
if err := bufferWriter.SetBuffered(false); err != nil {
return newError("failed to write A response payload").Base(err).AtWarning()
}
// from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBufer
if err := buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transfer response payload").Base(err).AtInfo()
}
return nil
}
if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), getResponse); err != nil {
common.Interrupt(serverReader)
common.Interrupt(serverWriter)
return newError("connection ends").Base(err).AtInfo()
}
return nil
}