package main

// What the agent is allowed to see here (its mode), what the machine is (virtualization), and the
// agent's own footprint (CPU and memory, reported in every rollup so you can check its cost).

import (
	"bytes"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// Linux capability numbers (include/uapi/linux/capability.h).
const (
	capDacOverride   = 1
	capDacReadSearch = 2
	capSysPtrace     = 19
	capSysAdmin      = 21
)

// Identity: how the agent runs.
type Identity struct {
	UID     int
	Root    bool
	DacRead bool // CAP_DAC_READ_SEARCH: may read any file (never writes: the unit's filesystem is read-only)
	Ptrace  bool // CAP_SYS_PTRACE: may look at other users' /proc/<pid>/fd, exe and io (PTRACE_MODE_READ checks)
	Caps    []string
	Mode    string // unprivileged | detailed | root
}

// DetectIdentity reads the effective capabilities from /proc/self/status (CapEff).
func DetectIdentity(procRoot string) Identity {
	id := Identity{UID: os.Geteuid()}
	id.Root = id.UID == 0
	var eff uint64
	if b, err := readSmall(filepath.Join(procRoot, "self/status"), 64*1024); err == nil {
		eff = ParseCapEff(b)
	}
	has := func(n uint) bool { return eff&(1<<n) != 0 }
	id.DacRead = has(capDacReadSearch) || has(capDacOverride)
	id.Ptrace = has(capSysPtrace)
	if has(capDacReadSearch) {
		id.Caps = append(id.Caps, "dac_read_search")
	}
	if has(capDacOverride) {
		id.Caps = append(id.Caps, "dac_override")
	}
	if has(capSysPtrace) {
		id.Caps = append(id.Caps, "sys_ptrace")
	}
	if has(capSysAdmin) {
		id.Caps = append(id.Caps, "sys_admin")
	}
	switch {
	case id.Root:
		id.Mode = "root"
	case id.DacRead || id.Ptrace:
		id.Mode = "detailed"
	default:
		id.Mode = "unprivileged"
	}
	return id
}

// ParseCapEff returns the CapEff mask of a /proc/<pid>/status file.
func ParseCapEff(b []byte) uint64 {
	for _, l := range bytes.Split(b, []byte("\n")) {
		if bytes.HasPrefix(l, []byte("CapEff:")) {
			v, err := strconv.ParseUint(strings.TrimSpace(string(l[7:])), 16, 64)
			if err == nil {
				return v
			}
		}
	}
	return 0
}

// SeesOthers: the kernel shows this agent other users' fd / exe / io links.
func (id Identity) SeesOthers() bool { return id.Root || id.Ptrace }

// ---------------------------------------------------------------------------
// virtualization
// ---------------------------------------------------------------------------

type VirtInfo struct {
	Virt    string // kvm | qemu | vmware | microsoft | xen | oracle | amazon | google | openstack | parallels | docker | lxc | podman | wsl | container | vm | none | ""
	Vendor  string
	Product string
}

// DetectVirt tells what the machine is without running systemd-detect-virt: container markers
// first (/run/systemd/container, /.dockerenv, /run/.containerenv, container= in PID 1's
// environment), then WSL, then the DMI strings in /sys/class/dmi/id, /sys/hypervisor and the
// "hypervisor" CPU flag.
func DetectVirt(root, proc, sys string) VirtInfo {
	var v VirtInfo
	rd := func(p string) string {
		b, err := readSmall(p, 4096)
		if err != nil {
			return ""
		}
		return strings.TrimSpace(string(b))
	}
	v.Vendor = truncate(rd(filepath.Join(sys, "class/dmi/id/sys_vendor")), 80)
	v.Product = truncate(rd(filepath.Join(sys, "class/dmi/id/product_name")), 80)
	if c := rd(filepath.Join(root, "run/systemd/container")); c != "" {
		v.Virt = containerKind(c)
		return v
	}
	if exists(filepath.Join(root, ".dockerenv")) {
		v.Virt = "docker"
		return v
	}
	if exists(filepath.Join(root, "run/.containerenv")) {
		v.Virt = "podman"
		return v
	}
	if b, err := readSmall(filepath.Join(proc, "1/environ"), 64*1024); err == nil {
		for _, kv := range bytes.Split(b, []byte{0}) {
			if bytes.HasPrefix(kv, []byte("container=")) {
				v.Virt = containerKind(string(kv[len("container="):]))
				return v
			}
		}
	}
	if strings.Contains(strings.ToLower(rd(filepath.Join(proc, "sys/kernel/osrelease"))), "microsoft") {
		v.Virt = "wsl"
		return v
	}
	if k := VirtFromDMI(v.Vendor, v.Product, rd(filepath.Join(sys, "class/dmi/id/bios_vendor"))); k != "" {
		v.Virt = k
		return v
	}
	if strings.Contains(strings.ToLower(rd(filepath.Join(sys, "hypervisor/type"))), "xen") {
		v.Virt = "xen"
		return v
	}
	if b, err := readSmall(filepath.Join(proc, "cpuinfo"), 256*1024); err == nil {
		for _, l := range strings.Split(string(b), "\n") {
			if strings.HasPrefix(l, "flags") || strings.HasPrefix(l, "Features") {
				if strings.Contains(" "+l+" ", " hypervisor ") {
					v.Virt = "vm"
				} else if v.Vendor != "" {
					v.Virt = "none"
				}
				break
			}
		}
	}
	return v
}

func containerKind(s string) string {
	s = strings.ToLower(strings.TrimSpace(s))
	switch {
	case strings.HasPrefix(s, "docker"):
		return "docker"
	case strings.HasPrefix(s, "lxc"):
		return "lxc"
	case strings.HasPrefix(s, "podman"):
		return "podman"
	case s == "":
		return ""
	}
	return "container"
}

// VirtFromDMI maps the DMI vendor / product / BIOS vendor strings to a hypervisor.
func VirtFromDMI(vendor, product, bios string) string {
	all := strings.ToLower(vendor + " | " + product + " | " + bios)
	switch {
	case strings.Contains(all, "amazon ec2") || strings.Contains(all, "amazon"):
		return "amazon"
	case strings.Contains(all, "google"):
		return "google"
	case strings.Contains(all, "vmware"):
		return "vmware"
	case strings.Contains(all, "microsoft corporation") && strings.Contains(all, "virtual"):
		return "microsoft"
	case strings.Contains(all, "innotek") || strings.Contains(all, "virtualbox"):
		return "oracle"
	case strings.Contains(all, "xen"):
		return "xen"
	case strings.Contains(all, "parallels"):
		return "parallels"
	case strings.Contains(all, "openstack"):
		return "openstack"
	case strings.Contains(all, "kvm") || strings.Contains(all, "digitalocean") || strings.Contains(all, "hetzner") ||
		strings.Contains(all, "alibaba") || strings.Contains(all, "rhev") || strings.Contains(all, "linode") || strings.Contains(all, "vultr") ||
		strings.Contains(all, "scaleway") || strings.Contains(all, "ovh") || strings.Contains(all, "contabo"):
		return "kvm"
	case strings.Contains(all, "qemu") || strings.Contains(all, "bochs") || strings.Contains(all, "seabios"):
		return "qemu"
	}
	return ""
}

// ---------------------------------------------------------------------------
// the agent's own footprint
// ---------------------------------------------------------------------------

// selfStats: the agent's CPU time and resident memory, from /proc/self/stat at each sample.
type selfStats struct {
	buf       []byte
	f         [24][]byte
	prevTicks uint64
	prevT     time.Time
	have      bool
	winTicks  uint64
	winT      time.Time
	peak      float64
	rssSum    int64
	rssMax    int64
	rssN      int64
}

func (s *selfStats) sample(procRoot string, now time.Time) {
	if s.buf == nil {
		s.buf = make([]byte, 1024)
	}
	n, err := readInto(procRoot+"/self/stat", s.buf)
	if err != nil {
		return
	}
	var st PidStat
	if _, ok := parsePidStatInto(s.buf[:n], &st, s.f[:]); !ok {
		return
	}
	ticks := st.UTime + st.STime
	if s.have {
		if el := now.Sub(s.prevT).Seconds(); el > 0 && ticks >= s.prevTicks {
			s.peak = maxF(s.peak, 100*float64(ticks-s.prevTicks)/clockTicks/el)
		}
	} else {
		s.winTicks, s.winT = ticks, now
	}
	s.prevTicks, s.prevT, s.have = ticks, now, true
	rss := st.RSSPages * pageSize
	s.rssSum += rss
	s.rssN++
	if rss > s.rssMax {
		s.rssMax = rss
	}
}

// window closes the rollup window: average CPU (% of one core) and memory since the previous call.
func (s *selfStats) window(now time.Time) (cpu, peak float64, rss, rssMax, windowS int64) {
	if !s.have {
		return 0, 0, 0, 0, 0
	}
	if el := s.prevT.Sub(s.winT).Seconds(); el > 0 && s.prevTicks >= s.winTicks {
		cpu = 100 * float64(s.prevTicks-s.winTicks) / clockTicks / el
	}
	windowS = int64(now.Sub(s.winT).Seconds())
	if s.rssN > 0 {
		rss = s.rssSum / s.rssN
	}
	peak, rssMax = s.peak, s.rssMax
	s.winTicks, s.winT = s.prevTicks, s.prevT
	s.peak, s.rssSum, s.rssN, s.rssMax = 0, 0, 0, 0
	return round3(cpu), round3(peak), rss, rssMax, windowS
}

func round3(v float64) float64 { return float64(int64(v*1000+0.5)) / 1000 }

// ---------------------------------------------------------------------------
// helpers of the collector
// ---------------------------------------------------------------------------

// procNameSet: the process names of the latest sample (time, firewall and fail2ban daemons).
func (c *Collector) procNameSet() map[string]bool {
	if c.namesAt == c.namesGen && c.procNames != nil {
		return c.procNames
	}
	names := make(map[string]bool, 128)
	for _, p := range c.lastProcs {
		if !p.kernel && len(names) < 4096 {
			names[p.Name] = true
		}
	}
	c.procNames, c.namesAt = names, c.namesGen
	return names
}

// procRefs copies what the worker needs about the processes of the latest sample.
func (c *Collector) procRefs() []procRef {
	out := make([]procRef, 0, len(c.lastProcs))
	for _, p := range c.lastProcs {
		out = append(out, procRef{PID: p.PID, Start: p.startTime, Kernel: p.kernel})
	}
	return out
}

// withUnits adds the systemd unit to the top processes (their cgroup is read once per process).
func (c *Collector) withUnits(ps []Proc) []Proc {
	for i := range ps {
		ps[i].Unit = c.procs.UnitOf(ps[i].PID)
	}
	return ps
}
