linsk/osspecifics/osspecifics.go

73 lines
1.6 KiB
Go
Raw Normal View History

2023-08-28 11:35:57 +02:00
//go:build !windows
2023-09-01 11:44:49 +01:00
package osspecifics
2023-08-28 11:35:57 +02:00
import (
2023-09-01 11:44:49 +01:00
"fmt"
"os"
2023-08-28 11:35:57 +02:00
"os/exec"
2023-09-01 11:44:49 +01:00
"os/user"
2023-08-29 15:31:17 +01:00
"path/filepath"
"strings"
2023-08-28 11:35:57 +02:00
"syscall"
2023-08-29 15:31:17 +01:00
"github.com/pkg/errors"
2023-08-28 11:35:57 +02:00
)
2023-09-01 11:44:49 +01:00
func SetNewProcessGroupCmd(cmd *exec.Cmd) {
2023-08-28 11:35:57 +02:00
// This is to prevent Ctrl+C propagating to the child process.
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
}
2023-09-01 11:44:49 +01:00
func TerminateProcess(pid int) error {
2023-08-28 11:35:57 +02:00
return syscall.Kill(-pid, syscall.SIGTERM)
}
2023-08-29 15:31:17 +01:00
// This is never used except for a band-aid that would check
// that there are no double-mounts.
2023-09-01 11:44:49 +01:00
func CheckDeviceSeemsMounted(devPathPrefix string) (bool, error) {
2023-08-31 21:01:45 +01:00
// Quite a bit hacky implementation, but it's to be used as a failsafe band-aid anyway.
2023-08-29 15:31:17 +01:00
absDevPathPrefix, err := filepath.Abs(devPathPrefix)
if err != nil {
return false, errors.Wrap(err, "get abs path")
}
mounts, err := exec.Command("mount").Output()
if err != nil {
return false, errors.Wrap(err, "run mount command")
}
for _, line := range strings.Split(string(mounts), "\n") {
// I know, I know, this is a rare band-aid.
if strings.HasPrefix(line, devPathPrefix) || strings.HasPrefix(line, absDevPathPrefix) {
return true, nil
}
}
return false, nil
}
2023-09-01 11:44:49 +01:00
func CheckValidDevicePath(devPath string) error {
stat, err := os.Stat(devPath)
if err != nil {
return errors.Wrap(err, "stat path")
}
isDev := stat.Mode()&os.ModeDevice != 0
if !isDev {
2023-09-01 16:40:41 +01:00
return fmt.Errorf("file mode is not device (%v)", stat.Mode())
2023-09-01 11:44:49 +01:00
}
return nil
}
func CheckRunAsRoot() (bool, error) {
currentUser, err := user.Current()
if err != nil {
return false, errors.Wrap(err, "get current user")
}
return currentUser.Username == "root", nil
}