|
| 1 | +package greyproxy |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "log/slog" |
| 6 | + "sync" |
| 7 | + "sync/atomic" |
| 8 | +) |
| 9 | + |
| 10 | +var nextConnID atomic.Uint64 |
| 11 | + |
| 12 | +// ConnTracker tracks active proxy connections by the rule ID that authorized |
| 13 | +// them. When a rule is deleted or changed to deny, all connections that were |
| 14 | +// allowed by that rule can be cancelled immediately. |
| 15 | +type ConnTracker struct { |
| 16 | + mu sync.Mutex |
| 17 | + conns map[int64]map[uint64]context.CancelFunc |
| 18 | +} |
| 19 | + |
| 20 | +func NewConnTracker() *ConnTracker { |
| 21 | + return &ConnTracker{ |
| 22 | + conns: make(map[int64]map[uint64]context.CancelFunc), |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +// Register associates a cancel function with a rule ID and returns an ID |
| 27 | +// that can be used to unregister later. |
| 28 | +func (ct *ConnTracker) Register(ruleID int64, cancel context.CancelFunc) uint64 { |
| 29 | + id := nextConnID.Add(1) |
| 30 | + |
| 31 | + ct.mu.Lock() |
| 32 | + defer ct.mu.Unlock() |
| 33 | + |
| 34 | + if ct.conns[ruleID] == nil { |
| 35 | + ct.conns[ruleID] = make(map[uint64]context.CancelFunc) |
| 36 | + } |
| 37 | + ct.conns[ruleID][id] = cancel |
| 38 | + |
| 39 | + slog.Info("conn_tracker: registered", "conn_id", id, "rule_id", ruleID, "total_for_rule", len(ct.conns[ruleID])) |
| 40 | + return id |
| 41 | +} |
| 42 | + |
| 43 | +// Unregister removes a previously registered connection. |
| 44 | +// Called when a connection ends naturally. |
| 45 | +func (ct *ConnTracker) Unregister(ruleID int64, id uint64) { |
| 46 | + ct.mu.Lock() |
| 47 | + defer ct.mu.Unlock() |
| 48 | + |
| 49 | + if m, ok := ct.conns[ruleID]; ok { |
| 50 | + delete(m, id) |
| 51 | + if len(m) == 0 { |
| 52 | + delete(ct.conns, ruleID) |
| 53 | + } |
| 54 | + slog.Info("conn_tracker: unregistered", "conn_id", id, "rule_id", ruleID) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// CancelByRule cancels all active connections that were authorized by the |
| 59 | +// given rule ID and removes them from tracking. |
| 60 | +func (ct *ConnTracker) CancelByRule(ruleID int64) { |
| 61 | + ct.mu.Lock() |
| 62 | + cancels := ct.conns[ruleID] |
| 63 | + delete(ct.conns, ruleID) |
| 64 | + ct.mu.Unlock() |
| 65 | + |
| 66 | + if len(cancels) == 0 { |
| 67 | + slog.Info("conn_tracker: cancel by rule, no active connections", "rule_id", ruleID) |
| 68 | + return |
| 69 | + } |
| 70 | + |
| 71 | + slog.Info("conn_tracker: cancel by rule, killing connections", "rule_id", ruleID, "count", len(cancels)) |
| 72 | + for id, cancel := range cancels { |
| 73 | + slog.Info("conn_tracker: cancelling conn", "conn_id", id, "rule_id", ruleID) |
| 74 | + cancel() |
| 75 | + } |
| 76 | +} |
0 commit comments