Create interface for socket info structs, fix caching bug

From PR Review https://github.com/safing/portmaster/pull/72
This commit is contained in:
Daniel
2020-07-10 14:09:53 +02:00
parent 3d0e01383f
commit 7c6c4552aa
5 changed files with 54 additions and 52 deletions

View File

@@ -21,31 +21,18 @@ var (
pidsByUser = make(map[int][]int)
)
// FindConnectionPID returns the pid of the given socket info.
func FindConnectionPID(socketInfo *socket.ConnectionInfo) (pid int) {
// GetPID returns the already existing pid of the given socket info or searches for it.
// This also acts as a getter for socket.*Info.PID, as locking for that occurs here.
func GetPID(socketInfo socket.Info) (pid int) {
pidsByUserLock.Lock()
defer pidsByUserLock.Unlock()
if socketInfo.PID != socket.UnidentifiedProcessID {
return socket.UnidentifiedProcessID
if socketInfo.GetPID() != socket.UnidentifiedProcessID {
return socketInfo.GetPID()
}
pid = findPID(socketInfo.UID, socketInfo.Inode)
socketInfo.PID = pid
return pid
}
// FindBindPID returns the pid of the given socket info.
func FindBindPID(socketInfo *socket.BindInfo) (pid int) {
pidsByUserLock.Lock()
defer pidsByUserLock.Unlock()
if socketInfo.PID != socket.UnidentifiedProcessID {
return socket.UnidentifiedProcessID
}
pid = findPID(socketInfo.UID, socketInfo.Inode)
socketInfo.PID = pid
pid = findPID(socketInfo.GetUID(), socketInfo.GetInode())
socketInfo.SetPID(pid)
return pid
}
@@ -175,6 +162,9 @@ entryLoop:
}
// readDirNames only reads the directory names. Using ioutil.ReadDir() would call `lstat` on every
// resulting directory name, which we don't need. This function will be called a lot, so we should
// refrain from unnecessary work.
func readDirNames(dir string) (names []string) {
file, err := os.Open(dir)
if err != nil {

View File

@@ -14,12 +14,12 @@ func TestSockets(t *testing.T) {
}
fmt.Println("\nTCP 4 connections:")
for _, connection := range connections {
pid := FindConnectionPID(connection)
pid := GetPID(connection)
fmt.Printf("%d: %+v\n", pid, connection)
}
fmt.Println("\nTCP 4 listeners:")
for _, listener := range listeners {
pid := FindBindPID(listener)
pid := GetPID(listener)
fmt.Printf("%d: %+v\n", pid, listener)
}
@@ -29,12 +29,12 @@ func TestSockets(t *testing.T) {
}
fmt.Println("\nTCP 6 connections:")
for _, connection := range connections {
pid := FindConnectionPID(connection)
pid := GetPID(connection)
fmt.Printf("%d: %+v\n", pid, connection)
}
fmt.Println("\nTCP 6 listeners:")
for _, listener := range listeners {
pid := FindBindPID(listener)
pid := GetPID(listener)
fmt.Printf("%d: %+v\n", pid, listener)
}
@@ -44,7 +44,7 @@ func TestSockets(t *testing.T) {
}
fmt.Println("\nUDP 4 binds:")
for _, bind := range binds {
pid := FindBindPID(bind)
pid := GetPID(bind)
fmt.Printf("%d: %+v\n", pid, bind)
}
@@ -54,7 +54,7 @@ func TestSockets(t *testing.T) {
}
fmt.Println("\nUDP 6 binds:")
for _, bind := range binds {
pid := FindBindPID(bind)
pid := GetPID(bind)
fmt.Printf("%d: %+v\n", pid, bind)
}
}