[code] [blog] [Repos] [GPS Tracker] [Music] [VNC] [Restart VNC] [E-Mail me]

browse files at this commit · zip

commit b84c0b7b5e9d46a33eb68b8744f1bd610fa5b374
Author: no-body-in-particular <admin@coredump.ws>
Date:   Fri Oct 30 12:53:18 2026 +0100

    tracker-mailer: one small C daemon instead of a Python script run from cron
    
    The reset-mail sender is now tracker-mailer/tracker-mailer.c: one libc-only
    C file (build command in its header) that runs as the user tracker-mail
    under supervise-daemon (etc/init.d/tracker-mailer) and watches the outbox
    with inotify, so a reset mail goes out within a second instead of up to a
    minute. It keeps every rule of the Python version: plain user@host.tld
    recipients and 32-hex keys only, jobs opened without following symlinks or
    blocking on FIFOs, the one fixed message with an explicit recipient and the
    sender Postfix pins, at most 20 an hour (same sent.json), an hour's expiry,
    syslog with only the recipient's domain, and no running as root. After a
    failed submission it waits 60 s before the next.
    
    Tested against the Python version before it was replaced: the recipient
    check agrees with TRACKER_MAIL_RE on 120,000 addresses, and nine outbox
    scenarios (malformed jobs, symlinks, FIFOs, hard links, expiry, the cap, a
    failing sendmail, a broken state file) leave the same files, make the same
    sendmail calls and save the same state, under ASan and UBSan.
    
    usr/local/libexec/tracker-mailer and etc/cron.d/tracker-mailer are gone;
    the README and the comments in config.php and recover.php say so.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---
 README.md                        |   7 +-
 etc/cron.d/tracker-mailer        |  10 -
 etc/init.d/tracker-mailer        |  21 ++
 tracker-mailer/tracker-mailer.c  | 614 +++++++++++++++++++++++++++++++++++++++
 usr/local/libexec/tracker-mailer | 239 ---------------
 var/www/tracker/config.php       |   4 +-
 var/www/tracker/recover.php      |   2 +-
 7 files changed, 642 insertions(+), 255 deletions(-)

diff --git a/README.md b/README.md
index 5ac809a..178779e 100644
--- a/README.md
+++ b/README.md
@@ -10,11 +10,12 @@
  
  The website that shows the data is contained in the /var/www folder. Both /var/www and /var/gps should be chown'd to your webserver's user.
 
- Password-reset mail is not sent by the website itself (since 2026-10-29). `recover.php` writes one job per reset into `/var/spool/tracker-outbox` (`TRACKER_OUTBOX` in config.php), and `usr/local/libexec/tracker-mailer`, run every minute from `etc/cron.d/tracker-mailer`, sends a fixed message for each. To set it up:
- - create a user and group `tracker-mail`, and the outbox `/var/spool/tracker-outbox` owned by `tracker-mail:tracker-mail` with mode 3770; add the webserver's (PHP) user to the group `tracker-mail`;
+ Password-reset mail is not sent by the website itself (since 2026-10-29). `recover.php` writes one job per reset into `/var/spool/tracker-outbox` (`TRACKER_OUTBOX` in config.php), and the small daemon in `tracker-mailer/tracker-mailer.c` sends a fixed message for each as soon as it appears. To set it up:
+ - change `SENDER` and `RESET_URL` at the top of `tracker-mailer.c` to your own site, then build it with the command in its header comment (plain libc, no dependencies) and install it as `/usr/local/sbin/tracker-mailer`;
+ - create a user and group `tracker-mail`, the state directory `/var/lib/tracker-mail` (owned by it, 0700) and the outbox `/var/spool/tracker-outbox` owned by `tracker-mail:tracker-mail` with mode 3770; add the webserver's (PHP) user to the group `tracker-mail`;
  - keep the PHP user out of the `postdrop` group and disable `mail()` in its PHP configuration, so code running in the website can't submit mail of its own;
  - in Postfix, allow `tracker-mail` in `authorized_submit_users` and pin its sender with `local_login_sender_maps` to a no-reply address (whose bounces go to /dev/null);
- - change `SENDER` and the reset link in tracker-mailer to your own site.
+ - start it with the OpenRC service `etc/init.d/tracker-mailer` (`rc-update add tracker-mailer default`), which runs it as `tracker-mail`. It logs to syslog.
 
  Resets are limited to 10 requests per client address per hour and 20 sent per hour site-wide; registrations to 5 per address and 50 site-wide per day. Without these limits, anyone could make the site send its (DKIM-signed) reset mail to any address.
  
diff --git a/etc/cron.d/tracker-mailer b/etc/cron.d/tracker-mailer
deleted file mode 100644
index efd5ec6..0000000
--- a/etc/cron.d/tracker-mailer
+++ /dev/null
@@ -1,10 +0,0 @@
-# /etc/cron.d/tracker-mailer - tracker-r12 (2026-10-29)
-# GPS tracker password-reset mail: tracker/recover.php leaves jobs in /var/spool/tracker-outbox
-# and tracker-mailer sends them as the user tracker-mail, whose envelope sender Postfix pins to
-# tracker-noreply@coredump.ws (local_login_sender_maps). At most 20 an hour.
-# It logs to syslog (mail facility, tag tracker-mailer). MAILTO is empty on purpose: cron would
-# submit its own mail as tracker-mail with a sender Postfix refuses for that user.
-SHELL=/bin/sh
-PATH=/usr/bin:/bin
-MAILTO=""
-* * * * * tracker-mail /usr/local/libexec/tracker-mailer
diff --git a/etc/init.d/tracker-mailer b/etc/init.d/tracker-mailer
new file mode 100755
index 0000000..3f9c024
--- /dev/null
+++ b/etc/init.d/tracker-mailer
@@ -0,0 +1,21 @@
+#!/sbin/openrc-run
+# GPS tracker password-reset mailer (tracker-mailer/tracker-mailer.c in CTracker): sends the
+# jobs tracker/recover.php leaves in /var/spool/tracker-outbox, as the user tracker-mail, whose
+# envelope sender Postfix pins to tracker-noreply@coredump.ws (local_login_sender_maps). At most
+# 20 an hour. Logs to syslog (facility mail, tag tracker-mailer).
+# No no_new_privs: Postfix's sendmail hands the mail to the set-gid postdrop, which it would break.
+
+description="GPS tracker password-reset mailer"
+command="/usr/local/sbin/tracker-mailer"
+command_user="tracker-mail:tracker-mail"
+supervisor="supervise-daemon"
+respawn_delay=5
+respawn_max=0
+pidfile="/run/tracker-mailer.pid"
+rc_ulimit="-c 0"
+
+depend() {
+	need localmount
+	use logger postfix
+	after postfix
+}
diff --git a/tracker-mailer/tracker-mailer.c b/tracker-mailer/tracker-mailer.c
new file mode 100644
index 0000000..478c1fd
--- /dev/null
+++ b/tracker-mailer/tracker-mailer.c
@@ -0,0 +1,614 @@
+/*
+ * tracker-mailer - sends the GPS tracker's password-reset mails.
+ *
+ * recover.php (var/www/tracker) drops one job per reset into the outbox:
+ * {"rcpt":"user@host.tld","key":"<32 hex>"}, written under a dot name and renamed to
+ * <16 hex>.json. This daemon runs as its own user, tracker-mail, under supervise-daemon
+ * (etc/init.d/tracker-mailer), watches the outbox with inotify and, for each job:
+ *  - accepts only a plain user@host.tld recipient (the tracker's own rule, TRACKER_MAIL_RE in
+ *    config.php) and a 32-hex key;
+ *  - renders the one fixed message itself, so the web code chooses only (recipient, key);
+ *  - submits it with sendmail, an explicit recipient (never -t) and the envelope sender Postfix
+ *    pins for this user (local_login_sender_maps: tracker-mail = SENDER);
+ *  - sends at most CAP_PER_HOUR an hour whatever is queued: a job over the cap waits, and a job
+ *    older than the reset link (an hour) is dropped unsent.
+ * A compromised web application can therefore at worst have CAP_PER_HOUR fixed reset mails an
+ * hour sent. The web pool's user owns what it writes to the outbox, so a job is opened without
+ * following a symlink or blocking on a FIFO, and must still be the regular, single-link file
+ * that was listed.
+ *
+ * Logs to syslog (facility mail, tag tracker-mailer): never a key, only the recipient's domain
+ * (Postfix logs the full address anyway). The hourly count is kept in STATE/sent.json, so a
+ * restart doesn't reset it.
+ *
+ * Build: cc -O2 -Wall -Wextra -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE -pie \
+ *           -Wl,-z,relro,-z,now -o tracker-mailer tracker-mailer.c
+ * Test hooks (environment): TM_OUTBOX TM_STATE TM_SENDMAIL TM_LOG=stderr TM_NOW (a fixed clock,
+ * in seconds) TM_ONCE=1 (one pass, then exit; status 1 if a submission failed).
+ *
+ * It replaces a Python script that ran every minute from cron (2026-10-29/30); sent.json has
+ * the same format, so the hourly count carries over.
+ */
+#define _GNU_SOURCE
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/file.h>
+#include <sys/inotify.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <syslog.h>
+#include <time.h>
+#include <unistd.h>
+
+#define SENDER       "tracker-noreply@coredump.ws"
+#define RESET_URL    "https://coredump.ws/tracker/reset.php?key="
+#define CAP_PER_HOUR 20        /* = MAIL_BUDGET['reset'] site-wide in tracker/database.php */
+#define WINDOW       3600.0
+#define JOB_TTL      3600.0    /* = RESET_KEY_TTL: an older link no longer works */
+#define MAX_SCAN     500       /* directory entries looked at per pass */
+#define MAX_JOB      4096
+#define MAX_SENT     256
+#define SEND_TIMEOUT 120.0     /* seconds for one sendmail run */
+#define IDLE_MS      60000     /* expiry and leftovers are looked at at least this often */
+#define BACKOFF      60.0      /* seconds without submissions after a failed one */
+
+static const char *outbox = "/var/spool/tracker-outbox";
+static const char *state = "/var/lib/tracker-mail";
+static const char *sendmail = "/usr/sbin/sendmail";
+static int log_stderr;
+static double fixed_now = -1;
+
+static void say(const char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	if (log_stderr) {
+		fputs("tracker-mailer: ", stderr);
+		vfprintf(stderr, fmt, ap);
+		fputc('\n', stderr);
+	} else
+		vsyslog(LOG_INFO, fmt, ap);
+	va_end(ap);
+}
+
+static double clock_s(clockid_t id)
+{
+	struct timespec ts;
+
+	clock_gettime(id, &ts);
+	return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
+}
+
+static double now(void) { return fixed_now >= 0 ? fixed_now : clock_s(CLOCK_REALTIME); }
+static double mono(void) { return clock_s(CLOCK_MONOTONIC); }
+
+static int alnum(int c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); }
+static int alpha(int c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
+
+static int hexn(const char *s, size_t n)
+{
+	for (size_t i = 0; i < n; i++)
+		if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f')))
+			return 0;
+	return 1;
+}
+
+static int job_name(const char *n) { return strlen(n) == 21 && hexn(n, 16) && !strcmp(n + 16, ".json"); }
+static int tmp_name(const char *n) { return strlen(n) == 21 && n[0] == '.' && hexn(n + 1, 16) && !strcmp(n + 17, ".tmp"); }
+static int valid_key(const char *k) { return strlen(k) == 32 && hexn(k, 32); }
+
+/*
+ * TRACKER_MAIL_RE of config.php, at most 254 characters:
+ * [A-Za-z0-9._+-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}
+ */
+static int valid_rcpt(const char *s)
+{
+	size_t i = 0;
+	const char *d, *last;
+
+	if (strlen(s) > 254)
+		return 0;
+	while (s[i] && s[i] != '@') {
+		if (!alnum(s[i]) && !strchr("._+-", s[i]))
+			return 0;
+		i++;
+	}
+	if (i < 1 || i > 64 || s[i] != '@')
+		return 0;
+	d = s + i + 1;
+	last = strrchr(d, '.');
+	if (!last || last == d)
+		return 0;
+	if (strlen(last + 1) < 2 || strlen(last + 1) > 63)
+		return 0;
+	for (const char *p = last + 1; *p; p++)
+		if (!alpha(*p))
+			return 0;
+	/* every label up to and including the one that ends at the last dot ("b..co" has an empty one) */
+	for (const char *p = d; p <= last;) {
+		const char *e = memchr(p, '.', last - p + 1);
+		size_t l = e - p;
+
+		if (l < 1 || l > 63 || !alnum(p[0]) || !alnum(p[l - 1]))
+			return 0;
+		for (size_t k = 0; k < l; k++)
+			if (!alnum(p[k]) && p[k] != '-')
+				return 0;
+		p = e + 1;
+	}
+	return 1;
+}
+
+static const char *ws(const char *p)
+{
+	while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
+		p++;
+	return p;
+}
+
+/* A JSON string without escapes (no valid recipient or key needs one) into out. */
+static const char *jstr(const char *p, char *out, size_t cap)
+{
+	size_t n = 0;
+
+	if (*p++ != '"')
+		return NULL;
+	while (*p && *p != '"') {
+		if (*p == '\\' || (unsigned char)*p < 0x20 || n + 1 >= cap)
+			return NULL;
+		out[n++] = *p++;
+	}
+	if (*p != '"')
+		return NULL;
+	out[n] = '\0';
+	return p + 1;
+}
+
+/* recover.php writes json_encode(['rcpt' => ..., 'key' => ...]): exactly these two members. */
+static int parse_job(const char *buf, char rcpt[256], char key[64])
+{
+	char name[8], val[256];
+	int have_rcpt = 0, have_key = 0;
+	const char *p = ws(buf);
+
+	if (*p++ != '{')
+		return 0;
+	for (int i = 0; i < 2; i++) {
+		if (!(p = jstr(ws(p), name, sizeof name)))
+			return 0;
+		p = ws(p);
+		if (*p++ != ':')
+			return 0;
+		if (!(p = jstr(ws(p), val, sizeof val)))
+			return 0;
+		if (!strcmp(name, "rcpt") && !have_rcpt) {
+			strcpy(rcpt, val);
+			have_rcpt = 1;
+		} else if (!strcmp(name, "key") && !have_key && strlen(val) < 64) {
+			strcpy(key, val);
+			have_key = 1;
+		} else
+			return 0;
+		p = ws(p);
+		if (i == 0 && *p++ != ',')
+			return 0;
+	}
+	if (*p++ != '}' || *ws(p))
+		return 0;
+	return valid_rcpt(rcpt) && valid_key(key);
+}
+
+/* The submission times of the last hour, from STATE/sent.json (a JSON array of numbers). */
+static int load_sent(double t, double *sent)
+{
+	char path[4096], buf[16384], *e;
+	const char *p;
+	ssize_t r;
+	int fd, n = 0;
+
+	snprintf(path, sizeof path, "%s/sent.json", state);
+	if ((fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) < 0)
+		return 0;
+	r = read(fd, buf, sizeof buf - 1);
+	close(fd);
+	if (r <= 0)
+		return 0;
+	buf[r] = '\0';
+	p = ws(buf);
+	if (*p++ != '[')
+		return 0;
+	for (p = ws(p); *p != ']'; p = ws(p + 1)) {
+		double x = strtod(p, &e);
+
+		if (e == p)
+			return 0;
+		if (t - WINDOW < x && x <= t + 60 && n < MAX_SENT)
+			sent[n++] = x;
+		p = ws(e);
+		if (*p == ']')
+			break;
+		if (*p != ',')
+			return 0;
+	}
+	return n;
+}
+
+static int save_sent(const double *sent, int n)
+{
+	char path[4096], tmp[4200], buf[MAX_SENT * 24 + 4];
+	size_t len = 0;
+	int fd, ok;
+
+	buf[len++] = '[';
+	for (int i = 0; i < n; i++)
+		len += snprintf(buf + len, sizeof buf - len, "%s%.6f", i ? ", " : "", sent[i]);
+	buf[len++] = ']';
+	snprintf(path, sizeof path, "%s/sent.json", state);
+	snprintf(tmp, sizeof tmp, "%s.tmp", path);
+	if ((fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0600)) < 0)
+		return -1;
+	ok = write(fd, buf, len) == (ssize_t)len && fsync(fd) == 0;
+	close(fd);
+	return ok && rename(tmp, path) == 0 ? 0 : -1;
+}
+
+struct job {
+	double mtime;
+	char name[22];
+	dev_t dev;
+	ino_t ino;
+};
+
+static int cmpjob(const void *a, const void *b)
+{
+	const struct job *x = a, *y = b;
+
+	if (x->mtime != y->mtime)
+		return x->mtime < y->mtime ? -1 : 1;
+	return strcmp(x->name, y->name);
+}
+
+/* The job's bytes if it is still the regular, single-link file that was listed; else -1. */
+static ssize_t read_job(int dfd, const struct job *j, char *buf)
+{
+	struct stat st;
+	ssize_t n = -1, r;
+	int fd = openat(dfd, j->name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
+
+	if (fd < 0)
+		return -1;
+	if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && st.st_nlink == 1 && st.st_ino == j->ino
+	    && st.st_dev == j->dev && st.st_size <= MAX_JOB) {
+		for (n = 0; n <= MAX_JOB; n += r)
+			if ((r = read(fd, buf + n, MAX_JOB + 1 - n)) <= 0)
+				break;
+		if (r < 0)
+			n = -1;
+	}
+	close(fd);
+	return n;
+}
+
+/* Submit the one fixed message. 0, or -1 with the reason in err. */
+static int send_mail(const char *rcpt, const char *key, char *err, size_t errlen)
+{
+	char msg[1024], ebuf[512];
+	char *argv[] = { (char *)sendmail, "-i", "-f", SENDER, "--", (char *)rcpt, NULL };
+	char *envp[] = { "PATH=/usr/sbin:/usr/bin:/bin", "LANG=C", NULL };
+	int in[2], ep[2], status = 0, werr = 0, eof = 0;
+	size_t en = 0;
+	ssize_t r, off = 0;
+	double deadline = mono() + SEND_TIMEOUT;
+	int mlen = snprintf(msg, sizeof msg,
+		"From: GPS tracker <" SENDER ">\n"
+		"To: %s\n"
+		"Subject: GPS tracker password reset\n"
+		"MIME-Version: 1.0\n"
+		"Content-Type: text/plain; charset=UTF-8\n"
+		"Content-Transfer-Encoding: 7bit\n"
+		"Auto-Submitted: auto-generated\n"
+		"\n"
+		"You can reset your password with the following link. It works once,\n"
+		"and for one hour.\n"
+		RESET_URL "%s\n", rcpt, key);
+	pid_t pid;
+
+	if (pipe2(in, O_CLOEXEC) < 0)
+		return snprintf(err, errlen, "sendmail did not run: pipe: %s", strerror(errno)), -1;
+	if (pipe2(ep, O_CLOEXEC) < 0) {
+		close(in[0]);
+		close(in[1]);
+		return snprintf(err, errlen, "sendmail did not run: pipe: %s", strerror(errno)), -1;
+	}
+	if ((pid = fork()) < 0) {
+		close(in[0]); close(in[1]); close(ep[0]); close(ep[1]);
+		return snprintf(err, errlen, "sendmail did not run: fork: %s", strerror(errno)), -1;
+	}
+	if (pid == 0) {
+		int nul = open("/dev/null", O_WRONLY);
+
+		signal(SIGPIPE, SIG_DFL);
+		if (dup2(in[0], 0) < 0 || nul < 0 || dup2(nul, 1) < 0 || dup2(ep[1], 2) < 0)
+			_exit(127);
+		execve(sendmail, argv, envp);
+		_exit(127);
+	}
+	close(in[0]);
+	close(ep[1]);
+	while (off < mlen) {
+		if ((r = write(in[1], msg + off, mlen - off)) < 0) {
+			if (errno == EINTR)
+				continue;
+			werr = errno;
+			break;
+		}
+		off += r;
+	}
+	close(in[1]);
+	for (;;) {
+		struct pollfd p = { ep[0], POLLIN, 0 };
+
+		if (!eof && poll(&p, 1, 100) > 0) {
+			char junk[512];
+
+			if (en < sizeof ebuf - 1)
+				r = read(ep[0], ebuf + en, sizeof ebuf - 1 - en);
+			else
+				r = read(ep[0], junk, sizeof junk);
+			if (r <= 0)
+				eof = 1;
+			else if (en < sizeof ebuf - 1)
+				en += r;
+		} else if (eof)
+			poll(NULL, 0, 100);
+		if ((r = waitpid(pid, &status, WNOHANG)) == pid)
+			break;
+		if (r < 0 && errno != EINTR) {
+			close(ep[0]);
+			return snprintf(err, errlen, "sendmail wait failed: %s", strerror(errno)), -1;
+		}
+		if (mono() > deadline) {
+			kill(pid, SIGKILL);
+			waitpid(pid, &status, 0);
+			close(ep[0]);
+			return snprintf(err, errlen, "sendmail did not run: timed out"), -1;
+		}
+	}
+	close(ep[0]);
+	ebuf[en] = '\0';
+	ebuf[strcspn(ebuf, "\n")] = '\0';
+	if (WIFEXITED(status) && WEXITSTATUS(status) == 0 && !werr)
+		return 0;
+	if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
+		snprintf(err, errlen, "sendmail exit %d: %.200s", WEXITSTATUS(status), ebuf);
+	else if (WIFSIGNALED(status))
+		snprintf(err, errlen, "sendmail killed by signal %d", WTERMSIG(status));
+	else
+		snprintf(err, errlen, "writing to sendmail failed: %s", strerror(werr));
+	return -1;
+}
+
+/*
+ * One pass over the outbox. Returns 0, or -errno if the outbox can't be read. *failed is set
+ * when a submission failed (the job stays for the next pass); *wake is the number of seconds
+ * until a job held back by the hourly cap could go out (0: none is waiting for that).
+ */
+static int pass(int may_send, int *failed, double *wake)
+{
+	static struct job jobs[MAX_SCAN];
+	double t = now(), sent[MAX_SENT];
+	int nsent = load_sent(t, sent), njobs = 0, seen = 0;
+	int malformed = 0, expired = 0, deferred = 0, notfile = 0;
+	struct dirent *de;
+	DIR *dir;
+	int dfd, fd2;
+
+	*failed = 0;
+	*wake = 0;
+	if ((dfd = open(outbox, O_RDONLY | O_DIRECTORY | O_CLOEXEC)) < 0)
+		return -errno;
+	if ((fd2 = dup(dfd)) < 0 || !(dir = fdopendir(fd2))) {
+		int e = errno;
+
+		if (fd2 >= 0)
+			close(fd2);
+		close(dfd);
+		return -e;
+	}
+	while (seen < MAX_SCAN && (de = readdir(dir))) {
+		const char *n = de->d_name;
+		struct stat st;
+		double mt;
+
+		if (!strcmp(n, ".") || !strcmp(n, ".."))
+			continue;
+		seen++;
+		if (fstatat(dfd, n, &st, AT_SYMLINK_NOFOLLOW) < 0)
+			continue;
+		mt = (double)st.st_mtim.tv_sec + (double)st.st_mtim.tv_nsec / 1e9;
+		if (tmp_name(n)) {
+			/* a job recover.php never finished writing */
+			if (t - mt > JOB_TTL)
+				unlinkat(dfd, n, S_ISDIR(st.st_mode) ? AT_REMOVEDIR : 0);
+			continue;
+		}
+		if (!job_name(n)) {
+			if (unlinkat(dfd, n, S_ISDIR(st.st_mode) ? AT_REMOVEDIR : 0) == 0)
+				malformed++;
+			continue;
+		}
+		if (!S_ISREG(st.st_mode)) {
+			if (unlinkat(dfd, n, S_ISDIR(st.st_mode) ? AT_REMOVEDIR : 0) == 0)
+				notfile++;
+			continue;
+		}
+		jobs[njobs].mtime = mt;
+		strcpy(jobs[njobs].name, n);
+		jobs[njobs].dev = st.st_dev;
+		jobs[njobs].ino = st.st_ino;
+		njobs++;
+	}
+	closedir(dir);
+	qsort(jobs, njobs, sizeof *jobs, cmpjob);
+
+	for (int i = 0; i < njobs; i++) {
+		const struct job *j = &jobs[i];
+		char buf[MAX_JOB + 2], rcpt[256], key[64], err[320];
+		const char *dom;
+		ssize_t len;
+
+		if (t - j->mtime > JOB_TTL) {
+			if (unlinkat(dfd, j->name, 0) == 0)
+				expired++;
+			continue;
+		}
+		len = read_job(dfd, j, buf);
+		if (len >= 0 && len <= MAX_JOB)
+			buf[len] = '\0';
+		if (len < 0 || len > MAX_JOB || strlen(buf) != (size_t)len || !parse_job(buf, rcpt, key)) {
+			if (unlinkat(dfd, j->name, 0) == 0)
+				malformed++;
+			continue;
+		}
+		if (nsent >= CAP_PER_HOUR || !may_send) {
+			deferred++;          /* stays queued for a later pass, until it expires */
+			continue;
+		}
+		dom = strchr(rcpt, '@') + 1;
+		if (send_mail(rcpt, key, err, sizeof err) < 0) {
+			say("job %.16s for *@%s not sent, kept for the next run: %s", j->name, dom, err);
+			*failed = 1;
+			break;
+		}
+		sent[nsent++] = now();
+		if (save_sent(sent, nsent) < 0)
+			say("cannot save %s/sent.json: %s", state, strerror(errno));
+		if (unlinkat(dfd, j->name, 0) < 0)
+			say("job %.16s sent but could not be removed", j->name);
+		say("job %.16s: reset mail submitted for *@%s (%d in the last hour)", j->name, dom, nsent);
+	}
+	close(dfd);
+
+	if (deferred || expired || malformed || notfile) {
+		char line[256];
+		size_t l = 0;
+
+#define COUNT(n, s) if (n) l += snprintf(line + l, sizeof line - l, "%s" s " %d", l ? ", " : "", n)
+		COUNT(deferred, "deferred");
+		COUNT(expired, "expired");
+		COUNT(malformed, "malformed");
+		COUNT(notfile, "not a file");
+#undef COUNT
+		say("%s; hourly cap %d, sent in the last hour %d", line, CAP_PER_HOUR, nsent);
+	}
+	if (deferred && nsent >= CAP_PER_HOUR) {
+		double oldest = sent[0];
+
+		for (int i = 1; i < nsent; i++)
+			if (sent[i] < oldest)
+				oldest = sent[i];
+		*wake = oldest + WINDOW - t;
+		if (*wake < 1)
+			*wake = 1;
+	}
+	return 0;
+}
+
+int main(void)
+{
+	const char *e;
+	char lockpath[4096];
+	int once, lfd, ifd, failed, last_err = 0;
+	double wake, retry_at = 0;
+
+	if ((e = getenv("TM_OUTBOX")))
+		outbox = e;
+	if ((e = getenv("TM_STATE")))
+		state = e;
+	if ((e = getenv("TM_SENDMAIL")))
+		sendmail = e;
+	if ((e = getenv("TM_NOW")))
+		fixed_now = strtod(e, NULL);
+	log_stderr = (e = getenv("TM_LOG")) && !strcmp(e, "stderr");
+	once = (e = getenv("TM_ONCE")) && !strcmp(e, "1");
+
+	if (geteuid() == 0) {
+		fputs("tracker-mailer: refusing to run as root (Postfix pins the sender for tracker-mail only)\n", stderr);
+		return 2;
+	}
+	umask(077);
+	signal(SIGPIPE, SIG_IGN);
+	if (!log_stderr)
+		openlog("tracker-mailer", LOG_PID, LOG_MAIL);
+
+	snprintf(lockpath, sizeof lockpath, "%s/lock", state);
+	if ((lfd = open(lockpath, O_RDONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0600)) < 0) {
+		say("cannot open the lock in %s: %s", state, strerror(errno));
+		return 1;
+	}
+	/* one instance; the daemon waits for a one-shot run (a test, say) to finish */
+	if (flock(lfd, LOCK_EX | (once ? LOCK_NB : 0)) < 0) {
+		if (once && errno == EWOULDBLOCK)
+			return 0;
+		say("cannot lock %s: %s", lockpath, strerror(errno));
+		return 1;
+	}
+	if (once) {
+		int r = pass(1, &failed, &wake);
+
+		if (r < 0) {
+			say("cannot read %s: %s", outbox, strerror(-r));
+			return 1;
+		}
+		return failed;
+	}
+
+	ifd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
+	if (ifd >= 0 && inotify_add_watch(ifd, outbox, IN_MOVED_TO | IN_CLOSE_WRITE) < 0) {
+		close(ifd);
+		ifd = -1;
+	}
+	say("started: outbox %s, at most %d mails an hour%s", outbox, CAP_PER_HOUR,
+	    ifd < 0 ? " (no inotify watch: polling every 10 s)" : "");
+	for (;;) {
+		int may_send = mono() >= retry_at, r = pass(may_send, &failed, &wake), ms = IDLE_MS;
+
+		if (r < 0) {
+			if (-r != last_err)
+				say("cannot read %s: %s", outbox, strerror(-r));
+			last_err = -r;
+			ms = 10000;
+		} else {
+			last_err = 0;
+			if (failed)
+				retry_at = mono() + BACKOFF;
+			if (wake > 0 && wake * 1000 < ms)
+				ms = (int)(wake * 1000) + 100;
+			if ((failed || !may_send) && (retry_at - mono()) * 1000 < ms)
+				ms = (int)((retry_at - mono()) * 1000) + 100;
+		}
+		if (ms < 100)
+			ms = 100;
+		if (ifd < 0) {
+			poll(NULL, 0, ms < 10000 ? ms : 10000);
+			continue;
+		}
+		struct pollfd p = { ifd, POLLIN, 0 };
+
+		if (poll(&p, 1, ms) > 0) {
+			char ev[4096];
+
+			poll(NULL, 0, 200);          /* let a burst of renames settle */
+			while (read(ifd, ev, sizeof ev) > 0)
+				;
+		}
+	}
+}
diff --git a/usr/local/libexec/tracker-mailer b/usr/local/libexec/tracker-mailer
deleted file mode 100755
index 3541821..0000000
--- a/usr/local/libexec/tracker-mailer
+++ /dev/null
@@ -1,239 +0,0 @@
-#!/usr/bin/python3 -I
-# /usr/local/libexec/tracker-mailer - sends the GPS tracker's password-reset mails.
-# tracker-r12 (2026-10-29), from mail-tooling's patches/02-tracker-mailer.py.
-#
-# The php-tracker pool no longer submits mail: it is out of group postdrop, mail() is disabled
-# in its profile, and Postfix's authorized_submit_users no longer lists it. Group postdrop let
-# any code running in that pool (ffmpeg on device-supplied audio included) write raw queue files
-# into maildrop with any sender and From:, which pickup accepts as local mail and OpenDKIM signs.
-#
-# recover.php drops one job per reset into OUTBOX: {"rcpt": "user@host.tld", "key": "<32 hex>"}
-# (tracker-mail:tracker-mail 3770; php-tracker writes it as a member of group tracker-mail).
-# This runs every minute from /etc/cron.d/tracker-mailer as the user tracker-mail, and
-#   - accepts only a plain user@host.tld recipient (the tracker's own rule) and a 32-hex key;
-#   - renders the one fixed message itself, so the pool chooses only (recipient, key);
-#   - submits it with an explicit recipient (never -t) and the envelope sender Postfix pins for
-#     this user (local_login_sender_maps: tracker-mail = tracker-noreply@coredump.ws);
-#   - sends at most CAP_PER_HOUR an hour, whatever the pool queues: a job over the cap waits
-#     for the next run, and a job older than the reset link (an hour) is dropped unsent.
-# A compromised pool can therefore at worst have CAP_PER_HOUR fixed reset mails an hour sent.
-#
-# Logs to syslog (facility mail, tag tracker-mailer). Never logs a key, only the recipient's
-# domain (Postfix logs the full address anyway).
-# Test hooks: TM_OUTBOX TM_STATE TM_SENDMAIL TM_LOG=stderr TM_NOW (fixed clock).
-import errno
-import fcntl
-import json
-import os
-import re
-import stat
-import subprocess
-import sys
-import time
-
-E = os.environ.get
-OUTBOX = E('TM_OUTBOX', '/var/spool/tracker-outbox')
-STATE = E('TM_STATE', '/var/lib/tracker-mail')
-SENDMAIL = E('TM_SENDMAIL', '/usr/sbin/sendmail')
-SENDER = 'tracker-noreply@coredump.ws'
-CAP_PER_HOUR = 20          # = MAIL_BUDGET['reset'] site-wide in tracker/database.php
-WINDOW = 3600
-JOB_TTL = 3600             # = RESET_KEY_TTL: an older link no longer works
-MAX_SCAN = 500             # directory entries looked at per run
-MAX_JOB = 4096
-JOB_NAME = re.compile(r'[0-9a-f]{16}\.json')
-TMP_NAME = re.compile(r'\.[0-9a-f]{16}\.tmp')
-# the same rule as TRACKER_MAIL_RE in tracker/config.php (fullmatch, so no trailing newline)
-RCPT = re.compile(r'[A-Za-z0-9._+-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}')
-KEY = re.compile(r'[0-9a-f]{32}')
-MESSAGE = ('From: GPS tracker <%(sender)s>\n'
-           'To: %(rcpt)s\n'
-           'Subject: GPS tracker password reset\n'
-           'MIME-Version: 1.0\n'
-           'Content-Type: text/plain; charset=UTF-8\n'
-           'Content-Transfer-Encoding: 7bit\n'
-           'Auto-Submitted: auto-generated\n'
-           '\n'
-           'You can reset your password with the following link. It works once,\n'
-           'and for one hour.\n'
-           'https://coredump.ws/tracker/reset.php?key=%(key)s\n')
-
-if E('TM_LOG') == 'stderr':
-    def log(msg):
-        print('tracker-mailer: ' + msg, file=sys.stderr)
-else:
-    import syslog
-    syslog.openlog('tracker-mailer', syslog.LOG_PID, syslog.LOG_MAIL)
-
-    def log(msg):
-        syslog.syslog(syslog.LOG_INFO, msg)
-
-
-def now():
-    return float(E('TM_NOW')) if E('TM_NOW') else time.time()
-
-
-def load_sent(t):
-    try:
-        with open(os.path.join(STATE, 'sent.json')) as f:
-            data = json.load(f)
-        return [float(x) for x in data if isinstance(x, (int, float)) and t - WINDOW < x <= t + 60]
-    except (OSError, ValueError, TypeError):
-        return []
-
-
-def save_sent(sent):
-    path = os.path.join(STATE, 'sent.json')
-    tmp = path + '.tmp'
-    with open(tmp, 'w') as f:
-        json.dump(sent, f)
-        f.flush()
-        os.fsync(f.fileno())
-    os.replace(tmp, path)
-
-
-def remove(entry):
-    try:
-        if entry.is_dir(follow_symlinks=False):
-            os.rmdir(entry.path)
-        else:
-            os.unlink(entry.path)
-        return True
-    except OSError:
-        return False
-
-
-def read_job(entry, st):
-    """The job's bytes, or None. The pool's user owns what it writes here, so the file is opened
-    without following a symlink and without blocking on a FIFO, and must still be the regular,
-    single-link file that was listed."""
-    try:
-        fd = os.open(entry.path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
-    except OSError:
-        return None
-    try:
-        fst = os.fstat(fd)
-        if (not stat.S_ISREG(fst.st_mode) or fst.st_nlink != 1 or fst.st_ino != st.st_ino
-                or fst.st_dev != st.st_dev or fst.st_size > MAX_JOB):
-            return None
-        return os.read(fd, MAX_JOB + 1)
-    finally:
-        os.close(fd)
-
-
-def parse(data):
-    """(rcpt, key) from a job, or None."""
-    if data is None or len(data) > MAX_JOB:
-        return None
-    try:
-        job = json.loads(data.decode('ascii'))
-    except (UnicodeDecodeError, ValueError):
-        return None
-    if not isinstance(job, dict) or set(job) != {'rcpt', 'key'}:
-        return None
-    rcpt, key = job['rcpt'], job['key']
-    if not (isinstance(rcpt, str) and len(rcpt) <= 254 and RCPT.fullmatch(rcpt)
-            and isinstance(key, str) and KEY.fullmatch(key)):
-        return None
-    return rcpt, key
-
-
-def send(rcpt, key):
-    msg = MESSAGE % {'sender': SENDER, 'rcpt': rcpt, 'key': key}
-    try:
-        r = subprocess.run([SENDMAIL, '-i', '-f', SENDER, '--', rcpt], input=msg.encode('ascii'),
-                           stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=120,
-                           env={'PATH': '/usr/sbin:/usr/bin:/bin', 'LANG': 'C'}, check=False)
-    except (OSError, subprocess.TimeoutExpired) as e:
-        return 'sendmail did not run: %s' % e.__class__.__name__
-    if r.returncode != 0:
-        err = r.stderr.decode('utf-8', 'replace').strip().splitlines()
-        return 'sendmail exit %d: %s' % (r.returncode, (err[0] if err else '')[:200])
-    return None
-
-
-def main():
-    if os.geteuid() == 0:
-        print('tracker-mailer: refusing to run as root (Postfix pins the sender for tracker-mail only)',
-              file=sys.stderr)
-        return 2
-    try:
-        # read-only is enough for flock, and works whoever created the file (verify.sh holds it as root)
-        lock = os.open(os.path.join(STATE, 'lock'), os.O_RDONLY | os.O_CREAT | os.O_CLOEXEC, 0o600)
-    except OSError as e:
-        log('cannot open the lock in %s: %s' % (STATE, e.strerror))
-        return 1
-    try:
-        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
-    except OSError as e:
-        if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
-            return 0            # the previous run is still busy
-        raise
-
-    t = now()
-    sent = load_sent(t)
-    jobs, counts = [], {'malformed': 0, 'expired': 0, 'deferred': 0, 'not a file': 0}
-    try:
-        it = os.scandir(OUTBOX)
-    except OSError as e:
-        log('cannot read %s: %s' % (OUTBOX, e.strerror))
-        return 1
-    with it:
-        for i, entry in enumerate(it):
-            if i >= MAX_SCAN:
-                break
-            name = entry.name
-            try:
-                st = entry.stat(follow_symlinks=False)
-            except OSError:
-                continue
-            if TMP_NAME.fullmatch(name):
-                # a job recover.php never finished writing
-                if t - st.st_mtime > JOB_TTL:
-                    remove(entry)
-                continue
-            if not JOB_NAME.fullmatch(name):
-                if remove(entry):
-                    counts['malformed'] += 1
-                continue
-            if not stat.S_ISREG(st.st_mode):
-                if remove(entry):
-                    counts['not a file'] += 1
-                continue
-            jobs.append((st.st_mtime, name, entry, st))
-
-    status = 0
-    for mtime, name, entry, st in sorted(jobs, key=lambda j: (j[0], j[1])):
-        if t - mtime > JOB_TTL:
-            if remove(entry):
-                counts['expired'] += 1
-            continue
-        job = parse(read_job(entry, st))
-        if job is None:
-            if remove(entry):
-                counts['malformed'] += 1
-            continue
-        if len(sent) >= CAP_PER_HOUR:
-            counts['deferred'] += 1         # stays queued for a later run, until it expires
-            continue
-        rcpt, key = job
-        err = send(rcpt, key)
-        if err:
-            log('job %s for *@%s not sent, kept for the next run: %s' % (name[:16], rcpt.split('@')[1], err))
-            status = 1
-            break
-        sent.append(now())
-        save_sent(sent)
-        if not remove(entry):
-            log('job %s sent but could not be removed' % name[:16])
-        log('job %s: reset mail submitted for *@%s (%d in the last hour)' % (name[:16], rcpt.split('@')[1], len(sent)))
-
-    left = {k: v for k, v in counts.items() if v}
-    if left:
-        log('%s; hourly cap %d, sent in the last hour %d' % (
-            ', '.join('%s %d' % kv for kv in sorted(left.items())), CAP_PER_HOUR, len(sent)))
-    return status
-
-
-if __name__ == '__main__':
-    sys.exit(main())
diff --git a/var/www/tracker/config.php b/var/www/tracker/config.php
index ae404cb..2b4b7a3 100644
--- a/var/www/tracker/config.php
+++ b/var/www/tracker/config.php
@@ -19,8 +19,8 @@ define('DATABASE', '/var/lib/tracker/database.db');
  * Password-reset mail. This pool does not send mail itself: it is not in group postdrop, and
  * mail() is disabled in its PHP profile, because any code running here (ffmpeg on device audio
  * included) could otherwise submit mail of its own, DKIM-signed as coredump.ws. recover.php drops
- * one job, {"rcpt": ..., "key": ...}, into TRACKER_OUTBOX; /usr/local/libexec/tracker-mailer, run
- * every minute by cron as the user tracker-mail, checks it, renders the one fixed message and
+ * one job, {"rcpt": ..., "key": ...}, into TRACKER_OUTBOX; the tracker-mailer daemon (running as
+ * the user tracker-mail, watching the directory) picks it up, checks it, renders the one fixed message and
  * submits it with the envelope sender Postfix pins for that user (tracker-noreply@coredump.ws),
  * at most 20 an hour. The directory is tracker-mail:tracker-mail 3770 (setgid, sticky); this
  * pool's user writes it as a member of group tracker-mail.
diff --git a/var/www/tracker/recover.php b/var/www/tracker/recover.php
index c876b8e..265fb1e 100644
--- a/var/www/tracker/recover.php
+++ b/var/www/tracker/recover.php
@@ -46,7 +46,7 @@ if ('POST' === $_SERVER['REQUEST_METHOD'] ) {
          if($key){
             /*
              * This pool no longer sends mail itself (config.php, TRACKER_OUTBOX): it hands
-             * (recipient, key) to the outbox, and tracker-mailer - its own user, from cron -
+             * (recipient, key) to the outbox, and tracker-mailer - a daemon, its own user -
              * renders the fixed message (the link, wrapped text, From: GPS tracker
              * <tracker-noreply@coredump.ws>, Auto-Submitted) and submits it with the envelope
              * sender Postfix pins for it. Written under a dot name and renamed, so the mailer