From eb1adf629fa6217d48e28f34366e3c39627a5dca Mon Sep 17 00:00:00 2001 From: Maisem Ali Date: Fri, 9 Dec 2022 16:46:37 +0500 Subject: [PATCH] net/tstun: reuse buffered packet from pool We would call parsedPacketPool.Get() for all packets received in Read/Write. This was wasteful and not necessary, fetch a single *packet.Parsed for all packets. Signed-off-by: Maisem Ali --- net/tstun/wrap.go | 15 +++++++-------- net/tstun/wrap_test.go | 8 ++++++-- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/net/tstun/wrap.go b/net/tstun/wrap.go index f57b5525e..b6e36a988 100644 --- a/net/tstun/wrap.go +++ b/net/tstun/wrap.go @@ -559,9 +559,9 @@ func (t *Wrapper) Read(buffs [][]byte, sizes []int, offset int) (int, error) { metricPacketOut.Add(int64(len(res.data))) var buffsPos int + p := parsedPacketPool.Get().(*packet.Parsed) + defer parsedPacketPool.Put(p) for _, data := range res.data { - p := parsedPacketPool.Get().(*packet.Parsed) - defer parsedPacketPool.Put(p) p.Decode(data[res.dataOffset:]) if m := t.destIPActivity.Load(); m != nil { if fn := m[p.Dst.Addr()]; fn != nil { @@ -629,11 +629,7 @@ func (t *Wrapper) injectedRead(res tunInjectedRead, buf []byte, offset int) (int return n, nil } -func (t *Wrapper) filterIn(buf []byte) filter.Response { - p := parsedPacketPool.Get().(*packet.Parsed) - defer parsedPacketPool.Put(p) - p.Decode(buf) - +func (t *Wrapper) filterIn(p *packet.Parsed) filter.Response { if p.IPProto == ipproto.TSMP { if pingReq, ok := p.AsTSMPPing(); ok { t.noteActivity() @@ -732,8 +728,11 @@ func (t *Wrapper) Write(buffs [][]byte, offset int) (int, error) { metricPacketIn.Add(int64(len(buffs))) i := 0 if !t.disableFilter { + p := parsedPacketPool.Get().(*packet.Parsed) + defer parsedPacketPool.Put(p) for _, buff := range buffs { - if t.filterIn(buff[offset:]) != filter.Accept { + p.Decode(buff[offset:]) + if t.filterIn(p) != filter.Accept { metricPacketInDrop.Add(1) } else { buffs[i] = buff diff --git a/net/tstun/wrap_test.go b/net/tstun/wrap_test.go index a3cb80adf..12d397ff2 100644 --- a/net/tstun/wrap_test.go +++ b/net/tstun/wrap_test.go @@ -518,9 +518,11 @@ func TestPeerAPIBypass(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + p := new(packet.Parsed) + p.Decode(tt.pkt) tt.w.SetFilter(tt.filter) tt.w.disableTSMPRejected = true - if got := tt.w.filterIn(tt.pkt); got != tt.want { + if got := tt.w.filterIn(p); got != tt.want { t.Errorf("got = %v; want %v", got, tt.want) } }) @@ -548,7 +550,9 @@ func TestFilterDiscoLoop(t *testing.T) { uh.Marshal(pkt) copy(pkt[uh.Len():], discoPayload) - got := tw.filterIn(pkt) + p := new(packet.Parsed) + p.Decode(pkt) + got := tw.filterIn(p) if got != filter.DropSilently { t.Errorf("got %v; want DropSilently", got) }