A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): detect host os, memory, ownership and low ports
Hampusc9fcc9733e5c
diff --git a/fluxer_rexctl/internal/host/exec.go b/fluxer_rexctl/internal/host/exec.gonew file mode 100644index 000000000..de255757d--- /dev/null+++ b/fluxer_rexctl/internal/host/exec.go@@ -0,0 +1,87 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "bufio"+ "bytes"+ "context"+ "errors"+ "fmt"+ "io"+ "os"+ "os/exec"+ "strings"+ "sync"+)++var ErrNeedsRoot = errors.New("host: needs root or sudo")++func privileged(name string, args ...string) (string, []string, error) {+ if isRoot() {+ return name, args, nil+ }+ sudo, err := exec.LookPath("sudo")+ if err != nil {+ return "", nil, ErrNeedsRoot+ }+ return sudo, append([]string{name}, args...), nil+}++func output(ctx context.Context, quiet bool, name string, args ...string) ([]byte, error) {+ bin, argv, err := privileged(name, args...)+ if err != nil {+ return nil, err+ }+ if quiet && bin != name {+ argv = append([]string{"-n"}, argv...)+ }+ cmd := exec.CommandContext(ctx, bin, argv...)+ var stderr bytes.Buffer+ cmd.Stderr = &stderr+ if !quiet {+ cmd.Stdin = os.Stdin+ }+ out, err := cmd.Output()+ if err != nil {+ return out, fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))+ }+ return out, nil+}++func stream(ctx context.Context, log func(string), name string, args ...string) error {+ bin, argv, err := privileged(name, args...)+ if err != nil {+ return err+ }+ cmd := exec.CommandContext(ctx, bin, argv...)+ cmd.Stdin = os.Stdin+ pr, pw := io.Pipe()+ cmd.Stdout = pw+ cmd.Stderr = pw+ var wg sync.WaitGroup+ wg.Add(1)+ go func() {+ defer wg.Done()+ s := bufio.NewScanner(pr)+ s.Buffer(make([]byte, 64*1024), 1024*1024)+ for s.Scan() {+ if log != nil {+ log(s.Text())+ }+ }+ _, _ = io.Copy(io.Discard, pr)+ }()+ err = cmd.Run()+ _ = pw.Close()+ wg.Wait()+ if err != nil {+ return fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)+ }+ return nil+}++func has(name string) bool {+ _, err := exec.LookPath(name)+ return err == nil+}diff --git a/fluxer_rexctl/internal/host/host.go b/fluxer_rexctl/internal/host/host.gonew file mode 100644index 000000000..989404e44--- /dev/null+++ b/fluxer_rexctl/internal/host/host.go@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "bufio"+ "bytes"+ "context"+ "os"+ "path/filepath"+ "runtime"+ "strings"+)++type Info struct {+ OS string+ Distro string+ DistroVersion string+ Arch string+ MemoryBytes uint64+ FreeDiskBytes uint64+ Root bool+ WSL bool+}++func Detect(ctx context.Context, dir string) (*Info, error) {+ info := &Info{OS: runtime.GOOS, Arch: runtime.GOARCH, Root: isRoot()}+ if info.OS == "linux" {+ if data, err := os.ReadFile("/etc/os-release"); err == nil {+ info.Distro, info.DistroVersion = parseOSRelease(data)+ }+ if data, err := os.ReadFile("/proc/sys/kernel/osrelease"); err == nil {+ info.WSL = strings.Contains(strings.ToLower(string(data)), "microsoft")+ }+ }+ if mem, err := Memory(); err == nil {+ info.MemoryBytes = mem+ }+ if free, err := FreeDisk(existingParent(dir)); err == nil {+ info.FreeDiskBytes = free+ }+ return info, ctx.Err()+}++func isRoot() bool {+ return runtime.GOOS != "windows" && os.Geteuid() == 0+}++func parseOSRelease(data []byte) (id, version string) {+ s := bufio.NewScanner(bytes.NewReader(data))+ for s.Scan() {+ k, v, ok := strings.Cut(strings.TrimSpace(s.Text()), "=")+ if !ok {+ continue+ }+ v = strings.Trim(v, `"'`)+ switch k {+ case "ID":+ id = strings.ToLower(v)+ case "VERSION_ID":+ version = v+ }+ }+ return id, version+}++func existingParent(dir string) string {+ if dir == "" {+ dir = "."+ }+ p, err := filepath.Abs(dir)+ if err != nil {+ return dir+ }+ for {+ if _, err := os.Stat(p); err == nil {+ return p+ }+ parent := filepath.Dir(p)+ if parent == p {+ return p+ }+ p = parent+ }+}diff --git a/fluxer_rexctl/internal/host/low_ports.go b/fluxer_rexctl/internal/host/low_ports.gonew file mode 100644index 000000000..c0f7cb699--- /dev/null+++ b/fluxer_rexctl/internal/host/low_ports.go@@ -0,0 +1,36 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "context"+ "os"+ "runtime"+ "strconv"+ "strings"+)++const (+ LowPortsSetting = "net.ipv4.ip_unprivileged_port_start = 80"+ LowPortsFile = "/etc/sysctl.d/60-fluxer-ports.conf"+)++func LowPortsBlocked(rootless bool) bool {+ if !rootless || runtime.GOOS != "linux" {+ return false+ }+ data, err := os.ReadFile("/proc/sys/net/ipv4/ip_unprivileged_port_start")+ if err != nil {+ return false+ }+ n, err := strconv.Atoi(strings.TrimSpace(string(data)))+ return err == nil && n > 80+}++func AllowLowPorts(ctx context.Context) error {+ if _, err := output(ctx, false, "sh", "-c", "printf '"+LowPortsSetting+"\\n' > "+LowPortsFile); err != nil {+ return err+ }+ _, err := output(ctx, false, "sysctl", "-p", LowPortsFile)+ return err+}diff --git a/fluxer_rexctl/internal/host/owner_unix.go b/fluxer_rexctl/internal/host/owner_unix.gonew file mode 100644index 000000000..ca1620084--- /dev/null+++ b/fluxer_rexctl/internal/host/owner_unix.go@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++//go:build !windows++package host++import (+ "os"+ "os/user"+ "strconv"+ "syscall"+)++func dirOwner(dir string) string {+ info, err := os.Stat(dir)+ if err != nil {+ return ""+ }+ st, ok := info.Sys().(*syscall.Stat_t)+ if !ok || st.Uid == 0 {+ return ""+ }+ u, err := user.LookupId(strconv.FormatUint(uint64(st.Uid), 10))+ if err != nil {+ return strconv.FormatUint(uint64(st.Uid), 10)+ }+ return u.Username+}diff --git a/fluxer_rexctl/internal/host/owner_windows.go b/fluxer_rexctl/internal/host/owner_windows.gonew file mode 100644index 000000000..a692bce7f--- /dev/null+++ b/fluxer_rexctl/internal/host/owner_windows.go@@ -0,0 +1,5 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++func dirOwner(string) string { return "" }diff --git a/fluxer_rexctl/internal/host/sys.go b/fluxer_rexctl/internal/host/sys.gonew file mode 100644index 000000000..caaad6ee7--- /dev/null+++ b/fluxer_rexctl/internal/host/sys.go@@ -0,0 +1,181 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "context"+ "crypto/rand"+ "encoding/binary"+ "errors"+ "fmt"+ "net"+ "time"+)++var ErrNoPublicIP = errors.New("host: no STUN server answered")++var stunServers = []string{+ "stun.cloudflare.com:3478",+ "stun.l.google.com:19302",+ "stun1.l.google.com:19302",+}++const (+ stunMagic = 0x2112A442+ stunBindingRequest = 0x0001+ stunBindingSuccess = 0x0101+ stunMappedAddress = 0x0001+ stunXORMapped = 0x0020+)++func PublicIP(ctx context.Context) (string, error) {+ var last error = ErrNoPublicIP+ for _, network := range []string{"udp4", "udp6"} {+ for _, server := range stunServers {+ ip, err := stunQuery(ctx, network, server)+ if err == nil {+ return ip.String(), nil+ }+ last = err+ if ctx.Err() != nil {+ return "", ctx.Err()+ }+ }+ }+ return "", fmt.Errorf("%w: %v", ErrNoPublicIP, last)+}++func stunQuery(ctx context.Context, network, server string) (net.IP, error) {+ ctx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ var d net.Dialer+ conn, err := d.DialContext(ctx, network, server)+ if err != nil {+ return nil, err+ }+ defer conn.Close()+ if deadline, ok := ctx.Deadline(); ok {+ _ = conn.SetDeadline(deadline)+ }+ req := make([]byte, 20)+ binary.BigEndian.PutUint16(req[0:], stunBindingRequest)+ binary.BigEndian.PutUint32(req[4:], stunMagic)+ if _, err := rand.Read(req[8:20]); err != nil {+ return nil, err+ }+ buf := make([]byte, 1500)+ for attempt := 0; attempt < 2; attempt++ {+ if _, err := conn.Write(req); err != nil {+ return nil, err+ }+ n, err := conn.Read(buf)+ if err != nil {+ continue+ }+ ip, err := parseSTUN(buf[:n], req[8:20])+ if err == nil {+ return ip, nil+ }+ }+ return nil, fmt.Errorf("host: no answer from %s", server)+}++func parseSTUN(msg, txid []byte) (net.IP, error) {+ if len(msg) < 20 || binary.BigEndian.Uint16(msg[0:]) != stunBindingSuccess {+ return nil, errors.New("host: not a STUN binding response")+ }+ if binary.BigEndian.Uint32(msg[4:]) != stunMagic || string(msg[8:20]) != string(txid) {+ return nil, errors.New("host: STUN response for another request")+ }+ length := int(binary.BigEndian.Uint16(msg[2:]))+ if 20+length > len(msg) {+ return nil, errors.New("host: short STUN response")+ }+ attrs := msg[20 : 20+length]+ var mapped net.IP+ for len(attrs) >= 4 {+ typ := binary.BigEndian.Uint16(attrs[0:])+ alen := int(binary.BigEndian.Uint16(attrs[2:]))+ if 4+alen > len(attrs) {+ break+ }+ val := attrs[4 : 4+alen]+ switch typ {+ case stunXORMapped:+ if ip := stunAddress(val, true, txid); ip != nil {+ return ip, nil+ }+ case stunMappedAddress:+ mapped = stunAddress(val, false, txid)+ }+ attrs = attrs[4+(alen+3)&^3:]+ }+ if mapped != nil {+ return mapped, nil+ }+ return nil, errors.New("host: STUN response has no address")+}++func stunAddress(val []byte, xor bool, txid []byte) net.IP {+ if len(val) < 8 {+ return nil+ }+ var size int+ switch val[1] {+ case 0x01:+ size = net.IPv4len+ case 0x02:+ size = net.IPv6len+ default:+ return nil+ }+ if len(val) < 4+size {+ return nil+ }+ ip := make(net.IP, size)+ copy(ip, val[4:4+size])+ if xor {+ key := make([]byte, 16)+ binary.BigEndian.PutUint32(key, stunMagic)+ copy(key[4:], txid)+ for i := range ip {+ ip[i] ^= key[i]+ }+ }+ return ip+}++func PortInUse(proto string, port int) (bool, string, error) {+ if proto != "tcp" && proto != "udp" {+ return false, "", fmt.Errorf("host: unknown protocol %q", proto)+ }+ if port <= 0 || port > 65535 {+ return false, "", fmt.Errorf("host: port %d is out of range", port)+ }+ return portInUse(proto, port)+}++func bindTest(proto string, port int) (bool, error) {+ addr := fmt.Sprintf(":%d", port)+ var err error+ if proto == "tcp" {+ var l net.Listener+ l, err = net.Listen("tcp", addr)+ if err == nil {+ _ = l.Close()+ }+ } else {+ var c net.PacketConn+ c, err = net.ListenPacket("udp", addr)+ if err == nil {+ _ = c.Close()+ }+ }+ if err == nil {+ return false, nil+ }+ if addrInUse(err) {+ return true, nil+ }+ return false, err+}diff --git a/fluxer_rexctl/internal/host/sys_darwin.go b/fluxer_rexctl/internal/host/sys_darwin.gonew file mode 100644index 000000000..fe0d30590--- /dev/null+++ b/fluxer_rexctl/internal/host/sys_darwin.go@@ -0,0 +1,59 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "bufio"+ "bytes"+ "context"+ "errors"+ "fmt"+ "os/exec"+ "strings"+ "syscall"+ "time"++ "golang.org/x/sys/unix"+)++func Memory() (uint64, error) { return unix.SysctlUint64("hw.memsize") }++func FreeDisk(path string) (uint64, error) {+ var st unix.Statfs_t+ if err := unix.Statfs(existingParent(path), &st); err != nil {+ return 0, err+ }+ return st.Bavail * uint64(st.Bsize), nil+}++func addrInUse(err error) bool { return errors.Is(err, syscall.EADDRINUSE) }++func portInUse(proto string, port int) (bool, string, error) {+ used, err := bindTest(proto, port)+ if err != nil || !used {+ return used, "", err+ }+ return true, lsofOwner(proto, port), nil+}++func lsofOwner(proto string, port int) string {+ if !has("lsof") {+ return ""+ }+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ args := []string{"-nP", "-F", "c"}+ if proto == "tcp" {+ args = append(args, fmt.Sprintf("-iTCP:%d", port), "-sTCP:LISTEN")+ } else {+ args = append(args, fmt.Sprintf("-iUDP:%d", port))+ }+ out, _ := exec.CommandContext(ctx, "lsof", args...).Output()+ s := bufio.NewScanner(bytes.NewReader(out))+ for s.Scan() {+ if name, ok := strings.CutPrefix(s.Text(), "c"); ok && name != "" {+ return name+ }+ }+ return ""+}diff --git a/fluxer_rexctl/internal/host/sys_linux.go b/fluxer_rexctl/internal/host/sys_linux.gonew file mode 100644index 000000000..f55b8a2ed--- /dev/null+++ b/fluxer_rexctl/internal/host/sys_linux.go@@ -0,0 +1,135 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "bufio"+ "bytes"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "syscall"+)++func Memory() (uint64, error) {+ data, err := os.ReadFile("/proc/meminfo")+ if err != nil {+ return 0, err+ }+ return parseMeminfo(data)+}++func parseMeminfo(data []byte) (uint64, error) {+ s := bufio.NewScanner(bytes.NewReader(data))+ for s.Scan() {+ fields := strings.Fields(s.Text())+ if len(fields) >= 2 && fields[0] == "MemTotal:" {+ kb, err := strconv.ParseUint(fields[1], 10, 64)+ if err != nil {+ return 0, err+ }+ return kb * 1024, nil+ }+ }+ return 0, errors.New("host: no MemTotal in /proc/meminfo")+}++func FreeDisk(path string) (uint64, error) {+ var st syscall.Statfs_t+ if err := syscall.Statfs(existingParent(path), &st); err != nil {+ return 0, err+ }+ return st.Bavail * uint64(st.Bsize), nil+}++func addrInUse(err error) bool { return errors.Is(err, syscall.EADDRINUSE) }++func portInUse(proto string, port int) (bool, string, error) {+ inodes, err := listeningInodes(proto, port)+ if err != nil {+ used, berr := bindTest(proto, port)+ return used, "", berr+ }+ if len(inodes) == 0 {+ return false, "", nil+ }+ return true, socketOwner(inodes), nil+}++func listeningInodes(proto string, port int) (map[string]bool, error) {+ inodes := map[string]bool{}+ read := 0+ for _, name := range []string{proto, proto + "6"} {+ data, err := os.ReadFile(filepath.Join("/proc/net", name))+ if err != nil {+ continue+ }+ read+++ for _, ino := range parseProcNet(data, proto, port) {+ inodes[ino] = true+ }+ }+ if read == 0 {+ return nil, errors.New("host: /proc/net is not readable")+ }+ return inodes, nil+}++func parseProcNet(data []byte, proto string, port int) []string {+ want := fmt.Sprintf(":%04X", port)+ var out []string+ s := bufio.NewScanner(bytes.NewReader(data))+ first := true+ for s.Scan() {+ if first {+ first = false+ continue+ }+ f := strings.Fields(s.Text())+ if len(f) < 10 || !strings.HasSuffix(f[1], want) {+ continue+ }+ if proto == "tcp" && f[3] != "0A" {+ continue+ }+ if proto == "udp" && f[3] != "07" {+ continue+ }+ out = append(out, f[9])+ }+ return out+}++func socketOwner(inodes map[string]bool) string {+ procs, err := os.ReadDir("/proc")+ if err != nil {+ return ""+ }+ for _, p := range procs {+ if _, err := strconv.Atoi(p.Name()); err != nil {+ continue+ }+ fdDir := filepath.Join("/proc", p.Name(), "fd")+ fds, err := os.ReadDir(fdDir)+ if err != nil {+ continue+ }+ for _, fd := range fds {+ link, err := os.Readlink(filepath.Join(fdDir, fd.Name()))+ if err != nil || !strings.HasPrefix(link, "socket:[") {+ continue+ }+ if inodes[strings.TrimSuffix(strings.TrimPrefix(link, "socket:["), "]")] {+ comm, err := os.ReadFile(filepath.Join("/proc", p.Name(), "comm"))+ if err != nil {+ return ""+ }+ return strings.TrimSpace(string(comm))+ }+ }+ }+ return ""+}diff --git a/fluxer_rexctl/internal/host/sys_windows.go b/fluxer_rexctl/internal/host/sys_windows.gonew file mode 100644index 000000000..03b841805--- /dev/null+++ b/fluxer_rexctl/internal/host/sys_windows.go@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "errors"+ "unsafe"++ "golang.org/x/sys/windows"+)++type memoryStatusEx struct {+ Length uint32+ MemoryLoad uint32+ TotalPhys uint64+ AvailPhys uint64+ TotalPageFile uint64+ AvailPageFile uint64+ TotalVirtual uint64+ AvailVirtual uint64+ AvailExtendedVirtual uint64+}++var procGlobalMemoryStatusEx = windows.NewLazySystemDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx")++func Memory() (uint64, error) {+ var m memoryStatusEx+ m.Length = uint32(unsafe.Sizeof(m))+ r, _, err := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&m)))+ if r == 0 {+ return 0, err+ }+ return m.TotalPhys, nil+}++func FreeDisk(path string) (uint64, error) {+ p, err := windows.UTF16PtrFromString(existingParent(path))+ if err != nil {+ return 0, err+ }+ var free, total, totalFree uint64+ if err := windows.GetDiskFreeSpaceEx(p, &free, &total, &totalFree); err != nil {+ return 0, err+ }+ return free, nil+}++func addrInUse(err error) bool {+ return errors.Is(err, windows.WSAEADDRINUSE) || errors.Is(err, windows.WSAEACCES)+}++func portInUse(proto string, port int) (bool, string, error) {+ used, err := bindTest(proto, port)+ return used, "", err+}