@@ -4,15 +4,13 @@ import (
44 "context"
55 "errors"
66 "fmt"
7- "io"
87 "net"
98 "slices"
109 "strings"
11- "sync"
1210 "time"
1311
12+ socks5Proxy "github.com/haxii/socks5"
1413 "github.com/ipfs/go-log/v2"
15- pool "github.com/libp2p/go-buffer-pool"
1614 "github.com/libp2p/go-libp2p/core/network"
1715
1816 "github.com/anywherelan/awl/config"
@@ -129,7 +127,7 @@ func (s *SOCKS5) ProxyStreamHandler(stream network.Stream) {
129127 // e.g reader on the other side may not read everything we sent because of stream.Reset()
130128 // in case of socks5 errors (small payload), receiver could get EOF
131129 // TODO: make better workaround for this. stream.CloseWrite(), etc doesn't help
132- time .Sleep (20 * time .Millisecond )
130+ time .Sleep (50 * time .Millisecond )
133131}
134132
135133func (s * SOCKS5 ) ServeConns (ctx context.Context ) {
@@ -191,50 +189,25 @@ func (s *SOCKS5) proxyConn(ctx context.Context, conn net.Conn) error {
191189
192190 s .handleStream (conn , stream )
193191
192+ // stream.Write() + stream.Reset() are not guaranteed to run sequentially
193+ // e.g reader on the other side may not read everything we sent because of stream.Reset()
194+ // in case of socks5 errors (small payload), receiver could get EOF
195+ // TODO: make better workaround for this. stream.CloseWrite(), etc doesn't help
196+ time .Sleep (50 * time .Millisecond )
197+
194198 return nil
195199}
196200
197201func (s * SOCKS5 ) handleStream (conn net.Conn , stream network.Stream ) {
198- // TODO: SetDeadline on conn for ~5 min just in case?
199- wg := & sync.WaitGroup {}
200- wg .Add (2 )
202+ doneCh := make (chan struct {})
201203 go func () {
202- defer wg . Done ( )
204+ defer close ( doneCh )
203205 // Copy from conn to stream
204- _ = s . copyStream (conn , stream )
206+ _ = socks5Proxy . ProxyStream (conn , stream )
205207 }()
206208
207- go func () {
208- defer wg .Done ()
209- // Copy from stream to conn
210- _ = s .copyStream (stream , conn )
211- }()
212-
213- wg .Wait ()
214- }
215-
216- func (s * SOCKS5 ) copyStream (from io.ReadCloser , to io.WriteCloser ) error {
217- const bufSize = 32 * 1024
218- buf := pool .Get (bufSize )
219-
220- defer func () {
221- pool .Put (buf )
222- }()
223- _ , err := io .CopyBuffer (to , from , buf )
224-
225- type closeWriter interface {
226- CloseWrite () error
227- }
228- if conn , ok := to .(closeWriter ); ok {
229- _ = conn .CloseWrite ()
230- }
231-
232- type closeReader interface {
233- CloseRead () error
234- }
235- if conn , ok := from .(closeReader ); ok {
236- _ = conn .CloseRead ()
237- }
209+ // Copy from stream to conn
210+ _ = socks5Proxy .ProxyStream (stream , conn )
238211
239- return err
212+ <- doneCh
240213}
0 commit comments