1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-04 17:27:23 -05:00
v2fly/proxy/shadowsocks/shadowsocks.go

232 lines
6.3 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"
"github.com/v2ray/v2ray-core/app"
2016-01-31 11:01:28 -05:00
"github.com/v2ray/v2ray-core/app/dispatcher"
2016-01-28 06:33:58 -05:00
"github.com/v2ray/v2ray-core/common/alloc"
2016-01-29 08:39:55 -05:00
v2io "github.com/v2ray/v2ray-core/common/io"
"github.com/v2ray/v2ray-core/common/log"
2016-01-27 06:46:40 -05:00
v2net "github.com/v2ray/v2ray-core/common/net"
2016-01-30 16:57:20 -05:00
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/proxy"
2016-01-28 06:33:58 -05:00
"github.com/v2ray/v2ray-core/proxy/internal"
2016-01-28 11:08:32 -05:00
"github.com/v2ray/v2ray-core/transport/hub"
2016-01-27 06:46:40 -05:00
)
type Shadowsocks struct {
2016-01-31 11:01:28 -05:00
packetDispatcher dispatcher.PacketDispatcher
config *Config
port v2net.Port
accepting bool
tcpHub *hub.TCPHub
udpHub *hub.UDPHub
}
func NewShadowsocks(config *Config, packetDispatcher dispatcher.PacketDispatcher) *Shadowsocks {
return &Shadowsocks{
config: config,
packetDispatcher: packetDispatcher,
}
2016-01-27 06:46:40 -05:00
}
func (this *Shadowsocks) Port() v2net.Port {
return this.port
}
func (this *Shadowsocks) 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-01-27 06:46:40 -05:00
func (this *Shadowsocks) Listen(port v2net.Port) error {
if this.accepting {
if this.port == port {
return nil
} else {
return proxy.ErrorAlreadyListening
}
}
2016-01-28 15:30:05 -05:00
this.accepting = true
2016-01-28 15:30:05 -05:00
tcpHub, err := hub.ListenTCP(port, this.handleConnection)
if err != nil {
2016-01-28 15:30:05 -05:00
log.Error("Shadowsocks: Failed to listen TCP on port ", port, ": ", err)
return err
}
2016-01-28 15:30:05 -05:00
this.tcpHub = tcpHub
if this.config.UDP {
udpHub, err := hub.ListenUDP(port, this.handlerUDPPayload)
if err != nil {
log.Error("Shadowsocks: Failed to listen UDP on port ", port, ": ", err)
}
this.udpHub = udpHub
}
2016-01-27 06:46:40 -05:00
return nil
}
2016-01-30 16:36:28 -05:00
func (this *Shadowsocks) handlerUDPPayload(payload *alloc.Buffer, source v2net.Destination) {
2016-01-28 15:30:05 -05:00
defer payload.Release()
iv := payload.Value[:this.config.Cipher.IVSize()]
key := this.config.Key
payload.SliceFrom(this.config.Cipher.IVSize())
reader, err := this.config.Cipher.NewDecodingStream(key, iv, payload)
if err != nil {
log.Error("Shadowsocks: Failed to create decoding stream: ", err)
return
}
2016-01-29 15:55:42 -05:00
request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)), true)
2016-01-28 15:30:05 -05:00
if err != nil {
2016-01-30 16:57:20 -05:00
log.Access(source, serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
log.Warning("Shadowsocks: Invalid request from ", source, ": ", err)
2016-01-28 15:30:05 -05:00
return
}
2016-01-30 16:36:28 -05:00
dest := v2net.UDPDestination(request.Address, request.Port)
2016-01-30 16:57:20 -05:00
log.Access(source, dest, log.AccessAccepted, serial.StringLiteral(""))
2016-01-30 16:36:28 -05:00
log.Info("Shadowsocks: Tunnelling request to ", dest)
2016-01-30 16:57:20 -05:00
2016-01-30 16:36:28 -05:00
packet := v2net.NewPacket(dest, request.UDPPayload, false)
2016-01-31 11:01:28 -05:00
ray := this.packetDispatcher.DispatchToOutbound(packet)
2016-01-28 15:30:05 -05:00
close(ray.InboundInput())
for respChunk := range ray.InboundOutput() {
response := alloc.NewBuffer().Slice(0, this.config.Cipher.IVSize())
rand.Read(response.Value)
respIv := response.Value
2016-01-28 15:30:05 -05:00
writer, err := this.config.Cipher.NewEncodingStream(key, respIv, response)
2016-01-28 15:30:05 -05:00
if err != nil {
log.Error("Shadowsocks: Failed to create encoding stream: ", err)
return
}
switch {
case request.Address.IsIPv4():
writer.Write([]byte{AddrTypeIPv4})
writer.Write(request.Address.IP())
case request.Address.IsIPv6():
writer.Write([]byte{AddrTypeIPv6})
writer.Write(request.Address.IP())
case request.Address.IsDomain():
writer.Write([]byte{AddrTypeDomain, byte(len(request.Address.Domain()))})
writer.Write([]byte(request.Address.Domain()))
}
writer.Write(request.Port.Bytes())
writer.Write(respChunk.Value)
respChunk.Release()
if request.OTA {
respAuth := NewAuthenticator(HeaderKeyGenerator(key, respIv))
2016-01-29 15:55:42 -05:00
respAuth.Authenticate(response.Value, response.Value[this.config.Cipher.IVSize():])
}
2016-01-30 16:36:28 -05:00
this.udpHub.WriteTo(response.Value, source)
2016-01-28 15:30:05 -05:00
response.Release()
}
}
2016-01-28 11:08:32 -05:00
func (this *Shadowsocks) handleConnection(conn *hub.TCPConn) {
defer conn.Close()
2016-01-28 06:33:58 -05:00
buffer := alloc.NewSmallBuffer()
defer buffer.Release()
_, err := io.ReadFull(conn, buffer.Value[:this.config.Cipher.IVSize()])
2016-01-28 06:33:58 -05:00
if err != nil {
2016-01-30 16:57:20 -05:00
log.Access(conn.RemoteAddr(), serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
2016-01-28 06:33:58 -05:00
log.Error("Shadowsocks: Failed to read IV: ", err)
return
}
iv := buffer.Value[:this.config.Cipher.IVSize()]
key := this.config.Key
reader, err := this.config.Cipher.NewDecodingStream(key, iv, conn)
if err != nil {
log.Error("Shadowsocks: Failed to create decoding stream: ", err)
return
}
2016-01-29 15:55:42 -05:00
request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(iv, key)), false)
2016-01-28 06:33:58 -05:00
if err != nil {
2016-01-30 16:57:20 -05:00
log.Access(conn.RemoteAddr(), serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
log.Warning("Shadowsocks: Invalid request from ", conn.RemoteAddr(), ": ", err)
2016-01-28 06:33:58 -05:00
return
}
2016-01-30 16:57:20 -05:00
dest := v2net.TCPDestination(request.Address, request.Port)
log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, serial.StringLiteral(""))
log.Info("Shadowsocks: Tunnelling request to ", dest)
packet := v2net.NewPacket(dest, nil, true)
2016-01-31 11:01:28 -05:00
ray := this.packetDispatcher.DispatchToOutbound(packet)
2016-01-28 06:33:58 -05:00
var writeFinish sync.Mutex
writeFinish.Lock()
go func() {
2016-01-31 15:37:00 -05:00
if payload, ok := <-ray.InboundOutput(); ok {
payload.SliceBack(16)
rand.Read(payload.Value[:16])
2016-01-28 07:40:00 -05:00
2016-01-31 15:37:00 -05:00
writer, err := this.config.Cipher.NewEncodingStream(key, payload.Value[:16], conn)
if err != nil {
log.Error("Shadowsocks: Failed to create encoding stream: ", err)
return
}
2016-01-28 07:40:00 -05:00
2016-01-31 15:37:00 -05:00
writer.Write(payload.Value)
2016-01-28 07:40:00 -05:00
payload.Release()
2016-01-29 08:39:55 -05:00
v2io.ChanToWriter(writer, ray.InboundOutput())
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)
}
v2io.ReaderToChan(ray.InboundInput(), payloadReader)
2016-01-28 06:33:58 -05:00
close(ray.InboundInput())
writeFinish.Lock()
}
func init() {
internal.MustRegisterInboundHandlerCreator("shadowsocks",
func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
2016-01-31 11:01:28 -05:00
if !space.HasApp(dispatcher.APP_ID) {
return nil, internal.ErrorBadConfiguration
}
return NewShadowsocks(
rawConfig.(*Config),
space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)), nil
2016-01-28 06:33:58 -05:00
})
}