package main

// Who listens on a port: the process holding the socket (found through /proc/<pid>/fd links,
// which needs CAP_SYS_PTRACE for other users' processes: the kernel checks PTRACE_MODE_READ before
// it shows another process's fd or exe link), its systemd unit (from /proc/<pid>/cgroup) and, when
// it runs in a Docker container, the container's name (from Docker's own metadata file
// /var/lib/docker/containers/<id>/config.v2.json, read-only). A port published by Docker belongs
// to docker-proxy: its -container-ip argument names the container it forwards to.
//
// The search runs on the background worker only when the set of listening sockets changed, a few
// processes at a time (newest first: a new port usually belongs to a new process), and stops as
// soon as every socket has an owner.

import (
	"bytes"
	"encoding/json"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"
)

// Owner is the process behind a listening socket.
type Owner struct {
	PID       int
	Name      string
	User      string
	Exe       string
	Unit      string
	Container string
	CID       string
}

// ParseCgroup returns the systemd unit and the container id (first 12 hex digits) of a process
// from its /proc/<pid>/cgroup: the cgroup v2 line "0::/…", else the v1 name=systemd line.
func ParseCgroup(b []byte) (unit, cid string) {
	var path []byte
	for len(b) > 0 {
		var line []byte
		if i := bytes.IndexByte(b, '\n'); i >= 0 {
			line, b = b[:i], b[i+1:]
		} else {
			line, b = b, nil
		}
		if bytes.HasPrefix(line, []byte("0::")) {
			path = line[3:]
			break
		}
		if i := bytes.Index(line, []byte(":name=systemd:")); i >= 0 && path == nil {
			path = line[i+len(":name=systemd:"):]
		}
	}
	if path == nil {
		return "", ""
	}
	parts := strings.Split(string(path), "/")
	for i, p := range parts {
		if cid == "" {
			if id := containerID(p); id != "" {
				cid = id
			} else if i > 0 && (parts[i-1] == "docker" || parts[i-1] == "libpod" || parts[i-1] == "containerd") && isHex(p, 64) {
				cid = p[:12]
			}
		}
		if unit == "" && (strings.HasSuffix(p, ".service") || strings.HasSuffix(p, ".scope")) && containerID(p) == "" {
			unit = truncate(p, 120)
		}
	}
	return unit, cid
}

// containerID: "docker-<64 hex>.scope", "libpod-<id>.scope", "cri-containerd-<id>.scope".
func containerID(p string) string {
	for _, pre := range []string{"docker-", "libpod-", "cri-containerd-", "crio-"} {
		if strings.HasPrefix(p, pre) {
			id := strings.TrimSuffix(strings.TrimPrefix(p, pre), ".scope")
			if isHex(id, 64) {
				return id[:12]
			}
		}
	}
	return ""
}

func isHex(s string, n int) bool {
	if len(s) != n {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
			return false
		}
	}
	return true
}

// DockerIndex maps container ids and container IP addresses to container names, from
// /var/lib/docker/containers/*/config.v2.json (read again only when that directory changes).
type DockerIndex struct {
	root   string
	mu     sync.Mutex
	mtime  time.Time
	byID   map[string]string // 12-hex id -> name
	byIP   map[string]string
	loaded bool
}

func NewDockerIndex(root string) *DockerIndex { return &DockerIndex{root: root} }

func (d *DockerIndex) refresh() {
	dir := filepath.Join(d.root, "var/lib/docker/containers")
	fi, err := os.Stat(dir)
	if err != nil {
		d.byID, d.byIP, d.loaded = nil, nil, true
		return
	}
	if d.loaded && fi.ModTime().Equal(d.mtime) {
		return
	}
	d.mtime, d.loaded = fi.ModTime(), true
	d.byID, d.byIP = map[string]string{}, map[string]string{}
	ents, err := os.ReadDir(dir)
	if err != nil {
		return
	}
	for i, e := range ents {
		if i >= 500 {
			break
		}
		if !e.IsDir() || !isHex(e.Name(), 64) {
			continue
		}
		b, err := readSmall(filepath.Join(dir, e.Name(), "config.v2.json"), 2<<20)
		if err != nil {
			continue
		}
		var cfg struct {
			Name            string
			NetworkSettings struct {
				Networks map[string]struct{ IPAddress, GlobalIPv6Address string }
			}
		}
		if json.Unmarshal(b, &cfg) != nil {
			continue
		}
		name := truncate(strings.TrimPrefix(cfg.Name, "/"), 100)
		if name == "" {
			continue
		}
		d.byID[e.Name()[:12]] = name
		for _, n := range cfg.NetworkSettings.Networks {
			if n.IPAddress != "" {
				d.byIP[n.IPAddress] = name
			}
			if n.GlobalIPv6Address != "" {
				d.byIP[n.GlobalIPv6Address] = name
			}
		}
	}
}

// Name of a container by its 12-hex id ("" when unknown).
func (d *DockerIndex) Name(cid string) string {
	d.mu.Lock()
	defer d.mu.Unlock()
	d.refresh()
	return d.byID[cid]
}

// ByIP: the container that has this address on a Docker network.
func (d *DockerIndex) ByIP(ip string) string {
	d.mu.Lock()
	defer d.mu.Unlock()
	d.refresh()
	return d.byIP[ip]
}

// procRef is the little the owner search needs about a process, copied from the sample.
type procRef struct {
	PID    int
	Start  uint64
	Kernel bool
}

// FindOwners maps socket inodes to the process holding them, keeping the owners already known for
// sockets that are still there. budget bounds the fd entries looked at (a busy proxy can hold a
// million); g paces the work.
func FindOwners(procRoot string, inodes map[uint64]bool, known map[uint64]Owner, procs []procRef, users *UserCache,
	docker *DockerIndex, g *Gentle, budget int) map[uint64]Owner {
	out := make(map[uint64]Owner, len(inodes))
	missing := 0
	for ino := range inodes {
		if o, ok := known[ino]; ok {
			out[ino] = o
		} else {
			missing++
		}
	}
	if missing == 0 {
		return out
	}
	order := append([]procRef(nil), procs...)
	sort.Slice(order, func(i, j int) bool { return order[i].Start > order[j].Start }) // newest first
	lbuf := make([]byte, 128)
	found := map[int]bool{}
	var pids []int
	byPid := map[int][]uint64{}
	for _, p := range order {
		if budget <= 0 || missing == 0 {
			break
		}
		if p.Kernel || p.PID <= 0 {
			continue
		}
		g.Tick()
		fdDir := procRoot + "/" + strconv.Itoa(p.PID) + "/fd"
		d, err := os.Open(fdDir)
		if err != nil {
			continue
		}
		names, _ := d.Readdirnames(budget)
		d.Close()
		budget -= len(names)
		for _, n := range names {
			k, err := readlinkInto(fdDir+"/"+n, lbuf)
			if err != nil || k < 9 || !bytes.HasPrefix(lbuf[:k], []byte("socket:[")) || lbuf[k-1] != ']' {
				continue
			}
			ino, ok := parseUintBytes(lbuf[8 : k-1])
			if !ok || !inodes[ino] {
				continue
			}
			if _, have := out[ino]; have {
				continue
			}
			out[ino] = Owner{PID: p.PID}
			missing--
			if !found[p.PID] {
				found[p.PID] = true
				pids = append(pids, p.PID)
			}
			byPid[p.PID] = append(byPid[p.PID], ino)
		}
	}
	for _, pid := range pids {
		g.Tick()
		o := describeOwner(procRoot, pid, users, docker)
		for _, ino := range byPid[pid] {
			out[ino] = o
		}
	}
	return out
}

// describeOwner reads name, user, executable, unit and container of one process.
func describeOwner(procRoot string, pid int, users *UserCache, docker *DockerIndex) Owner {
	o := Owner{PID: pid}
	dir := procRoot + "/" + strconv.Itoa(pid)
	buf := make([]byte, 4096)
	if n, err := readInto(dir+"/stat", buf); err == nil {
		var st PidStat
		var f [24][]byte
		if comm, ok := parsePidStatInto(buf[:n], &st, f[:]); ok {
			o.Name = truncate(string(comm), 64)
		}
	}
	var st syscall.Stat_t
	if syscall.Stat(dir, &st) == nil {
		o.User = users.Name(int(st.Uid))
	}
	if n, err := readlinkInto(dir+"/exe", buf); err == nil {
		o.Exe = truncate(string(buf[:n]), 200)
	}
	if n, err := readInto(dir+"/cgroup", buf); err == nil {
		o.Unit, o.CID = ParseCgroup(buf[:n])
	}
	if o.CID != "" && docker != nil {
		o.Container = docker.Name(o.CID)
	}
	if docker != nil && o.Container == "" && (o.Name == "docker-proxy" || strings.HasSuffix(o.Exe, "/docker-proxy")) {
		if n, err := readInto(dir+"/cmdline", buf); err == nil {
			args := strings.Split(strings.TrimRight(string(buf[:n]), "\x00"), "\x00")
			for i := 0; i+1 < len(args); i++ {
				if args[i] == "-container-ip" {
					o.Container = docker.ByIP(args[i+1])
				}
			}
		}
	}
	return o
}
