package main

import (
	"bytes"
	"os"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"
)

const clockTicks = 100 // USER_HZ: 100 on every Linux build for amd64 and arm64

var pageSize = int64(os.Getpagesize())

// Proc is one process as reported (top lists and signal evidence).
type Proc struct {
	PID   int     `json:"pid"`
	Name  string  `json:"name"`
	User  string  `json:"user"`
	Exe   string  `json:"exe,omitempty"`
	Cmd   string  `json:"cmd,omitempty"`
	CPU   float64 `json:"cpu"`                  // percent of one core over the last sample interval
	RSS   int64   `json:"rss"`                  // bytes
	Unit  string  `json:"unit,omitempty"`       // systemd unit (0.3.0), from /proc/<pid>/cgroup
	Start int64   `json:"started_at,omitempty"` // unix seconds (0.3.0)
	// internal
	uid       int
	cmdRaw    string // the command line as read, never sent (Reported() redacts it into Cmd)
	argv0     string
	exeKnown  bool
	startTime uint64
	kernel    bool
	minerWhy  string // MinerMatch, computed when the command line was read
	sigDone   bool   // minerWhy is set (Procs built by hand in tests leave it false)
	cmdRed    string // Redact(cmdRaw), computed when the command line was read
	redDone   bool
}

// procEntry is what the sampler remembers about one process (pid + start time) between samples:
// the CPU ticks of the previous sample, and what is read only when the process is first seen and
// then again every refreshEvery samples (owner, executable, command line, the miner verdict).
type procEntry struct {
	start    uint64
	ticks    uint64    // utime+stime at the previous sample
	at       time.Time // when they were read (the sample is spread over a few seconds)
	gen      uint32
	uid      int
	user     string
	name     string
	exe      string
	exeKnown bool
	argv0    string
	cmdRaw   string
	cmdRed   string // redacted once per read of the command line, not at every report
	minerWhy string
	unit     string
	unitRead bool
}

// ProcSampler reads /proc/<pid>/stat of every process once per sample (one small read, parsed
// without allocating) and keeps the CPU ticks of the previous sample to turn them into a
// percentage. The owner, the executable path and the command line of a process are read when it
// is first seen and then once every refreshEvery samples, spread over the pids (so a sample never
// re-reads all of them at once): a command line rewritten later, or a binary deleted after start,
// is still noticed within that period.
type ProcSampler struct {
	root         string
	ents         map[int]*procEntry
	prevT        time.Time
	users        *UserCache
	gen          uint32
	refreshEvery uint32
	bootTime     int64
	buf          []byte // /proc/<pid>/stat
	lbuf         []byte // readlink
	cbuf         []byte // cmdline, cgroup
	out          []Proc
	fields       [24][]byte
	pbuf         []byte
	// Gentle mode: the processes are read in chunks of Chunk with a Pause between chunks (the
	// kernel spends most of a sample generating the stat files), so a sample of a few hundred
	// processes is spread over a second or two instead of one burst. Sleep nil: no pauses (tests).
	Chunk int
	Pause time.Duration
	Sleep func(time.Duration)
}

func NewProcSampler(root string, users *UserCache) *ProcSampler {
	return &ProcSampler{root: root, ents: map[int]*procEntry{}, users: users, refreshEvery: 15,
		buf: make([]byte, 1024), lbuf: make([]byte, 4096), cbuf: make([]byte, 4096)}
}

// maxProcs bounds the work per sample on a machine with an extreme number of processes.
const maxProcs = 32768

// Sample returns every process. The slice is reused by the next call: callers copy what they keep.
func (s *ProcSampler) Sample(now time.Time) []Proc {
	d, err := os.Open(s.root)
	if err != nil {
		return nil
	}
	names, _ := d.Readdirnames(maxProcs + 512)
	d.Close()
	s.gen++
	out := s.out[:0]
	readAt := time.Now()
	done := 0
	for _, name := range names {
		if len(name) == 0 || name[0] < '0' || name[0] > '9' {
			continue
		}
		pid, err := strconv.Atoi(name)
		if err != nil || pid <= 0 {
			continue
		}
		if done++; s.Sleep != nil && s.Chunk > 0 && done%s.Chunk == 0 {
			s.Sleep(s.Pause)
			readAt = time.Now()
		}
		s.pbuf = append(append(append(append(s.pbuf[:0], s.root...), '/'), name...), "/stat\x00"...)
		n, err := readIntoZ(s.pbuf, s.buf)
		if err != nil || n == 0 {
			continue
		}
		var st PidStat
		comm, ok := parsePidStatInto(s.buf[:n], &st, s.fields[:])
		if !ok {
			continue
		}
		kernel := pid == 2 || st.PPid == 2
		e := s.ents[pid]
		isNew := e == nil || e.start != st.StartTime
		if isNew {
			e = &procEntry{start: st.StartTime}
			s.ents[pid] = e
		}
		e.gen = s.gen
		reread := isNew || (uint32(pid)+s.gen)%s.refreshEvery == 0
		if e.name != string(comm) {
			e.name = string(comm)
			reread = true // renamed (exec): read it again
		}
		if reread {
			s.fill(e, s.root+"/"+name, kernel)
		}
		ticks := st.UTime + st.STime
		var cpu float64
		at := readAt
		if s.Sleep == nil { // no pauses: the sample's own time (tests drive it)
			at = now
		}
		if elapsed := at.Sub(e.at).Seconds(); !isNew && elapsed > 0 && ticks >= e.ticks {
			cpu = round1(100 * float64(ticks-e.ticks) / clockTicks / elapsed)
		}
		e.ticks, e.at = ticks, at
		p := Proc{PID: pid, Name: e.name, User: e.user, Exe: e.exe, CPU: cpu, RSS: st.RSSPages * pageSize, uid: e.uid,
			cmdRaw: e.cmdRaw, argv0: e.argv0, exeKnown: e.exeKnown, startTime: st.StartTime, kernel: kernel,
			minerWhy: e.minerWhy, sigDone: true, Unit: e.unit, cmdRed: e.cmdRed, redDone: true}
		if s.bootTime > 0 {
			p.Start = s.bootTime + int64(st.StartTime/clockTicks)
		}
		out = append(out, p)
		if len(out) >= maxProcs {
			break
		}
	}
	for pid, e := range s.ents {
		if e.gen != s.gen {
			delete(s.ents, pid)
		}
	}
	s.out = out
	s.prevT = now
	return out
}

// fill reads the owner, executable and command line of one process.
func (s *ProcSampler) fill(e *procEntry, dir string, kernel bool) {
	var st syscall.Stat_t
	if err := syscall.Stat(dir, &st); err == nil {
		e.uid = int(st.Uid)
	} else {
		e.uid = -1
	}
	e.user = s.users.Name(e.uid)
	if kernel {
		return
	}
	if n, err := readlinkInto(dir+"/exe", s.lbuf); err == nil {
		if e.exe != string(s.lbuf[:n]) {
			e.exe = string(s.lbuf[:n])
		}
		e.exeKnown = true
	} else {
		e.exeKnown = false
	}
	e.argv0, e.cmdRaw = "", ""
	if n, err := readInto(dir+"/cmdline", s.cbuf); err == nil && n > 0 {
		cb := bytes.TrimRight(s.cbuf[:n], "\x00")
		if i := bytes.IndexByte(cb, 0); i >= 0 {
			e.argv0 = string(cb[:i])
		} else {
			e.argv0 = string(cb)
		}
		e.cmdRaw = strings.ReplaceAll(string(cb), "\x00", " ")
	}
	e.minerWhy = sigs.MinerMatch(e.name, e.argv0, e.cmdRaw)
	e.cmdRed = truncate(Redact(e.cmdRaw), 200)
}

// UnitOf returns the systemd unit of a process the last sample saw (read from its cgroup once).
func (s *ProcSampler) UnitOf(pid int) string {
	e := s.ents[pid]
	if e == nil {
		return ""
	}
	if !e.unitRead {
		e.unitRead = true
		if n, err := readInto(s.root+"/"+strconv.Itoa(pid)+"/cgroup", s.cbuf); err == nil {
			e.unit, _ = ParseCgroup(s.cbuf[:n])
		}
	}
	return e.unit
}

// sendCmdline: the `cmdline` check (on unless `disable: [cmdline]`).
var sendCmdline = true

// Reported is the process as it goes over the network: the command line redacted (see Redact)
// and cut to 200 characters, or left out with `disable: [cmdline]`.
func (p Proc) Reported() Proc {
	q := p
	q.Cmd = ""
	if sendCmdline {
		if p.redDone {
			q.Cmd = p.cmdRed
		} else {
			q.Cmd = truncate(Redact(p.cmdRaw), 200)
		}
	}
	q.Exe = truncate(p.Exe, 200)
	q.Name = truncate(p.Name, 64)
	q.cmdRaw, q.argv0, q.cmdRed = "", "", ""
	return q
}

var (
	// key=value and key: value where the key names a secret (DB_PASSWORD=, api_key:, ?token=)
	redactKV = regexp.MustCompile(`(?i)((?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|auth|credentials?|private[_-]?key|session[_-]?key)[\w.-]*[=:])[^\s&;,'"]+`)
	// --password VALUE, --token=VALUE ...
	redactFlag = regexp.MustCompile(`(?i)(--?(?:pass(?:word|wd|phrase)?|secret|token|api-?key|auth(?:-token)?|access-key|secret-key|private-key|client-secret)[ =])[^\s'"]+`)
	// HTTP headers on a command line (curl -H "Authorization: Bearer ...")
	redactHeader = regexp.MustCompile(`(?i)((?:authorization|proxy-authorization|x-api-key|x-auth-token|cookie)\s*[:=]\s*(?:(?:bearer|basic|token|digest)\s+)?)[^\s'"]+`)
	redactBearer = regexp.MustCompile(`(?i)(\bbearer\s+)[A-Za-z0-9._~+/=-]{8,}`)
	// user:password@ in URLs, curl -u user:password, sshpass -p
	redactURL  = regexp.MustCompile(`(://[^/\s:@]+:)[^@\s/]+@`)
	redactUser = regexp.MustCompile(`((?:^|\s)(?:-u|--user)\s*[^\s:'"]+:)[^\s'"]+`)
	redactPass = regexp.MustCompile(`(\bsshpass\s+-p\s*)\S+`)
	redactMy   = regexp.MustCompile(`(\s-p)[^\s]+`)
	// Well-known token formats, wherever they appear: JWTs, AWS access keys, GitHub / GitLab /
	// Slack / Stripe tokens, PEM private keys pasted into an argument.
	redactToken = regexp.MustCompile(`\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}|\b(?:AKIA|ASIA)[0-9A-Z]{16}\b|` +
		`\bgh[pousr]_[A-Za-z0-9]{30,}|\bgithub_pat_[A-Za-z0-9_]{30,}|\bglpat-[A-Za-z0-9_-]{20,}|\bxox[abposr]-[A-Za-z0-9-]{10,}|` +
		`\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}|-----BEGIN [A-Z ]*PRIVATE KEY-----[^-]*`)
)

// Redact hides values that look like secrets in a command line or a crontab line: key=value
// pairs named like passwords or tokens, --password values, Authorization headers, bearer tokens,
// user:password@ in URLs, curl -u user:password, sshpass -p, mysql-style -pSECRET and tokens in
// well-known formats. It errs on the side of hiding.
func Redact(cmd string) string {
	cmd = redactToken.ReplaceAllString(cmd, "***")
	cmd = redactHeader.ReplaceAllString(cmd, "${1}***")
	cmd = redactBearer.ReplaceAllString(cmd, "${1}***")
	cmd = redactKV.ReplaceAllString(cmd, "${1}***")
	cmd = redactFlag.ReplaceAllString(cmd, "${1}***")
	cmd = redactURL.ReplaceAllString(cmd, "${1}***@")
	cmd = redactUser.ReplaceAllString(cmd, "${1}***")
	cmd = redactPass.ReplaceAllString(cmd, "${1}***")
	if strings.Contains(cmd, "mysql") || strings.Contains(cmd, "mariadb") {
		cmd = redactMy.ReplaceAllString(cmd, "${1}***")
	}
	return cmd
}

// TopBy returns the n processes with the highest key (ties: lower pid first), as reported.
func TopBy(ps []Proc, n int, key func(Proc) float64) []Proc {
	cp := topRaw(ps, n, key)
	out := make([]Proc, len(cp))
	for i, p := range cp {
		out[i] = p.Reported()
	}
	return out
}

// topRaw keeps the n best in a small sorted array: one pass, no copy or sort of the whole table.
func topRaw(ps []Proc, n int, key func(Proc) float64) []Proc {
	if n <= 0 {
		return nil
	}
	top := make([]Proc, 0, n)
	keys := make([]float64, 0, n)
	better := func(k float64, p Proc, i int) bool {
		return k > keys[i] || (k == keys[i] && p.PID < top[i].PID)
	}
	for _, p := range ps {
		k := key(p)
		if len(top) == n && !better(k, p, n-1) {
			continue
		}
		i := len(top)
		if i < n {
			top = append(top, p)
			keys = append(keys, k)
		} else {
			i = n - 1
		}
		for i > 0 && better(k, p, i-1) {
			top[i], keys[i] = top[i-1], keys[i-1]
			i--
		}
		top[i], keys[i] = p, k
	}
	return top
}

// UserCache maps uids to names from /etc/passwd, reloading when the file changes.
type UserCache struct {
	path    string
	mu      sync.Mutex
	mtime   time.Time
	checked time.Time
	names   map[int]string
	all     []PasswdEntry
}

func NewUserCache(path string) *UserCache { return &UserCache{path: path, names: map[int]string{}} }

func (u *UserCache) refresh() {
	if now := time.Now(); now.Sub(u.checked) < 30*time.Second && u.names != nil && len(u.all) > 0 {
		return
	} else {
		u.checked = now
	}
	fi, err := os.Stat(u.path)
	if err != nil || fi.ModTime().Equal(u.mtime) {
		return
	}
	b, err := os.ReadFile(u.path)
	if err != nil {
		return
	}
	u.mtime = fi.ModTime()
	u.all = ParsePasswd(b)
	u.names = make(map[int]string, len(u.all))
	for _, e := range u.all {
		if _, ok := u.names[e.UID]; !ok {
			u.names[e.UID] = e.Name
		}
	}
}

func (u *UserCache) Name(uid int) string {
	u.mu.Lock()
	defer u.mu.Unlock()
	u.refresh()
	if n, ok := u.names[uid]; ok {
		return n
	}
	return strconv.Itoa(uid)
}

func (u *UserCache) All() []PasswdEntry {
	u.mu.Lock()
	defer u.mu.Unlock()
	u.refresh()
	return append([]PasswdEntry(nil), u.all...)
}

func fileUID(fi os.FileInfo) int {
	if st, ok := fi.Sys().(*syscall.Stat_t); ok {
		return int(st.Uid)
	}
	return -1
}

func round1(v float64) float64 { return float64(int64(v*10+0.5)) / 10 }

func itoa(n int) string     { return strconv.Itoa(n) }
func itoa64(n int64) string { return strconv.FormatInt(n, 10) }
