1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-14 08:15:55 -05:00
v2fly/proxy/shadowsocks/server.go

252 lines
7.1 KiB
Go
Raw Normal View History

2016-01-27 06:46:40 -05:00
package shadowsocks
import (
"context"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/log"
"github.com/v2fly/v2ray-core/v5/common/net"
2022-01-02 11:33:29 -05:00
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/protocol"
udp_proto "github.com/v2fly/v2ray-core/v5/common/protocol/udp"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
2016-01-27 06:46:40 -05:00
)
2016-05-12 13:42:08 -04:00
type Server struct {
2020-08-26 07:35:33 -04:00
config *ServerConfig
2018-10-21 04:27:13 -04:00
user *protocol.MemoryUser
policyManager policy.Manager
2016-01-31 11:01:28 -05:00
}
2017-04-07 16:45:07 -04:00
// NewServer create a new Shadowsocks server.
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
2016-09-17 18:41:21 -04:00
if config.GetUser() == nil {
2017-04-08 19:43:25 -04:00
return nil, newError("user is not specified")
2016-01-31 11:01:28 -05:00
}
2016-10-31 10:24:28 -04:00
2018-08-26 18:11:32 -04:00
mUser, err := config.User.ToMemoryUser()
2016-11-02 11:17:57 -04:00
if err != nil {
2018-08-26 18:11:32 -04:00
return nil, newError("failed to parse user account").Base(err)
2016-11-02 11:17:57 -04:00
}
2018-10-21 04:27:13 -04:00
v := core.MustFromContext(ctx)
2016-09-17 18:41:21 -04:00
s := &Server{
2020-08-26 07:35:33 -04:00
config: config,
2018-10-21 04:27:13 -04:00
user: mUser,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}
2017-11-27 16:09:30 -05:00
2016-09-17 18:41:21 -04:00
return s, nil
2016-01-27 06:46:40 -05:00
}
2018-11-20 10:58:26 -05:00
func (s *Server) Network() []net.Network {
list := s.config.Network
if len(list) == 0 {
list = append(list, net.Network_TCP)
2017-01-14 18:57:06 -05:00
}
if s.config.UdpEnabled {
2018-11-20 10:58:26 -05:00
list = append(list, net.Network_UDP)
2017-01-14 18:57:06 -05:00
}
return list
}
func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
switch network {
case net.Network_TCP:
return s.handleConnection(ctx, conn, dispatcher)
case net.Network_UDP:
return s.handlerUDPPayload(ctx, conn, dispatcher)
default:
2017-04-08 19:43:25 -04:00
return newError("unknown network: ", network)
}
}
func (s *Server) handlerUDPPayload(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
2021-12-30 17:20:10 -05:00
udpDispatcherConstructor := udp.NewSplitDispatcher
switch s.config.PacketEncoding {
case packetaddr.PacketAddrType_None:
break
case packetaddr.PacketAddrType_Packet:
packetAddrDispatcherFactory := udp.NewPacketAddrDispatcherCreator(ctx)
udpDispatcherConstructor = packetAddrDispatcherFactory.NewPacketAddrDispatcher
}
udpServer := udpDispatcherConstructor(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
request := protocol.RequestHeaderFromContext(ctx)
if request == nil {
2021-12-30 17:20:10 -05:00
request = &protocol.RequestHeader{
Port: packet.Source.Port,
Address: packet.Source.Address,
User: s.user,
}
}
2019-01-05 15:43:22 -05:00
payload := packet.Payload
data, err := EncodeUDPPacket(request, payload.Bytes())
payload.Release()
if err != nil {
newError("failed to encode UDP packet").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx))
return
}
defer data.Release()
conn.Write(data.Bytes())
})
2016-01-28 15:30:05 -05:00
2018-10-15 02:36:50 -04:00
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
}
inbound.User = s.user
2018-08-26 18:11:32 -04:00
2019-02-07 13:14:37 -05:00
reader := buf.NewPacketReader(conn)
for {
2017-11-09 16:33:15 -05:00
mpayload, err := reader.ReadMultiBuffer()
2016-01-28 15:30:05 -05:00
if err != nil {
break
2016-01-28 15:30:05 -05:00
}
2017-04-15 15:07:23 -04:00
for _, payload := range mpayload {
2017-09-19 17:27:49 -04:00
request, data, err := DecodeUDPPacket(s.user, payload)
2017-04-15 15:07:23 -04:00
if err != nil {
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
newError("dropping invalid UDP packet from: ", inbound.Source).Base(err).WriteToLog(session.ExportIDToError(ctx))
2017-12-19 15:28:12 -05:00
log.Record(&log.AccessMessage{
From: inbound.Source,
2017-12-19 15:28:12 -05:00
To: "",
Status: log.AccessRejected,
Reason: err,
})
2017-04-15 15:07:23 -04:00
}
payload.Release()
continue
2017-02-09 16:49:38 -05:00
}
currentPacketCtx := ctx
2017-04-15 15:07:23 -04:00
dest := request.Destination()
2018-10-15 02:36:50 -04:00
if inbound.Source.IsValid() {
currentPacketCtx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: inbound.Source,
2017-12-19 15:28:12 -05:00
To: dest,
Status: log.AccessAccepted,
Reason: "",
Email: request.User.Email,
2017-12-19 15:28:12 -05:00
})
2017-04-15 15:07:23 -04:00
}
newError("tunnelling request to ", dest).WriteToLog(session.ExportIDToError(currentPacketCtx))
2016-11-02 11:17:57 -04:00
currentPacketCtx = protocol.ContextWithRequestHeader(currentPacketCtx, request)
udpServer.Dispatch(currentPacketCtx, dest, data)
2017-04-15 15:07:23 -04:00
}
}
2016-01-28 15:30:05 -05:00
return nil
2016-01-28 15:30:05 -05:00
}
func (s *Server) handleConnection(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
2018-10-21 04:27:13 -04:00
sessionPolicy := s.policyManager.ForLevel(s.user.Level)
conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake))
bufferedReader := buf.BufferedReader{Reader: buf.NewReader(conn)}
2018-04-20 18:54:53 -04:00
request, bodyReader, err := ReadTCPSession(s.user, &bufferedReader)
2016-01-28 06:33:58 -05:00
if err != nil {
2017-12-19 15:28:12 -05:00
log.Record(&log.AccessMessage{
From: conn.RemoteAddr(),
To: "",
Status: log.AccessRejected,
Reason: err,
})
2017-04-08 19:43:25 -04:00
return newError("failed to create request from: ", conn.RemoteAddr()).Base(err)
2016-01-28 06:33:58 -05:00
}
2017-01-31 10:49:59 -05:00
conn.SetReadDeadline(time.Time{})
2016-10-31 10:24:28 -04:00
2018-10-15 02:36:50 -04:00
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
}
inbound.User = s.user
2016-10-31 10:24:28 -04:00
dest := request.Destination()
2019-06-12 01:04:34 -04:00
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
2017-12-19 15:28:12 -05:00
From: conn.RemoteAddr(),
To: dest,
Status: log.AccessAccepted,
Reason: "",
Email: request.User.Email,
2017-12-19 15:28:12 -05:00
})
newError("tunnelling request to ", dest).WriteToLog(session.ExportIDToError(ctx))
2016-01-30 16:57:20 -05: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
2018-10-11 16:34:31 -04:00
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
2018-04-16 18:31:10 -04:00
link, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return err
}
2016-01-28 06:33:58 -05:00
2018-04-11 10:45:09 -04:00
responseDone := func() error {
2018-02-23 11:07:45 -05:00
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
2017-11-09 16:33:15 -05:00
bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
2016-10-31 10:24:28 -04:00
responseWriter, err := WriteTCPResponse(request, bufferedWriter)
if err != nil {
2017-04-08 19:43:25 -04:00
return newError("failed to write response").Base(err)
2016-10-31 10:24:28 -04:00
}
2016-02-23 12:16:13 -05:00
2018-03-28 16:23:24 -04:00
{
2018-04-16 18:31:10 -04:00
payload, err := link.Reader.ReadMultiBuffer()
2018-03-28 16:23:24 -04:00
if err != nil {
return err
}
if err := responseWriter.WriteMultiBuffer(payload); err != nil {
return err
}
2017-01-06 05:40:49 -05:00
}
if err := bufferedWriter.SetBuffered(false); err != nil {
return err
}
2018-04-16 18:31:10 -04:00
if err := buf.Copy(link.Reader, responseWriter, buf.UpdateActivity(timer)); err != nil {
2017-04-08 19:43:25 -04:00
return newError("failed to transport all TCP response").Base(err)
2016-01-28 07:40:00 -05:00
}
2016-01-28 06:33:58 -05:00
2016-12-29 18:32:20 -05:00
return nil
2018-04-11 10:45:09 -04:00
}
2016-12-29 18:32:20 -05:00
2018-04-11 10:45:09 -04:00
requestDone := func() error {
2018-02-23 11:07:45 -05:00
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
2016-12-29 18:32:20 -05:00
2018-04-16 18:31:10 -04:00
if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
2017-04-08 19:43:25 -04:00
return newError("failed to transport all TCP request").Base(err)
2016-12-29 18:32:20 -05:00
}
2018-02-23 11:07:45 -05:00
2016-12-29 18:32:20 -05:00
return nil
2018-04-11 10:45:09 -04:00
}
2016-01-28 06:33:58 -05:00
2021-05-19 17:28:52 -04:00
requestDoneAndCloseWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
2018-12-06 05:35:02 -05:00
if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil {
2018-12-31 15:25:10 -05:00
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
2017-04-08 19:43:25 -04:00
return newError("connection ends").Base(err)
2016-12-29 18:32:20 -05:00
}
return nil
2016-01-28 06:33:58 -05:00
}
func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewServer(ctx, config.(*ServerConfig))
}))
2016-06-14 16:54:08 -04:00
}