Skip to content

Commit

Permalink
Fix norduser pid detection
Browse files Browse the repository at this point in the history
  • Loading branch information
bartoszWojciechO committed May 13, 2024
1 parent 3fc9543 commit 2ab66ea
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
14 changes: 9 additions & 5 deletions norduser/service/fork.go
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -71,15 +72,18 @@ func getRunningNorduserPIDs() ([]int, error) {
}

func findPIDOfUID(uids string, desiredUID uint32) int {
for _, pidUid := range strings.Split(uids, "\n") {
var pid, uid int
_, err := fmt.Sscanf(pidUid, " %d %d", &uid, &pid)
if err != nil {
log.Println("error when scanning ps output line: ", err)
re := regexp.MustCompile(`\s*(\d+)\s+(\d+)\s*`)

for _, uidPid := range strings.Split(uids, "\n") {
match := re.FindStringSubmatch(uidPid)
if len(match) != 3 {
log.Println(internal.ErrorPrefix+" invalid input line: ", uidPid)
continue
}

uid, _ := strconv.Atoi(match[1])
if uid == int(desiredUID) {
pid, _ := strconv.Atoi(match[2])
return pid
}
}
Expand Down
13 changes: 12 additions & 1 deletion norduser/service/fork_test.go
Expand Up @@ -48,34 +48,45 @@ func Test_findPIDOfUID(t *testing.T) {
tests := []struct {
name string
uidToPID []string
uid int
expectedPID int
}{
{
name: "empty list",
uidToPID: []string{},
uid: 1001,
expectedPID: -1,
},
{
name: "uid not present",
uidToPID: []string{" 1004 35139", " 1003 35153", " 1002 35144"},
uid: 1001,
expectedPID: -1,
},
{
name: "invalid pid",
uidToPID: []string{" 1001 aaaa", " 1003 35153", " 1002 35144"},
uid: 1001,
expectedPID: -1,
},
{
name: "pid found",
uidToPID: []string{" 1001 35255", " 1003 35153", " 1002 35144"},
uid: 1001,
expectedPID: 35255,
},
{
name: "different format",
uidToPID: []string{" 1001 35255", "10003 35153", "1002 35144"},
uid: 10003,
expectedPID: 35153,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
pids := strings.Join(test.uidToPID, "\n")
result := findPIDOfUID(pids, 1001)
result := findPIDOfUID(pids, uint32(test.uid))
assert.Equal(t, test.expectedPID, result)
})
}
Expand Down

0 comments on commit 2ab66ea

Please sign in to comment.