package main

// A minimal D-Bus client: just enough of the wire protocol
// (https://dbus.freedesktop.org/doc/dbus-specification.html) to ask systemd for its units over the
// system bus, as `systemctl list-units` does, without running systemctl. It authenticates as its
// own uid (EXTERNAL), says Hello and calls read-only methods any user may call:
// org.freedesktop.systemd1.Manager.ListUnits, and, for a failed unit only,
// org.freedesktop.DBus.Properties.GetAll on that unit (its description, result, exit code or
// signal, restart count and when it failed: what `systemctl status` shows). Every read is bounded
// and the whole exchange has a deadline.

import (
	"bufio"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"net"
	"os"
	"strconv"
	"strings"
	"time"
)

const (
	dbusMethodCall   = 1
	dbusMethodReturn = 2
	dbusError        = 3
	dbusSignal       = 4
	dbusMaxMessage   = 16 << 20
	dbusMaxDepth     = 32
)

// UnitInfo is one loaded systemd unit.
type UnitInfo struct {
	Name, Description, LoadState, ActiveState, SubState string
	Path                                                string // D-Bus object path
}

// UnitDetail is what systemd says about a failed unit.
type UnitDetail struct {
	Unit        string   `json:"unit"`
	Description string   `json:"description,omitempty"`
	Result      string   `json:"result,omitempty"` // exit-code | signal | core-dump | timeout | start-limit-hit | resources | oom-kill …
	ExitCode    *int     `json:"exit_code"`        // the main process's exit status (203 = EXEC: binary missing …)
	Signal      *string  `json:"signal"`           // SIGKILL … when it was killed
	Restarts    *int     `json:"restarts"`
	Since       int64    `json:"since,omitempty"` // when it entered the failed state
	Log         []string `json:"log,omitempty"`   // the last lines it logged (redacted), only once after it newly failed
}

var signalNames = map[int]string{1: "SIGHUP", 2: "SIGINT", 3: "SIGQUIT", 4: "SIGILL", 5: "SIGTRAP", 6: "SIGABRT", 7: "SIGBUS",
	8: "SIGFPE", 9: "SIGKILL", 10: "SIGUSR1", 11: "SIGSEGV", 12: "SIGUSR2", 13: "SIGPIPE", 14: "SIGALRM", 15: "SIGTERM", 24: "SIGXCPU", 25: "SIGXFSZ"}

// unitIface: the interface that carries Result for a unit type.
func unitIface(name string) string {
	i := strings.LastIndexByte(name, '.')
	if i < 0 {
		return ""
	}
	switch name[i+1:] {
	case "service":
		return "org.freedesktop.systemd1.Service"
	case "socket":
		return "org.freedesktop.systemd1.Socket"
	case "mount":
		return "org.freedesktop.systemd1.Mount"
	case "timer":
		return "org.freedesktop.systemd1.Timer"
	case "swap":
		return "org.freedesktop.systemd1.Swap"
	case "path":
		return "org.freedesktop.systemd1.Path"
	case "scope":
		return "org.freedesktop.systemd1.Scope"
	case "automount":
		return "org.freedesktop.systemd1.Automount"
	}
	return ""
}

// UnitDetails asks systemd for the properties of a few units (at most 20) over one connection.
func UnitDetails(socket string, timeout time.Duration, units []UnitInfo) (map[string]UnitDetail, error) {
	out := map[string]UnitDetail{}
	if len(units) == 0 {
		return out, nil
	}
	conn, err := net.DialTimeout("unix", socket, timeout)
	if err != nil {
		return nil, err
	}
	defer conn.Close()
	_ = conn.SetDeadline(time.Now().Add(timeout))
	d := &dbusConn{w: conn, r: bufio.NewReaderSize(conn, 32*1024)}
	if err := d.auth(); err != nil {
		return nil, err
	}
	if _, _, err := d.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello"); err != nil {
		return nil, fmt.Errorf("hello: %w", err)
	}
	for i, u := range units {
		if i >= 20 || !strings.HasPrefix(u.Path, "/org/freedesktop/systemd1/unit/") {
			continue
		}
		props := map[string]any{}
		for _, iface := range []string{"org.freedesktop.systemd1.Unit", unitIface(u.Name)} {
			if iface == "" {
				continue
			}
			h, body, err := d.callArgs("org.freedesktop.systemd1", u.Path, "org.freedesktop.DBus.Properties", "GetAll", iface)
			if err != nil || h.signature != "a{sv}" {
				continue
			}
			for k, v := range parseProps(body, h.order) {
				props[k] = v
			}
		}
		out[u.Name] = unitDetailFrom(u, props)
	}
	return out, nil
}

func unitDetailFrom(u UnitInfo, p map[string]any) UnitDetail {
	ud := UnitDetail{Unit: truncate(u.Name, 120), Description: truncate(u.Description, 200)}
	if s, ok := p["Description"].(string); ok && s != "" {
		ud.Description = truncate(s, 200)
	}
	if s, ok := p["Result"].(string); ok {
		ud.Result = truncate(s, 40)
	}
	code, hasCode := p["ExecMainCode"].(int32)
	status, hasStatus := p["ExecMainStatus"].(int32)
	if hasCode && hasStatus {
		switch code {
		case 1: // CLD_EXITED
			v := int(status)
			ud.ExitCode = &v
		case 2, 3: // CLD_KILLED, CLD_DUMPED
			name := signalNames[int(status)]
			if name == "" {
				name = "SIG" + strconv.Itoa(int(status))
			}
			ud.Signal = &name
		}
	}
	if n, ok := p["NRestarts"].(uint32); ok {
		v := int(n)
		ud.Restarts = &v
	}
	for _, k := range []string{"StateChangeTimestamp", "InactiveEnterTimestamp"} {
		if t, ok := p[k].(uint64); ok && t > 0 {
			ud.Since = int64(t / 1_000_000)
			break
		}
	}
	return ud
}

// parseProps decodes the a{sv} reply of Properties.GetAll, keeping strings, integers and booleans.
func parseProps(body []byte, bo binary.ByteOrder) map[string]any {
	out := map[string]any{}
	d := &dbusDec{b: body, bo: bo}
	n := int(d.u32())
	d.align(8)
	end := d.off + n
	if d.err != nil || end > len(body) {
		return out
	}
	for d.err == nil && d.off < end && len(out) < 1000 {
		d.align(8)
		key := d.str()
		sig := d.sig()
		if d.err != nil {
			break
		}
		if k, err := typeEnd(sig, 0, 0); err != nil || k != len(sig) {
			break
		}
		switch sig {
		case "s", "o":
			out[key] = d.str()
		case "i":
			out[key] = int32(d.u32())
		case "u":
			out[key] = d.u32()
		case "t", "x":
			d.align(8)
			if d.need(8) {
				out[key] = d.bo.Uint64(d.b[d.off:])
				d.off += 8
			}
		case "b":
			out[key] = d.u32() != 0
		default:
			d.skip(sig, 1)
		}
	}
	return out
}

// SystemBusPath: $DBUS_SYSTEM_BUS_ADDRESS (unix:path=...) or the standard socket.
func SystemBusPath() string {
	if a := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS"); strings.HasPrefix(a, "unix:path=") {
		p := strings.TrimPrefix(a, "unix:path=")
		if i := strings.IndexByte(p, ','); i >= 0 {
			p = p[:i]
		}
		return p
	}
	return "/run/dbus/system_bus_socket"
}

// ListUnits returns the units systemd has loaded (active, failed, and inactive ones still referenced).
func ListUnits(socket string, timeout time.Duration) ([]UnitInfo, error) {
	conn, err := net.DialTimeout("unix", socket, timeout)
	if err != nil {
		return nil, err
	}
	defer conn.Close()
	_ = conn.SetDeadline(time.Now().Add(timeout))
	d := &dbusConn{w: conn, r: bufio.NewReaderSize(conn, 32*1024)}
	if err := d.auth(); err != nil {
		return nil, err
	}
	if _, _, err := d.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello"); err != nil {
		return nil, fmt.Errorf("hello: %w", err)
	}
	h, body, err := d.call("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "ListUnits")
	if err != nil {
		return nil, fmt.Errorf("ListUnits: %w", err)
	}
	if h.signature != "a(ssssssouso)" {
		return nil, fmt.Errorf("ListUnits: unexpected reply signature %q", h.signature)
	}
	return parseUnitList(body, h.order)
}

type dbusConn struct {
	w      io.Writer
	r      *bufio.Reader
	serial uint32
}

func (d *dbusConn) auth() error {
	uid := strconv.Itoa(os.Geteuid())
	if _, err := d.w.Write([]byte("\x00AUTH EXTERNAL " + hex.EncodeToString([]byte(uid)) + "\r\n")); err != nil {
		return err
	}
	line, err := d.r.ReadSlice('\n')
	if err != nil {
		return fmt.Errorf("auth: %w", err)
	}
	if !strings.HasPrefix(string(line), "OK ") {
		return fmt.Errorf("auth refused: %q", truncate(strings.TrimSpace(string(line)), 80))
	}
	_, err = d.w.Write([]byte("BEGIN\r\n"))
	return err
}

// call sends a method call without arguments and waits for its reply, skipping signals.
func (d *dbusConn) call(dest, path, iface, member string) (dbusHeader, []byte, error) {
	return d.callArgs(dest, path, iface, member)
}

// callArgs sends a method call with string arguments (the interface name for Properties.GetAll)
// and waits for its reply, skipping signals.
func (d *dbusConn) callArgs(dest, path, iface, member string, args ...string) (dbusHeader, []byte, error) {
	d.serial++
	if _, err := d.w.Write(encodeCall(d.serial, dest, path, iface, member, args...)); err != nil {
		return dbusHeader{}, nil, err
	}
	for i := 0; i < 64; i++ {
		h, body, err := d.read()
		if err != nil {
			return h, nil, err
		}
		if h.replySerial != d.serial || (h.typ != dbusMethodReturn && h.typ != dbusError) {
			continue // NameAcquired and other signals
		}
		if h.typ == dbusError {
			return h, nil, errors.New(truncate(h.errName, 120))
		}
		return h, body, nil
	}
	return dbusHeader{}, nil, errors.New("no reply")
}

// encodeCall builds a METHOD_CALL message (little endian) whose body is the string arguments.
func encodeCall(serial uint32, dest, path, iface, member string, args ...string) []byte {
	body := &dbusEnc{}
	for _, a := range args {
		body.str(a)
	}
	e := &dbusEnc{}
	e.b = append(e.b, 'l', dbusMethodCall, 0, 1)
	e.u32(0) // body length
	e.u32(serial)
	at := len(e.b)
	e.u32(0) // header fields array length, filled below
	start := len(e.b)
	field := func(code byte, typ, val string) {
		e.align(8)
		e.b = append(e.b, code)
		e.sig(typ)
		e.str(val)
	}
	field(1, "o", path)
	field(2, "s", iface)
	field(3, "s", member)
	field(6, "s", dest)
	if len(args) > 0 {
		e.align(8)
		e.b = append(e.b, 8)
		e.sig("g")
		e.sig(strings.Repeat("s", len(args)))
	}
	binary.LittleEndian.PutUint32(e.b[at:], uint32(len(e.b)-start))
	e.align(8)
	binary.LittleEndian.PutUint32(e.b[4:], uint32(len(body.b)))
	return append(e.b, body.b...)
}

type dbusEnc struct{ b []byte }

func (e *dbusEnc) align(n int) {
	for len(e.b)%n != 0 {
		e.b = append(e.b, 0)
	}
}
func (e *dbusEnc) u32(v uint32) { e.align(4); e.b = binary.LittleEndian.AppendUint32(e.b, v) }
func (e *dbusEnc) str(s string) { e.u32(uint32(len(s))); e.b = append(append(e.b, s...), 0) }
func (e *dbusEnc) sig(s string) { e.b = append(append(append(e.b, byte(len(s))), s...), 0) }

type dbusHeader struct {
	typ         byte
	order       binary.ByteOrder
	replySerial uint32
	signature   string
	errName     string
}

// read reads one message: its header fields of interest and its body.
func (d *dbusConn) read() (dbusHeader, []byte, error) {
	var h dbusHeader
	var fixed [16]byte
	if _, err := io.ReadFull(d.r, fixed[:]); err != nil {
		return h, nil, err
	}
	switch fixed[0] {
	case 'l':
		h.order = binary.LittleEndian
	case 'B':
		h.order = binary.BigEndian
	default:
		return h, nil, fmt.Errorf("bad endianness byte %q", fixed[0])
	}
	h.typ = fixed[1]
	bodyLen := h.order.Uint32(fixed[4:])
	fieldsLen := h.order.Uint32(fixed[12:])
	if bodyLen > dbusMaxMessage || fieldsLen > dbusMaxMessage {
		return h, nil, errors.New("message too large")
	}
	hdrLen := 16 + int(fieldsLen)
	pad := (8 - hdrLen%8) % 8
	total := hdrLen + pad + int(bodyLen)
	if total > dbusMaxMessage {
		return h, nil, errors.New("message too large")
	}
	buf := make([]byte, total)
	copy(buf, fixed[:])
	if _, err := io.ReadFull(d.r, buf[16:]); err != nil {
		return h, nil, err
	}
	hd := &dbusDec{b: buf[:hdrLen], off: 12, bo: h.order}
	n := int(hd.u32())
	end := hd.off + n
	for hd.err == nil && hd.off < end {
		hd.align(8)
		code := hd.u8()
		t := hd.sig()
		if hd.err != nil {
			break
		}
		if k, err := typeEnd(t, 0, 0); err != nil || k != len(t) {
			return h, nil, errors.New("bad header field type")
		}
		switch {
		case code == 5 && t == "u":
			h.replySerial = hd.u32()
		case code == 8 && t == "g":
			h.signature = hd.sig()
		case code == 4 && t == "s":
			h.errName = hd.str()
		default:
			hd.skip(t, 0)
		}
	}
	if hd.err != nil {
		return h, nil, fmt.Errorf("header: %w", hd.err)
	}
	return h, buf[hdrLen+pad:], nil
}

// parseUnitList decodes the a(ssssssouso) reply of ListUnits.
func parseUnitList(body []byte, bo binary.ByteOrder) ([]UnitInfo, error) {
	d := &dbusDec{b: body, bo: bo}
	n := int(d.u32())
	d.align(8)
	end := d.off + n
	if d.err == nil && end > len(body) {
		return nil, errors.New("unit list: truncated")
	}
	var out []UnitInfo
	for d.err == nil && d.off < end && len(out) < 50000 {
		d.align(8)
		u := UnitInfo{Name: d.str(), Description: d.str(), LoadState: d.str(), ActiveState: d.str(), SubState: d.str()}
		d.str()          // following
		u.Path = d.str() // unit object path
		d.u32()          // job id
		d.str()          // job type
		d.str()          // job object path
		if d.err == nil {
			out = append(out, u)
		}
	}
	if d.err != nil {
		return nil, fmt.Errorf("unit list: %w", d.err)
	}
	return out, nil
}

var errShort = errors.New("truncated message")

type dbusDec struct {
	b   []byte
	off int
	bo  binary.ByteOrder
	err error
}

func (d *dbusDec) need(n int) bool {
	if d.err != nil {
		return false
	}
	if n < 0 || d.off+n > len(d.b) {
		d.err = errShort
		return false
	}
	return true
}

func (d *dbusDec) align(n int) {
	p := (d.off + n - 1) / n * n
	if d.need(p - d.off) {
		d.off = p
	}
}

func (d *dbusDec) u8() byte {
	if !d.need(1) {
		return 0
	}
	d.off++
	return d.b[d.off-1]
}

func (d *dbusDec) u32() uint32 {
	d.align(4)
	if !d.need(4) {
		return 0
	}
	d.off += 4
	return d.bo.Uint32(d.b[d.off-4:])
}

func (d *dbusDec) str() string {
	n := int(d.u32())
	if !d.need(n + 1) {
		return ""
	}
	s := string(d.b[d.off : d.off+n])
	d.off += n + 1
	return s
}

func (d *dbusDec) sig() string {
	n := int(d.u8())
	if !d.need(n + 1) {
		return ""
	}
	s := string(d.b[d.off : d.off+n])
	d.off += n + 1
	return s
}

func dbusAlign(c byte) int {
	switch c {
	case 'n', 'q':
		return 2
	case 'b', 'i', 'u', 'h', 's', 'o', 'a':
		return 4
	case 'x', 't', 'd', '(', '{':
		return 8
	}
	return 1 // y, g, v
}

// typeEnd returns the index just past the single complete type starting at sig[i].
func typeEnd(sig string, i, depth int) (int, error) {
	if depth > dbusMaxDepth || i >= len(sig) {
		return 0, errors.New("bad signature")
	}
	switch c := sig[i]; c {
	case 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 'h', 's', 'o', 'g', 'v':
		return i + 1, nil
	case 'a':
		return typeEnd(sig, i+1, depth+1)
	case '(', '{':
		closer := byte(')')
		if c == '{' {
			closer = '}'
		}
		j := i + 1
		for j < len(sig) && sig[j] != closer {
			k, err := typeEnd(sig, j, depth+1)
			if err != nil {
				return 0, err
			}
			j = k
		}
		if j >= len(sig) || j == i+1 {
			return 0, errors.New("bad signature")
		}
		return j + 1, nil
	}
	return 0, errors.New("bad signature")
}

// skip moves past one value of the single complete type t.
func (d *dbusDec) skip(t string, depth int) {
	if d.err != nil {
		return
	}
	if depth > dbusMaxDepth || t == "" {
		d.err = errors.New("bad signature")
		return
	}
	switch t[0] {
	case 'y':
		d.u8()
	case 'n', 'q':
		d.align(2)
		if d.need(2) {
			d.off += 2
		}
	case 'b', 'i', 'u', 'h':
		d.u32()
	case 'x', 't', 'd':
		d.align(8)
		if d.need(8) {
			d.off += 8
		}
	case 's', 'o':
		d.str()
	case 'g':
		d.sig()
	case 'v':
		inner := d.sig()
		if k, err := typeEnd(inner, 0, depth+1); err != nil || k != len(inner) {
			d.err = errors.New("bad variant")
			return
		}
		d.skip(inner, depth+1)
	case 'a':
		n := int(d.u32())
		elem := t[1:]
		d.align(dbusAlign(elem[0]))
		if !d.need(n) {
			return
		}
		end := d.off + n
		for d.err == nil && d.off < end {
			before := d.off
			d.skip(elem, depth+1)
			if d.off <= before {
				d.err = errors.New("bad array")
			}
		}
		if d.err == nil && d.off != end {
			d.err = errors.New("bad array length")
		}
	case '(', '{':
		d.align(8)
		j := 1
		for d.err == nil && j < len(t)-1 {
			k, err := typeEnd(t, j, depth+1)
			if err != nil {
				d.err = err
				return
			}
			d.skip(t[j:k], depth+1)
			j = k
		}
	default:
		d.err = errors.New("bad signature")
	}
}
