package namespace import ( "fmt" "os" "path/filepath" "strconv" "syscall" "git.theodohertyfamily.com/tools/wg-wrap/internal/paths" ) // GetProfileNamespacePath returns the path to the pinned namespace file for a profile. func GetProfileNamespacePath(pm *paths.PathManager, profile string) string { return pm.ProfileNamespacePath(profile) } // GetPidsDirPath returns the path to the directory where process PIDs are tracked for a profile. func GetPidsDirPath(pm *paths.PathManager, profile string) string { return pm.ProfilePidsDir(profile) } // RegisterProcess marks the current process as using the specified profile. func RegisterProcess(pm *paths.PathManager, profile string) error { pidsDir := GetPidsDirPath(pm, profile) if err := os.MkdirAll(pidsDir, 0755); err != nil { return fmt.Errorf("failed to create pids directory: %v", err) } pid := os.Getpid() pidFile := filepath.Join(pidsDir, strconv.Itoa(pid)) if err := os.WriteFile(pidFile, []byte(""), 0644); err != nil { return fmt.Errorf("failed to register process pid %d: %v", pid, err) } return nil } // UnregisterProcess removes the current process from the profile's tracking. func UnregisterProcess(pm *paths.PathManager, profile string) error { pid := os.Getpid() pidFile := filepath.Join(GetPidsDirPath(pm, profile), strconv.Itoa(pid)) if err := os.Remove(pidFile); err != nil && !os.IsNotExist(err) { return fmt.Errorf("failed to unregister process pid %d: %v", pid, err) } return nil } // PruneStalePids removes PID files that no longer correspond to active processes. func PruneStalePids(pm *paths.PathManager, profile string) error { pidsDir := GetPidsDirPath(pm, profile) files, err := os.ReadDir(pidsDir) if err != nil { if os.IsNotExist(err) { return nil } return fmt.Errorf("failed to read pids directory: %v", err) } for _, file := range files { pid, err := strconv.Atoi(file.Name()) if err != nil { continue // Ignore non-numeric files } process, err := os.FindProcess(pid) if err != nil { if err := os.Remove(filepath.Join(pidsDir, file.Name())); err != nil { fmt.Printf("failed to remove stale pid file %s: %v\n", file.Name(), err) } continue } err = process.Signal(syscall.Signal(0)) if err != nil { if err := os.Remove(filepath.Join(pidsDir, file.Name())); err != nil { fmt.Printf("failed to remove stale pid file %s: %v\n", file.Name(), err) } } } return nil } // IsLastProcess checks if the current process is the only active user of the profile. func IsLastProcess(pm *paths.PathManager, profile string) (bool, error) { pidsDir := GetPidsDirPath(pm, profile) files, err := os.ReadDir(pidsDir) if err != nil { if os.IsNotExist(err) { return true, nil } return false, fmt.Errorf("failed to read pids directory: %v", err) } activeCount := 0 for _, file := range files { pid, err := strconv.Atoi(file.Name()) if err != nil { continue } process, err := os.FindProcess(pid) if err != nil { continue } if process.Signal(syscall.Signal(0)) == nil { activeCount++ } } return activeCount <= 1, nil }