1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-28 14:56:33 -04:00
v2fly/proxy/shadowsocks/server.go

292 lines
7.8 KiB
Go
Raw Normal View History

2016-01-27 06:46:40 -05:00
// R.I.P Shadowsocks
package shadowsocks
import (
2016-01-28 07:40:00 -05:00
"crypto/rand"
"io"
2016-01-28 06:33:58 -05:00
"sync"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/app"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/common"
"v2ray.com/core/common/alloc"
"v2ray.com/core/common/crypto"
v2io "v2ray.com/core/common/io"
"v2ray.com/core/common/log"
v2net "v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/proxy"
"v2ray.com/core/proxy/registry"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/udp"
2016-01-27 06:46:40 -05:00
)
2016-05-12 13:42:08 -04:00
type Server struct {
2016-01-31 11:01:28 -05:00
packetDispatcher dispatcher.PacketDispatcher
config *Config
2016-09-17 18:41:21 -04:00
cipher Cipher
cipherKey []byte
2016-06-04 08:25:13 -04:00
meta *proxy.InboundHandlerMeta
2016-01-31 11:01:28 -05:00
accepting bool
2016-06-14 16:54:08 -04:00
tcpHub *internet.TCPHub
udpHub *udp.UDPHub
udpServer *udp.UDPServer
2016-01-31 11:01:28 -05:00
}
2016-09-17 18:41:21 -04:00
func NewServer(config *Config, space app.Space, meta *proxy.InboundHandlerMeta) (*Server, error) {
if config.GetUser() == nil {
return nil, protocol.ErrUserMissing
2016-01-31 11:01:28 -05:00
}
2016-09-17 18:41:21 -04:00
account := new(Account)
if _, err := config.GetUser().GetTypedAccount(account); err != nil {
return nil, err
}
cipher := config.GetCipher()
s := &Server{
config: config,
meta: meta,
cipher: cipher,
cipherKey: account.GetCipherKey(cipher.KeySize()),
}
space.InitializeApplication(func() error {
if !space.HasApp(dispatcher.APP_ID) {
return app.ErrMissingApplication
}
s.packetDispatcher = space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
return nil
})
return s, nil
2016-01-27 06:46:40 -05:00
}
2016-05-12 13:42:08 -04:00
func (this *Server) Port() v2net.Port {
2016-06-04 08:25:13 -04:00
return this.meta.Port
2016-01-27 06:46:40 -05:00
}
2016-05-12 13:42:08 -04:00
func (this *Server) Close() {
this.accepting = false
2016-01-30 16:50:36 -05:00
// TODO: synchronization
if this.tcpHub != nil {
this.tcpHub.Close()
this.tcpHub = nil
}
if this.udpHub != nil {
this.udpHub.Close()
this.udpHub = nil
}
2016-01-28 15:30:46 -05:00
}
2016-06-03 18:38:22 -04:00
func (this *Server) Start() error {
if this.accepting {
2016-06-03 18:38:22 -04:00
return nil
}
2016-06-14 16:54:08 -04:00
tcpHub, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.handleConnection, this.meta.StreamSettings)
if err != nil {
2016-06-04 08:25:13 -04:00
log.Error("Shadowsocks: Failed to listen TCP on ", this.meta.Address, ":", this.meta.Port, ": ", err)
return err
}
2016-01-28 15:30:05 -05:00
this.tcpHub = tcpHub
2016-09-17 18:41:21 -04:00
if this.config.UdpEnabled {
2016-08-12 17:37:21 -04:00
this.udpServer = udp.NewUDPServer(this.meta, this.packetDispatcher)
2016-08-15 11:44:46 -04:00
udpHub, err := udp.ListenUDP(this.meta.Address, this.meta.Port, udp.ListenOption{Callback: this.handlerUDPPayload})
2016-01-28 15:30:05 -05:00
if err != nil {
2016-06-04 08:25:13 -04:00
log.Error("Shadowsocks: Failed to listen UDP on ", this.meta.Address, ":", this.meta.Port, ": ", err)
2016-02-03 15:44:20 -05:00
return err
2016-01-28 15:30:05 -05:00
}
this.udpHub = udpHub
}
2016-02-16 08:35:24 -05:00
this.accepting = true
2016-01-27 06:46:40 -05:00
return nil
}
2016-08-15 11:44:46 -04:00
func (this *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) {
2016-01-28 15:30:05 -05:00
defer payload.Release()
2016-08-15 11:44:46 -04:00
source := session.Source
2016-09-17 18:41:21 -04:00
ivLen := this.cipher.IVSize()
2016-02-23 12:16:13 -05:00
iv := payload.Value[:ivLen]
payload.SliceFrom(ivLen)
2016-01-28 15:30:05 -05:00
2016-09-17 18:41:21 -04:00
stream, err := this.cipher.NewDecodingStream(this.cipherKey, iv)
2016-01-28 15:30:05 -05:00
if err != nil {
log.Error("Shadowsocks: Failed to create decoding stream: ", err)
return
}
2016-02-23 12:16:13 -05:00
reader := crypto.NewCryptionReader(stream, payload)
2016-09-17 18:41:21 -04:00
request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(this.cipherKey, iv)), true)
2016-01-28 15:30:05 -05:00
if err != nil {
2016-06-03 14:21:46 -04:00
if err != io.EOF {
log.Access(source, "", log.AccessRejected, err)
log.Warning("Shadowsocks: Invalid request from ", source, ": ", err)
}
2016-01-28 15:30:05 -05:00
return
}
2016-05-02 03:38:50 -04:00
//defer request.Release()
2016-01-28 15:30:05 -05:00
2016-01-30 16:36:28 -05:00
dest := v2net.UDPDestination(request.Address, request.Port)
2016-05-24 16:41:51 -04:00
log.Access(source, dest, log.AccessAccepted, "")
2016-01-30 16:36:28 -05:00
log.Info("Shadowsocks: Tunnelling request to ", dest)
2016-01-30 16:57:20 -05:00
2016-08-14 11:08:01 -04:00
this.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: dest}, request.DetachUDPPayload(), func(destination v2net.Destination, payload *alloc.Buffer) {
2016-04-25 18:13:26 -04:00
defer payload.Release()
2016-01-28 15:30:05 -05:00
2016-02-23 12:16:13 -05:00
response := alloc.NewBuffer().Slice(0, ivLen)
2016-02-01 15:34:07 -05:00
defer response.Release()
2016-01-28 15:30:05 -05:00
rand.Read(response.Value)
respIv := response.Value
2016-01-28 15:30:05 -05:00
2016-09-17 18:41:21 -04:00
stream, err := this.cipher.NewEncodingStream(this.cipherKey, respIv)
2016-01-28 15:30:05 -05:00
if err != nil {
log.Error("Shadowsocks: Failed to create encoding stream: ", err)
return
}
2016-02-23 12:16:13 -05:00
writer := crypto.NewCryptionWriter(stream, response)
2016-08-14 12:14:12 -04:00
switch request.Address.Family() {
case v2net.AddressFamilyIPv4:
2016-01-28 15:30:05 -05:00
writer.Write([]byte{AddrTypeIPv4})
writer.Write(request.Address.IP())
2016-08-14 12:14:12 -04:00
case v2net.AddressFamilyIPv6:
2016-01-28 15:30:05 -05:00
writer.Write([]byte{AddrTypeIPv6})
writer.Write(request.Address.IP())
2016-08-14 12:14:12 -04:00
case v2net.AddressFamilyDomain:
2016-01-28 15:30:05 -05:00
writer.Write([]byte{AddrTypeDomain, byte(len(request.Address.Domain()))})
writer.Write([]byte(request.Address.Domain()))
}
2016-06-26 16:34:48 -04:00
writer.Write(request.Port.Bytes(nil))
2016-04-25 18:13:26 -04:00
writer.Write(payload.Value)
2016-01-28 15:30:05 -05:00
if request.OTA {
2016-09-17 18:41:21 -04:00
respAuth := NewAuthenticator(HeaderKeyGenerator(this.cipherKey, respIv))
2016-02-23 12:16:13 -05:00
respAuth.Authenticate(response.Value, response.Value[ivLen:])
}
2016-01-30 16:36:28 -05:00
this.udpHub.WriteTo(response.Value, source)
2016-02-01 15:34:07 -05:00
})
2016-01-28 15:30:05 -05:00
}
2016-06-14 16:54:08 -04:00
func (this *Server) handleConnection(conn internet.Connection) {
defer conn.Close()
2016-01-28 06:33:58 -05:00
buffer := alloc.NewSmallBuffer()
defer buffer.Release()
timedReader := v2net.NewTimeOutReader(16, conn)
2016-05-01 11:18:02 -04:00
defer timedReader.Release()
bufferedReader := v2io.NewBufferedReader(timedReader)
defer bufferedReader.Release()
2016-09-17 18:41:21 -04:00
ivLen := this.cipher.IVSize()
2016-05-01 11:18:02 -04:00
_, err := io.ReadFull(bufferedReader, buffer.Value[:ivLen])
2016-01-28 06:33:58 -05:00
if err != nil {
2016-06-03 14:21:46 -04:00
if err != io.EOF {
log.Access(conn.RemoteAddr(), "", log.AccessRejected, err)
log.Warning("Shadowsocks: Failed to read IV: ", err)
}
2016-01-28 06:33:58 -05:00
return
}
2016-02-23 12:16:13 -05:00
iv := buffer.Value[:ivLen]
2016-01-28 06:33:58 -05:00
2016-09-17 18:41:21 -04:00
stream, err := this.cipher.NewDecodingStream(this.cipherKey, iv)
2016-01-28 06:33:58 -05:00
if err != nil {
log.Error("Shadowsocks: Failed to create decoding stream: ", err)
return
}
2016-05-01 11:18:02 -04:00
reader := crypto.NewCryptionReader(stream, bufferedReader)
2016-02-23 12:16:13 -05:00
2016-09-17 18:41:21 -04:00
request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(this.cipherKey, iv)), false)
2016-01-28 06:33:58 -05:00
if err != nil {
2016-05-24 16:41:51 -04:00
log.Access(conn.RemoteAddr(), "", log.AccessRejected, err)
2016-01-30 16:57:20 -05:00
log.Warning("Shadowsocks: Invalid request from ", conn.RemoteAddr(), ": ", err)
2016-01-28 06:33:58 -05:00
return
}
2016-05-01 11:18:02 -04:00
defer request.Release()
bufferedReader.SetCached(false)
2016-01-28 06:33:58 -05:00
2016-09-17 18:41:21 -04:00
userSettings := this.config.GetUser().GetSettings()
2016-02-03 06:18:28 -05:00
timedReader.SetTimeOut(userSettings.PayloadReadTimeout)
2016-01-30 16:57:20 -05:00
dest := v2net.TCPDestination(request.Address, request.Port)
2016-05-24 16:41:51 -04:00
log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, "")
2016-01-30 16:57:20 -05:00
log.Info("Shadowsocks: Tunnelling request to ", dest)
2016-08-14 11:08:01 -04:00
ray := this.packetDispatcher.DispatchToOutbound(this.meta, &proxy.SessionInfo{
2016-08-14 17:20:23 -04:00
Source: v2net.DestinationFromAddr(conn.RemoteAddr()),
2016-08-14 11:08:01 -04:00
Destination: dest,
})
2016-05-07 03:53:15 -04:00
defer ray.InboundOutput().Release()
2016-01-28 06:33:58 -05:00
var writeFinish sync.Mutex
writeFinish.Lock()
go func() {
2016-04-18 12:44:10 -04:00
if payload, err := ray.InboundOutput().Read(); err == nil {
2016-02-23 12:16:13 -05:00
payload.SliceBack(ivLen)
rand.Read(payload.Value[:ivLen])
2016-01-28 07:40:00 -05:00
2016-09-17 18:41:21 -04:00
stream, err := this.cipher.NewEncodingStream(this.cipherKey, payload.Value[:ivLen])
2016-01-31 15:37:00 -05:00
if err != nil {
log.Error("Shadowsocks: Failed to create encoding stream: ", err)
return
}
2016-02-23 12:16:13 -05:00
stream.XORKeyStream(payload.Value[ivLen:], payload.Value[ivLen:])
2016-01-28 07:40:00 -05:00
2016-02-23 12:16:13 -05:00
conn.Write(payload.Value)
2016-01-28 07:40:00 -05:00
payload.Release()
2016-02-23 12:16:13 -05:00
writer := crypto.NewCryptionWriter(stream, conn)
v2writer := v2io.NewAdaptiveWriter(writer)
v2io.Pipe(ray.InboundOutput(), v2writer)
2016-05-01 11:18:02 -04:00
writer.Release()
v2writer.Release()
2016-01-28 07:40:00 -05:00
}
2016-01-28 06:33:58 -05:00
writeFinish.Unlock()
}()
var payloadReader v2io.Reader
if request.OTA {
payloadAuth := NewAuthenticator(ChunkKeyGenerator(iv))
2016-01-29 14:54:06 -05:00
payloadReader = NewChunkReader(reader, payloadAuth)
} else {
payloadReader = v2io.NewAdaptiveReader(reader)
}
2016-04-18 12:44:10 -04:00
v2io.Pipe(payloadReader, ray.InboundInput())
ray.InboundInput().Close()
2016-04-12 15:43:13 -04:00
payloadReader.Release()
2016-01-28 06:33:58 -05:00
writeFinish.Lock()
}
2016-06-14 16:54:08 -04:00
type ServerFactory struct{}
func (this *ServerFactory) StreamCapability() internet.StreamConnectionType {
return internet.StreamConnectionTypeRawTCP
}
func (this *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
if !space.HasApp(dispatcher.APP_ID) {
2016-08-18 02:21:20 -04:00
return nil, common.ErrBadConfiguration
2016-06-14 16:54:08 -04:00
}
2016-09-17 18:41:21 -04:00
return NewServer(rawConfig.(*Config), space, meta)
2016-06-14 16:54:08 -04:00
}
2016-01-28 06:33:58 -05:00
func init() {
registry.MustRegisterInboundHandlerCreator("shadowsocks", new(ServerFactory))
}