| 1 |
package firewall |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"log/slog" |
| 6 |
"sync/atomic" |
| 7 |
"time" |
| 8 |
) |
| 9 |
|
| 10 |
// ConntrackCache is used as a local routine cache to know if a given flow |
| 11 |
// has been seen in the conntrack table. |
| 12 |
type ConntrackCache map[Packet]struct{} |
| 13 |
|
| 14 |
type ConntrackCacheTicker struct { |
| 15 |
cacheV uint64 |
| 16 |
cacheTick atomic.Uint64 |
| 17 |
|
| 18 |
l *slog.Logger |
| 19 |
cache ConntrackCache |
| 20 |
} |
| 21 |
|
| 22 |
func NewConntrackCacheTicker(ctx context.Context, l *slog.Logger, d time.Duration) *ConntrackCacheTicker { |
| 23 |
if d == 0 { |
| 24 |
return nil |
| 25 |
} |
| 26 |
|
| 27 |
c := &ConntrackCacheTicker{ |
| 28 |
l: l, |
| 29 |
cache: ConntrackCache{}, |
| 30 |
} |
| 31 |
|
| 32 |
go c.tick(ctx, d) |
| 33 |
|
| 34 |
return c |
| 35 |
} |
| 36 |
|
| 37 |
func (c *ConntrackCacheTicker) tick(ctx context.Context, d time.Duration) { |
| 38 |
t := time.NewTicker(d) |
| 39 |
defer t.Stop() |
| 40 |
for { |
| 41 |
select { |
| 42 |
case <-ctx.Done(): |
| 43 |
return |
| 44 |
case <-t.C: |
| 45 |
c.cacheTick.Add(1) |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
// Get checks if the cache ticker has moved to the next version before returning |
| 51 |
// the map. If it has moved, we reset the map. |
| 52 |
func (c *ConntrackCacheTicker) Get() ConntrackCache { |
| 53 |
if c == nil { |
| 54 |
return nil |
| 55 |
} |
| 56 |
if tick := c.cacheTick.Load(); tick != c.cacheV { |
| 57 |
c.cacheV = tick |
| 58 |
if ll := len(c.cache); ll > 0 { |
| 59 |
if c.l.Enabled(context.Background(), slog.LevelDebug) { |
| 60 |
c.l.Debug("resetting conntrack cache", "len", ll) |
| 61 |
} |
| 62 |
c.cache = make(ConntrackCache, ll) |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
return c.cache |
| 67 |
} |