@@ -55,12 +55,13 @@ func (r *PacketReactor) Close() error {
5555}
5656
5757type reactorConnection struct {
58- ctx context.Context
59- cancel context.CancelFunc
60- reactor * PacketReactor
61- onClose N.CloseHandlerFunc
62- upload * reactorStream
63- download * reactorStream
58+ ctx context.Context
59+ cancel context.CancelFunc
60+ reactor * PacketReactor
61+ onClose N.CloseHandlerFunc
62+ upload * reactorStream
63+ download * reactorStream
64+ stopReactorWatch func () bool
6465
6566 closeOnce sync.Once
6667 done chan struct {}
@@ -93,6 +94,9 @@ func (r *PacketReactor) Copy(ctx context.Context, source N.PacketConn, destinati
9394 onClose : onClose ,
9495 done : make (chan struct {}),
9596 }
97+ conn .stopReactorWatch = common .ContextAfterFunc (r .ctx , func () {
98+ conn .closeWithError (r .ctx .Err ())
99+ })
96100
97101 conn .upload = r .prepareStream (conn , source , destination )
98102 select {
@@ -126,10 +130,12 @@ func (r *PacketReactor) prepareStream(conn *reactorConnection, source N.PacketRe
126130 if cachedReader , isCached := source .(N.CachedPacketReader ); isCached {
127131 packet := cachedReader .ReadCachedPacket ()
128132 if packet != nil {
129- dataLen := packet .Buffer .Len ()
130- err := destination .WritePacket (packet .Buffer , packet .Destination )
133+ buffer := packet .Buffer
134+ dataLen := buffer .Len ()
135+ err := destination .WritePacket (buffer , packet .Destination )
131136 N .PutPacketBuffer (packet )
132137 if err != nil {
138+ buffer .Leak ()
133139 conn .closeWithError (err )
134140 return stream
135141 }
@@ -151,7 +157,10 @@ func (r *PacketReactor) prepareStream(conn *reactorConnection, source N.PacketRe
151157
152158 stream .readWaiter , _ = CreatePacketReadWaiter (source )
153159 if stream .readWaiter != nil {
154- stream .readWaiter .InitializeReadWaiter (stream .options )
160+ needCopy := stream .readWaiter .InitializeReadWaiter (stream .options )
161+ if needCopy {
162+ stream .readWaiter = nil
163+ }
155164 }
156165
157166 if pushable , ok := source .(N.PacketPushable ); ok {
@@ -343,7 +352,7 @@ func (s *reactorStream) HandleFDEvent() {
343352}
344353
345354func (s * reactorStream ) runLegacyCopy () {
346- _ , err := CopyPacket (s .destination , s .source )
355+ _ , err := CopyPacketWithCounters (s .destination , s .source , s . originSource , s . readCounters , s . writeCounters )
347356 s .closeWithError (err )
348357}
349358
@@ -353,6 +362,12 @@ func (s *reactorStream) closeWithError(err error) {
353362
354363func (c * reactorConnection ) closeWithError (err error ) {
355364 c .closeOnce .Do (func () {
365+ defer close (c .done )
366+
367+ if c .stopReactorWatch != nil {
368+ c .stopReactorWatch ()
369+ }
370+
356371 c .err = err
357372 c .cancel ()
358373
@@ -375,8 +390,6 @@ func (c *reactorConnection) closeWithError(err error) {
375390 if c .onClose != nil {
376391 c .onClose (c .err )
377392 }
378-
379- close (c .done )
380393 })
381394}
382395
0 commit comments