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

348 lines
9.5 KiB
Go
Raw Normal View History

package inbound
2015-09-10 18:24:18 -04:00
2017-12-02 19:04:57 -05:00
//go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg inbound -path Proxy,VMess,Inbound
2017-04-08 19:43:25 -04:00
2015-09-10 18:24:18 -04:00
import (
2017-01-13 17:42:39 -05:00
"context"
2016-05-30 18:21:41 -04:00
"io"
2018-02-09 05:32:12 -05:00
"strings"
2017-02-13 07:10:43 -05:00
"sync"
2017-01-31 06:42:05 -05:00
"time"
"v2ray.com/core"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common"
2016-12-09 05:35:27 -05:00
"v2ray.com/core/common/buf"
2016-12-04 03:10:47 -05:00
"v2ray.com/core/common/errors"
2017-12-19 15:28:12 -05:00
"v2ray.com/core/common/log"
2017-01-13 17:42:39 -05:00
"v2ray.com/core/common/net"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common/protocol"
2016-12-15 05:51:09 -05:00
"v2ray.com/core/common/serial"
2016-12-29 16:17:12 -05:00
"v2ray.com/core/common/signal"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common/uuid"
"v2ray.com/core/proxy/vmess"
"v2ray.com/core/proxy/vmess/encoding"
"v2ray.com/core/transport/internet"
2018-04-16 18:31:10 -04:00
"v2ray.com/core/transport/pipe"
2015-09-10 18:24:18 -04:00
)
2016-02-25 08:38:41 -05:00
type userByEmail struct {
2018-02-09 05:32:12 -05:00
sync.Mutex
2016-05-07 14:26:29 -04:00
cache map[string]*protocol.User
2016-09-17 18:41:21 -04:00
defaultLevel uint32
2016-02-25 08:38:41 -05:00
defaultAlterIDs uint16
}
2018-02-09 05:43:23 -05:00
func newUserByEmail(config *DefaultConfig) *userByEmail {
2016-02-25 08:38:41 -05:00
return &userByEmail{
2018-02-09 05:43:23 -05:00
cache: make(map[string]*protocol.User),
2016-02-25 08:38:41 -05:00
defaultLevel: config.Level,
2016-09-24 17:11:58 -04:00
defaultAlterIDs: uint16(config.AlterId),
2016-02-25 08:38:41 -05:00
}
}
2018-02-09 05:32:12 -05:00
func (v *userByEmail) addNoLock(u *protocol.User) bool {
email := strings.ToLower(u.Email)
user, found := v.cache[email]
if found {
return false
}
v.cache[email] = user
return true
}
func (v *userByEmail) Add(u *protocol.User) bool {
v.Lock()
defer v.Unlock()
return v.addNoLock(u)
}
2016-11-27 15:39:09 -05:00
func (v *userByEmail) Get(email string) (*protocol.User, bool) {
2018-02-09 05:32:12 -05:00
email = strings.ToLower(email)
v.Lock()
defer v.Unlock()
user, found := v.cache[email]
2016-02-25 08:38:41 -05:00
if !found {
2018-02-09 05:32:12 -05:00
id := uuid.New()
account := &vmess.Account{
Id: id.String(),
AlterId: uint32(v.defaultAlterIDs),
}
user = &protocol.User{
Level: v.defaultLevel,
Email: email,
Account: serial.ToTypedMessage(account),
2016-02-25 08:38:41 -05:00
}
2018-02-09 05:32:12 -05:00
v.cache[email] = user
2016-02-25 08:38:41 -05:00
}
return user, found
}
2018-02-09 05:32:12 -05:00
func (v *userByEmail) Remove(email string) bool {
email = strings.ToLower(email)
v.Lock()
defer v.Unlock()
if _, found := v.cache[email]; !found {
return false
}
delete(v.cache, email)
return true
}
2017-02-13 07:16:37 -05:00
// Handler is an inbound connection handler that handles messages in VMess protocol.
type Handler struct {
policyManager core.PolicyManager
inboundHandlerManager core.InboundHandlerManager
clients *vmess.TimedUserValidator
2016-02-25 08:38:41 -05:00
usersByEmail *userByEmail
2016-06-01 16:45:12 -04:00
detours *DetourConfig
2017-02-12 10:53:23 -05:00
sessionHistory *encoding.SessionHistory
secure bool
2015-09-10 18:24:18 -04:00
}
2017-11-25 09:20:59 -05:00
// New creates a new VMess inbound handler.
2017-02-13 07:16:37 -05:00
func New(ctx context.Context, config *Config) (*Handler, error) {
2018-02-21 11:05:29 -05:00
v := core.MustFromContext(ctx)
handler := &Handler{
policyManager: v.PolicyManager(),
inboundHandlerManager: v.InboundHandlerManager(),
2018-02-08 09:39:46 -05:00
clients: vmess.NewTimedUserValidator(protocol.DefaultIDHash),
detours: config.Detour,
2018-02-09 05:43:23 -05:00
usersByEmail: newUserByEmail(config.GetDefaultValue()),
2018-02-07 10:35:22 -05:00
sessionHistory: encoding.NewSessionHistory(),
secure: config.SecureEncryptionOnly,
}
2018-01-31 07:23:23 -05:00
for _, user := range config.User {
if err := handler.AddUser(ctx, user); err != nil {
return nil, newError("failed to initiate user").Base(err)
}
}
return handler, nil
}
2018-02-08 09:39:46 -05:00
// Close implements common.Closable.
func (h *Handler) Close() error {
common.Close(h.clients)
common.Close(h.sessionHistory)
common.Close(h.usersByEmail)
return nil
}
2017-02-13 07:16:37 -05:00
// Network implements proxy.Inbound.Network().
func (*Handler) Network() net.NetworkList {
2017-01-14 18:57:06 -05:00
return net.NetworkList{
Network: []net.Network{net.Network_TCP},
}
}
2017-11-25 09:20:59 -05:00
func (h *Handler) GetUser(email string) *protocol.User {
user, existing := h.usersByEmail.Get(email)
2016-02-25 08:38:41 -05:00
if !existing {
2017-11-25 09:20:59 -05:00
h.clients.Add(user)
2016-02-25 08:38:41 -05:00
}
return user
2016-01-08 18:10:57 -05:00
}
2018-01-31 07:23:23 -05:00
func (h *Handler) AddUser(ctx context.Context, user *protocol.User) error {
2018-02-09 05:43:23 -05:00
if len(user.Email) > 0 && !h.usersByEmail.Add(user) {
2018-02-09 05:32:12 -05:00
return newError("User ", user.Email, " already exists.")
}
2018-01-31 07:23:23 -05:00
return h.clients.Add(user)
}
2018-02-05 17:38:24 -05:00
func (h *Handler) RemoveUser(ctx context.Context, email string) error {
2018-02-09 05:43:23 -05:00
if len(email) == 0 {
return newError("Email must not be empty.")
}
2018-02-09 05:32:12 -05:00
if !h.usersByEmail.Remove(email) {
return newError("User ", email, " not found.")
}
h.clients.Remove(email)
return nil
2018-02-05 17:38:24 -05:00
}
2018-04-16 18:31:10 -04:00
func transferRequest(timer signal.ActivityUpdater, session *encoding.ServerSession, request *protocol.RequestHeader, input io.Reader, output buf.Writer) error {
defer common.Close(output)
2016-12-29 16:17:12 -05:00
bodyReader := session.DecodeRequestBody(request, input)
2017-04-27 16:30:48 -04:00
if err := buf.Copy(bodyReader, output, buf.UpdateActivity(timer)); err != nil {
2017-09-19 17:27:49 -04:00
return newError("failed to transfer request").Base(err)
2016-12-29 16:17:12 -05:00
}
return nil
}
func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input buf.Reader, output io.Writer) error {
2016-12-29 16:17:12 -05:00
session.EncodeResponseHeader(response, output)
bodyWriter := session.EncodeResponseBody(request, output)
2018-03-28 16:23:24 -04:00
{
// Optimize for small response packet
data, err := input.ReadMultiBuffer()
if err != nil {
return err
}
2016-12-29 16:17:12 -05:00
2018-03-28 16:23:24 -04:00
if err := bodyWriter.WriteMultiBuffer(data); err != nil {
return err
}
2017-01-06 05:59:51 -05:00
}
2016-12-29 16:17:12 -05:00
2017-02-15 16:51:01 -05:00
if bufferedWriter, ok := output.(*buf.BufferedWriter); ok {
2017-01-06 05:59:51 -05:00
if err := bufferedWriter.SetBuffered(false); err != nil {
2016-12-29 16:17:12 -05:00
return err
}
}
2017-04-27 16:30:48 -04:00
if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
2017-01-06 05:59:51 -05:00
return err
}
2016-12-29 16:17:12 -05:00
if request.Option.Has(protocol.RequestOptionChunkStream) {
2017-11-09 16:33:15 -05:00
if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
2016-12-29 16:17:12 -05:00
return err
}
}
return nil
}
func isInecureEncryption(s protocol.SecurityType) bool {
return s == protocol.SecurityType_NONE || s == protocol.SecurityType_LEGACY || s == protocol.SecurityType_UNKNOWN
}
2017-02-13 07:16:37 -05:00
// Process implements proxy.Inbound.Process().
func (h *Handler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher core.Dispatcher) error {
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()
2017-05-30 11:33:41 -04:00
}
2017-05-23 19:35:05 -04:00
2018-04-20 18:54:53 -04:00
reader := &buf.BufferedReader{Reader: buf.NewReader(connection)}
2017-11-25 09:20:59 -05:00
session := encoding.NewServerSession(h.clients, h.sessionHistory)
2016-02-27 11:28:21 -05:00
request, err := session.DecodeRequestHeader(reader)
2015-09-10 18:24:18 -04:00
if err != nil {
2016-12-04 03:10:47 -05:00
if errors.Cause(err) != io.EOF {
2017-12-19 15:28:12 -05:00
log.Record(&log.AccessMessage{
From: connection.RemoteAddr(),
To: "",
Status: log.AccessRejected,
Reason: err,
})
2018-01-18 05:35:04 -05:00
err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo()
2016-05-30 18:21:41 -04:00
}
return err
2015-09-10 18:24:18 -04:00
}
2017-05-17 15:13:01 -04:00
if h.secure && isInecureEncryption(request.Security) {
log.Record(&log.AccessMessage{
From: connection.RemoteAddr(),
To: "",
Status: log.AccessRejected,
Reason: "Insecure encryption",
})
return newError("client is using insecure encryption: ", request.Security)
}
2018-04-04 15:32:54 -04:00
if request.Command != protocol.RequestCommandMux {
log.Record(&log.AccessMessage{
From: connection.RemoteAddr(),
To: request.Destination(),
Status: log.AccessAccepted,
Reason: "",
})
}
2017-12-19 15:28:12 -05:00
2018-02-22 09:26:00 -05:00
newError("received request for ", request.Destination()).WithContext(ctx).WriteToLog()
2015-09-10 18:24:18 -04:00
if err := connection.SetReadDeadline(time.Time{}); err != nil {
2018-02-22 09:26:00 -05:00
newError("unable to set back read deadline").Base(err).WithContext(ctx).WriteToLog()
}
2017-01-31 10:49:59 -05:00
sessionPolicy = h.policyManager.ForLevel(request.User.Level)
ctx = protocol.ContextWithUser(ctx, request.User)
2017-03-31 15:10:33 -04:00
2017-11-14 18:36:14 -05:00
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
2018-05-25 06:08:28 -04:00
ctx = core.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
2018-04-16 18:31:10 -04:00
link, err := dispatcher.Dispatch(ctx, request.Destination())
if err != nil {
2017-04-09 03:49:19 -04:00
return newError("failed to dispatch request to ", request.Destination()).Base(err)
}
2018-04-11 10:45:09 -04:00
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
2018-04-16 18:31:10 -04:00
return transferRequest(timer, session, request, reader, link.Writer)
2018-04-11 10:45:09 -04:00
}
2018-04-11 10:45:09 -04:00
responseDone := func() error {
2017-11-09 16:33:15 -05:00
writer := buf.NewBufferedWriter(buf.NewWriter(connection))
2017-05-23 19:35:05 -04:00
defer writer.Flush()
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
2017-05-23 19:35:05 -04:00
response := &protocol.ResponseHeader{
2017-11-25 09:20:59 -05:00
Command: h.generateCommand(ctx, request),
2017-05-23 19:35:05 -04:00
}
2018-04-16 18:31:10 -04:00
return transferResponse(timer, session, request, response, link.Reader, writer)
2018-04-11 10:45:09 -04:00
}
2016-05-12 20:20:07 -04:00
2018-04-11 10:45:09 -04:00
if err := signal.ExecuteParallel(ctx, requestDone, responseDone); err != nil {
2018-04-16 18:31:10 -04:00
pipe.CloseError(link.Reader)
pipe.CloseError(link.Writer)
2017-04-09 03:49:19 -04:00
return newError("connection ends").Base(err)
2016-06-10 19:37:33 -04:00
}
2015-09-18 06:31:42 -04:00
return nil
}
2017-11-25 09:20:59 -05:00
func (h *Handler) generateCommand(ctx context.Context, request *protocol.RequestHeader) protocol.ResponseCommand {
if h.detours != nil {
tag := h.detours.To
if h.inboundHandlerManager != nil {
handler, err := h.inboundHandlerManager.GetHandler(ctx, tag)
if err != nil {
2018-02-22 09:26:00 -05:00
newError("failed to get detour handler: ", tag).Base(err).AtWarning().WithContext(ctx).WriteToLog()
return nil
}
proxyHandler, port, availableMin := handler.GetRandomInboundProxy()
2017-02-13 07:16:37 -05:00
inboundHandler, ok := proxyHandler.(*Handler)
if ok && inboundHandler != nil {
if availableMin > 255 {
availableMin = 255
}
2018-02-22 09:26:00 -05:00
newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug().WithContext(ctx).WriteToLog()
user := inboundHandler.GetUser(request.User.Email)
if user == nil {
return nil
}
account, _ := user.GetTypedAccount()
return &protocol.CommandSwitchAccount{
Port: port,
ID: account.(*vmess.InternalAccount).ID.UUID(),
AlterIds: uint16(len(account.(*vmess.InternalAccount).AlterIDs)),
Level: user.Level,
ValidMin: byte(availableMin),
}
}
}
}
return nil
2015-09-10 18:24:18 -04:00
}
2016-06-14 16:54:08 -04:00
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
2015-09-10 18:24:18 -04:00
}