Skip to content
This repository has been archived by the owner on Mar 29, 2024. It is now read-only.

Commit

Permalink
Merge pull request #15 from safing/fix/expire-pending-requests
Browse files Browse the repository at this point in the history
Add expiry for pending sluice requests
  • Loading branch information
dhaavi authored Sep 29, 2021
2 parents 9e931d4 + baa738c commit 1e35536
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
2 changes: 2 additions & 0 deletions sluice/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net"
"time"

"github.com/safing/portmaster/network"
"github.com/safing/portmaster/network/packet"
Expand All @@ -20,6 +21,7 @@ var (
type Request struct {
ConnInfo *network.Connection
CallbackFn RequestCallbackFunc
Expires time.Time
}

type RequestCallbackFunc func(connInfo *network.Connection, conn net.Conn)
Expand Down
27 changes: 25 additions & 2 deletions sluice/sluice.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,14 @@ func StartSluice(network, address string) {
}

func (s *Sluice) AwaitRequest(r *Request) {
// Set default expiry.
if r.Expires.IsZero() {
r.Expires = time.Now().Add(time.Minute)
}

s.lock.Lock()
defer s.lock.Unlock()

// TODO: Make requests expire eventually.

key := net.JoinHostPort(r.ConnInfo.LocalIP.String(), strconv.Itoa(int(r.ConnInfo.LocalPort)))
s.pendingRequests[key] = r
}
Expand All @@ -65,6 +68,9 @@ func (s *Sluice) getRequest(address string) (r *Request, ok bool) {
defer s.lock.Unlock()

r, ok = s.pendingRequests[address]
if ok {
delete(s.pendingRequests, address)
}
return
}

Expand Down Expand Up @@ -182,6 +188,23 @@ func (s *Sluice) listenHandler(_ context.Context) error {
return fmt.Errorf("failed to accept connection: %s", err)
}

// Handle accepted connection.
s.handleConnection(conn)

// Clean up old leftovers.
s.cleanConnections()
}
}

func (s *Sluice) cleanConnections() {
s.lock.Lock()
defer s.lock.Unlock()

now := time.Now()
for address, request := range s.pendingRequests {
if now.After(request.Expires) {
delete(s.pendingRequests, address)
log.Debugf("spn/sluice: removed expired pending %s connection %s", s.network, request.ConnInfo)
}
}
}

0 comments on commit 1e35536

Please sign in to comment.