func (v *Server) transport(input io.Reader, output io.Writer, ray ray.InboundRay) { var wg sync.WaitGroup wg.Add(2) defer wg.Wait() go func() { v2reader := buf.NewReader(input) defer v2reader.Release() if err := buf.PipeUntilEOF(v2reader, ray.InboundInput()); err != nil { log.Info("HTTP: Failed to transport all TCP request: ", err) } ray.InboundInput().Close() wg.Done() }() go func() { v2writer := buf.NewWriter(output) defer v2writer.Release() if err := buf.PipeUntilEOF(ray.InboundOutput(), v2writer); err != nil { log.Info("HTTP: Failed to transport all TCP response: ", err) } ray.InboundOutput().Release() wg.Done() }() }
func (v *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer) error { ray := v.packetDispatcher.DispatchToOutbound(ctx) input := ray.InboundInput() output := ray.InboundOutput() requestDone := signal.ExecuteAsync(func() error { defer input.Close() v2reader := buf.NewReader(reader) if err := buf.PipeUntilEOF(v2reader, input); err != nil { log.Info("Socks|Server: Failed to transport all TCP request: ", err) return err } return nil }) responseDone := signal.ExecuteAsync(func() error { v2writer := buf.NewWriter(writer) if err := buf.PipeUntilEOF(output, v2writer); err != nil { log.Info("Socks|Server: Failed to transport all TCP response: ", err) return err } return nil }) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { log.Info("Socks|Server: Connection ends with ", err) input.CloseError() output.CloseError() return err } return nil }
func (v *Server) transport(reader io.Reader, writer io.Writer, session *proxy.SessionInfo) { ray := v.packetDispatcher.DispatchToOutbound(session) input := ray.InboundInput() output := ray.InboundOutput() defer input.Close() defer output.Release() go func() { v2reader := buf.NewReader(reader) defer v2reader.Release() if err := buf.PipeUntilEOF(v2reader, input); err != nil { log.Info("Socks|Server: Failed to transport all TCP request: ", err) } input.Close() }() v2writer := buf.NewWriter(writer) defer v2writer.Release() if err := buf.PipeUntilEOF(output, v2writer); err != nil { log.Info("Socks|Server: Failed to transport all TCP response: ", err) } output.Release() }
func (v *DokodemoDoor) HandleTCPConnection(conn internet.Connection) { defer conn.Close() var dest v2net.Destination if v.config.FollowRedirect { originalDest := GetOriginalDestination(conn) if originalDest.Network != v2net.Network_Unknown { log.Info("Dokodemo: Following redirect to: ", originalDest) dest = originalDest } } if dest.Network == v2net.Network_Unknown && v.address != nil && v.port > v2net.Port(0) { dest = v2net.TCPDestination(v.address, v.port) } if dest.Network == v2net.Network_Unknown { log.Info("Dokodemo: Unknown destination, stop forwarding...") return } log.Info("Dokodemo: Handling request to ", dest) ray := v.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{ Source: v2net.DestinationFromAddr(conn.RemoteAddr()), Destination: dest, Inbound: v.meta, }) defer ray.InboundOutput().Release() var wg sync.WaitGroup reader := v2net.NewTimeOutReader(v.config.Timeout, conn) defer reader.Release() wg.Add(1) go func() { v2reader := buf.NewReader(reader) defer v2reader.Release() if err := buf.PipeUntilEOF(v2reader, ray.InboundInput()); err != nil { log.Info("Dokodemo: Failed to transport all TCP request: ", err) } wg.Done() ray.InboundInput().Close() }() wg.Add(1) go func() { v2writer := buf.NewWriter(conn) defer v2writer.Release() if err := buf.PipeUntilEOF(ray.InboundOutput(), v2writer); err != nil { log.Info("Dokodemo: Failed to transport all TCP response: ", err) } wg.Done() }() wg.Wait() }
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 data, err := input.Read() if err != nil { return err } if err := bodyWriter.Write(data); err != nil { return err } data.Release() if bufferedWriter, ok := output.(*bufio.BufferedWriter); ok { if err := bufferedWriter.SetBuffered(false); err != nil { return err } } if err := buf.PipeUntilEOF(input, bodyWriter); err != nil { return err } if request.Option.Has(protocol.RequestOptionChunkStream) { if err := bodyWriter.Write(buf.NewLocal(8)); err != nil { return err } } return nil }
func (v *VMessOutboundHandler) handleRequest(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, payload *buf.Buffer, input buf.Reader, finish *sync.Mutex) { defer finish.Unlock() writer := bufio.NewWriter(conn) defer writer.Release() session.EncodeRequestHeader(request, writer) bodyWriter := session.EncodeRequestBody(request, writer) defer bodyWriter.Release() if !payload.IsEmpty() { if err := bodyWriter.Write(payload); err != nil { log.Info("VMess|Outbound: Failed to write payload. Disabling connection reuse.", err) conn.SetReusable(false) } payload.Release() } writer.SetCached(false) if err := buf.PipeUntilEOF(input, bodyWriter); err != nil { conn.SetReusable(false) } if request.Option.Has(protocol.RequestOptionChunkStream) { err := bodyWriter.Write(buf.NewLocal(8)) if err != nil { conn.SetReusable(false) } } return }
func (v *VMessOutboundHandler) handleResponse(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, dest v2net.Destination, output buf.Writer, finish *sync.Mutex) { defer finish.Unlock() reader := bufio.NewReader(conn) defer reader.Release() header, err := session.DecodeResponseHeader(reader) if err != nil { conn.SetReusable(false) log.Warning("VMess|Outbound: Failed to read response from ", request.Destination(), ": ", err) return } v.handleCommand(dest, header.Command) conn.SetReusable(header.Option.Has(protocol.ResponseOptionConnectionReuse)) reader.SetCached(false) bodyReader := session.DecodeResponseBody(request, reader) defer bodyReader.Release() if err := buf.PipeUntilEOF(bodyReader, output); err != nil { conn.SetReusable(false) } return }
func (s *Server) handleConnect(ctx context.Context, request *http.Request, reader io.Reader, writer io.Writer) error { response := &http.Response{ Status: "200 OK", StatusCode: 200, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: http.Header(make(map[string][]string)), Body: nil, ContentLength: 0, Close: false, } if err := response.Write(writer); err != nil { log.Warning("HTTP|Server: failed to write back OK response: ", err) return err } ray := s.packetDispatcher.DispatchToOutbound(ctx) requestDone := signal.ExecuteAsync(func() error { defer ray.InboundInput().Close() v2reader := buf.NewReader(reader) if err := buf.PipeUntilEOF(v2reader, ray.InboundInput()); err != nil { return err } return nil }) responseDone := signal.ExecuteAsync(func() error { v2writer := buf.NewWriter(writer) if err := buf.PipeUntilEOF(ray.InboundOutput(), v2writer); err != nil { return err } return nil }) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { log.Info("HTTP|Server: Connection ends with: ", err) ray.InboundInput().CloseError() ray.InboundOutput().CloseError() return err } return nil }
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 (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn internet.Connection) error { log.Debug("Dokodemo: processing connection from: ", conn.RemoteAddr()) conn.SetReusable(false) ctx = proxy.ContextWithDestination(ctx, net.Destination{ Network: network, Address: d.address, Port: d.port, }) inboundRay := d.packetDispatcher.DispatchToOutbound(ctx) requestDone := signal.ExecuteAsync(func() error { defer inboundRay.InboundInput().Close() timedReader := net.NewTimeOutReader(d.config.Timeout, conn) chunkReader := buf.NewReader(timedReader) if err := buf.PipeUntilEOF(chunkReader, inboundRay.InboundInput()); err != nil { log.Info("Dokodemo: Failed to transport request: ", err) return err } return nil }) responseDone := signal.ExecuteAsync(func() error { v2writer := buf.NewWriter(conn) if err := buf.PipeUntilEOF(inboundRay.InboundOutput(), v2writer); err != nil { log.Info("Dokodemo: Failed to transport response: ", err) return err } return nil }) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { inboundRay.InboundInput().CloseError() inboundRay.InboundOutput().CloseError() log.Info("Dokodemo: Connection ends with ", err) return err } return nil }
func (s *Server) handleConnection(ctx context.Context, conn internet.Connection) error { conn.SetReusable(false) timedReader := net.NewTimeOutReader(16, conn) bufferedReader := bufio.NewReader(timedReader) request, bodyReader, err := ReadTCPSession(s.user, bufferedReader) if err != nil { log.Access(conn.RemoteAddr(), "", log.AccessRejected, err) log.Info("Shadowsocks|Server: Failed to create request from: ", conn.RemoteAddr(), ": ", err) return err } bufferedReader.SetBuffered(false) userSettings := s.user.GetSettings() timedReader.SetTimeOut(userSettings.PayloadReadTimeout) dest := request.Destination() log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, "") log.Info("Shadowsocks|Server: Tunnelling request to ", dest) ctx = proxy.ContextWithDestination(ctx, dest) ctx = protocol.ContextWithUser(ctx, request.User) ray := s.packetDispatcher.DispatchToOutbound(ctx) requestDone := signal.ExecuteAsync(func() error { bufferedWriter := bufio.NewWriter(conn) responseWriter, err := WriteTCPResponse(request, bufferedWriter) if err != nil { log.Warning("Shadowsocks|Server: Failed to write response: ", err) return err } payload, err := ray.InboundOutput().Read() if err != nil { return err } if err := responseWriter.Write(payload); err != nil { return err } payload.Release() if err := bufferedWriter.SetBuffered(false); err != nil { return err } if err := buf.PipeUntilEOF(ray.InboundOutput(), responseWriter); err != nil { log.Info("Shadowsocks|Server: Failed to transport all TCP response: ", err) return err } return nil }) responseDone := signal.ExecuteAsync(func() error { defer ray.InboundInput().Close() if err := buf.PipeUntilEOF(bodyReader, ray.InboundInput()); err != nil { log.Info("Shadowsocks|Server: Failed to transport all TCP request: ", err) return err } return nil }) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { log.Info("Shadowsocks|Server: Connection ends with ", err) ray.InboundInput().CloseError() ray.InboundOutput().CloseError() return err } return nil }
func (v *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay) error { destination := proxy.DestinationFromContext(ctx) if v.destOverride != nil { server := v.destOverride.Server destination = net.Destination{ Network: destination.Network, Address: server.Address.AsAddress(), Port: net.Port(server.Port), } } log.Info("Freedom: Opening connection to ", destination) input := outboundRay.OutboundInput() output := outboundRay.OutboundOutput() var conn internet.Connection if v.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() { destination = v.ResolveIP(destination) } dialer := proxy.DialerFromContext(ctx) err := retry.ExponentialBackoff(5, 100).On(func() error { rawConn, err := dialer.Dial(ctx, destination) 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() conn.SetReusable(false) requestDone := signal.ExecuteAsync(func() error { v2writer := buf.NewWriter(conn) if err := buf.PipeUntilEOF(input, v2writer); err != nil { return err } return nil }) var reader io.Reader = conn timeout := v.timeout if destination.Network == net.Network_UDP { timeout = 16 } if timeout > 0 { reader = net.NewTimeOutReader(timeout /* seconds */, conn) } responseDone := signal.ExecuteAsync(func() error { defer output.Close() v2reader := buf.NewReader(reader) if err := buf.PipeUntilEOF(v2reader, output); err != nil { return err } return nil }) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { log.Info("Freedom: Connection ending with ", err) input.CloseError() output.CloseError() return err } return nil }
func (v *Client) Dispatch(destination v2net.Destination, payload *buf.Buffer, ray ray.OutboundRay) { 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 = v.serverPicker.PickServer() dest := server.Destination() dest.Network = network rawConn, err := internet.Dial(v.meta.Address, dest, v.meta.GetDialerOptions()) if err != nil { return err } conn = rawConn return nil }) if err != nil { log.Warning("Shadowsocks|Client: Failed to find an available destination:", err) return } 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 { log.Warning("Shadowsocks|Client: Failed to get a valid user account: ", err) return } account := rawAccount.(*ShadowsocksAccount) request.User = user if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled { request.Option |= RequestOptionOneTimeAuth } if request.Command == protocol.RequestCommandTCP { bufferedWriter := bufio.NewWriter(conn) defer bufferedWriter.Release() bodyWriter, err := WriteTCPRequest(request, bufferedWriter) defer bodyWriter.Release() if err != nil { log.Info("Shadowsock|Client: Failed to write request: ", err) return } if err := bodyWriter.Write(payload); err != nil { log.Info("Shadowsocks|Client: Failed to write payload: ", err) return } 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) return } if err := buf.PipeUntilEOF(responseReader, ray.OutboundOutput()); err != nil { log.Info("Shadowsocks|Client: Failed to transport all TCP response: ", err) } }() bufferedWriter.SetCached(false) if err := buf.PipeUntilEOF(ray.OutboundInput(), bodyWriter); err != nil { log.Info("Shadowsocks|Client: Failed to trasnport all TCP request: ", err) } 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, } if err := buf.PipeUntilEOF(reader, ray.OutboundOutput()); err != nil { log.Info("Shadowsocks|Client: Failed to transport all UDP response: ", err) } }() writer := &UDPWriter{ Writer: conn, Request: request, } if !payload.IsEmpty() { if err := writer.Write(payload); err != nil { log.Info("Shadowsocks|Client: Failed to write payload: ", err) return } } if err := buf.PipeUntilEOF(ray.OutboundInput(), writer); err != nil { log.Info("Shadowsocks|Client: Failed to transport all UDP request: ", err) } responseMutex.Lock() } }
// Dispatch implements OutboundHandler.Dispatch(). func (v *VMessOutboundHandler) Process(ctx context.Context, outboundRay ray.OutboundRay) error { var rec *protocol.ServerSpec var conn internet.Connection dialer := proxy.DialerFromContext(ctx) err := retry.ExponentialBackoff(5, 100).On(func() error { rec = v.serverPicker.PickServer() rawConn, err := dialer.Dial(ctx, rec.Destination()) if err != nil { return err } conn = rawConn return nil }) if err != nil { log.Warning("VMess|Outbound: Failed to find an available destination:", err) return err } defer conn.Close() target := proxy.DestinationFromContext(ctx) log.Info("VMess|Outbound: Tunneling request to ", target, " via ", rec.Destination()) command := protocol.RequestCommandTCP if target.Network == net.Network_UDP { command = protocol.RequestCommandUDP } request := &protocol.RequestHeader{ Version: encoding.Version, User: rec.PickUser(), Command: command, Address: target.Address, Port: target.Port, Option: protocol.RequestOptionChunkStream, } rawAccount, err := request.User.GetTypedAccount() if err != nil { log.Warning("VMess|Outbound: Failed to get user account: ", err) return err } account := rawAccount.(*vmess.InternalAccount) request.Security = account.Security conn.SetReusable(true) if conn.Reusable() { // Conn reuse may be disabled on transportation layer request.Option.Set(protocol.RequestOptionConnectionReuse) } input := outboundRay.OutboundInput() output := outboundRay.OutboundOutput() session := encoding.NewClientSession(protocol.DefaultIDHash) requestDone := signal.ExecuteAsync(func() error { writer := bufio.NewWriter(conn) session.EncodeRequestHeader(request, writer) bodyWriter := session.EncodeRequestBody(request, writer) firstPayload, err := input.ReadTimeout(time.Millisecond * 500) if err != nil && err != ray.ErrReadTimeout { return errors.Base(err).Message("VMess|Outbound: Failed to get first payload.") } if !firstPayload.IsEmpty() { if err := bodyWriter.Write(firstPayload); err != nil { return errors.Base(err).Message("VMess|Outbound: Failed to write first payload.") } firstPayload.Release() } writer.SetBuffered(false) if err := buf.PipeUntilEOF(input, bodyWriter); err != nil { return err } if request.Option.Has(protocol.RequestOptionChunkStream) { if err := bodyWriter.Write(buf.NewLocal(8)); err != nil { return err } } return nil }) responseDone := signal.ExecuteAsync(func() error { defer output.Close() reader := bufio.NewReader(conn) header, err := session.DecodeResponseHeader(reader) if err != nil { return err } v.handleCommand(rec.Destination(), header.Command) conn.SetReusable(header.Option.Has(protocol.ResponseOptionConnectionReuse)) reader.SetBuffered(false) bodyReader := session.DecodeResponseBody(request, reader) if err := buf.PipeUntilEOF(bodyReader, output); err != nil { return err } return nil }) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { log.Info("VMess|Outbound: Connection ending with ", err) conn.SetReusable(false) input.CloseError() output.CloseError() return err } return nil }
func (c *Client) Process(ctx context.Context, ray ray.OutboundRay) error { destination := proxy.DestinationFromContext(ctx) var server *protocol.ServerSpec var conn internet.Connection dialer := proxy.DialerFromContext(ctx) err := retry.ExponentialBackoff(5, 100).On(func() error { server = c.serverPicker.PickServer() dest := server.Destination() rawConn, err := dialer.Dial(ctx, dest) if err != nil { return err } conn = rawConn return nil }) if err != nil { log.Warning("Socks|Client: Failed to find an available destination.") return err } defer conn.Close() conn.SetReusable(false) request := &protocol.RequestHeader{ Version: socks5Version, Command: protocol.RequestCommandTCP, Address: destination.Address, Port: destination.Port, } if destination.Network == net.Network_UDP { request.Command = protocol.RequestCommandUDP } user := server.PickUser() if user != nil { request.User = user } udpRequest, err := ClientHandshake(request, conn, conn) if err != nil { log.Warning("Socks|Client: Failed to establish connection to server: ", err) return err } var requestFunc func() error var responseFunc func() error if request.Command == protocol.RequestCommandTCP { requestFunc = func() error { return buf.PipeUntilEOF(ray.OutboundInput(), buf.NewWriter(conn)) } responseFunc = func() error { defer ray.OutboundOutput().Close() return buf.PipeUntilEOF(buf.NewReader(conn), ray.OutboundOutput()) } } else if request.Command == protocol.RequestCommandUDP { udpConn, err := dialer.Dial(ctx, udpRequest.Destination()) if err != nil { log.Info("Socks|Client: Failed to create UDP connection: ", err) return err } defer udpConn.Close() requestFunc = func() error { return buf.PipeUntilEOF(ray.OutboundInput(), &UDPWriter{request: request, writer: udpConn}) } responseFunc = func() error { defer ray.OutboundOutput().Close() reader := &UDPReader{reader: net.NewTimeOutReader(16, udpConn)} return buf.PipeUntilEOF(reader, ray.OutboundOutput()) } } requestDone := signal.ExecuteAsync(requestFunc) responseDone := signal.ExecuteAsync(responseFunc) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { log.Info("Socks|Client: Connection ends with ", err) ray.OutboundInput().CloseError() ray.OutboundOutput().CloseError() return err } return nil }
// Process implements OutboundHandler.Process(). func (v *Client) Process(ctx context.Context, outboundRay ray.OutboundRay) error { destination := proxy.DestinationFromContext(ctx) network := destination.Network var server *protocol.ServerSpec var conn internet.Connection dialer := proxy.DialerFromContext(ctx) err := retry.ExponentialBackoff(5, 100).On(func() error { server = v.serverPicker.PickServer() dest := server.Destination() dest.Network = network rawConn, err := dialer.Dial(ctx, dest) if err != nil { return err } conn = rawConn return nil }) if err != nil { log.Warning("Shadowsocks|Client: Failed to find an available destination:", err) return err } 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 == net.Network_TCP { request.Command = protocol.RequestCommandTCP } else { request.Command = protocol.RequestCommandUDP } user := server.PickUser() rawAccount, err := user.GetTypedAccount() if err != nil { log.Warning("Shadowsocks|Client: Failed to get a valid user account: ", err) return err } account := rawAccount.(*ShadowsocksAccount) request.User = user if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled { request.Option |= RequestOptionOneTimeAuth } if request.Command == protocol.RequestCommandTCP { bufferedWriter := bufio.NewWriter(conn) bodyWriter, err := WriteTCPRequest(request, bufferedWriter) if err != nil { log.Info("Shadowsocks|Client: Failed to write request: ", err) return err } bufferedWriter.SetBuffered(false) requestDone := signal.ExecuteAsync(func() error { if err := buf.PipeUntilEOF(outboundRay.OutboundInput(), bodyWriter); err != nil { return err } return nil }) responseDone := signal.ExecuteAsync(func() error { defer outboundRay.OutboundOutput().Close() responseReader, err := ReadTCPResponse(user, conn) if err != nil { return err } if err := buf.PipeUntilEOF(responseReader, outboundRay.OutboundOutput()); err != nil { return err } return nil }) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { log.Info("Shadowsocks|Client: Connection ends with ", err) outboundRay.OutboundInput().CloseError() outboundRay.OutboundOutput().CloseError() return err } return nil } if request.Command == protocol.RequestCommandUDP { writer := &UDPWriter{ Writer: conn, Request: request, } requestDone := signal.ExecuteAsync(func() error { if err := buf.PipeUntilEOF(outboundRay.OutboundInput(), writer); err != nil { log.Info("Shadowsocks|Client: Failed to transport all UDP request: ", err) return err } return nil }) timedReader := net.NewTimeOutReader(16, conn) responseDone := signal.ExecuteAsync(func() error { defer outboundRay.OutboundOutput().Close() reader := &UDPReader{ Reader: timedReader, User: user, } if err := buf.PipeUntilEOF(reader, outboundRay.OutboundOutput()); err != nil { log.Info("Shadowsocks|Client: Failed to transport all UDP response: ", err) return err } return nil }) if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil { log.Info("Shadowsocks|Client: Connection ends with ", err) outboundRay.OutboundInput().CloseError() outboundRay.OutboundOutput().CloseError() return err } return nil } return nil }
func (v *Server) handleConnection(conn internet.Connection) { defer conn.Close() conn.SetReusable(false) timedReader := v2net.NewTimeOutReader(16, conn) defer timedReader.Release() bufferedReader := bufio.NewReader(timedReader) defer bufferedReader.Release() request, bodyReader, err := ReadTCPSession(v.user, bufferedReader) if err != nil { log.Access(conn.RemoteAddr(), "", log.AccessRejected, err) log.Info("Shadowsocks|Server: Failed to create request from: ", conn.RemoteAddr(), ": ", err) return } defer bodyReader.Release() bufferedReader.SetCached(false) userSettings := v.user.GetSettings() timedReader.SetTimeOut(userSettings.PayloadReadTimeout) dest := request.Destination() log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, "") log.Info("Shadowsocks|Server: Tunnelling request to ", dest) ray := v.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{ Source: v2net.DestinationFromAddr(conn.RemoteAddr()), Destination: dest, User: request.User, Inbound: v.meta, }) defer ray.InboundOutput().Release() var writeFinish sync.Mutex writeFinish.Lock() go func() { defer writeFinish.Unlock() bufferedWriter := bufio.NewWriter(conn) defer bufferedWriter.Release() responseWriter, err := WriteTCPResponse(request, bufferedWriter) if err != nil { log.Warning("Shadowsocks|Server: Failed to write response: ", err) return } defer responseWriter.Release() if payload, err := ray.InboundOutput().Read(); err == nil { responseWriter.Write(payload) bufferedWriter.SetCached(false) if err := buf.PipeUntilEOF(ray.InboundOutput(), responseWriter); err != nil { log.Info("Shadowsocks|Server: Failed to transport all TCP response: ", err) } } }() if err := buf.PipeUntilEOF(bodyReader, ray.InboundInput()); err != nil { log.Info("Shadowsocks|Server: Failed to transport all TCP request: ", err) } ray.InboundInput().Close() writeFinish.Lock() }