1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-27 01:45:23 +00:00
v2fly/proxy/vmess/inbound/inbound.go

283 lines
7.5 KiB
Go
Raw Normal View History

package inbound
2015-09-10 22:24:18 +00:00
import (
2017-01-13 22:42:39 +00:00
"context"
2016-05-30 22:21:41 +00:00
"io"
2015-09-23 12:14:53 +00:00
"sync"
2015-09-10 22:24:18 +00:00
2016-08-20 18:55:45 +00:00
"v2ray.com/core/app"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/proxyman"
"v2ray.com/core/common"
2016-12-09 10:35:27 +00:00
"v2ray.com/core/common/buf"
2016-12-09 12:17:34 +00:00
"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"
2017-01-13 22:42:39 +00:00
"v2ray.com/core/common/net"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/protocol"
2016-12-15 10:51:09 +00:00
"v2ray.com/core/common/serial"
2016-12-29 21:17:12 +00:00
"v2ray.com/core/common/signal"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/uuid"
"v2ray.com/core/proxy"
"v2ray.com/core/proxy/vmess"
"v2ray.com/core/proxy/vmess/encoding"
"v2ray.com/core/transport/internet"
2016-12-28 22:42:32 +00:00
"v2ray.com/core/transport/ray"
2015-09-10 22:24:18 +00:00
)
2016-02-25 13:38:41 +00:00
type userByEmail struct {
sync.RWMutex
2016-05-07 18:26:29 +00:00
cache map[string]*protocol.User
2016-09-17 22:41:21 +00:00
defaultLevel uint32
2016-02-25 13:38:41 +00:00
defaultAlterIDs uint16
}
2016-05-07 18:26:29 +00:00
func NewUserByEmail(users []*protocol.User, config *DefaultConfig) *userByEmail {
cache := make(map[string]*protocol.User)
2016-02-25 13:38:41 +00:00
for _, user := range users {
cache[user.Email] = user
}
return &userByEmail{
cache: cache,
defaultLevel: config.Level,
2016-09-24 21:11:58 +00:00
defaultAlterIDs: uint16(config.AlterId),
2016-02-25 13:38:41 +00:00
}
}
2016-11-27 20:39:09 +00:00
func (v *userByEmail) Get(email string) (*protocol.User, bool) {
2016-05-07 18:26:29 +00:00
var user *protocol.User
2016-02-25 13:38:41 +00:00
var found bool
2016-11-27 20:39:09 +00:00
v.RLock()
user, found = v.cache[email]
v.RUnlock()
2016-02-25 13:38:41 +00:00
if !found {
2016-11-27 20:39:09 +00:00
v.Lock()
user, found = v.cache[email]
2016-02-25 13:38:41 +00:00
if !found {
2016-10-12 16:43:55 +00:00
account := &vmess.Account{
2016-09-17 22:41:21 +00:00
Id: uuid.New().String(),
2016-11-27 20:39:09 +00:00
AlterId: uint32(v.defaultAlterIDs),
2016-09-17 22:41:21 +00:00
}
user = &protocol.User{
2016-11-27 20:39:09 +00:00
Level: v.defaultLevel,
2016-09-17 22:41:21 +00:00
Email: email,
2016-12-15 10:51:09 +00:00
Account: serial.ToTypedMessage(account),
2016-05-28 11:44:11 +00:00
}
2016-11-27 20:39:09 +00:00
v.cache[email] = user
2016-02-25 13:38:41 +00:00
}
2016-11-27 20:39:09 +00:00
v.Unlock()
2016-02-25 13:38:41 +00:00
}
return user, found
}
// Inbound connection handler that handles messages in VMess format.
2015-09-10 22:24:18 +00:00
type VMessInboundHandler struct {
sync.RWMutex
2017-01-13 12:53:44 +00:00
packetDispatcher dispatcher.Interface
2016-01-31 16:01:28 +00:00
inboundHandlerManager proxyman.InboundHandlerManager
2016-05-07 18:26:29 +00:00
clients protocol.UserValidator
2016-02-25 13:38:41 +00:00
usersByEmail *userByEmail
2016-06-01 20:45:12 +00:00
detours *DetourConfig
2015-09-10 22:24:18 +00:00
}
func New(ctx context.Context, config *Config) (*VMessInboundHandler, error) {
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, errors.New("VMess|Inbound: No space in context.")
}
allowedClients := vmess.NewTimedUserValidator(protocol.DefaultIDHash)
for _, user := range config.User {
allowedClients.Add(user)
}
handler := &VMessInboundHandler{
clients: allowedClients,
detours: config.Detour,
usersByEmail: NewUserByEmail(config.User, config.GetDefaultValue()),
}
space.OnInitialize(func() error {
handler.packetDispatcher = dispatcher.FromSpace(space)
if handler.packetDispatcher == nil {
return errors.New("VMess|Inbound: Dispatcher is not found in space.")
}
handler.inboundHandlerManager = proxyman.InboundHandlerManagerFromSpace(space)
if handler.inboundHandlerManager == nil {
return errors.New("VMess|Inbound: InboundHandlerManager is not found is space.")
}
return nil
})
return handler, nil
}
func (*VMessInboundHandler) Network() net.NetworkList {
2017-01-14 23:57:06 +00:00
return net.NetworkList{
Network: []net.Network{net.Network_TCP},
}
}
2016-11-27 20:39:09 +00:00
func (v *VMessInboundHandler) GetUser(email string) *protocol.User {
v.RLock()
defer v.RUnlock()
2016-11-27 20:39:09 +00:00
user, existing := v.usersByEmail.Get(email)
2016-02-25 13:38:41 +00:00
if !existing {
2016-11-27 20:39:09 +00:00
v.clients.Add(user)
2016-02-25 13:38:41 +00:00
}
return user
2016-01-08 23:10:57 +00:00
}
2016-12-29 21:17:12 +00:00
func transferRequest(session *encoding.ServerSession, request *protocol.RequestHeader, input io.Reader, output ray.OutputStream) error {
defer output.Close()
bodyReader := session.DecodeRequestBody(request, input)
if err := buf.PipeUntilEOF(bodyReader, output); err != nil {
return err
}
return nil
}
func transferResponse(session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input ray.InputStream, output io.Writer) error {
session.EncodeResponseHeader(response, output)
bodyWriter := session.EncodeResponseBody(request, output)
// Optimize for small response packet
2017-01-06 10:59:51 +00:00
data, err := input.Read()
if err != nil {
return err
}
2016-12-29 21:17:12 +00:00
2017-01-06 10:59:51 +00:00
if err := bodyWriter.Write(data); err != nil {
return err
}
data.Release()
2016-12-29 21:17:12 +00:00
2017-01-06 10:59:51 +00:00
if bufferedWriter, ok := output.(*bufio.BufferedWriter); ok {
if err := bufferedWriter.SetBuffered(false); err != nil {
2016-12-29 21:17:12 +00:00
return err
}
}
2017-01-06 10:59:51 +00:00
if err := buf.PipeUntilEOF(input, bodyWriter); err != nil {
return err
}
2016-12-29 21:17:12 +00:00
if request.Option.Has(protocol.RequestOptionChunkStream) {
if err := bodyWriter.Write(buf.NewLocal(8)); err != nil {
return err
}
}
return nil
}
func (v *VMessInboundHandler) Process(ctx context.Context, network net.Network, connection internet.Connection) error {
2017-01-13 22:42:39 +00:00
connReader := net.NewTimeOutReader(8, connection)
2016-12-09 12:17:34 +00:00
reader := bufio.NewReader(connReader)
2016-11-27 20:39:09 +00:00
session := encoding.NewServerSession(v.clients)
2016-02-27 16:28:21 +00:00
request, err := session.DecodeRequestHeader(reader)
2015-09-10 22:24:18 +00:00
if err != nil {
2016-12-04 08:10:47 +00:00
if errors.Cause(err) != io.EOF {
2016-05-30 22:21:41 +00:00
log.Access(connection.RemoteAddr(), "", log.AccessRejected, err)
2016-12-29 23:32:20 +00:00
log.Info("VMess|Inbound: Invalid request from ", connection.RemoteAddr(), ": ", err)
2016-05-30 22:21:41 +00:00
}
2016-06-05 23:20:20 +00:00
connection.SetReusable(false)
return err
2015-09-10 22:24:18 +00:00
}
2016-05-24 20:41:51 +00:00
log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, "")
2016-12-29 23:32:20 +00:00
log.Info("VMess|Inbound: Received request for ", request.Destination())
2015-09-10 22:24:18 +00:00
2016-06-14 20:54:08 +00:00
connection.SetReusable(request.Option.Has(protocol.RequestOptionConnectionReuse))
2016-05-30 22:21:41 +00:00
ctx = proxy.ContextWithDestination(ctx, request.Destination())
ctx = protocol.ContextWithUser(ctx, request.User)
ray := v.packetDispatcher.DispatchToOutbound(ctx)
input := ray.InboundInput()
output := ray.InboundOutput()
2016-05-07 07:53:15 +00:00
2016-09-17 22:41:21 +00:00
userSettings := request.User.GetSettings()
2015-10-31 08:39:45 +00:00
connReader.SetTimeOut(userSettings.PayloadReadTimeout)
2016-12-27 20:41:44 +00:00
reader.SetBuffered(false)
2016-06-02 19:34:25 +00:00
2016-12-29 21:17:12 +00:00
requestDone := signal.ExecuteAsync(func() error {
return transferRequest(session, request, reader, input)
2016-12-28 22:42:32 +00:00
})
2016-12-09 12:17:34 +00:00
writer := bufio.NewWriter(connection)
2016-05-07 18:26:29 +00:00
response := &protocol.ResponseHeader{
Command: v.generateCommand(ctx, request),
2016-02-27 16:28:21 +00:00
}
2015-11-03 20:26:16 +00:00
2016-06-14 20:54:08 +00:00
if connection.Reusable() {
2016-06-02 19:34:25 +00:00
response.Option.Set(protocol.ResponseOptionConnectionReuse)
}
2016-12-29 21:17:12 +00:00
responseDone := signal.ExecuteAsync(func() error {
return transferResponse(session, request, response, output, writer)
2016-12-28 22:42:32 +00:00
})
2016-05-13 00:20:07 +00:00
2016-12-29 23:32:20 +00:00
if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
log.Info("VMess|Inbound: Connection ending with ", err)
2016-12-28 22:42:32 +00:00
connection.SetReusable(false)
2017-01-10 13:22:42 +00:00
input.CloseError()
output.CloseError()
return err
2016-06-10 23:37:33 +00:00
}
2015-09-18 10:31:42 +00:00
2016-12-29 21:17:12 +00:00
if err := writer.Flush(); err != nil {
2016-12-29 23:32:20 +00:00
log.Info("VMess|Inbound: Failed to flush remain data: ", err)
2016-12-28 22:42:32 +00:00
connection.SetReusable(false)
return err
2016-12-28 22:42:32 +00:00
}
return nil
}
func (v *VMessInboundHandler) generateCommand(ctx context.Context, request *protocol.RequestHeader) protocol.ResponseCommand {
if v.detours != nil {
tag := v.detours.To
if v.inboundHandlerManager != nil {
handler, err := v.inboundHandlerManager.GetHandler(ctx, tag)
if err != nil {
log.Warning("VMess|Inbound: Failed to get detour handler: ", tag, err)
return nil
}
proxyHandler, port, availableMin := handler.GetRandomInboundProxy()
inboundHandler, ok := proxyHandler.(*VMessInboundHandler)
if ok {
if availableMin > 255 {
availableMin = 255
}
log.Info("VMessIn: Pick detour handler for port ", port, " for ", availableMin, " minutes.")
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 22:24:18 +00:00
}
2016-06-14 20:54:08 +00: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 22:24:18 +00:00
}