Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion sbin/prowlctl/tests/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ PACKAGE= tests
ATF_TESTS_SH+= prowlctl_test notify_test trust_test

BINDIR= ${TESTSDIR}
PROGS+= notify_helper
PROGS+= notify_helper pdfork_helper

# Each test starts its own prowld in a scratch directory; they do not share
# state, but they do start and kill daemons, so do not run them in parallel
Expand Down
63 changes: 63 additions & 0 deletions sbin/prowlctl/tests/pdfork_helper.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/* SPDX-License-Identifier: BSD-2-Clause */
/*
* pdfork_helper hold pidfile program [argument ...]
*
* A launcher for a daemon created with pdfork(2). Start program with
* PD_DAEMON, write its PID to pidfile and exit 0, leaving a forked holder
* that keeps the process descriptor open for hold seconds.
*/
#include <sys/types.h>
#include <sys/procdesc.h>

#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(int argc, char **argv)
{
FILE *fp;
char *end;
long hold;
pid_t pid, holder;
int pd;

if (argc < 4)
errx(2, "usage: pdfork_helper hold pidfile program "
"[argument ...]");
errno = 0;
hold = strtol(argv[1], &end, 10);
if (errno != 0 || end == argv[1] || *end != '\0' || hold < 0 ||
hold > 3600)
errx(2, "bad hold time: %s", argv[1]);

/* The child does not inherit its own descriptor. */
pid = pdfork(&pd, PD_DAEMON);
if (pid == -1)
err(1, "pdfork");
if (pid == 0) {
execv(argv[3], argv + 3);
_exit(127);
}

holder = fork();
if (holder == -1)
err(1, "fork");
if (holder == 0) {
/* Exiting closes the last descriptor. */
sleep((unsigned int)hold);
_exit(0);
}
if (close(pd) == -1)
err(1, "close");

fp = fopen(argv[2], "w");
if (fp == NULL)
err(1, "%s", argv[2]);
fprintf(fp, "%d\n", (int)pid);
if (fclose(fp) != 0)
err(1, "%s", argv[2]);
return (0);
}
115 changes: 115 additions & 0 deletions sbin/prowlctl/tests/prowlctl_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,118 @@ forking_pidfile_cleanup()
stop_prowld
}

# wait_gone pid: wait for a process to disappear
wait_gone()
{
for i in $(jot 25); do
kill -0 "$1" 2>/dev/null || return 0
sleep 0.2
done
atf_fail "pid $1 is still running"
}

# require_kinfo_procdesc: skip on kernels that cannot report pdfork(2)
require_kinfo_procdesc()
{
[ "$(sysctl -n kern.features.kinfo_procdesc 2>/dev/null)" = 1 ] ||
atf_skip "kernel does not report process descriptors"
}

atf_test_case forking_pdfork_held cleanup
forking_pdfork_held_head()
{
atf_set descr "A pdfork(2) daemon is not adopted while another process holds its descriptor"
atf_set require.user root
atf_set timeout 60
}
forking_pdfork_held_body()
{
require_kinfo_procdesc
dir=$(pwd)
mkdir units
cat >units/held.unit <<EOF
{"label":"org.test.held","type":"daemon",
"program":"$(atf_get_srcdir)/pdfork_helper",
"arguments":["60","$dir/daemon.pid","/bin/sleep","301"],
"pid_name":"sleep","run_at_load":true}
EOF
start_prowld
wait_state org.test.held failed
atf_check_equal "-1" "$(job_pid org.test.held)"
# The cancelled launch kills the daemon along with its holder.
wait_gone "$(cat daemon.pid)"
}
forking_pdfork_held_cleanup()
{
stop_prowld
pkill -KILL -f "sleep 301" 2>/dev/null || true
}

atf_test_case forking_pdfork_closed cleanup
forking_pdfork_closed_head()
{
atf_set descr "A pdfork(2) daemon is adopted once its descriptor closes"
atf_set require.user root
atf_set timeout 60
}
forking_pdfork_closed_body()
{
require_kinfo_procdesc
dir=$(pwd)
mkdir units
cat >units/closed.unit <<EOF
{"label":"org.test.closed","type":"daemon",
"program":"$(atf_get_srcdir)/pdfork_helper",
"arguments":["1","$dir/daemon.pid","/bin/sleep","302"],
"pid_name":"sleep","run_at_load":true}
EOF
start_prowld
wait_state org.test.closed running
pid=$(cat daemon.pid)
atf_check_equal "$pid" "$(job_pid org.test.closed)"
atf_check -o ignore ${CTL} stop org.test.closed
wait_state org.test.closed stopped
wait_gone "$pid"
}
forking_pdfork_closed_cleanup()
{
stop_prowld
pkill -KILL -f "sleep 302" 2>/dev/null || true
}

atf_test_case forking_uid cleanup
forking_uid_head()
{
atf_set descr "A double-forked daemon that changes user ID is adopted and stopped"
atf_set require.user root
atf_set require.progs "chroot"
atf_set timeout 60
}
forking_uid_body()
{
dir=$(pwd)
mkdir units
cat >launch.sh <<'EOF'
(chroot -u nobody / /bin/sleep 303 &)
EOF
cat >units/uid.unit <<EOF
{"label":"org.test.uid","type":"daemon","program":"/bin/sh",
"arguments":["$dir/launch.sh"],"pid_name":"sleep","run_at_load":true}
EOF
start_prowld
wait_state org.test.uid running
pid=$(job_pid org.test.uid)
atf_check_equal "$(id -u nobody)" "$(ps -o uid= -p "$pid" | tr -d ' ')"
atf_check -o ignore ${CTL} stop org.test.uid
wait_state org.test.uid stopped
wait_gone "$pid"
}
forking_uid_cleanup()
{
stop_prowld
pkill -KILL -f "sleep 303" 2>/dev/null || true
}

atf_test_case shim_pidfile_status cleanup
shim_pidfile_status_head()
{
Expand Down Expand Up @@ -1671,6 +1783,9 @@ atf_init_test_cases()
atf_add_test_case forking_launch_identity
atf_add_test_case forking_pidfile
atf_add_test_case shim_pidfile_status
atf_add_test_case forking_pdfork_held
atf_add_test_case forking_pdfork_closed
atf_add_test_case forking_uid
atf_add_test_case shared_provide
atf_add_test_case expansion
atf_add_test_case actions
Expand Down
6 changes: 5 additions & 1 deletion sbin/prowld/prowl-unit.5
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.Dd November 22, 2026
.Dd November 30, 2026
.Dt PROWL-UNIT 5
.Os
.Sh NAME
Expand Down Expand Up @@ -341,6 +341,10 @@ A temporary process reaper identifies the daemon across forks and changes of
session or user ID.
Until adoption succeeds, status reports no daemon PID.
If the launch fails or is cancelled, the reaper cleans up its descendants.
A process created with
.Xr pdfork 2
is not adopted while any process holds a descriptor for it,
since closing that descriptor could reap it and free its PID for reuse.
The daemon is looked for every 200 milliseconds for up to 10 seconds; if it
does not appear the job is treated as having failed.
Only one of the two may be given.
Expand Down
2 changes: 1 addition & 1 deletion sbin/prowld/prowld-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ File extension: `.unit` (language-neutral; libucl auto-detects syntax).
**Execution**
- `program` *(required unless `arguments[0]` is a full path)*: Path to executable
- `arguments` *(array of strings)*: argv (argv[0] is `program` basename by default)
- `pid_file` / `pid_name` *(string, exclusive)*: for a daemon that forks and lets its launcher exit. A private reaper waits for the launcher to exit successfully and selects a live child from that launch. It uses the PID on the first line of a regular file, or the oldest matching process name. The service manages any existing pidfile at startup. The reaper retries every 200 ms for up to 10 seconds and cleans up its descendants on failure or cancellation. prowld checks the process identity at handoff and reports the adopted PID.
- `pid_file` / `pid_name` *(string, exclusive)*: for a daemon that forks and lets its launcher exit. A private reaper waits for the launcher to exit successfully and selects a live child from that launch. It uses the PID on the first line of a regular file, or the oldest matching process name. The service manages any existing pidfile at startup. The reaper retries every 200 ms for up to 10 seconds and cleans up its descendants on failure or cancellation. A `pdfork(2)` process is not adopted while a process descriptor for it is open, because closing that descriptor reaps it without prowld; kernels without the `kinfo_procdesc` feature cannot report this. prowld checks the process identity at handoff and reports the adopted PID.
- `start_pre` / `start_post` / `stop_pre` / `stop_post` *(array of arrays of strings, at most 8 commands each)*: commands around the job, each `[program, args...]` with `@name@` expansion; a leading `-` on the program ignores its failure. Conditions may precede the program: `?var` (rc.conf variable is YES/TRUE/ON/1), `!var` (it is not), `+var` (it is not empty), `~var` (it is empty), `<var` (its value names a readable file), `!<var` (it does not); all must hold or the command is skipped. `start_post` (after a oneshot's command exited 0; a failing command fails the job) and `stop_pre` (before a oneshot's stop command) are for oneshot jobs only. `start_pre` commands run in order in the child that is about to exec the job, as the job's user; the first failure ends the child so the job does not start, and a daemon is not "up" while they run. `stop_post` commands run in the parent after the job's process has ended, however it ended; failures are logged and the rest still run, each is killed after 30 s, and prowld waits for them (also at shutdown).
- Entries of `requires`, `wants` and `activates` may start with a condition and a space (`"?var service"`, `"!var service"`, `"+var service"`): the entry counts only if the rc.conf variable is YES, is not YES, or is not empty.
- `activates` *(array of strings)*: like `requires`, but a provider that is disabled is started (as `prowlctl start` would) rather than waited for forever. The job starts once they are up, at load or by hand. Masked providers and rc.d-only providers are not started.
Expand Down
3 changes: 3 additions & 0 deletions sbin/prowld/prowld.c
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,9 @@ main(int argc, char *argv[])
g_reaper = true;
else
prowl_log(LOG_WARNING, "procctl reaper: %m");
if (g_reaper && !feature_present("kinfo_procdesc"))
prowl_log(LOG_NOTICE, "kernel does not report process "
"descriptors; pdfork(2) daemons are adopted unchecked");

g_kqueue_fd = kqueue();
if (g_kqueue_fd == -1) {
Expand Down
23 changes: 18 additions & 5 deletions sbin/prowld/supervisor.c
Original file line number Diff line number Diff line change
Expand Up @@ -1805,6 +1805,21 @@ supervisor_socket_activate(job_t *job)
job->label, (int)pid);
}

/*
* Whether a child is ours alone to reap. Closing the last descriptor of a
* pdfork(2) process reaps it without us, which frees its PID for reuse
* between a check and kill(2). A descriptor is never attached again once
* detached, so a child without one at adoption stays safe to signal.
* Kernels without kinfo_procdesc never set KI_PROCDESC.
*/
static bool
adoptable(const struct kinfo_proc *kp, pid_t self)
{
return (kp->ki_ppid == self && kp->ki_stat != SZOMB &&
(kp->ki_flag & (P_WEXIT | P_TRACED)) == 0 &&
(kp->ki_kiflag & KI_PROCDESC) == 0);
}

/*
* kinfo_proc reports start time relative to the wall clock. Subtract the
* kernel's boot time so setting the clock cannot invalidate an adopted PID.
Expand All @@ -1825,8 +1840,7 @@ child_start_time(pid_t pid, struct timeval *start)
kp = kinfo_getproc(pid);
if (kp == NULL)
return (false);
if (kp->ki_ppid != getpid() || kp->ki_stat == SZOMB ||
(kp->ki_flag & (P_WEXIT | P_TRACED)) != 0) {
if (!adoptable(kp, getpid())) {
free(kp);
errno = ESRCH;
return (false);
Expand Down Expand Up @@ -2542,10 +2556,9 @@ find_daemon(const job_t *job, struct launch_result *result)

result->pid = 0;
self = getpid();
/* A held descriptor may close before the next poll; keep looking. */
for (i = 0; i < count; i++) {
if (kp[i].ki_ppid != self || kp[i].ki_stat == SZOMB ||
(kp[i].ki_flag & (P_WEXIT | P_TRACED)) != 0 ||
(job->pid_file == NULL &&
if (!adoptable(&kp[i], self) || (job->pid_file == NULL &&
strcmp(kp[i].ki_comm, job->pid_name) != 0))
continue;
if (result->pid == 0 ||
Expand Down
10 changes: 10 additions & 0 deletions sys/kern/kern_proc.c
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@
#include <compat/freebsd32/freebsd32_util.h>
#endif

FEATURE(kinfo_procdesc, "kinfo_proc reports attached process descriptors");

SDT_PROVIDER_DEFINE(proc);

MALLOC_DEFINE(M_SESSION, "session", "session header");
Expand Down Expand Up @@ -1101,6 +1103,14 @@ fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp)
kp->ki_vmspace = p->p_vmspace;
kp->ki_flag = p->p_flag;
kp->ki_flag2 = p->p_flag2;
/*
* A descriptor is attached only by pdfork(2) and, once detached, never
* returns. While attached, closing it can reap the process without its
* parent, so report it to supervisors that signal adopted PIDs.
*/
sx_assert(&proctree_lock, SA_LOCKED);
if (p->p_procdesc != NULL)
kp->ki_kiflag |= KI_PROCDESC;
cred = p->p_ucred;
if (cred) {
kp->ki_uid = cred->cr_uid;
Expand Down
1 change: 1 addition & 0 deletions sys/sys/user.h
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ void fill_kinfo_proc(struct proc *, struct kinfo_proc *);
#define KI_CTTY 0x00000001 /* controlling tty vnode active */
#define KI_SLEADER 0x00000002 /* session leader */
#define KI_LOCKBLOCK 0x00000004 /* proc blocked on lock ki_lockname */
#define KI_PROCDESC 0x00000008 /* process descriptor attached */

/*
* This used to be the per-process structure containing data that
Expand Down
59 changes: 59 additions & 0 deletions tests/sys/kern/sysctl_kern_proc.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@
*/

#include <sys/param.h>
#include <sys/procctl.h>
#include <sys/procdesc.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/user.h>
#include <sys/wait.h>

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Expand Down Expand Up @@ -190,10 +193,66 @@ ATF_TC_BODY(sysctl_kern_proc_filedesc, tc)
sysctl_kern_proc_all(cmd);
}

static long
proc_kiflag(pid_t pid)
{
struct kinfo_proc kp;
size_t sz;
int mib[4];

mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = pid;
sz = sizeof(kp);
ATF_REQUIRE(sysctl(mib, 4, &kp, &sz, NULL, 0) == 0);
ATF_REQUIRE(sz == sizeof(kp));
return (kp.ki_kiflag);
}

/*
* KI_PROCDESC is reported while a process descriptor is attached, and
* cleared when the last descriptor for a live process closes.
*/
ATF_TC_WITHOUT_HEAD(sysctl_kern_proc_procdesc);
ATF_TC_BODY(sysctl_kern_proc_procdesc, tc)
{
pid_t child;
int pd, status;

ATF_REQUIRE(feature_present("kinfo_procdesc"));
/* A detached child is reparented to its reaper; make that us. */
ATF_REQUIRE(procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) == 0);

child = fork();
ATF_REQUIRE(child != -1);
if (child == 0) {
pause();
_exit(0);
}
ATF_REQUIRE((proc_kiflag(child) & KI_PROCDESC) == 0);
ATF_REQUIRE(kill(child, SIGKILL) == 0);
ATF_REQUIRE(waitpid(child, &status, 0) == child);

child = pdfork(&pd, PD_DAEMON);
ATF_REQUIRE(child != -1);
if (child == 0) {
pause();
_exit(0);
}
ATF_REQUIRE((proc_kiflag(child) & KI_PROCDESC) != 0);
/* PD_DAEMON: closing the descriptor detaches it without a kill. */
ATF_REQUIRE(close(pd) == 0);
ATF_REQUIRE((proc_kiflag(child) & KI_PROCDESC) == 0);
ATF_REQUIRE(kill(child, SIGKILL) == 0);
ATF_REQUIRE(waitpid(child, &status, 0) == child);
}

ATF_TP_ADD_TCS(tp)
{
ATF_TP_ADD_TC(tp, sysctl_kern_proc_cwd);
ATF_TP_ADD_TC(tp, sysctl_kern_proc_filedesc);
ATF_TP_ADD_TC(tp, sysctl_kern_proc_procdesc);

return (atf_no_error());
}
Loading