func (this *AuthenticationWriter) Write(payload *alloc.Buffer) error { defer payload.Release() this.Authenticator.Seal(payload) _, err := this.Writer.Write(payload.Value) return err }
func (this *OutboundConnectionHandler) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { input := ray.OutboundInput() output := ray.OutboundOutput() this.Destination = destination if !payload.IsEmpty() { this.ConnOutput.Write(payload.Value) } payload.Release() writeFinish := &sync.Mutex{} writeFinish.Lock() go func() { v2writer := v2io.NewAdaptiveWriter(this.ConnOutput) defer v2writer.Release() v2io.Pipe(input, v2writer) writeFinish.Unlock() input.Release() }() writeFinish.Lock() v2reader := v2io.NewAdaptiveReader(this.ConnInput) defer v2reader.Release() v2io.Pipe(v2reader, output) output.Close() return nil }
func (this *FreedomConnection) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { log.Info("Freedom: Opening connection to ", destination) defer payload.Release() defer ray.OutboundInput().Release() defer ray.OutboundOutput().Close() var conn internet.Connection if this.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() { destination = this.ResolveIP(destination) } err := retry.ExponentialBackoff(5, 100).On(func() error { rawConn, err := internet.Dial(this.meta.Address, destination, this.meta.GetDialerOptions()) if err != nil { return err } conn = rawConn return nil }) if err != nil { log.Warning("Freedom: Failed to open connection to ", destination, ": ", err) return err } defer conn.Close() input := ray.OutboundInput() output := ray.OutboundOutput() if !payload.IsEmpty() { conn.Write(payload.Value) } go func() { v2writer := v2io.NewAdaptiveWriter(conn) defer v2writer.Release() v2io.Pipe(input, v2writer) if tcpConn, ok := conn.(*tcp.RawConnection); ok { tcpConn.CloseWrite() } }() var reader io.Reader = conn timeout := this.timeout if destination.Network == v2net.Network_UDP { timeout = 16 } if timeout > 0 { reader = v2net.NewTimeOutReader(timeout /* seconds */, conn) } v2reader := v2io.NewAdaptiveReader(reader) v2io.Pipe(v2reader, output) v2reader.Release() ray.OutboundOutput().Close() return nil }
func (this *DokodemoDoor) handleUDPResponse(dest v2net.Destination, payload *alloc.Buffer) { defer payload.Release() this.udpMutex.RLock() defer this.udpMutex.RUnlock() if !this.accepting { return } this.udpHub.WriteTo(payload.Value, dest) }
func (this *BlackHole) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { payload.Release() this.response.WriteTo(ray.OutboundOutput()) ray.OutboundOutput().Close() ray.OutboundInput().Release() return nil }
// Write implements Writer.Write(). Write() takes ownership of the given buffer. func (this *AdaptiveWriter) Write(buffer *alloc.Buffer) error { defer buffer.Release() for !buffer.IsEmpty() { nBytes, err := this.writer.Write(buffer.Value) if err != nil { return err } buffer.SliceFrom(nBytes) } return nil }
func (this *Listener) OnReceive(payload *alloc.Buffer, session *proxy.SessionInfo) { defer payload.Release() src := session.Source if valid := this.authenticator.Open(payload); !valid { log.Info("KCP|Listener: discarding invalid payload from ", src) return } if !this.running { return } this.Lock() defer this.Unlock() if !this.running { return } if payload.Len() < 4 { return } conv := serial.BytesToUint16(payload.Value) cmd := Command(payload.Value[2]) sourceId := src.NetAddr() + "|" + serial.Uint16ToString(conv) conn, found := this.sessions[sourceId] if !found { if cmd == CommandTerminate { return } log.Debug("KCP|Listener: Creating session with id(", sourceId, ") from ", src) writer := &Writer{ id: sourceId, hub: this.hub, dest: src, listener: this, } srcAddr := &net.UDPAddr{ IP: src.Address.IP(), Port: int(src.Port), } auth, err := this.config.GetAuthenticator() if err != nil { log.Error("KCP|Listener: Failed to create authenticator: ", err) } conn = NewConnection(conv, writer, this.Addr().(*net.UDPAddr), srcAddr, auth, this.config) select { case this.awaitingConns <- conn: case <-time.After(time.Second * 5): conn.Close() return } this.sessions[sourceId] = conn } conn.Input(payload.Value) }
func (this *Server) handleUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) { source := session.Source log.Info("Socks: Client UDP connection from ", source) request, err := protocol.ReadUDPRequest(payload.Value) payload.Release() if err != nil { log.Error("Socks: Failed to parse UDP request: ", err) return } if request.Data.Len() == 0 { request.Data.Release() return } if request.Fragment != 0 { log.Warning("Socks: Dropping fragmented UDP packets.") // TODO handle fragments request.Data.Release() return } log.Info("Socks: Send packet to ", request.Destination(), " with ", request.Data.Len(), " bytes") log.Access(source, request.Destination, log.AccessAccepted, "") this.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: request.Destination()}, request.Data, func(destination v2net.Destination, payload *alloc.Buffer) { response := &protocol.Socks5UDPRequest{ Fragment: 0, Address: request.Destination().Address(), Port: request.Destination().Port(), Data: payload, } log.Info("Socks: Writing back UDP response with ", payload.Len(), " bytes to ", destination) udpMessage := alloc.NewLocalBuffer(2048).Clear() response.Write(udpMessage) this.udpMutex.RLock() if !this.accepting { this.udpMutex.RUnlock() return } nBytes, err := this.udpHub.WriteTo(udpMessage.Value, destination) this.udpMutex.RUnlock() udpMessage.Release() response.Data.Release() if err != nil { log.Error("Socks: failed to write UDP message (", nBytes, " bytes) to ", destination, ": ", err) } }) }
func (this *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) { source := session.Source request, data, err := DecodeUDPPacket(this.user, payload) if err != nil { log.Info("Shadowsocks|Server: Skipping invalid UDP packet from: ", source, ": ", err) log.Access(source, "", log.AccessRejected, err) payload.Release() return } if request.Option.Has(RequestOptionOneTimeAuth) && this.account.OneTimeAuth == Account_Disabled { log.Info("Shadowsocks|Server: Client payload enables OTA but server doesn't allow it.") payload.Release() return } if !request.Option.Has(RequestOptionOneTimeAuth) && this.account.OneTimeAuth == Account_Enabled { log.Info("Shadowsocks|Server: Client payload disables OTA but server forces it.") payload.Release() return } dest := request.Destination() log.Access(source, dest, log.AccessAccepted, "") log.Info("Shadowsocks|Server: Tunnelling request to ", dest) this.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: dest, User: request.User, Inbound: this.meta}, data, func(destination v2net.Destination, payload *alloc.Buffer) { defer payload.Release() data, err := EncodeUDPPacket(request, payload) if err != nil { log.Warning("Shadowsocks|Server: Failed to encode UDP packet: ", err) return } defer data.Release() this.udpHub.WriteTo(data.Value, source) }) }
func (this *Client) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { defer payload.Release() defer ray.OutboundInput().Release() defer ray.OutboundOutput().Close() network := destination.Network var server *protocol.ServerSpec var conn internet.Connection err := retry.ExponentialBackoff(5, 100).On(func() error { server = this.serverPicker.PickServer() dest := server.Destination() dest.Network = network rawConn, err := internet.Dial(this.meta.Address, dest, this.meta.GetDialerOptions()) if err != nil { return err } conn = rawConn return nil }) if err != nil { return errors.New("Shadowsocks|Client: Failed to find an available destination:" + err.Error()) } log.Info("Shadowsocks|Client: Tunneling request to ", destination, " via ", server.Destination()) conn.SetReusable(false) request := &protocol.RequestHeader{ Version: Version, Address: destination.Address, Port: destination.Port, } if destination.Network == v2net.Network_TCP { request.Command = protocol.RequestCommandTCP } else { request.Command = protocol.RequestCommandUDP } user := server.PickUser() rawAccount, err := user.GetTypedAccount() if err != nil { return errors.New("Shadowsocks|Client: Failed to get a valid user account: " + err.Error()) } account := rawAccount.(*ShadowsocksAccount) request.User = user if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled { request.Option |= RequestOptionOneTimeAuth } if request.Command == protocol.RequestCommandTCP { bufferedWriter := v2io.NewBufferedWriter(conn) defer bufferedWriter.Release() bodyWriter, err := WriteTCPRequest(request, bufferedWriter) defer bodyWriter.Release() if err != nil { return errors.New("Shadowsock|Client: Failed to write request: " + err.Error()) } if err := bodyWriter.Write(payload); err != nil { return errors.New("Shadowsocks|Client: Failed to write payload: " + err.Error()) } var responseMutex sync.Mutex responseMutex.Lock() go func() { defer responseMutex.Unlock() responseReader, err := ReadTCPResponse(user, conn) if err != nil { log.Warning("Shadowsocks|Client: Failed to read response: " + err.Error()) return } v2io.Pipe(responseReader, ray.OutboundOutput()) }() bufferedWriter.SetCached(false) v2io.Pipe(ray.OutboundInput(), bodyWriter) responseMutex.Lock() } if request.Command == protocol.RequestCommandUDP { timedReader := v2net.NewTimeOutReader(16, conn) var responseMutex sync.Mutex responseMutex.Lock() go func() { defer responseMutex.Unlock() reader := &UDPReader{ Reader: timedReader, User: user, } v2io.Pipe(reader, ray.OutboundOutput()) }() writer := &UDPWriter{ Writer: conn, Request: request, } if !payload.IsEmpty() { if err := writer.Write(payload); err != nil { return errors.New("Shadowsocks|Client: Failed to write payload: " + err.Error()) } } v2io.Pipe(ray.OutboundInput(), writer) responseMutex.Lock() } return nil }
func (this *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) { defer payload.Release() source := session.Source ivLen := this.config.Cipher.IVSize() iv := payload.Value[:ivLen] key := this.config.Key payload.SliceFrom(ivLen) stream, err := this.config.Cipher.NewDecodingStream(key, iv) if err != nil { log.Error("Shadowsocks: Failed to create decoding stream: ", err) return } reader := crypto.NewCryptionReader(stream, payload) request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)), true) if err != nil { if err != io.EOF { log.Access(source, "", log.AccessRejected, err) log.Warning("Shadowsocks: Invalid request from ", source, ": ", err) } return } //defer request.Release() dest := v2net.UDPDestination(request.Address, request.Port) log.Access(source, dest, log.AccessAccepted, "") log.Info("Shadowsocks: Tunnelling request to ", dest) this.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: dest}, request.DetachUDPPayload(), func(destination v2net.Destination, payload *alloc.Buffer) { defer payload.Release() response := alloc.NewBuffer().Slice(0, ivLen) defer response.Release() rand.Read(response.Value) respIv := response.Value stream, err := this.config.Cipher.NewEncodingStream(key, respIv) if err != nil { log.Error("Shadowsocks: Failed to create encoding stream: ", err) return } writer := crypto.NewCryptionWriter(stream, response) switch request.Address.Family() { case v2net.AddressFamilyIPv4: writer.Write([]byte{AddrTypeIPv4}) writer.Write(request.Address.IP()) case v2net.AddressFamilyIPv6: writer.Write([]byte{AddrTypeIPv6}) writer.Write(request.Address.IP()) case v2net.AddressFamilyDomain: writer.Write([]byte{AddrTypeDomain, byte(len(request.Address.Domain()))}) writer.Write([]byte(request.Address.Domain())) } writer.Write(request.Port.Bytes(nil)) writer.Write(payload.Value) if request.OTA { respAuth := NewAuthenticator(HeaderKeyGenerator(key, respIv)) respAuth.Authenticate(response.Value, response.Value[ivLen:]) } this.udpHub.WriteTo(response.Value, source) }) }
func (this *AuthChunkReader) Read() (*alloc.Buffer, error) { var buffer *alloc.Buffer if this.last != nil { buffer = this.last this.last = nil } else { buffer = alloc.NewBufferWithSize(4096).Clear() } if this.chunkLength == -1 { for buffer.Len() < 6 { _, err := buffer.FillFrom(this.reader) if err != nil { buffer.Release() return nil, io.ErrUnexpectedEOF } } length := serial.BytesToUint16(buffer.Value[:2]) this.chunkLength = int(length) - 4 this.validator = NewValidator(serial.BytesToUint32(buffer.Value[2:6])) buffer.SliceFrom(6) if buffer.Len() < this.chunkLength && this.chunkLength <= 2048 { _, err := buffer.FillFrom(this.reader) if err != nil { buffer.Release() return nil, io.ErrUnexpectedEOF } } } else if buffer.Len() < this.chunkLength { _, err := buffer.FillFrom(this.reader) if err != nil { buffer.Release() return nil, io.ErrUnexpectedEOF } } if this.chunkLength == 0 { buffer.Release() return nil, io.EOF } if buffer.Len() < this.chunkLength { this.validator.Consume(buffer.Value) this.chunkLength -= buffer.Len() } else { this.validator.Consume(buffer.Value[:this.chunkLength]) if !this.validator.Validate() { buffer.Release() return nil, transport.ErrCorruptedPacket } leftLength := buffer.Len() - this.chunkLength if leftLength > 0 { this.last = alloc.NewBufferWithSize(leftLength + 4096).Clear() this.last.Append(buffer.Value[this.chunkLength:]) buffer.Slice(0, this.chunkLength) } this.chunkLength = -1 this.validator = nil } return buffer, nil }