Compare commits

...
94 Commits
Author SHA1 Message Date
Joachim Wiberg 8fc4cf8b4b sm: keep /etc/nologin when entering runlevel 1 from S
Booting straight into single user mode left logins allowed.  The same
happened going from runlevel 1 to 0 or 6, logins were let in while the
system went down.

The file was created when the new runlevel was 1, 0, 6 or S, and after
that removed when the previous one was.  With both true, the removal
undid the creation.

Remove it only when the new runlevel does not want it.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-23 02:17:23 +01:00
Joachim Wiberg a629c8add3 tmpfiles: skip a C entry with a relative path to copy from
The argument of a C entry was used as it is, so a relative one was
copied from the directory tmpfiles happened to be started in.  With
--root that directory is outside the new root, and

    C /etc/copy - - - - ../../../etc/shadow

in a file below the root copied a file of the running system into it.

systemd skips a C line when the path to copy from is not absolute.
Do the same, with a warning.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:51 +01:00
Joachim Wiberg 225b2594b7 tmpfiles: add --root, run on the system below a directory
There was no way to run the tmpfiles.d files of a root file system
that is not the running one, for example an image that is being put
together.

systemd-tmpfiles has --root=DIR for that.  Add the same:

    tmpfiles --create --root=/mnt/target

The tmpfiles.d files, users, and groups are those below DIR, and so is
every path, also what an absolute link there points to.  A file on the
command line is opened before the root is changed, as systemd does.

It is done with chroot(2), so tmpfiles must be run as root.  The new
root most likely has no /proc, which is needed to set the mode, ACL,
or attributes of a path opened with O_PATH.  The work directory is
therefore left in the /proc/self/fd of the old root.  Users and groups
are read from /etc/passwd and /etc/group, NSS would be that of the old
root.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:51 +01:00
Joachim Wiberg 26568bc0fd tmpfiles: add --purge and the $ modifier
When a package is removed, the state its tmpfiles.d file made is left
behind, there was no way to ask for it to be removed.

systemd-tmpfiles has --purge for that, which removes what the entries
marked with a $ after the type make:

    d$ /var/lib/app 0750 app app
    tmpfiles --purge /usr/lib/tmpfiles.d/app.conf

Add the same.  It only takes the entries of files on the command line,
never all of the tmpfiles.d files, and a path is removed before the
one above it.  A $ was until now read and ignored.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:50 +01:00
Joachim Wiberg 575267f09b tmpfiles: add --replace, files on the command line in place of one
A package script may run before the package's tmpfiles.d file is on
disk, and gives the entries on the command line or on standard input.
Then only those entries were read, so one that the admin has changed
in /etc/tmpfiles.d was run as the package has it.

With --replace=PATH all the tmpfiles.d files are read, and the ones on
the command line are read where the file PATH would be, as in
systemd-tmpfiles:

    tmpfiles --create --replace=/usr/lib/tmpfiles.d/app.conf -

They are not read at all when a later directory has a file of that
name, as with a file that is installed.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:50 +01:00
Joachim Wiberg fa430d0a02 tmpfiles: read a file named - from standard input
A package script that has its entries at hand, and not yet in a file,
gives them to systemd-tmpfiles on standard input:

    echo 'd /var/lib/app 0750 app app' | tmpfiles --create -

Finit's tmpfiles took - as the name of a file and failed to open it.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:49 +01:00
Joachim Wiberg dd186287d7 tmpfiles: read the files by name, the first entry for a path counts
The files were read one directory at a time, Finit's own first and
/etc/tmpfiles.d last, and every entry for a path was run.  With two
entries for a path the last one read won, so an entry in /etc won over
one in /usr/lib whatever the files were called.

tmpfiles.d(5) reads the files in the order of their names, whatever
directory they are in, and goes by the first entry that makes a path.
A package relies on that when it names its file to sort before or
after another.  Do the same.  As before, a file in a later directory
is read in place of one of the same name in an earlier one.

A later entry is skipped when it makes a path an earlier one makes, or
when both take a glob and remove, write to, or keep the path.  Several
w+ entries may add to one file.  The skip is only told about with
--dry-run or --debug, since Finit's files and those of other packages
overlap on most systems.

Finit's own files had two entries for some paths, and relied on the
last one.  Drop the ones that lost: /run/lock, /run/lock/subsys, and
/var/lock in legacy.conf, and /var/run and a second /var/spool in
var.conf.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:49 +01:00
Joachim Wiberg 86bb79d7a1 tmpfiles: create a path after those above it, glob entries last
An entry was run as its line was read, so the outcome followed the
order of the lines and of the files.  With

    f /var/run/app/file
    L /var/run - - - - ../run

the f entry made /var/run a directory, and the link was never made.
An entry like z or w, placed before the one that makes its path, found
nothing to change.

tmpfiles.d(5) has a path created after the paths above it and removed
after those below it, and runs the entries that take a glob after the
others.  Do the same.  Every entry is now read before the first one is
run, which also means a line is parsed once, not once per pass, and
the pass that only gathered the x and X entries is gone.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:48 +01:00
Joachim Wiberg 4bec72fcf2 tmpfiles: skip an entry with a relative path
An entry with a path like tmp/file was run on the directory tmpfiles
happened to be started in.  tmpfiles.d(5) only has absolute paths, and
systemd skips such a line.  Do the same, with a warning.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:48 +01:00
Joachim Wiberg ce5a08e866 tmpfiles: handle an ACL of any size
An a or A entry for a path with an ACL of more than 32 entries, or one
that would get more, left the path as it was with a warning.  The ACL
was kept in a fixed array.  It is now allocated to the size it needs.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 19:23:47 +01:00
Joachim Wiberg c7f55a8b90 util: remove mksubsys(), it has no callers
Services get their directories from mksubsysd(), which takes the ids
already resolved.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 18:57:16 +01:00
Joachim Wiberg 1f7208f88f doc: note what sorting the tmpfiles.d files by name needs
Sorting the files by name across directories is not a change to make
on its own.  Finit runs every entry for a path, so the last one wins,
where systemd goes by the first.  Sorted, an entry in /etc would lose
to one in /usr/lib with a later name.

Say so in the TODO, and add the relative paths found in review.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:15:13 +01:00
Joachim Wiberg f2c0888375 tmpfiles: add the = modifier, remove a path of another kind
When there is a file where an entry wants a directory, or the other
way around, the entry fails or leaves the path as it is.  In
tmpfiles.d(5) an = after the type has the path removed first when it
is of another kind than the entry makes:

    d= /var/lib/foo 0755 foo foo

The same goes for the directories above the path, anything else in
place of one is removed.  tmpfiles ignores the =.

Remove what does not match before the b, c, d, D, f, F, L, and p
entries, the ones that make a path of one kind.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:12 +01:00
Joachim Wiberg 37cbc12946 tmpfiles: add the C+ entry, copy to a directory that is not empty
A C entry leaves a directory alone when there is something in it.  In
tmpfiles.d(5) a C+ entry copies to it anyway: what the directory lacks
is added, and what it has is not overwritten.

    C+ /etc/skel - - - - /usr/share/factory/etc/skel

tmpfiles reads C+ as C.  Let the + through to copy_tree().

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:04 +01:00
Joachim Wiberg 7b3b217e60 tmpfiles: fix C entries, never copy over what exists
A C entry for a directory does the opposite of tmpfiles.d(5):

    C /etc/pam.d - - - -

When /etc/pam.d does not exist the entry fails with "Not a directory",
the files of the source are copied to a file with the name of the
path, one over the other.  When it is an empty directory nothing is
copied.  When it has files in it, they are overwritten with the ones
from /usr/share/factory, at every boot.  For a file, an existing one
is overwritten as well.

is_dir_empty() returns true for a directory that is not empty, and
rsync() from libite copies over what is there and needs a slash at the
end of a destination directory that is missing.

Copy with a tree walk of our own instead.  It copies to a path that
is missing or an empty directory, overwrites nothing, and does not
follow links.  Mode, owner, and modification time are those of the
source.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:04 +01:00
Joachim Wiberg 9160ca3ddf tmpfiles: clean what an x entry keeps by the age of the entry
An x or X entry can have an age of its own in tmpfiles.d(5).  What it
keeps from the cleaning of the directory above is then cleaned by that
age instead:

    d /tmp       1777 root root 10d
    x /tmp/build -    -    -    30d

tmpfiles does not read the age, so /tmp/build is never cleaned.

Clean the paths of such an entry by its age, with the entry itself
left out of what is kept.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:03 +01:00
Joachim Wiberg 9ea64e5c3c tmpfiles: let %T and %V follow $TMPDIR
The %T and %V specifiers are always /tmp and /var/tmp.  In systemd
both are the first of $TMPDIR, $TEMP, and $TMP that is set to an
absolute path of a directory, and only otherwise /tmp and /var/tmp.

Do the same.  At boot none of them are set, so nothing changes there.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:03 +01:00
Joachim Wiberg c349d564d4 tmpfiles: take --graceful
Package scripts written for systemd-tmpfiles may call it with
--graceful, to not fail on an entry for a user or group that does not
exist.  tmpfiles then stops at the unknown option and prints its usage
text:

    tmpfiles --create --graceful /usr/lib/tmpfiles.d/foo.conf

Take the option and do nothing.  An entry with an unknown user is
already skipped without an error, and an unknown group left alone.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:02 +01:00
Joachim Wiberg 6b5a8e0386 tmpfiles: add --cat-config, to show the files that would be read
With files in five directories, where one in /etc replaces the one
with the same name in /usr/lib, it is not easy to tell what tmpfiles
goes by.  systemd-tmpfiles has --cat-config for this.

Add the option.  It prints each file that would be read below a line
with its name, and exits:

    /libexec/finit/tmpfiles --cat-config

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:02 +01:00
Joachim Wiberg 09dcf91877 tmpfiles: add the ~ modifier, an argument in Base64
In tmpfiles.d(5) a ~ after the type of an f, F, or w entry means the
argument is Base64, for content that cannot be written on a line:

    f~ /root/.ssh/authorized_keys 0600 root root - c3NoLWVkMjU1MTkg...

tmpfiles ignores the ~ and writes the argument as it is.

Decode the argument.  As in systemd it is not looked at for specifiers
or escapes, and an entry with an argument that is not Base64 is
skipped.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:02 +01:00
Joachim Wiberg ed96814fdc tmpfiles: read quotes and escapes in the fields before the argument
There is no way to write an entry for a path with a space in it, the
fields are split at every space.  In tmpfiles.d(5) a field can be
quoted, and have C-style escapes:

    d "/srv/my files"
    d /srv/my\sfiles

Split the fields with a function that resolves both.  The argument is
still the rest of the line as it is, quotes and all, like in systemd.
An entry with a quote left open is skipped.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:14:01 +01:00
Joachim Wiberg aa38c72044 tmpfiles: do not truncate the file of a w entry
A w entry empties the file before it writes the argument.  With a file
that holds "abcdef":

    w /tmp/file - - - - XY

leaves "XY".  With systemd-tmpfiles the file holds "XYcdef", it writes
over the start of what is there.  For a file in /proc or /sys there is
no difference.

Open the file without O_TRUNC.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:13:53 +01:00
Joachim Wiberg 309844fc11 tmpfiles: only take a # at the start of a line as a comment
An entry with a # in the argument loses it and the rest of the line:

    f /tmp/file - - - - a#b c

gives a file holding "a".  The lines are read with fparseln(), which
by default takes a # anywhere in a line as the start of a comment.  In
tmpfiles.d(5) only a line that starts with # is a comment.

Read the lines without a comment character and skip the lines that
start with one.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:13:53 +01:00
Joachim Wiberg 7ec4376eb0 tmpfiles: take 8 and 9 as hex digits in an \x escape
An f or w entry with \x39 in the argument writes the byte 3 followed
by a 9, where it should write a 9:

    f /tmp/file - - - - \x39

write_hex() only takes the digits 0 to 7, as for an octal escape.
Take all hex digits.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:13:53 +01:00
Joachim Wiberg 64e299bedc sm: remove /run/nologin when leaving runlevel S
On a system with systemd's tmpfiles.d files installed, only root can
log in after boot.  The files have a boot-only entry:

    f+! /run/nologin 0644 - - - "System is booting up. ..."

On systemd the file is removed by systemd-user-sessions when boot is
done.  Finit runs the entry, but only removes /etc/nologin, so
pam_nologin keeps refusing everyone but root.

Remove /run/nologin too when leaving runlevel S.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-21 17:13:52 +01:00
Joachim Wiberg a4a518d970 tmpfiles: stop at a backslash that ends the argument
write_arg() takes the character after a backslash as an escape.  With
the backslash last in the argument that character is the end of the
string, and the loop went on reading past it.

fparseln() takes a backslash at the end of a line as a continuation,
so an argument does not end in one today.  Write the backslash as it
is and stop, should that change.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 19:10:04 +01:00
Joachim Wiberg 81ce7a2833 tmpfiles: skip an entry that takes its argument from a credential
A ^ after the type says the argument is the name of a credential to
read the real argument from.  Files from systemd have them:

    f^ /etc/hosts - - - - network.hosts

The ^ was not read, so on a system without /etc/hosts this made one
holding the text "network.hosts".

Finit has no credentials.  Skip the entry, which is what systemd does
when the credential is not set.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 19:10:04 +01:00
Joachim Wiberg ddb4f18fa9 tmpfiles: add --dry-run, to show what would be run
There was no way to see what the tmpfiles.d files on a system amount
to, short of running them:

    tmpfiles --dry-run --create --remove --boot

With -n or --dry-run each entry that would be run is printed, with
what would be done, remove, clean, or create, in the order it would
be.  Nothing is changed.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 19:10:04 +01:00
Joachim Wiberg a27c0d40f3 tmpfiles: no warning for a d entry on a link to a directory
A d entry for a path that is a link to a directory warned that mode
and owner could not be set:

    d /var/lock 0755

Here /var/lock is a link to /run/lock.  The link is not followed, on
purpose, and the open fails.

That is not an error, leave the directory alone without a warning.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 19:10:03 +01:00
Joachim Wiberg 7ee991daf2 tmpfiles: make a new file 0644 when the f entry has no mode
A file from an f entry without a mode got what the umask left of
0666, so the result depended on who called tmpfiles:

    f /run/app/state

tmpfiles.d(5) has 0644 as the default.  Use that for a file the entry
creates.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 19:10:03 +01:00
Joachim Wiberg af10d09762 tmpfiles: write all of the argument to every match of a w entry
A w entry with a glob wrote its whole argument to the first path
only.  The rest got it up to the first backslash:

    w /sys/class/net/eth*/queues/rx-0/rps_cpus - - - - f\n

write_arg() put a NUL in the argument at each escape as it went, so
the second call saw a shorter string.

Leave the argument as it is.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 19:10:02 +01:00
Joachim Wiberg 3ff5c33217 tmpfiles: add the h and H entries, file attributes
tmpfiles.d(5) has h to set file attributes, as chattr(1) does, and H
for the path and everything below it:

    h /var/log/journal - - - - +C

tmpfiles skipped them as unsupported.

Add both.  The argument is the letters chattr(1) has, after a + to
add them, which is the default, a - to remove them, or a = to have
just these set.  Only files and directories have such attributes,
anything else is left alone.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 19:10:02 +01:00
Joachim Wiberg 1ef0da9c50 tmpfiles: add the t and T entries, extended attributes
tmpfiles.d(5) has t to set extended attributes on a path, and T for
the path and everything below it:

    t /srv/www - - - - user.mime_type=text/html

tmpfiles skipped them as unsupported.

Add both.  The argument is one or more NAME=VALUE with space between,
a value with space in it goes in quotes.  They are set with
lsetxattr(), a link is never followed.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 19:10:02 +01:00
Joachim Wiberg e19e37286a tmpfiles: add the L? entry
tmpfiles.d(5) has L? for a link that is only made when what it points
to exists:

    L? /etc/localtime - - - - ../usr/share/zoneinfo/UTC

The ? was not read, so this made the link whatever was there.

Finit has had this as its own l entry.  Read L? as l.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:35:37 +01:00
Joachim Wiberg 0a2beb9b6d tmpfiles: add --prefix, to only run entries below a path
A package that ships a tmpfiles.d file wants its own paths created
when it is installed, without running every other entry on the
system:

    tmpfiles --create --prefix=/var/lib/app

Add the option, it can be given more than once.  It and
--exclude-prefix compare whole path components now, before
--exclude-prefix=/dev also left out /devices.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:35:36 +01:00
Joachim Wiberg fb3b13a245 tmpfiles: add the specifiers for the OS release and architecture
An entry with %a, or one of the specifiers that come from os-release,
was skipped as unsupported:

    d /var/lib/app/%o-%w 0755 - - -

Add %o, %w, %W, %B, %M, and %A, read from /etc/os-release with
/usr/lib/os-release as fallback, and %a with the names tmpfiles.d(5)
has for the architectures.  A field that os-release lacks gives an
empty string, as in tmpfiles.d(5).  An entry is still skipped when
the architecture is not one of those known.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:35:36 +01:00
Joachim Wiberg bccd04d81d tmpfiles: clean what an e entry with a glob matches
An e entry takes a glob, but cleaning looked for a directory with
the pattern as its name:

    e /var/cache/* - - - 10d

    tmpfiles --clean t.conf

This cleaned nothing.

Expand the glob and clean each directory it matches.  Also use the
age of a C entry, tmpfiles.d(5) has it clean what it copied.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:34 +01:00
Joachim Wiberg 9d49eaf4c7 tmpfiles: read all of the age formats in tmpfiles.d(5)
Only one number with one unit was read from the age of an entry.  An
age like this one was taken as two days:

    d /var/tmp 1777 root root 2d12h

What came after the first unit was not looked at.  ms and us were not
known, so 500ms gave no cleaning at all.

Read any number of values with units, us, ms, s, m or min, h, d, and
w, and refuse an age that cannot be read or that overflows.  Add the ~
prefix, which keeps what is right in the directory, and the prefix
that says which timestamps to go by, e.g. "aAmM:" for access and
modification time of files and directories.

Without that prefix the birth time of a file now counts too, as in
tmpfiles.d(5).  It is read with statx(), where the C library has it,
and left out on a file system that has none.

A prefix that names timestamps for files only, or directories only,
leaves the default set for the other.  The age is capped at what a 32
bit time_t holds, and nothing is cleaned when it reaches back past
the epoch.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:33 +01:00
Joachim Wiberg b87d235cf7 tmpfiles: add the % specifiers for path and argument
An entry with a % in the path was skipped, and files from
distributions have them:

    d /run/log/journal/%m 2755 root systemd-journal - -

Expand the specifiers that do not need the OS release or the
architecture: %b, %m, %H, %l, %v, the directories %t, %T, %V, %S, %C,
%L, %h, and the user ones %u, %U, %g, %G.  tmpfiles runs as root, so
the last ones are fixed.  An entry with any other specifier is still
skipped.

The argument of C, f, F, L, and w entries is expanded too, as in
tmpfiles.d(5).  A literal % in such an argument must from now on be
written %%.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:33 +01:00
Joachim Wiberg 83f4dceb1b tmpfiles: make a directory for v, q, and Q entries
Files from distributions use v, q, and Q for directories that should
be btrfs subvolumes when that is possible:

    v /var/lib/machines 0700 - - -

tmpfiles skipped them as unsupported, so the directory was missing.

On a file system without subvolumes tmpfiles.d(5) has them make a
plain directory.  Do that everywhere, read them as d.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:33 +01:00
Joachim Wiberg 7422a6fac7 doc: ChangeLog entry for the fgetval() crash fix
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:32 +01:00
Joachim Wiberg 4fcc7ba686 plugins: fix leak of unknown 'set' command in modules-load
An unknown 'set foo' line in modules-load.d leaks the string returned
by fgetval().  Free it before skipping the line.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
(cherry picked from commit b5d8c2b16b)
2026-11-20 18:03:32 +01:00
Joachim Wiberg b350ad0d94 helpers: fix fgetval() crash on empty value
getty crashes reading /etc/os-release when a key it looks for has no
value, e.g.:

    VERSION=

initctl crashes the same way reading .initrc, and so does the
modules-load plugin on a bare 'set' or 'set index=', which takes down
PID 1.

The loop skipping separators calls strchr(sep, str[0]), which matches
the NUL terminator at the end of the string.  strsep() then sets str to
NULL and the next iteration dereferences it.  A line with no separator
at all dereferences NULL right away.

Return NULL when there is no separator, and skip separators with
strspn() instead.

Reported-by: Tobias Waldekranz <tobias@waldekranz.com>
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
(cherry picked from commit f8c2927672)
2026-11-20 18:03:32 +01:00
Joachim Wiberg 74da582488 tmpfiles: set the owner before the mode
An entry that sets both setuid or setgid and another owner lost the
bit again:

    f /usr/libexec/helper 4755 app app

The mode was set first, and a change of owner drops setuid and setgid
from a file.  A second run put it back, the owner was right by then.

Change the owner first.  A mode that is not in the entry is put back
the same way.  Also, a mode that ~ masks down to 0 is now set, 0 was
taken for no mode.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:31 +01:00
Joachim Wiberg 777ecd77c8 tmpfiles: allow major or minor 0 in b and c entries
An entry for a device with a 0 in its number was skipped:

    c /dev/tty 0666 root tty - 5:0

parse_mm() took 0 to mean atoi() could not read the number.

Use atonum(), which tells the two apart.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:31 +01:00
Joachim Wiberg adf7080fca tmpfiles: set mode and owner for the entries that ignored them
Several types read the mode and owner of an entry and did nothing
with them.  An f entry was skipped when the file was there:

    f /var/log/app.log 0640 app adm

This left a file with another mode or owner as it was.  The owner of
p, b, and c entries was never set, and their mode was cut by the
umask.  C, z, and Z entries had neither applied.

Set them for all of these, Z for everything below the path.  Fifos
and device nodes are opened with O_PATH, so nothing is opened for
real.  A path that is not what the entry makes, like a directory
where a p entry wants a fifo, is left alone.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:30 +01:00
Joachim Wiberg ec67ecc805 tmpfiles: add the : and ~ prefixes for mode, user, and group
A mode with a prefix was not read as a number, so the entry was taken
to have no mode, and a user with one was looked up with the colon in
the name, which skipped the entry:

    d /var/lib/app :0750 :app :app

With : the mode, user, or group is only set on a path the entry
creates, an existing one keeps what it has.  With ~ the mode loses
read, write, or execute when no one has that on the existing path,
and setuid, setgid, and sticky when it is not a directory.

Mode and owner now go through perm_set() in tmpfiles, which knows the
entry created the path or not.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:37 +01:00
Joachim Wiberg a726aff30b tmpfiles: skip any entry with an unknown user
What an unknown user in an entry did depended on the type.  A d entry
was skipped, but this one made a file owned by root:

    f /run/frr/state 0640 frr frr

The user was looked up in each type on its own, and only d checked
the result.

Look it up once for the entry, and skip the entry when the user is
not known.  An unknown group leaves the group of the path as it is,
for a new path that is the group of root, as before.  Both are only
reported with --debug, Finit's own files have entries for services
that may not be installed.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:36 +01:00
Joachim Wiberg f5e7946489 doc: how to run tmpfiles --clean, from cron
Finit only runs tmpfiles at boot, to create and remove.  The age of an
entry has no effect until something calls tmpfiles --clean, and the
documentation said there was no aging at all.

Describe how to call it from cron, with a service as the fallback on a
system without cron, and what cleaning leaves alone.  Update the
tmpfiles TODO to match.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:36 +01:00
Joachim Wiberg bc2f2ba4bb tmpfiles: age 0 cleans everything
An entry with the age 0 was read as having no age, so nothing in its
directory was ever cleaned:

    d /var/spool/work - - - 0

    tmpfiles --clean t.conf

In tmpfiles.d(5) age 0 means everything in the directory is removed
on each clean.  parse_age() returned 0 for both.

It now returns -1 for no age and for one it cannot read, and with
age 0 the timestamps are not looked at.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:36 +01:00
Joachim Wiberg 60cd11ab23 tmpfiles: keep what x and X entries name from being cleaned
The x and X entries were read and ignored, so a path that a package
had marked to be left alone was cleaned like the rest:

    d /var/tmp      - - - 30d
    x /var/tmp/keep

    tmpfiles --clean t.conf

This removed what was old in /var/tmp/keep.

Gather the x and X entries of all files in a pass before the cleaning,
they may come after the entry they apply to, or in another file.  x
keeps the path and what is in it, X the path alone.  A directory that
is not empty afterwards is no longer warned about.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:36 +01:00
Joachim Wiberg 9392f2082e tmpfiles: stay on one file system when cleaning
Cleaning the directory of an entry with an age went into whatever was
mounted below it:

    d /srv - - - 10d

    tmpfiles --clean t.conf

With a disk mounted on /srv/data this removed every file on it older
than ten days.

Give nftw() FTW_MOUNT, so it stays on the file system of the directory.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:35 +01:00
Joachim Wiberg 3c9500fc08 tmpfiles: run boot-only entries only at boot
A ! after the type marks an entry that is only safe to run at boot.
Finit's own files have them, like this one in x11.conf:

    D! /tmp/.X11-unix 1777 root root

tmpfiles ignored the ! and ran these entries on every call, so this
emptied the directory under a running X server:

    tmpfiles --remove

Only the character right after the type was looked at, and only for
a +.

Read all the modifiers after the type, in any order, and skip an
entry with ! unless the new --boot option is given.  Finit gives it
at boot, together with --remove.  Before this the r, R, and D entries
were never run at boot, so "r! /forcefsck" in legacy.conf left the
file in place.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:35 +01:00
Joachim Wiberg 4a11294f98 tmpfiles: skip an entry that is not supported, do not exit
tmpfiles exited at the first entry with a type it does not know, or
with a % specifier in the path:

    h /tmp/dir - - - - +i
    f /tmp/dir/after

    tmpfiles --create t.conf

This never created /tmp/dir/after.  At boot it meant that one such
line, in any tmpfiles.d file, stopped every entry after it, in that
file and in all the files sorted after it.  The message says skipping,
but errx() exits.

Warn and go on with the next entry.  With two passes, for --create
with --remove, only the second one warns.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:34 +01:00
Joachim Wiberg 9195d145d1 tmpfiles: remove before creating when asked to do both
With both --create and --remove each entry was removed and then
created before the next one was read.  An r entry took what an entry
above it had just created:

    f /tmp/file - - - - new
    r /tmp/file

    tmpfiles --create --remove t.conf

This left no /tmp/file.  The same goes for --clean.

Run all the files twice in that case, first to remove and clean, then
to create.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:34 +01:00
Joachim Wiberg 3a283d40b5 tmpfiles: free the glob result of r, R, w, z, and Z entries
Same leak as for e entries: the path list from glob() was never freed.
With the address sanitizer LeakSanitizer makes tmpfiles exit with an
error:

    tmpfiles --remove r.conf

Free the list in glob_do() and after the loops for w and z/Z.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:34 +01:00
Joachim Wiberg 674cf8a2ed doc: list what tmpfiles lacks compared to tmpfiles.d(5)
Ranked, with what Finit's own tmpfiles.d files and common packages
already rely on first.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:34 +01:00
Joachim Wiberg f8571aba1f tmpfiles: add the a and A entries, POSIX ACLs
The tpm2-tss package sets a default ACL on its keystore:

    d  /var/lib/tpm2-tss/system/keystore 2775 tss tss - -
    a+ /var/lib/tpm2-tss/system/keystore -    -   -   - default:group:tss:rwx

tmpfiles skipped the a+ line as unsupported, so what was created in
the keystore did not get the group access it relies on.

Add a and A, the latter recursive, with and without +.  With + the
entries are added to the ACL of the path, without it they replace it.
The ACL is written to the system.posix_acl_access and _default
extended attributes in the format the kernel uses, which saves a
dependency on libacl.  As with setfacl, the mask is made to cover the
named entries unless the entry sets one.

An ACL can have at most 32 entries.  A path with more is left as it
is, with a warning.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:02:33 +01:00
Joachim Wiberg 3bc7c83731 tmpfiles: skip the space before the argument of an entry
An entry written in aligned columns got the space after the age field
as part of its argument:

    L  /tmp/null  -  -  -  -    /dev/null

This made a link to "   /dev/null".  Only the first separator after
the age was dropped.  A lone "-" for no argument was also taken as is,
so an f entry with it made a file holding a dash.

Skip all the space before the argument, and read "-" as no argument.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 12:00:50 +01:00
Joachim Wiberg f95db7e6df tmpfiles: keep the owner of an existing path when none is given
An entry without a user or group, or with "-", made root the owner of
an existing directory or file:

    mkdir -p /tmp/t && chown daemon:daemon /tmp/t
    echo 'd /tmp/t' > t.conf
    tmpfiles --create t.conf
    stat -c %U:%G /tmp/t

This gave root:root.  A missing field was read as "root" when parsing
the entry, the same as if it had been written out.  tmpfiles.d(5)
only adjusts the owner when the entry gives one.

A missing user or group is now -1, and fdperm() looks at the two ids
separately, so "d /tmp/t - - sys" changes the group and keeps the
owner.  mksubsys() and the service directories used uid -1 to skip
the chown altogether, they now pass -1 for the group as well.

Issue #523

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 11:23:36 +01:00
Joachim Wiberg 94bdccd200 tmpfiles: keep the mode of an existing directory when none is given
A d entry without a mode reset an existing directory to 0755.  On
finix a bare "d /tmp" line took the sticky bit and the write
permission for others off the /tmp mount, so nobody but root could
create files there:

    mkdir -p /tmp/t && chmod 1777 /tmp/t
    echo 'd /tmp/t' > t.conf
    tmpfiles --create t.conf
    stat -c %a /tmp/t

This gave 755.  Commit 9bfbdc6b made the chmod of an existing
directory work, and it used the 0755 default for a new directory as
the mode to set.

The default is now only for creating the directory.  With no mode in
the entry, dirperm() leaves the mode alone.

Fixes #523

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 11:03:15 +01:00
Joachim Wiberg 73ebc7fb36 tmpfiles: free the glob result of an e entry
An e entry leaked the path list from glob().  tmpfiles exits right
after, so it only shows in a build with the address sanitizer, where
LeakSanitizer makes tmpfiles exit with an error:

    tmpfiles --create e.conf

Free the list when the entry is done.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 11:03:05 +01:00
Joachim Wiberg c94fd9c495 initctl: add the settings of a service to the JSON status
initctl -j status had the state of a service but little of how it is
set up.  A program reading it could not tell how the service is
stopped, what scripts it runs, or how it signals readiness.

Add the settings: stop, reload, notify, remain, scripts, directories,
cgroup-config, rlimits, log or tty, provides, conflicts, if, groups,
capabilities, pam, name, id, protected, and nowarn.  The restart
object also gets sec, respawn, and oncrash, and the state Finit keeps
for its own use goes in internal:

    "stop": {
      "signal": "SIGTERM",
      "timeout": 3,
      "scope": "pgroup"
    },
    "scripts": {
      "exec-stop-post": { "command": "/bin/true", "timeout": 7 }
    },

initctl reads the status over D-Bus first, so each setting is also a
property of org.finit.Service1.  The new test checks that the JSON is
the same over D-Bus as over the initctl socket.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 21:51:23 +01:00
Joachim Wiberg 9fa50746a7 initctl: add what was missing from the JSON status
initctl -j status is for other programs and should have all there is,
the plain view is the one kept short.  It was the other way around:
the restart counter and restart-max were only in the plain view, and
the restart delay of restart-max-sec was not in the JSON either.

Add a restart object:

    "restarts": 7,
    "restart": {
      "count": 4,
      "max": -1,
      "delay": 160,
      "limit": 300
    },

Also add manual and started, and give starts for all services, not
only those with manual-start.  The restarts total stays where it is.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:43 +01:00
Joachim Wiberg 308287923d initctl: show the restart delay of a service with restart-max-sec
With restart-max-sec the delay before the next restart varies, and
nothing showed what it was or how far it could grow.

Show both in initctl status, for a service that has the setting:

       Restarts : 7 (4/-1)
     Restart in : 160 sec (max 300)

Add the D-Bus properties RestartDelay and RestartDelayMax for it, so
the status is the same when initctl goes over D-Bus.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:43 +01:00
Joachim Wiberg 7f652770e3 test: list what to install to run the test suite
A new machine lacks more than the build dependencies.  Without the
uidmap package every test fails:

    unshare: failed to execute newuidmap: No such file or directory

List the packages for Debian, Ubuntu, and Linux Mint, and what each is
used for.  The build instructions asked for libite and libuEv v2.2.0,
configure wants v2.6.1 and v2.4.1.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:42 +01:00
Joachim Wiberg aae640b8f3 service: spell the restart_sec: option restart-sec:
restart_sec: was the only setting in snake_case.  Every other option
of the line-based format is in kebab-case, and so is the block format,
restart-sec = SEC.

Take restart-sec: and keep restart_sec: as an alias, so a .conf from
an older Finit loads as before:

    service restart-sec:10 foo -- Foo daemon

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:42 +01:00
Joachim Wiberg 62bd5f4892 service: add restart-max-sec, a limit for the restart back-off
The delay between restarts of a crashing service is fixed: two
seconds, then five, or restart-sec if that is longer.  A service that
should be retried quickly at first and then less and less often, e.g.
a modem dialer, cannot be set up.

Add restart-max-sec, in the block format and as the restart-max-sec:
token:

    service dialer {
        restart         = "always"
        restart-sec     = 10
        restart-max-sec = 300
        command         = "dialer"
    }

When set, the delay doubles for each restart, from restart-sec up to
the limit: 10, 20, 40, 80, 160, 300.  Without restart-sec the first
restart is at once, then after 2, 4, 8 seconds.  The delay follows the
restart counter, so it comes down again as the counter ages.  With
restart always the counter stops where the delay peaks.

Fixes #306

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:42 +01:00
Joachim Wiberg bba286036e service: save the configured restart delay when registering
The configured restart delay was saved at the first restart, when the
restart counter went from zero to one, and restored when a restart
succeeded.  The counter ages back to zero while the service runs.  If
it did so right after a restart and the service crashed again, the
back-off delay was saved over the configured one.  From then on the
first restart after a crash waited two or five seconds, until the next
reload.

Save it once, when the service is registered.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:41 +01:00
Joachim Wiberg 644279cd72 service: stop the restart counter of restart always from overflowing
The restart counter is a char, and with restart always nothing stops
it.  A service restarted more often than the counter ages wrapped it
after 127 restarts, 255 on Arm.  initctl status then showed a negative
count and the back-off fell back to two seconds.

Make the counter an int that stops at INT_MAX.  With restart always it
stops at 10, the default restart-max.  The back-off peaks at half of
that, and from 10 the counter ages back within the hour.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:41 +01:00
Joachim Wiberg 4e1b0d4fbe service: start restart always at two seconds between restarts
A crashing service with restart always waited five seconds before
every restart.  It should wait two seconds for the first five, like a
service with the default restart-max:

    service foo {
        restart = "always"
        command = "foo"
    }

The back-off starts after half of restart-max attempts.  For restart
always restart-max is -1, so half of it was zero and the back-off
began with the first restart.  Use the default restart-max instead.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:40 +01:00
Joachim Wiberg 631baab756 api: acknowledge reboot, halt, and poweroff
Finit carried out a reboot, halt, or poweroff requested over the
initctl socket, but replied with a NACK.  The command printed an
empty line and fell back to signalling PID 1.

The result was never set from the action taken.  Return what
shutdown_now() returns.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 11:00:49 +01:00
Joachim Wiberg 20c422af69 shutdown: add time argument, wall message, and cancel
shutdown ignored everything after its options, so a delayed shutdown
went down right away:

    shutdown -r +10 "Upgrading, back in five"

Take a time, now, +MIN, or the next HH:MM, and an optional message.
Finit keeps the countdown, so it survives logging out:

  - warns logged-in users at 60, 30, 15 and 10 minutes left, then
    every minute from five, and on the console
  - writes the message to /etc/nologin from five minutes before,
    leaving one already in place alone
  - shutdown -c cancels, and a new shutdown TIME replaces it

Without a time, or with now and no message, shutdown acts right away
as before.  An immediate reboot, halt, or power-off, also over D-Bus,
cancels a scheduled one.  The warnings are written by a child, reading
utmp and closing a serial tty can block.

Fixes #149

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 11:00:49 +01:00
Joachim Wiberg d51f521bf8 service: add stop-scope, which processes a stop applies to
When the main process of a service exits, Finit sends SIGKILL to its
process group.  That killed the action script of avahi-autoipd, which
it runs on SIGTERM to deconfigure the interface, before it was done.

Add stop-scope, in the block format and as the stop-scope: token:

    service avahi-autoipd {
        stop-scope = "process"
        command    = "avahi-autoipd eth0"
    }

  - pgroup: the stop signal to the main process, SIGKILL to its
    process group when it exits, as before and the default
  - process: only the main process
  - cgroup: the stop signal to all of the cgroup, SIGKILL to the rest
  - mixed: the stop signal to the main process, SIGKILL to the rest of
    the cgroup, like systemd's KillMode=mixed

SIGKILL to a cgroup uses cgroup.kill when the kernel has it.  Without
a cgroup, cgroup and mixed fall back to the process group.  Services
in the same .conf file share a cgroup, Finit warns when one of them
uses a cgroup scope.

Fixes #413

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 11:00:48 +01:00
Joachim Wiberg 35c313c2fa service: keep a stop of a forking service waiting for its PID file
Stopping a forking service after its start script had exited, but
before the daemon had written its PID file, did not hold.  When the
PID file showed up, the service was reported running again and the
daemon was left alone:

    initctl stop ext

service_forked() cleared any block on the service, the user's stop
included.

Keep a user stop, and let the state machine stop the late daemon of
a service no longer enabled.  The service is briefly RUNNING on its
way to STOPPING, so service/NAME/running blinks on and off.

Follow-up to #452

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 07:49:50 +01:00
Joachim Wiberg a1706e8ebd pidfile: don't let a stopped service claim a PID file
A stopped service with a daemon-owned PID file came back as running
when another process wrote that file, e.g., a container started by
hand:

    sudo podman start dash

turned container:dash from stopped to running in initctl, with the
podman PID adopted, moved to the service's cgroup, and its conditions
set.  The same happened to a service waiting for its conditions.

The plugin acted on any new or changed PID file, only skipping
services stopping or running scripts, and service_forked() then
cleared the stop.

Only let a service that is starting or running claim its PID file.

Fixes #452

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:44:45 +01:00
Joachim Wiberg a162551896 service: bind the systemd notify socket before fork
A notify:systemd service that calls sd_notify() early could lose its
READY=1 and never become ready.  Seen with udevd in an initramfs.

The socket address contained the PID of the service, so it was bound
in the parent after fork(), racing the service.

Let the kernel pick a unique abstract address instead, bound before
fork(), and pass it in NOTIFY_SOCKET.

Fixes #505

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:21:26 +01:00
Joachim Wiberg 14fd315f38 keventd: touch the PID file after SIGHUP
After a SIGHUP, from initctl reload or a changed service, Finit waits
for a pid-notify daemon to recreate or touch its PID file to reassert
readiness.  keventd only reloaded its rules, so with a daemon-owned
PID file it never did.

Touch it with pidfile() after reloading the rules, once keventd has
created it.  With -c that is after the coldplug queue has drained.

Fixes #503

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:21:26 +01:00
Joachim Wiberg bf42811a13 service: drop a service's group when the configuration drops it
Changing a service from @alice:wheel to @alice, or removing group from
a block, and reloading kept the service running as group wheel, also
after a restart.

The group is only set when the configuration has one, and on reload
the service is updated in place, so the old one stayed.

Clear it before parsing, like a new service gets it.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:21:25 +01:00
Joachim Wiberg de73b06415 service: lift the limit of four supplementary groups
A service listing more than four supplementary groups, in extra-groups
or as @user:group,sup1,sup2,..., got only the first four:

    too many supplementary groups, max 4

The names were stored in a fixed array of four.  It was also only
reset when the new configuration listed groups, so groups dropped from
a service lingered until reboot.

Store the list as one string, split when the service starts, and set
it on every (re)registration.  A list longer than 511 characters drops
the name it cuts off, which may otherwise match another group.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:21:24 +01:00
Joachim Wiberg 8451c4087a Merge pull request #522 from firasuke/master
doc: list libcap as a dependency
2026-11-14 12:14:04 +01:00
Firas Khana e280569941 doc: list libcap as a dependency 2026-11-14 13:44:58 +03:00
Joachim Wiberg f15e95d1cc service: don't take a command named like an option for one
A run/task/service whose command starts like an option without a ':'
lost its command, e.g. the example in finit.conf(5):

    run [2345] @joe:users logger "Hello world"

was registered as the log option, running "Hello world".  Same for
pidof, pidproxy, cgroupfs-mount, and in block format too.

The option parser matches with MATCH_CMD(), a prefix match, also for
the options with no trailing ':' to end the prefix: log, pid, cgroup,
respawn, nowarn, and the rest.

Match these against the whole token, allowing only the separator that
starts a value: "log:", "pid:", "cgroup." and "cgroup:".

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-13 16:00:25 +01:00
Joachim Wiberg 34a0a4b1ff conf: pass -- in a block command to the program
A command that takes -- as an argument lost it, and everything after
it, to the description:

    service name {
        command     = "cmd -- arg"
        description = "a cmd"
    }

ran `cmd` with description `arg`.

The block translator builds a legacy one-liner, appending the
description as "-- text", and service_register() splits that line at
the first "-- ", here the one in the command.

Split the description off only for legacy one-liners.  Blocks now hand
it to the new service_register_desc() as an argument.

Fixes #512

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-13 15:56:30 +01:00
Paweł c03059a9a0 keventd: don't publish whole-disk by-id links for partitions
disk_serial_id() falls back to <disk>/../serial so a partition got a
by-id link named after its parent disk's serial, clobbering the link
created for the whole disk.

(cherry picked from commit 4b2f8c89c5)
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-13 15:06:08 +01:00
Joachim Wiberg 297d2de1da Merge pull request #511 from zhangxiaohui1/fix/remain-task-control
service: preserve explicit stop for remain tasks
2026-11-12 21:06:47 +01:00
Joachim Wiberg 3acf1cb7b1 Merge pull request #517 from vazub/hwdb-parse-fix
keventd: fix hwdb lookups that never match
2026-11-12 19:25:38 +01:00
Joachim Wiberg eb9fb83011 Merge pull request #516 from vazub/symlink-fix
keventd: fix dangling and misnamed /dev/input/by-id links
2026-11-12 19:24:02 +01:00
Joachim Wiberg b6f0d5314b Merge pull request #521 from firasuke/firasuke-patch-1
Add conditional include for sm.h based on AUTO_RELOAD
2026-11-12 19:22:53 +01:00
Firas Khana 90512b07a0 Add conditional include for sm.h based on AUTO_RELOAD 2026-11-06 23:09:13 +03:00
Firas Khana d313b1fd74 Add conditional include for sm.h based on AUTO_RELOAD 2026-11-06 23:04:57 +03:00
Basil Zubko 439cab0558 keventd: fix hwdb parsing issues 2026-10-31 20:42:07 +01:00
Basil Zubko 98b2effb52 keventd: fix dev symlinks 2026-10-30 12:30:40 +01:00
zhangxiaohui 3a18ca4a30 service: preserve explicit stop for remain tasks
A completed remain task unconditionally cleared its user stop block
after running its post script.  Since it was still valid in the current
runlevel, it immediately started again, making initctl stop ineffective.

Keep explicit stops blocked, distinguish automatic and requested
restarts, and route initctl restart through teardown before rerunning the
task.  Cover stop, start, restart, reload, and runlevel transitions with
a regression test.

Signed-off-by: zhangxiaohui <xiaohui.zhang@wbstar.com>
2026-10-21 19:03:46 +08:00
69 changed files with 6216 additions and 554 deletions

No files matched your search

+1 -1
View File
@@ -40,7 +40,7 @@ AC_PROG_MKDIR_P
# Configuration.
AC_CHECK_HEADERS([termios.h sys/ioctl.h mntent.h sys/sysmacros.h])
AC_CHECK_FUNCS([strstr getopt getmntent getmntent_r close_range])
AC_CHECK_FUNCS([strstr getopt getmntent getmntent_r close_range statx])
# Check for uint[8,16,32]_t
AC_TYPE_UINT8_T
+217 -2
View File
@@ -8,6 +8,111 @@ All relevant changes are documented in this file.
### Changes
- `shutdown` now takes a time, `now`, `+MIN`, or `HH:MM`, and a message.
Finit warns logged-in users as the time approaches, refuses new logins
from five minutes before, and `shutdown -c` cancels. Issue #149
- tmpfiles: entries marked boot-only, with a `!` after the type, are now
skipped unless the new `--boot` option is given. Finit gives it at
boot, and now also `--remove`, so `r`, `R`, and `D` entries take effect
at boot and no longer need a separate call
- tmpfiles: add the `%` specifiers of tmpfiles.d(5) for the path, and for
the argument of `C`, `f`, `F`, `L`, and `w` entries: `%b`, `%m`, `%H`,
`%l`, `%v`, `%a`, the directories `%t`, `%T`, `%V`, `%S`, `%C`, `%L`,
`%h`, the user ones `%u`, `%U`, `%g`, `%G`, and from os-release `%o`,
`%w`, `%W`, `%B`, `%M`, and `%A`. Before, an entry with a `%`
in the path was skipped. **Note:** a literal `%` in such an argument,
e.g. in a `w` entry for `core_pattern`, must now be written `%%`
- tmpfiles: add `-n`, `--dry-run`, to show the entries that would be run,
in the order they would be, without doing anything
- tmpfiles: add the `t` and `T` entries, to set extended attributes on
a path, `T` also on everything below it
- tmpfiles: add the `h` and `H` entries, to set file attributes as with
chattr(1), `H` also on everything below the path
- tmpfiles: add the `L?` entry, a link that is only made when what it
points to exists, the same as Finit's own `l` entry
- tmpfiles: the path of an entry can now be quoted and have backslash
escapes, for a path with a space in it: `d "/srv/my files"`
- tmpfiles: add the `~` modifier for `f`, `F`, and `w` entries, as in
`f~`, where the argument is Base64, for a file with binary content
- tmpfiles: add `--cat-config`, to show the files that would be read,
each below a line with its name
- tmpfiles: add `--graceful`, for scripts that give it. It changes
nothing, an unknown user or group is never an error in Finit
- tmpfiles: the `%T` and `%V` specifiers now follow `$TMPDIR`, `$TEMP`,
or `$TMP`, when set to a directory
- tmpfiles: an `x` or `X` entry with an age now has what it keeps cleaned
by that age, as in `x /tmp/build 30d` below a `/tmp` cleaned after ten
days. Before the age was not read
- tmpfiles: add the `C+` entry, which also copies to a directory that has
something in it. What is missing is added, nothing is overwritten
- tmpfiles: add the `=` modifier, as in `d=`, to first remove what is in
place of the path when it is of another kind than the entry makes, also
what is in place of a directory above it
- tmpfiles: every entry is now read before the first one is run. As in
tmpfiles.d(5), a path is created after the paths above it, and removed
after those below it, wherever in the files the entries are. Entries
that take a glob, like `w` and `z`, are run after the others
- tmpfiles: the files are now read in the order of their names, whatever
directory they are in, and the first entry that makes a path is the one
that counts, as in tmpfiles.d(5). Before, they were read one directory
at a time and every entry for a path was run, so the last one won. To
change an entry from a file in `/usr/lib/tmpfiles.d`, use a file of the
same name in `/etc/tmpfiles.d`, or one with a name that sorts before it.
`tmpfiles --dry-run` tells which entries are skipped
- tmpfiles: a file named `-` on the command line is read from standard
input
- tmpfiles: add `--replace=PATH`, to read all files with the ones on the
command line in place of the file `PATH`, as in systemd-tmpfiles. For
a package script that runs before the package's own file is installed
- tmpfiles: add `--purge` and the `$` modifier, as in systemd-tmpfiles.
`tmpfiles --purge FILE` removes what the entries of `FILE` that are
marked with a `$`, as in `d$`, make. For when a package is removed
- tmpfiles: add `--root=DIR`, to run on the system below `DIR`: its
tmpfiles.d files, its `/etc/passwd` and `/etc/group`, and its paths.
For a root file system that is being put together. Finit's tmpfiles
does this with chroot(2), so unlike systemd-tmpfiles it must be run
as root
- tmpfiles: add `--prefix=PATH`, to only run the entries for paths below
it. `--prefix` and `--exclude-prefix` match whole path components,
`--exclude-prefix=/dev` no longer skips `/devices`
- tmpfiles: the age of an entry can now have several units, as in
`1d12h`, also `ms`, `us`, and `min`. New are the `~` prefix, to keep
what is right in the directory, and a choice of the timestamps to go
by, as in `aAmM:10d`. The birth time of a file now counts too, like
its other timestamps, when the file system has one
- tmpfiles: the `v`, `q`, and `Q` entries now make a plain directory, like
`d`. Finit has no support for btrfs subvolumes, and before the entries
were skipped as unsupported
- tmpfiles: add the `:` prefix for mode, user, and group, to set them only
on a path the entry creates, and the `~` prefix for the mode, to drop
read, write, or execute where the existing path has it for no one
- tmpfiles: the `x` and `X` entries now keep paths from being cleaned by
`tmpfiles --clean`, before they were read and ignored
- tmpfiles: add the `a`, `a+`, `A`, and `A+` entries for POSIX ACLs, used
by for example the tpm2-tss package. Finit sets them itself, no need
for libacl or `setfacl`
- The `restart_sec:` option of the line-based format is now spelled
`restart-sec:`, kebab-case like every other setting. The old spelling
is still accepted
- `initctl -j status` now has all `initctl` gets from Finit about a
service. New is a `restart` object with the restart counter,
`restart-max`, the current restart delay and its limit, and `manual`
and `started`. `starts` is now there for all services, not only those
with `manual-start`. Also new are the settings of the service: `stop`,
`reload`, `notify`, `remain`, `scripts`, `directories`, `log` or `tty`,
`cgroup-config`, `rlimits`, `provides`, `conflicts`, `if`, `groups`,
`capabilities`, `pam`, `name`, `id`, `protected`, `nowarn`, and the
state Finit keeps for its own use in `internal`, see
[Commands & Status](initctl.md), with a D-Bus property for each
- Add `restart-max-sec`, a limit for the delay between restarts of a
crashing service. When set, the delay doubles for each restart, from
`restart-sec` up to the limit, and comes down again as the service keeps
running. `initctl status` shows the current delay and the limit, also
available as the D-Bus properties `RestartDelay` and `RestartDelayMax`.
Issue #306
- Add `stop-scope`, which processes a stop applies to: `pgroup`, the process
group of the main process (default), `process`, only the main process,
`cgroup`, the cgroup of the service, or `mixed` like systemd. Issue #413
- keventd is now a full device manager, promoted from the power supply
monitor it was in v4, and the device management defaults have swapped:
keventd is enabled by default (`--without-keventd` opts out, libblkid is
@@ -143,6 +248,13 @@ All relevant changes are documented in this file.
- Service `user:` and `group:` names, including supplementary groups, can
now be up to 63 characters, up from 15. Longer names were silently
truncated before the lookup, so the service never started. By Anees Rehman
- A service can have more than four supplementary groups, `extra-groups` or
`@user:group,sup1,sup2,...`. The list may now be up to 511 characters.
Groups dropped from a service's configuration are now also dropped the
next time it starts, before they lingered until reboot
- Fix a service's group lingering after it was dropped from the
configuration, e.g. `@alice:wheel` changed to `@alice` kept running as
`wheel` until reboot
- `stop:` and `reload:` scripts take a timeout of their own, `stop:5,/path`,
defaulting to the kill delay as before. Such a line used to crash Finit at
config load
@@ -153,6 +265,36 @@ All relevant changes are documented in this file.
### Fixes
- Fix #512: `--` in the `command` of a block-format .conf, it was taken as the
start of the description, so `command = "cmd -- arg"` ran `cmd` with
description `arg`. Found by Alexandru Paniș
- Fix #503: keventd did not touch its PID file after SIGHUP, so with a
daemon-owned PID file Finit never saw it reassert readiness after a
reload. Reported by Aaron Andersen
- Fix #505: a `notify:systemd` service could send `READY=1` before Finit
had bound the notify socket, losing it, so the service never became
ready. Seen with udevd in an initramfs. Reported by Aaron Andersen
- Fix #452: a stopped or waiting service with a daemon-owned PID file was
reported as running, with its conditions set, when another process wrote
that PID file, e.g., a container started by hand with podman. Found by
Mattias Walström
- Fix `initctl stop` of a forking service before it had written its PID
file. The PID file showing up later undid the stop and the service was
reported running. Now the late daemon is stopped instead
- Fix `reboot`, `halt`, and `poweroff` being refused by Finit over the
initctl socket, although carried out. The commands then also fell
back to signalling PID 1
- Fix a command whose name starts like a service option, e.g. `logger` or
`pidof`. It was taken as the `log` or `pid` option and the next argument
ran as the command, which also broke the `logger` example in finit.conf(5)
- Fix the delay before the first restart of a crashing service, it could
grow to the back-off delay and stay there until the next reload
- Fix the restart counter of a service with `restart = "always"`, nothing
stopped it and it overflowed after 127 restarts, 255 on Arm. It now
stops at 10, where the back-off has long since peaked, and ages from
there
- Fix `restart = "always"` skipping the initial two second delay between
restarts, every restart waited five seconds
- Reject a .conf file that declares the same block title twice. The title is
the service identity and libConfuse merges two sections sharing one, so the
file loaded as a single service holding a mix of both declarations,
@@ -171,17 +313,90 @@ All relevant changes are documented in this file.
- Fix misspelled `SIGUNKOWN` returned by `sig_name()` for unknown signal
numbers, now spelled correctly as `SIGUNKNOWN`. Surfaced by the new restart
log above
- Fix mode of existing `d`/`D` directories in tmpfiles, the chmod branch
never ran because the directory creation swallowed `EEXIST`. Mode and owner
- Fix mode of existing `d`/`D` directories in tmpfiles when the entry gives
one, the chmod branch never ran because the directory creation swallowed
`EEXIST`. Mode and owner
of `d`/`D`, `e`, and `f`/`F` entries, and of the service directories
`mksubsysd()` creates, are now set through an open fd and only when they
differ, so an immutable directory like `/var/empty` no longer warns on every
boot. By Sam Brkopac
- Fix owner of existing directories and files in tmpfiles, an entry with no
user or group, or `-`, reset them to `root`. As in tmpfiles.d(5), the
owner and the group are now each left alone unless the entry gives them
- Fix the argument of a tmpfiles entry written in aligned columns, the space
after the age field ended up in the argument, e.g. in the target of an `L`
link. A lone `-` is now read as no argument
- Fix `tmpfiles --create --remove`, each entry was removed and created in
turn, so an `r` entry removed what an entry above it had just created.
All of the removing is now done first
- Fix tmpfiles giving up at the first entry it does not support, an unknown
type or a `%` specifier in the path. No entry after it was run, in that
file or in the files after it. Such an entry is now skipped with a warning
- Fix `tmpfiles --clean` cleaning other file systems mounted below the
directory of an entry, it now stays on the file system of the directory
- Fix tmpfiles entries with an unknown user: `d` skipped the entry, but `f`
created the file owned by root and `e` set the group anyway. All of them
now skip the entry. An unknown group still only leaves the group as it is
- Fix mode and owner of tmpfiles entries that ignored them: an `f` entry for
a file that exists, the owner of `p`, `b`, and `c` entries, and both for
`C`, `z`, and `Z` entries
- Fix tmpfiles `b` and `c` entries for a device with major or minor 0,
like `5:0` for `/dev/tty`, they were skipped as invalid
- Fix `tmpfiles --clean` for an `e` entry with a glob in the path, like
`e /var/cache/* - - - 10d`, nothing was cleaned. The age of a `C`
entry is now used as well
- Fix tmpfiles entries with a `^` after the type, as in `f^`, where the
argument names a credential. The name was written to the file, with
files from systemd that gave an `/etc/hosts` holding `network.hosts`
when there was none. Finit has no credentials, such an entry is now
skipped, as systemd does when the credential is not set
- Fix mode of a new file from a tmpfiles `f` entry without a mode, it is
now 0644 as in tmpfiles.d(5), before it followed the umask
- Fix tmpfiles `w` entries with a glob that matches several paths, all
but the first got the argument only up to its first backslash escape
- Fix age `0` in a tmpfiles entry, it was read as no age. As in
tmpfiles.d(5), `tmpfiles --clean` now empties the directory of such an
entry
- Fix `\x` escapes with the digits 8 or 9 in the argument of a tmpfiles
entry, `\x39` was written as the byte 3 and a `9`
- Fix a `#` in the argument of a tmpfiles entry, it and the rest of the
line were dropped as a comment. As in tmpfiles.d(5), only a line that
starts with `#` is a comment. **Note:** a comment at the end of an
entry is now read as its argument
- Fix tmpfiles `w` entries for a regular file, the file was truncated.
As in tmpfiles.d(5), the argument is now written over the start of what
the file holds
- Fix tmpfiles `C` entries. A directory was not copied to a path that
did not exist, or to an empty directory, and was copied over a
directory that had files in it, at every boot, as with the `/etc/pam.d`
entry in Finit's own `etc.conf`. A file was copied over an existing
one. As in tmpfiles.d(5), nothing that exists is now overwritten, and
links are copied as links
- Fix tmpfiles entries with a relative path, they were run on whatever
directory `tmpfiles` was started in. As in tmpfiles.d(5), such an
entry is now skipped with a warning
- Fix tmpfiles `C` entries with a relative path to copy from, it was
taken from whatever directory `tmpfiles` was started in. As in
tmpfiles.d(5), such an entry is now skipped with a warning
- Fix logins refused after boot on a system with systemd's tmpfiles.d
files installed. They create `/run/nologin` at boot, and on systemd it
is removed by systemd-user-sessions. Finit now removes it when leaving
runlevel S, like it already does with `/etc/nologin`
- Fix logins allowed in single user mode when booting straight into
runlevel 1, and while going from runlevel 1 to halt or reboot. The
`/etc/nologin` file was created for the new runlevel and then removed
again for the one being left
- Fix a lost reload for a service paused mid-reload by a condition in
flux. A second reload arriving meanwhile re-parsed the unchanged .conf
and cleared the pending mark, so the service resumed without ever being
reloaded. Seen on Infix, where sshd kept its old listen addresses after
a change that landed as two reloads in a row
- Fix crash on a line with a key but no value, or no separator at all.
A `VERSION=` line in `/etc/os-release` crashed getty, the same in
`.initrc` crashed `initctl`, and a bare `set` or `set index=` line in
a `modules-load.d` file crashed the `modules-load` plugin, taking down
PID 1. An unknown `set` line there also leaked memory. Found by
Tobias Waldekranz
[4.17][] - 2026-04-28
---------------------
+7
View File
@@ -34,6 +34,13 @@ Some of these are also registered in the issue tracker on GitHub.
that functionality is not yet released.
tmpfiles
--------
What is missing compared to tmpfiles.d(5) is listed, ranked, in
[tmpfiles-todo.md](tmpfiles-todo.md).
Initctl
-------
+12 -2
View File
@@ -15,6 +15,10 @@ and `/dev/disk/by-label/` symlinks after. keventd is enabled by
default, so this is a hard requirement unless you build with
`--without-keventd`.
Linux capabilities support for services is also built by default. It needs
[libcap][] (-lcap); the build falls back to no capabilities support when that
library is missing, or with `--disable-libcap`.
PAM session support for services is built by default. It needs
[Linux-PAM][] (-lpam); the build falls back to no PAM support when that
library is missing. A static build, `--enable-static`, disables PAM
@@ -33,10 +37,11 @@ too, since libpam loads its modules with `dlopen()`.
The configure script checks for all dependencies, including the correct
version of the above mentioned libraries. Currently required versions:
- libite v2.2.0, or later
- libuEv v2.2.0, or later
- libite v2.6.1, or later
- libuEv v2.4.1, or later
- libConfuse v3.3, or later
- libblkid, any version, when keventd is enabled
- libcap, any version, unless `--disable-libcap` is given
Configure
@@ -59,6 +64,10 @@ Below are a few of the main switches to configure:
built-ins (.o files) and all external libraries, except the C library
will be linked statically.
* `--disable-libcap`: Opt out of Finit's built-in Linux capabilities support,
enabled by default. Needs libcap, and falls back to disabled when it is
missing. See [Linux Capabilities](config/capabilities.md)
* `--disable-pam`: Opt out of Finit's built-in PAM session support,
enabled by default, which lets a service declare `pam = "name"` and
run inside a session set up from `/etc/pam.d/name`. Needs libpam,
@@ -298,4 +307,5 @@ it only for debugging start up issues when Finit crashes.
[libite]: https://github.com/troglobit/libite
[libConfuse]: https://github.com/libconfuse/libconfuse
[util-linux]: https://github.com/util-linux/util-linux
[libcap]: https://sites.google.com/site/fullycapable/
[Linux-PAM]: https://github.com/linux-pam/linux-pam
+22
View File
@@ -11,3 +11,25 @@ For compatibility reasons Finit listens to the same set of signals as
BusyBox init. This is not 100% compatible with SysV init, but clearly
the more common combination for Finit. For more details, see the
[Signal](signals.md) section.
Scheduled Shutdown
------------------
The `shutdown` command takes a time, and an optional message to warn
logged-in users with:
shutdown -r +10 "Upgrading to v5.0, back in five"
shutdown -h 23:30
shutdown -c
The time is `now`, `+MIN` minutes from now, at most a year, or the next
`HH:MM`. Finit keeps track of it, so it survives logging out. It counts
down the time left, changing the system clock does not move it. At 60, 30, 15 and 10
minutes left, and then every minute from five, Finit writes the warning
to the terminal of every logged-in user. From five minutes before, it
also creates `/etc/nologin`, with the message, to refuse new logins. A
`/etc/nologin` already in place is left alone.
A new `shutdown TIME` replaces the scheduled one, and `shutdown -c`
cancels it. Without a time, or with `now` and no message, `shutdown`
acts right away, as before.
+3 -2
View File
@@ -169,8 +169,9 @@ ps -o user,pid,cmd -p $(pidof nginx)
- Linux kernel 4.3+ (for ambient capabilities support)
- libcap library installed
- Finit built with `--enable-libcap`, otherwise a `capabilities` list is
ignored, with a warning
- Finit built with libcap support (enabled by default unless `--disable-libcap`
is given or libcap was missing at build time), otherwise a `capabilities` list
is ignored, with a warning
## Limitations
+5 -2
View File
@@ -63,12 +63,14 @@ Service options
| `manual:yes` | `manual-start = true` |
| `remain:yes` | `remain-after-exit = true` |
| `restart:always` / `restart:NUM` | `restart = "always"` / `restart-max = NUM` |
| `restart_sec:SEC` | `restart-sec = SEC` |
| `restart-sec:SEC` | `restart-sec = SEC` |
| `restart-max-sec:SEC` | `restart-max-sec = SEC` |
| `norestart` | `restart = "never"` |
| `respawn` | `respawn = true` |
| `oncrash:reboot` | `oncrash = "reboot"` |
| `halt:SIG` | `stop-signal = "SIG"` |
| `kill:SEC` | `stop-timeout = SEC` |
| `stop-scope:SCOPE` | `stop-scope = "SCOPE"` |
| `pre:[TMO,]/script` | `exec-start-pre`, `exec-start-pre-timeout` |
| `ready:[TMO,]/script` | `exec-start-ready`, and its `-timeout` |
| `stop:[TMO,]/script` | `exec-stop`, and its `-timeout` |
@@ -80,7 +82,8 @@ Service options
| `if:svc` / `if:<cond>` | `if = "svc"` / `if = "cond"`, no angle brackets |
| `tty:/dev/x` | `tty = "/dev/x"` |
| `nowarn` | leading `-` on `command` or `envfile` |
| `restarttmo:` | dropped, was already an alias for `restart_sec:` |
| `restart_sec:` | old spelling of `restart-sec:`, still accepted |
| `restarttmo:` | dropped, was already an alias for `restart-sec:` |
Repeated stanzas
----------------
+44 -2
View File
@@ -176,8 +176,20 @@ following settings are available:
* `restart-sec = SEC` -- number of seconds before Finit tries to
restart a crashing service. The default is 2 seconds for the first
half of `restart-max` attempts, then a back-off to 5 seconds -- with
the default `restart-max` that is the first five retries. The
greater of this configured value and the back-off is used
the default `restart-max`, and with `restart = "always"`, that is the
first five retries. The greater of this configured value and the
back-off is used
* `restart-max-sec = SEC` -- replaces that back-off with a delay that
doubles for each restart, from `restart-sec` up to this limit. With
`restart-sec = 10` and `restart-max-sec = 300` Finit waits 10, 20,
40, 80, 160, and then 300 seconds. Without `restart-sec` the first
restart is at once, then after 2, 4, 8 seconds, and so on. A service
that stays up longer than the current delay is restarted after
`restart-sec` the next time it crashes, and the delay comes down
again the longer the service keeps running. `initctl status NAME`
shows the current delay and the limit, see below. Useful with
`restart = "always"`, for a service that should be retried forever,
only less and less often
* `restart = "always"` -- no upper limit on the number of times Finit
tries to restart a crashing service
* `restart = "never"` -- do not restart on failures. `false` is
@@ -197,6 +209,15 @@ following settings are available:
* `oncrash = "script"` -- similarly, but instead of rebooting, call
the `exec-stop-post` script with exit code `crashed`, see below
With `restart-max-sec` set, `initctl status` shows the delay before the
next restart and its limit, here for a service that has crashed four
times in a row:
$ initctl status dialer
...
Restarts : 7 (4/-1)
Restart in : 160 sec (max 300)
Service directories
-------------------
@@ -259,6 +280,27 @@ down gracefully. If it has not been collected within 3 seconds,
* `stop-signal = "SIGPWR"` -- send this instead of `SIGTERM`
* `stop-timeout = 10` -- seconds to wait before `SIGKILL`, 1-300
* `stop-scope = "process"` -- which processes are stopped, see below
The stop signal goes to the main process of the service. When that
exits, Finit sends `SIGKILL` to any processes it left behind in its
process group. This is the default, `stop-scope = "pgroup"`. Other
scopes:
* `process` -- only the main process, anything it leaves behind is
left alone, e.g. a script it started on its way down
* `cgroup` -- the stop signal goes to all processes in the cgroup of
the service, and `SIGKILL` to those still there when the main
process exits
* `mixed` -- the stop signal goes to the main process, and `SIGKILL`
to the rest of the cgroup when it exits
All services declared in the same .conf file share a cgroup, unless
given a [name of their own](cgroups.md#overriding-cgroup-leaf-names),
so `cgroup` and `mixed` reach them all, Finit warns about this. Without
cgroups, these two fall back to the process group. A forking daemon
usually leaves the process group of its start command, so only `cgroup`
and `mixed` reach what it leaves behind.
Some services need more than a signal:
+67
View File
@@ -187,10 +187,77 @@ All read-only; observable via `Properties.Get` and `Properties.GetAll`.
| `ExitStatus` | `u` | Raw `waitpid(2)` status from the last exit |
| `RestartsTotal` | `u` | Restarts over the service's lifetime |
| `RestartMax` | `u` | Restart limit before the service is blocked |
| `RestartDelay` | `u` | Seconds before the next restart, should the service crash |
| `RestartDelayMax` | `u` | The `restart-max-sec` setting, 0 when not set |
| `Starts` | `u` | Times started, for `manual-start` units |
| `ManualStart` | `b` | `manual-start` set in the `.conf` |
| `Forking` | `b` | Daemon forks to background |
| `Started` | `b` | Run/task completed successfully |
| `Notify` | `s` | Readiness protocol: `none`, `pid`, `systemd`, or `s6` |
| `Remain` | `b` | `remain-after-exit` set in the `.conf` |
| `If` | `s` | The `if` setting, raw |
| `Provides` | `s` | Conditions from `provides`, comma separated |
| `Conflicts` | `s` | Services from `conflicts`, comma separated |
| `ExtraGroups` | `s` | Supplementary groups, comma separated |
| `Capabilities` | `s` | The `capabilities` setting, comma separated |
| `Pam` | `s` | PAM service name, empty when not set |
| `StopSignal` | `s` | Signal that stops the service, e.g. `SIGTERM` |
| `StopTimeout` | `u` | Seconds to wait for it to stop, before `SIGKILL` |
| `StopScope` | `s` | `pgroup`, `process`, `cgroup`, or `mixed` |
| `ReloadSignal` | `s` | `SIGHUP`, or `none` when a reload restarts the service |
| `RestartSec` | `u` | The `restart-sec` setting, 0 when not set |
| `Respawn` | `b` | `respawn` set in the `.conf` |
| `OnCrash` | `s` | `ignore`, `reboot`, or `script` |
| `RuntimeDir` | `s` | The `runtime-dir` setting, likewise for the four below |
| `StateDir` | `s` | |
| `CacheDir` | `s` | |
| `LogsDir` | `s` | |
| `ConfigDir` | `s` | |
| `RuntimeDirPreserve` | `s` | `no`, `restart`, or `yes` |
| `RuntimeDirMode` | `u` | Mode of the runtime directory, likewise for the four below |
| `StateDirMode` | `u` | |
| `CacheDirMode` | `u` | |
| `LogsDirMode` | `u` | |
| `ConfigDirMode` | `u` | |
| `Id` | `s` | The `:ID` part of the identity, empty when there is none |
| `Job` | `u` | Job number, internal |
| `OldPid` | `u` | PID of the previous run, internal |
| `Dirty` | `b` | Changed in the `.conf`, pending the next reload, internal |
| `Removed` | `b` | Gone from the `.conf`, pending removal, internal |
| `Starting` | `b` | Started, waiting for its PID file or readiness, internal |
| `Protected` | `b` | Built-in service, kept when the configuration is reloaded |
| `NoWarn` | `b` | No warning when the command is missing |
| `ReloadPropagate` | `b` | A reload of a dependency reloads this service too, `~` in its conditions |
| `CgroupName` | `s` | Control group the service joins, empty for the default |
| `CgroupConfig` | `s` | Its cgroup settings, `key:value` comma separated |
| `CgroupDelegate` | `b` | The service manages its own cgroup subtree |
| `Rlimits` | `s` | Resource limits as `name=soft:hard`, comma separated, a number or `unlimited` |
| `ExecStartPre` | `s` | Script, empty when not set, likewise for the five below |
| `ExecStartPreTimeout` | `u` | Seconds the script may run, one for each script |
| `ExecStartReady` | `s` | |
| `ExecStartReadyTimeout` | `u` | |
| `ExecStop` | `s` | |
| `ExecStopTimeout` | `u` | |
| `ExecStopPost` | `s` | |
| `ExecStopPostTimeout` | `u` | |
| `ExecReload` | `s` | |
| `ExecReloadTimeout` | `u` | |
| `ExecCleanup` | `s` | |
| `ExecCleanupTimeout` | `u` | |
| `Log` | `b` | Output is logged, not for a `tty` |
| `LogNull` | `b` | Output is discarded |
| `LogConsole` | `b` | Output goes to the console |
| `LogFile` | `s` | Log file, empty for syslog |
| `LogPriority` | `s` | Syslog facility and level, empty for the default |
| `LogIdentity` | `s` | Syslog identity, empty for the default |
| `TtyDevice` | `s` | Device of a `tty`, this and the below are empty or false for other types |
| `TtyBaud` | `s` | Baud rate, empty for the default |
| `TtyTerm` | `s` | The `TERM` to set |
| `TtyNoClear` | `b` | `noclear` set in the `.conf` |
| `TtyNoWait` | `b` | `nowait` set in the `.conf` |
| `TtyNoLogin` | `b` | `nologin` set in the `.conf` |
| `TtyNoTty` | `b` | `notty` set in the `.conf` |
| `TtyRescue` | `b` | `rescue` set in the `.conf` |
On every state transition the object also emits the standard
`org.freedesktop.DBus.Properties.PropertiesChanged` signal: `State`
+1 -1
View File
@@ -28,7 +28,7 @@ Features
* [Conditions](conditions.md) for network/process/custom dependencies
* [Readiness notification](config/service-sync.md); PID files (native) for synchronizing system
startup, support for systemd [sd_notify()][], or [s6 style][] too
* Limited support for [tmpfiles.d(5)][] (no aging, attributes, or subvolumes)
* Limited support for [tmpfiles.d(5)][] (no subvolumes)
* [Pre/Post script actions](config/service-wrappers.md)
* Rudimentary [templating support](config/templating.md)
* [Tooling](initctl.md) to enable/disable services
+111
View File
@@ -146,6 +146,117 @@ Apr 8 15:02:11 alpine authpriv.info dropbear[2634]: Child connection from 192.1
Apr 8 15:02:12 alpine authpriv.notice dropbear[2634]: Password auth succeeded for 'root' from 192.168.121.1:48576
```
With `-j` the same command gives JSON, for scripts and other programs.
The view above is kept short for reading, the JSON also has the
settings of the service:
```
alpine:~# initctl -j status dialer
{
"identity": "dialer",
"description": "Modem dialer",
"type": "service",
"forking": false,
"status": "restart",
"exit": { "code": 1 },
"origin": "/etc/finit.d/enabled/dialer.conf",
"command": "dialer",
"manual": false,
"started": false,
"starts": 0,
"restarts": 7,
"restart": {
"count": 4,
"max": -1,
"sec": 10,
"delay": 160,
"limit": 300,
"respawn": false,
"oncrash": "ignore"
},
"name": "dialer",
"id": "",
"internal": {
"job": 12,
"oldpid": 1234,
"starting": false,
"dirty": false,
"removed": false
},
"protected": false,
"nowarn": false,
"notify": "none",
"remain": false,
"stop": {
"signal": "SIGTERM",
"timeout": 3,
"scope": "pgroup"
},
"reload": {
"signal": "SIGHUP",
"propagate": false
},
"scripts": {
"exec-stop-post": { "command": "/usr/libexec/dialer-down", "timeout": 3 }
},
"directories": {
"runtime": { "name": "dialer", "mode": "0755" },
"preserve": "no"
},
"cgroup-config": {
"group": "",
"config": "",
"delegate": false
},
"rlimits": {
"core": { "soft": 0, "hard": "unlimited" },
"nofile": { "soft": 1024, "hard": 4096 },
...
},
"log": {
"enabled": true,
"null": false,
"console": false,
"file": "",
"priority": "",
"identity": "dialer"
},
"pidfile": "none",
"pid": 0,
"user": "root",
"group": "root",
"uptime": 0,
"runlevels": [ 2, 3, 4, 5 ]
}
```
In `restart`, `count` is the restart counter that `restart-max`, here
`max`, is compared to, -1 for `restart = "always"`. The total since
boot is in `restarts`. `delay` is the number of seconds before the
next restart, should the service crash, `sec` is `restart-sec`, and
`limit` is `restart-max-sec`, both 0 when not set. All times are in
seconds.
The settings use the names from the [configuration](config/service-opts.md):
`scripts` has the `exec-*` scripts that are set, each with its timeout,
`directories` the `runtime`, `state`, `cache`, `logs`, and `config`
directories that are set, and `preserve`. `cgroup-config` is the
`cgroup` setting of the service, where `cgroup` is the control group
it runs in right now. `rlimits` has every resource limit, the ones
from `rlimit` and the ones the service inherits. A `tty` has a `tty`
object with its device and flags where other types have `log`.
`internal` is state Finit keeps for its own use, it may change between
releases.
Left out when they do not apply are `environment`, `condition`, `exit`,
`if`, `provides`, `conflicts`, `groups`, `capabilities`, `pam`, and the
cgroup members `cgroup`, `memory`, `cpu`, and `limits`.
```
alpine:~# initctl -j status dialer | jq .restart.delay
160
```
Switch Root
-----------
+44 -4
View File
@@ -23,11 +23,51 @@ For your convenience a set of *optional* plugins are available:
file systems must be writable for this plugin to work.
This plugin is a wrapper for the [tmpfiles.d(5)][] implementation that
Finit has. Capable but limited: no aging, attributes, or subvolumes.
Finit has. Capable but limited: no btrfs subvolumes. It
runs `tmpfiles --create --remove --boot`, so entries marked boot-only
with a `!` are run here and at no other time.
By default, `/lib/finit/tmpfiles.d` carries all the default .conf
files distributed with Finit. It is read first but can be overridden
by any of the standard tmpfiles.d directories, e.g. `/etc/tmpfiles.d`.
The .conf files distributed with Finit are in `/lib/finit/tmpfiles.d`
and `/usr/lib/tmpfiles.d`. A file of the same name in `/run/tmpfiles.d`
or `/etc/tmpfiles.d` is read in its place. The files that remain are
read in the order of their names, whatever directory they are in, and
when two entries make the same path, the first one counts. So to
change an entry, copy its file to `/etc/tmpfiles.d` and edit it there,
or put the entry in a file with a name that sorts before it.
To see what the files on a system amount to, without anything being
done, add `--dry-run`:
/libexec/finit/tmpfiles --dry-run --create --remove --boot
It also tells which entries are skipped because a path already has
one.
The age of an entry, e.g. `10d` below, is used only by `tmpfiles
--clean`, which Finit never runs on its own:
d /var/tmp 1777 root root 10d
To have what is older than that removed, call it from cron, here
once a day from a system crontab. The program is installed in
`$libexecdir/finit/`, e.g. `/libexec/finit/`:
0 4 * * * root /libexec/finit/tmpfiles --clean
On a system without cron a service can do the same. It counts from
when it was started, so the time of day drifts with each boot:
service tmpfiles-clean {
description = "Periodic tmpfiles cleanup"
runlevel = "2345"
command = "sh -c 'while sleep 86400; do /libexec/finit/tmpfiles --clean; done'"
}
Cleaning stays on the file system of the directory, and it leaves
what `x` and `X` entries name. A file is kept as long as one of its
access, birth, change, and modification times is newer than the age,
or those the age names, as in `aAmM:10d` for access and modification
time only. With the age `0` everything in the directory is removed.
> [!NOTE]
> On an embedded system both `/var` and `/run` can be `tmpfs` RAM
+17
View File
@@ -0,0 +1,17 @@
tmpfiles TODO
=============
What `tmpfiles` lacks compared to [tmpfiles.d(5)][] and
systemd-tmpfiles(8), from a read of `src/tmpfiles.c` in November 2026.
[tmpfiles.d(5)]: https://www.freedesktop.org/software/systemd/man/tmpfiles.d.html
* `z` and `Z` only set the SELinux label when `restorecon` is installed,
and no other entry sets a label on what it creates. Doing it without
the program needs libselinux
* `--root` needs chroot(2), so it cannot be run as a regular user, or
under fakeroot when a root file system is built. The `%b` specifier
does not work there, the root has no `/proc`
* No `--image`, `--user`, or `--tldr`, and no btrfs subvolumes: `v`, `q`,
and `Q` make a plain directory
* An entry whose argument comes from a credential, `^`, is skipped
+76 -21
View File
@@ -81,6 +81,13 @@ static int builtin_kmod(struct uevent *ev, int argc, char **argv)
/* ---- hwdb -------------------------------------------------------- */
/*
* Longest lookup key. A key built by the stock name-based evdev rule
* (name, phys, ev and the DMI modalias) is 280 to 300 bytes with typical
* DMI strings, and 250 to 265 bytes for the plain name rule.
*/
#define HWDB_KEY_MAX 1024
/*
* Match a single text hwdb file against the lookup key.
* Text format: match lines at column 0, property lines indented.
@@ -106,7 +113,11 @@ static void hwdb_match_file(const char *path, const char *lookup,
while (fgets(line, sizeof(line), fp)) {
line[strcspn(line, "\n")] = '\0';
if (!line[0] || line[0] == '#') {
/* Comments do not end the record being read */
if (line[0] == '#')
continue;
if (!line[0]) {
matched = 0;
in_props = 0;
continue;
@@ -145,9 +156,11 @@ static void hwdb_match_file(const char *path, const char *lookup,
/*
* Build the hwdb lookup key for input devices.
*
* udev hwdb files use the format:
* evdev:input:b{BUS}v{VENDOR}p{PRODUCT}e{VERSION}*
* where all fields are 4-digit uppercase hex.
* The key is the modalias of the input device, which the rule's
* --lookup-prefix (evdev:, id-input:modalias:) is put in front of:
* input:b{BUS}v{VENDOR}p{PRODUCT}e{VERSION}-e{CAPABILITIES...}
* where the IDs are 4-digit uppercase hex. If the device has no modalias
* attribute, the part up to the version is built from the id/ files.
*
* The id/ files live under the input device directory. For eventN nodes
* (devpath ends in .../inputN/eventN) we strip the last component first.
@@ -156,7 +169,7 @@ static void hwdb_input_key(const struct uevent *ev, char *key, size_t len)
{
char base[PATH_MAX];
char path[PATH_MAX];
char bus_s[8], vendor_s[8], product_s[8], version_s[8];
char bus_s[8] = "", vendor_s[8] = "", product_s[8] = "", version_s[8] = "";
if (!ev->devpath)
return;
@@ -180,11 +193,28 @@ static void hwdb_input_key(const struct uevent *ev, char *key, size_t len)
snprintf(path, sizeof(path), "/sys%s", ev->devpath);
}
snprintf(base, sizeof(base), "%s/id/vendor", path); sysfs_read_file(base, vendor_s, sizeof(vendor_s));
snprintf(base, sizeof(base), "%s/id/product", path); sysfs_read_file(base, product_s, sizeof(product_s));
snprintf(base, sizeof(base), "%s/id/version", path); sysfs_read_file(base, version_s, sizeof(version_s));
/*
* Prefer the modalias of the input device. Unlike the id/ files it
* carries the capability bitmaps (-e0,1,2,4,k110,...) that some
* entries match on.
*/
snprintf(base, sizeof(base), "%s/modalias", path);
if (!sysfs_read_file(base, key, len) && !strncmp(key, "input:", 6))
return;
key[0] = '\0';
snprintf(key, len, "evdev:input:b%04Xv%04Xp%04Xe%04X*",
/* Otherwise build it from the id/ files; without a full set there is no key. */
snprintf(base, sizeof(base), "%s/id/vendor", path);
if (sysfs_read_file(base, vendor_s, sizeof(vendor_s)) < 0)
return;
snprintf(base, sizeof(base), "%s/id/product", path);
if (sysfs_read_file(base, product_s, sizeof(product_s)) < 0)
return;
snprintf(base, sizeof(base), "%s/id/version", path);
if (sysfs_read_file(base, version_s, sizeof(version_s)) < 0)
return;
snprintf(key, len, "input:b%04Xv%04Xp%04Xe%04X*",
(unsigned)strtoul(bus_s, NULL, 16),
(unsigned)strtoul(vendor_s, NULL, 16),
(unsigned)strtoul(product_s, NULL, 16),
@@ -265,24 +295,48 @@ static void hwdb_scan(const char *key, struct uevent *ev)
}
}
/* Insert prefix in front of key, in place; -1 if the result does not fit. */
static int hwdb_prepend(char *key, size_t len, const char *prefix)
{
size_t plen = strlen(prefix), klen = strlen(key);
if (plen + klen >= len)
return -1;
memmove(key + plen, key, klen + 1);
memcpy(key, prefix, plen);
return 0;
}
static int builtin_hwdb(struct uevent *ev, int argc, char **argv)
{
const char *subsys = NULL;
const char *prefix = NULL;
char key[256] = "";
const char *explicit_key = NULL;
char key[HWDB_KEY_MAX] = "";
int i;
/* Parse --subsystem=X and --lookup-prefix=Y */
/*
* Parse --subsystem=X and --lookup-prefix=Y. The first argument
* that is not an option is the lookup key itself, which is how the
* stock udev rules use the builtin:
*
* IMPORT{builtin}="hwdb 'evdev:name:$attr{name}:$attr{[dmi/id]modalias}'"
*/
for (i = 1; i < argc; i++) {
if (!strncmp(argv[i], "--subsystem=", 12))
subsys = argv[i] + 12;
else if (!strncmp(argv[i], "--lookup-prefix=", 16))
prefix = argv[i] + 16;
else if (argv[i][0] != '-' && !explicit_key)
explicit_key = argv[i];
}
if (!subsys)
subsys = ev->subsystem;
if (subsys && !strcmp(subsys, "input")) {
if (explicit_key) {
if (snprintf(key, sizeof(key), "%s", explicit_key) >= (int)sizeof(key))
goto too_long;
} else if (subsys && !strcmp(subsys, "input")) {
hwdb_input_key(ev, key, sizeof(key));
} else if (subsys && (!strcmp(subsys, "usb") ||
!strcmp(subsys, "usb_device"))) {
@@ -290,29 +344,30 @@ static int builtin_hwdb(struct uevent *ev, int argc, char **argv)
}
/* Fall back to MODALIAS / ev->modalias for pci, platform, etc. */
if (!key[0]) {
if (!key[0] && !explicit_key) {
const char *m = uevent_getenv(ev, "MODALIAS");
if (!m)
m = ev->modalias;
if (m)
snprintf(key, sizeof(key), "%s", m);
if (m && snprintf(key, sizeof(key), "%s", m) >= (int)sizeof(key))
goto too_long;
}
if (!key[0])
return 0;
/* --lookup-prefix scopes the match by prepending to the key. */
if (prefix && *prefix) {
char tmp[sizeof(key)];
snprintf(tmp, sizeof(tmp), "%s%s", prefix, key);
snprintf(key, sizeof(key), "%s", tmp);
}
if (prefix && *prefix && hwdb_prepend(key, sizeof(key), prefix))
goto too_long;
logit(LOG_DEBUG, "rules: hwdb lookup: %s", key);
hwdb_scan(key, ev);
return 0;
too_long:
logit(LOG_WARNING, "rules: hwdb key too long (max %d bytes), lookup skipped",
HWDB_KEY_MAX - 1);
return 0;
}
/* ---- path_id ----------------------------------------------------- */
+6
View File
@@ -143,6 +143,7 @@ static int num_ac;
static int level;
static int logon;
static int passive; /* power-supply only, no device management */
static int ready; /* pidfile created, see issue #503 */
static struct rule_list rules = TAILQ_HEAD_INITIALIZER(rules);
static char *rules_dir; /* extra rules dir from -r option */
@@ -507,10 +508,13 @@ static void sigterm_cb(uev_t *w, void *arg, int events)
uev_exit(w->ctx);
}
/* Finit expects the pidfile touched to reassert readiness after SIGHUP */
static void sighup_cb(uev_t *w, void *arg, int events)
{
(void)w; (void)arg; (void)events;
kev_rules_reload();
if (ready)
pidfile(NULL);
}
static void sigchld_cb(uev_t *w, void *arg, int events)
@@ -613,6 +617,7 @@ static void coldplug_pidfile_cb(uev_t *w, void *arg, int events)
return;
pidfile(NULL);
ready = 1;
logit(LOG_NOTICE, "keventd ready, coldplug queue drained");
uev_timer_stop(w);
}
@@ -826,6 +831,7 @@ int main(int argc, char *argv[])
logit(LOG_NOTICE, "keventd v%s started, draining coldplug queue...", KEVENTD_VERSION);
} else {
pidfile(NULL);
ready = 1;
logit(LOG_NOTICE, "keventd v%s started, waiting for events...", KEVENTD_VERSION);
}
+34 -3
View File
@@ -501,6 +501,33 @@ void rules_free(struct rule_list *list)
/* ----- variable substitution ------------------------------------------- */
/*
* Syspath of the parent device selected by the last successful
* KERNELS/SUBSYSTEMS/DRIVERS/ATTRS== match of the rule being evaluated.
* As in udev, $attr{} and %s{} fall back to this parent when the event
* device has no such attribute itself; the stock rules rely on it:
*
* ATTRS{bInterfaceNumber}=="?*", SYMLINK+="...-if$attr{bInterfaceNumber}-..."
*
* Cleared at the start of every rule and again once it has been applied.
*/
static char matched_parent[PATH_MAX];
/* Read an attribute for $attr{}/%s{}: the event device first, then the matched parent */
static int subst_read_attr(const struct uevent *ev, const char *attr,
char *buf, size_t len)
{
char path[PATH_MAX];
if (ev->devpath && !sysfs_read_attr(ev->devpath, attr, buf, len))
return 0;
if (!matched_parent[0])
return -1;
snprintf(path, sizeof(path), "%s/%s", matched_parent, attr);
return sysfs_read_file(path, buf, len);
}
static void append_str(char *buf, size_t *pos, size_t bufsz, const char *s)
{
size_t l;
@@ -604,8 +631,7 @@ static void subst_value(const char *src, char *buf, size_t bufsz,
al = sizeof(attr) - 1;
memcpy(attr, as, al);
attr[al] = 0;
if (!sysfs_read_attr(ev->devpath, attr,
tmp, sizeof(tmp)))
if (!subst_read_attr(ev, attr, tmp, sizeof(tmp)))
append_str(buf, &pos, bufsz, tmp);
p = ae + 1;
} else {
@@ -681,7 +707,7 @@ static void subst_value(const char *src, char *buf, size_t bufsz,
al = sizeof(attr) - 1;
memcpy(attr, as, al);
attr[al] = 0;
if (!sysfs_read_attr(ev->devpath, attr, tmp, sizeof(tmp)))
if (!subst_read_attr(ev, attr, tmp, sizeof(tmp)))
append_str(buf, &pos, bufsz, tmp);
p = ae + 1;
} else {
@@ -908,6 +934,8 @@ static int parent_cb(const char *syspath, void *data)
if (pattern_match(k->value, subject, k->pat_type)) {
ctx->found = 1;
if (k->op == OP_MATCH_EQ)
snprintf(matched_parent, sizeof(matched_parent), "%s", syspath);
return 0; /* stop walking */
}
return 1; /* keep walking */
@@ -1101,6 +1129,8 @@ static int rule_matches(const struct rule *r, struct uevent *ev)
{
int i;
matched_parent[0] = 0;
for (i = 0; i < r->nkeys; i++) {
const struct rule_key *k = &r->keys[i];
@@ -1627,6 +1657,7 @@ int rules_apply(struct rule_list *list, struct uevent *ev)
uevent_action_str(ev->action), ev->devpath ?: "");
exec_rule(r, ev);
matched_parent[0] = 0;
/* GOTO takes effect after this rule's assignments are applied */
goto_label = NULL;
+76 -18
View File
@@ -507,6 +507,62 @@ static struct devrule *find_rule(struct uevent *ev)
return &devrules[NELEMS(devrules) - 1];
}
/*
* Build the relative target of a symlink at /dev/<link> that points at the
* device node /dev/<node>, e.g.
*
* link "input/by-id/usb-X-event-kbd", node "input/event17" -> "../event17"
* link "disk/by-id/ata-X", node "sda" -> "../../sda"
*
* Both arguments are relative to /dev. The directory components the link
* and the node have in common are dropped, then one "../" is emitted for
* each directory the link still has to climb out of.
*/
static int symlink_relative_target(const char *link, const char *node,
char *buf, size_t len)
{
const char *l = link, *n = node;
size_t off = 0;
int ret;
while (*l == '/')
l++;
while (*n == '/')
n++;
/* Skip leading directories shared by both paths */
for (;;) {
const char *ls = strchr(l, '/');
const char *ns = strchr(n, '/');
if (!ls || !ns || ls - l != ns - n || strncmp(l, n, ls - l))
break;
l = ls + 1;
n = ns + 1;
while (*l == '/')
l++;
while (*n == '/')
n++;
}
buf[0] = 0;
for (; (l = strchr(l, '/')); l++) {
while (l[1] == '/')
l++;
if (!l[1])
break;
ret = snprintf(buf + off, len - off, "../");
if (ret < 0 || (size_t)ret >= len - off)
return -1;
off += ret;
}
ret = snprintf(buf + off, len - off, "%s", n);
if (ret < 0 || (size_t)ret >= len - off)
return -1;
return 0;
}
/*
* Create device node in /dev.
*/
@@ -792,7 +848,7 @@ static int disk_path_id(struct uevent *ev, char *id, size_t len)
static int symlink_add_disk(struct uevent *ev)
{
char target[PATH_MAX], link[PATH_MAX], id[256];
const char *name;
const char *name, *devtype;
if (!ev->devname)
return -1;
@@ -801,13 +857,22 @@ static int symlink_add_disk(struct uevent *ev)
name = strrchr(ev->devname, '/');
name = name ? name + 1 : ev->devname;
/* by-id: serial-based identifier */
/*
* by-id: serial-based identifier.
* Partitions are skipped, as their serial lives on the parent disk and would
* clobber its by-id link, partitions get theirs from the udev rules instead.
*/
devtype = uevent_getenv(ev, "DEVTYPE");
if (devtype && !strcmp(devtype, "partition"))
goto path;
if (!disk_serial_id(ev, id, sizeof(id))) {
snprintf(target, sizeof(target), "../../%s", name);
snprintf(link, sizeof(link), "/dev/disk/by-id/%s", id);
symlink_create(target, link, ev->devpath);
}
path:
/* by-path: topology-based identifier */
if (!disk_path_id(ev, id, sizeof(id))) {
snprintf(target, sizeof(target), "../../%s", name);
@@ -903,9 +968,6 @@ int symlink_add(struct uevent *ev)
for (i = 0; i < ev->applied.nsymlinks; i++) {
const char *devname, *sl;
char link[PATH_MAX], target[PATH_MAX];
size_t toff = 0;
int depth = 0;
const char *p;
sl = ev->applied.symlinks[i];
if (!sl || !*sl)
@@ -915,19 +977,15 @@ int symlink_add(struct uevent *ev)
if (!devname)
continue;
/* basename of devname for the symlink target */
const char *base = strrchr(devname, '/');
base = base ? base + 1 : devname;
/* Count '/' in symlink path to determine relative depth */
for (p = sl; *p; p++)
if (*p == '/')
depth++;
target[0] = 0;
for (int d = 0; d < depth; d++)
toff += snprintf(target + toff, sizeof(target) - toff, "../");
snprintf(target + toff, sizeof(target) - toff, "%s", base);
/*
* The node lives at /dev/<devname>, which is not necessarily
* directly in /dev (input/event17, dri/card0, ...), so the
* target must be computed relative to the link's directory.
*/
if (symlink_relative_target(sl, devname, target, sizeof(target))) {
logit(LOG_WARNING, "Symlink %s -> %s: path too long", sl, devname);
continue;
}
snprintf(link, sizeof(link), "/dev/%s", sl);
symlink_create(target, link, ev->devpath ?: "");
+1 -1
View File
@@ -94,7 +94,7 @@ and s6 notification is also supported.
.It
Limited support for
.Xr tmpfiles.d 5 ,
no aging, attributes, or subvolumes
no subvolumes
.It
Pre/Post script actions
.It
+25 -2
View File
@@ -379,11 +379,22 @@ marked
.Em crashed
and must be restarted manually with
.Xr initctl 8 .
.It Cm restart_sec:SEC
.It Cm restart-sec:SEC
number of seconds before Finit tries to restart
a crashing service, default: 2 seconds for the first five retries,
then back-off to 5 seconds. The maximum of this configured value
and the above (2 and 5) will be used
and the above (2 and 5) will be used. The old spelling,
.Cm restart_sec:SEC ,
is still accepted
.It Cm restart-max-sec:SEC
replaces that back-off with a delay that doubles for each restart, from
.Cm restart-sec
up to this limit, e.g. 10, 20, 40, and so on up to 300 seconds with
.Cm restart-sec:10 restart-max-sec:300 .
Without
.Cm restart-sec
the first restart is at once, then after 2, 4, 8 seconds. The delay
comes down again as the service keeps running
.It Cm restart:always
no upper limit on the number of times Finit tries to restart a crashing
service. Same as
@@ -470,6 +481,18 @@ modifier
e.g.,
.Cm kill:10
to wait 10 seconds before sending SIGKILL.
When the process exits, Finit sends SIGKILL to any processes left in
its process group. The command modifier
.Cm stop-scope:SCOPE
changes this:
.Cm process
leaves them alone,
.Cm cgroup
sends the halt signal to all processes in the cgroup of the service and
SIGKILL to the rest when the process exits, and
.Cm mixed
sends only SIGKILL to the rest of the cgroup. The default is
.Cm pgroup .
.Pp
Services, including the
.Cm sysv
+1
View File
@@ -11,6 +11,7 @@ extra_css:
exclude_docs: |
TODO.md
tmpfiles-todo.md
ChangeLog.md
README.md
+1 -1
View File
@@ -163,7 +163,7 @@ static void setup(void *arg)
kernel_links();
/* Create all system tmpfiles.d(5) */
run_interactive(_PATH_TMPFILES " --create", "Creating required directories and files");
run_interactive(_PATH_TMPFILES " --create --remove --boot", "Creating required directories and files");
/* Set BOOT_TIME UTMP entry */
utmp_set_boot();
+1
View File
@@ -156,6 +156,7 @@ static int modules_load(const char *file, int index)
}
/* unknown 'set' command, ignore. */
free(set);
goto next;
}
+10 -3
View File
@@ -109,6 +109,12 @@ static void pidfile_update_conds(char *dir, char *name, uint32_t mask)
}
if (mask & (IN_CLOSE_WRITE | IN_ATTRIB | IN_MODIFY | IN_MOVED_TO)) {
/* Only a starting or running service may claim a PID file, issue #452 */
if (!svc_is_starting(svc) && !svc_is_running(svc)) {
dbg("%s is %s, ignoring %s", nm, svc_status(svc), fn);
return;
}
/*
* only mark native services as started, the s6 and
* systemd style services rely on their respective
@@ -133,9 +139,6 @@ static void pidfile_update_conds(char *dir, char *name, uint32_t mask)
return;
}
/* Service is not crashing, let's tell state machine! */
service_forked(svc);
if (pid != svc->pid) {
dbg("Forking service %s (cmd %s) changed PID from %d to %d",
svc_ident(svc, NULL, 0), svc->cmd, svc->pid, pid);
@@ -145,6 +148,10 @@ static void pidfile_update_conds(char *dir, char *name, uint32_t mask)
logit(LOG_CONSOLE | LOG_NOTICE, "Started %s[%d]", svc_ident(svc, NULL, 0), pid);
cgroup_move_svc(svc);
}
/* Service is not crashing, let's tell state machine! */
if (!service_forked(svc))
return;
}
if (svc->notify == SVC_NOTIFY_PID)
+2 -1
View File
@@ -36,7 +36,7 @@ sulogin_SOURCES = sulogin.c
sulogin_CFLAGS = -W -Wall -Wextra -std=gnu99
sulogin_LDADD = -lcrypt
tmpfiles_SOURCES = tmpfiles.c util.c util.h log.h
tmpfiles_SOURCES = tmpfiles.c helpers.h util.c util.h log.h
tmpfiles_CFLAGS = -W -Wall -Wextra -std=gnu99
tmpfiles_CFLAGS += $(lite_CFLAGS) $(uev_CFLAGS)
tmpfiles_LDADD = $(lite_LIBS) $(uev_LIBS)
@@ -54,6 +54,7 @@ finit_SOURCES = api.c cgroup.c cgroup.h \
legacy.c legacy.h \
devmon.c devmon.h \
exec.c finit.c finit.h \
shutdown.c shutdown.h \
stty.c \
helpers.c helpers.h \
initramfs.c \
+15 -37
View File
@@ -48,6 +48,7 @@
#include "schedule.h"
#include "service.h"
#include "sm.h"
#include "shutdown.h"
#include "sig.h"
#include "util.h"
@@ -241,43 +242,9 @@ static int do_reboot(int cmd, int timeout, char *buf, size_t len)
switch (cmd) {
case INIT_CMD_REBOOT:
halt = SHUT_REBOOT;
break;
case INIT_CMD_HALT:
halt = SHUT_HALT;
break;
case INIT_CMD_POWEROFF:
halt = SHUT_OFF;
break;
case INIT_CMD_SUSPEND:
break;
default:
return 255;
}
shutdown_bypass(timeout);
switch (cmd) {
case INIT_CMD_REBOOT:
dbg("reboot");
halt = SHUT_REBOOT;
sm_runlevel(6);
break;
case INIT_CMD_HALT:
dbg("halt");
halt = SHUT_HALT;
sm_runlevel(0);
break;
case INIT_CMD_POWEROFF:
dbg("poweroff");
halt = SHUT_OFF;
sm_runlevel(0);
rc = shutdown_now(cmd, timeout);
break;
case INIT_CMD_SUSPEND:
@@ -293,8 +260,7 @@ static int do_reboot(int cmd, int timeout, char *buf, size_t len)
break;
default:
/* Handled previously */
break;
return 255;
}
return rc;
@@ -384,6 +350,7 @@ static void api_cb(uev_t *w, void *arg, int events)
case INIT_CMD_HALT:
case INIT_CMD_POWEROFF:
case INIT_CMD_SUSPEND:
case INIT_CMD_SHUTDOWN:
if (IS_RESERVED_RUNLEVEL(runlevel)) {
strterm(rq.data, sizeof(rq.data));
warnx("Unsupported command (cmd: %d, data: %s) in runlevel S and 6/0.",
@@ -484,6 +451,17 @@ static void api_cb(uev_t *w, void *arg, int events)
result = do_reboot(rq.cmd, rq.sleeptime, rq.data, sizeof(rq.data));
break;
case INIT_CMD_SHUTDOWN:
strterm(rq.data, sizeof(rq.data));
result = shutdown_schedule(rq.runlevel, rq.sleeptime, rq.data);
break;
case INIT_CMD_SHUTDOWN_CANCEL:
result = shutdown_cancel();
if (result)
strlcpy(rq.data, "No scheduled shutdown to cancel.", sizeof(rq.data));
break;
case INIT_CMD_SWITCH_ROOT:
result = do_switch_root_api(sd, &rq);
if (result)
+86 -11
View File
@@ -42,6 +42,9 @@
#include "iwatch.h"
#include "conf.h"
#include "service.h"
#ifdef AUTO_RELOAD
#include "sm.h"
#endif
#include "log.h"
#include "util.h"
@@ -219,6 +222,86 @@ int cgroup_move_svc(svc_t *svc)
svc->pid, svc->cgroup.delegate);
}
/*
* The cgroup @svc runs in, as set up by cgroup_prepare(). NULL for
* the root cgroup, which is not the service's own.
*/
static char *cgroup_svc_path(svc_t *svc, const char *name, char *buf, size_t len)
{
const char *group;
if (svc_is_tty(svc))
group = "user";
else if (!strcmp(svc->cgroup.name, "root"))
return NULL;
else
group = svc->cgroup.name[0] ? svc->cgroup.name : "system";
snprintf(buf, len, FINIT_CGPATH "/%s/%s", group, name);
return buf;
}
static void cgroup_signal_path(const char *path, int sig)
{
char fn[PATH_MAX];
struct dirent *d;
DIR *dir;
FILE *fp;
int pid;
fp = fopenf("r", "%s/cgroup.procs", path);
if (fp) {
/* A PID outside our PID namespace reads as 0, our own group */
while (fscanf(fp, "%d", &pid) == 1) {
if (pid > 1)
kill(pid, sig);
}
fclose(fp);
}
/* Delegated cgroups have their processes in sub-cgroups */
dir = opendir(path);
if (!dir)
return;
while ((d = readdir(dir))) {
if (d->d_type != DT_DIR || !strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
continue;
snprintf(fn, sizeof(fn), "%s/%s", path, d->d_name);
cgroup_signal_path(fn, sig);
}
closedir(dir);
}
/* True if @svc runs in a cgroup of its own, not the root cgroup */
int cgroup_svc_has(svc_t *svc)
{
return avail && svc && strcmp(svc->cgroup.name, "root");
}
/*
* Send @sig to every process in the cgroup of @svc. Returns -1 if
* it has no cgroup of its own, e.g. cgroups are not available.
*/
int cgroup_signal_svc(svc_t *svc, int sig)
{
char name[MAX_ARG_LEN];
char path[PATH_MAX];
if (!cgroup_svc_has(svc))
return -1;
if (!cgroup_svc_path(svc, cgroup_svc_name(svc, name, sizeof(name)), path, sizeof(path)) ||
!fisdir(path))
return -1;
/* Atomic and recursive, Linux 5.14 and later */
if (sig == SIGKILL && !fnwrite("1", "%s/cgroup.kill", path))
return 0;
cgroup_signal_path(path, sig);
return 0;
}
static void cgset(const char *path, char *ctrl, char *prop)
{
char *val;
@@ -795,23 +878,15 @@ int cgroup_del(char *dir)
*/
int cgroup_del_svc(svc_t *svc, const char *name)
{
const char *group;
char path[256];
char path[PATH_MAX];
if (!avail)
return 0;
/* Determine group from service */
if (svc_is_tty(svc)) {
group = "user";
} else if (svc->cgroup.name[0] && !strcmp(svc->cgroup.name, "root")) {
/* Root cgroup - nothing to delete */
/* Root cgroup - nothing to delete */
if (!cgroup_svc_path(svc, name, path, sizeof(path)))
return 0;
} else {
group = svc->cgroup.name[0] ? svc->cgroup.name : "system";
}
snprintf(path, sizeof(path), "/sys/fs/cgroup/%s/%s", group, name);
return cgroup_del(path);
}
+2
View File
@@ -58,6 +58,8 @@ int cgroup_watch (const char *group, const char *name);
int cgroup_move_pid(const char *group, const char *name, int pid, int delegate);
int cgroup_move_svc(svc_t *svc);
int cgroup_svc_has (svc_t *svc);
int cgroup_signal_svc(svc_t *svc, int sig);
void cgroup_prune (void);
+15 -8
View File
@@ -67,6 +67,9 @@
#include "legacy.h"
#include "private.h"
#include "service.h"
#ifdef AUTO_RELOAD
#include "sm.h"
#endif
#include "helpers.h"
#include "util.h"
@@ -258,6 +261,7 @@ static cfg_opt_t svc_opts[] = {
CFG_STR ("restart", NULL, CFGF_NODEFAULT),
CFG_INT ("restart-max", 0, CFGF_NODEFAULT),
CFG_INT ("restart-sec", 0, CFGF_NODEFAULT),
CFG_INT ("restart-max-sec", 0, CFGF_NODEFAULT),
CFG_STR ("oncrash", NULL, CFGF_NODEFAULT),
CFG_STR ("reload-signal", NULL, CFGF_NODEFAULT),
CFG_BOOL ("required", cfg_true, CFGF_NODEFAULT),
@@ -265,6 +269,7 @@ static cfg_opt_t svc_opts[] = {
CFG_STR ("halt", NULL, CFGF_NODEFAULT), /* alias */
CFG_INT ("stop-timeout", 0, CFGF_NODEFAULT),
CFG_INT ("kill", 0, CFGF_NODEFAULT), /* alias */
CFG_STR ("stop-scope", NULL, CFGF_NODEFAULT),
/* lifecycle scripts, each with its own bound */
EXEC_OPTS("exec-start-pre"),
@@ -1123,7 +1128,7 @@ static int sec_getbool(cfg_t *sec, const char *key, const char *alias)
* The line-based format could only spell this as one stanza per
* candidate, relying on nowarn to skip the ones that were not
* installed. A candidate not being there is not an error here, so
* only the winner is looked up again by service_register().
* only the winner is looked up again by service_register_desc().
*
* A leading '-' still says a missing binary is expected, cf. systemd
* ExecStart=-.
@@ -1440,7 +1445,7 @@ static void provides_translate(cfg_t *sec, svc_t *svc, char *file)
/*
* These have no legacy token, they are validated by service_set_dir()
* and stored directly on the registered svc. Empty means unset,
* service_register() has already cleared the fields.
* service_register_desc() has already cleared the fields.
*/
static void dirs_translate(cfg_t *sec, svc_t *svc, char *file)
{
@@ -1663,7 +1668,9 @@ static void svc_translate(cfg_t *sec, int type, struct rlimit rlimit[], char *fi
}
if (sec_getint(sec, "restart-sec", NULL, &num))
addtok(line, sizeof(line), "restart_sec:%ld", num);
addtok(line, sizeof(line), "restart-sec:%ld", num);
if (sec_getint(sec, "restart-max-sec", NULL, &num))
addtok(line, sizeof(line), "restart-max-sec:%ld", num);
if ((str = sec_getstr(sec, "oncrash", NULL)))
addtok(line, sizeof(line), "oncrash:%s", str);
@@ -1671,6 +1678,8 @@ static void svc_translate(cfg_t *sec, int type, struct rlimit rlimit[], char *fi
addtok(line, sizeof(line), "halt:%s", str);
if (sec_getint(sec, "stop-timeout", "kill", &num))
addtok(line, sizeof(line), "kill:%ld", num);
if ((str = sec_getstr(sec, "stop-scope", NULL)))
addtok(line, sizeof(line), "stop-scope:%s", str);
addscript(line, sizeof(line), sec, "exec-start-pre", "pre:");
addscript(line, sizeof(line), sec, "exec-start-ready", "ready:");
@@ -1725,11 +1734,9 @@ static void svc_translate(cfg_t *sec, int type, struct rlimit rlimit[], char *fi
/* the command and its arguments, verbatim */
addtok(line, sizeof(line), "%s", cmd);
if ((str = sec_getstr(sec, "description", "desc")))
addtok(line, sizeof(line), "-- %s", str);
str = sec_getstr(sec, "description", "desc");
dbg("translated: %s", line);
svc = service_register(type, line, rlimit, file);
svc = service_register_desc(type, line, str, rlimit, file);
if (!svc)
return;
@@ -1804,7 +1811,7 @@ static void tty_translate(cfg_t *sec, struct rlimit rlimit[], char *file)
addtok(line, sizeof(line), "%s", str);
dbg("translated: tty %s", line);
service_register(SVC_TYPE_TTY, line, rlimit, file);
service_register_desc(SVC_TYPE_TTY, line, NULL, rlimit, file);
}
/*
+176 -7
View File
@@ -50,6 +50,7 @@
#include "schedule.h"
#include "service.h"
#include "sig.h"
#include "shutdown.h"
#include "sm.h"
#include "svc.h"
#include "util.h"
@@ -438,7 +439,7 @@ static int manager_set_runlevel(link_call_t *call, void *userdata)
return 0;
}
static int dbus_shutdown(link_call_t *call, shutop_t target, int level)
static int dbus_shutdown(link_call_t *call, int cmd)
{
uint32_t timeout;
@@ -450,16 +451,14 @@ static int dbus_shutdown(link_call_t *call, shutop_t target, int level)
return link_call_reply_error(call,
"org.finit.Error.WrongRunlevel",
"Already in shutdown");
halt = target;
shutdown_bypass((int)timeout);
sm_runlevel(level);
shutdown_now(cmd, (int)timeout);
(void)link_call_reply(call);
return 0;
}
static int manager_reboot (link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, SHUT_REBOOT, 6); }
static int manager_poweroff(link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, SHUT_OFF, 0); }
static int manager_halt (link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, SHUT_HALT, 0); }
static int manager_reboot (link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, INIT_CMD_REBOOT); }
static int manager_poweroff(link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, INIT_CMD_POWEROFF); }
static int manager_halt (link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, INIT_CMD_HALT); }
static int manager_set_debug(link_call_t *call, void *u)
{
@@ -798,11 +797,114 @@ SVC_PROP_U32 (svc_prop_runlevels, runlevels)
SVC_PROP_U32 (svc_prop_exitstatus, status)
SVC_PROP_U32 (svc_prop_restarts_tot, restart_tot)
SVC_PROP_U32 (svc_prop_restart_max, restart_max)
SVC_PROP_U32 (svc_prop_restart_delay, restart_tmo / 1000) /* msec */
SVC_PROP_U32 (svc_prop_restart_delay_max, restart_tmo_max / 1000)
SVC_PROP_U32 (svc_prop_starts, once)
SVC_PROP_BOOL(svc_prop_manual, manual)
SVC_PROP_BOOL(svc_prop_forking, forking)
SVC_PROP_BOOL(svc_prop_started, started)
/* The settings of the service, for initctl -j status */
#define SVC_PROP_EXPR(fn, writer, expr) \
static int fn(link_writer_t *w, void *arg) \
{ \
svc_t *svc = arg; \
\
writer(w, expr); \
return 0; \
}
static int svc_prop_provides(link_writer_t *w, void *arg)
{
char buf[MAX_NUM_PROVIDES * MAX_COND_LEN];
link_w_string(w, svc_provides_str(arg, buf, sizeof(buf)));
return 0;
}
static int svc_prop_rlimits(link_writer_t *w, void *arg)
{
svc_t *svc = arg;
char buf[1024];
link_w_string(w, rlimits2str(svc->rlimit, buf, sizeof(buf)));
return 0;
}
static int svc_prop_stop_signal(link_writer_t *w, void *arg)
{
svc_t *svc = arg;
char buf[16];
/* Not sig_name(), initctl has only sig2str() for its own transport */
snprintf(buf, sizeof(buf), "SIG%s", sig2str(svc->sighalt));
link_w_string(w, buf);
return 0;
}
SVC_PROP_BOOL(svc_prop_remain, remain)
SVC_PROP_STR (svc_prop_if, ifstmt)
SVC_PROP_STR (svc_prop_conflicts, conflict)
SVC_PROP_STR (svc_prop_extra_groups, supgroups)
SVC_PROP_STR (svc_prop_capabilities, capabilities)
SVC_PROP_STR (svc_prop_pam, pam)
SVC_PROP_U32 (svc_prop_stop_timeout, killdelay / 1000)
SVC_PROP_U32 (svc_prop_restart_sec, restart_saved / 1000)
SVC_PROP_BOOL(svc_prop_respawn, respawn)
SVC_PROP_BOOL(svc_prop_protected, protect)
SVC_PROP_STR (svc_prop_id, id)
SVC_PROP_U32 (svc_prop_job, job)
SVC_PROP_U32 (svc_prop_old_pid, oldpid)
SVC_PROP_BOOL(svc_prop_dirty, dirty)
SVC_PROP_BOOL(svc_prop_removed, removed)
SVC_PROP_BOOL(svc_prop_starting, starting)
SVC_PROP_BOOL(svc_prop_no_warn, nowarn)
SVC_PROP_BOOL(svc_prop_reload_propagate, flux_reload)
SVC_PROP_STR (svc_prop_cgroup_name, cgroup.name)
SVC_PROP_STR (svc_prop_cgroup_config, cgroup.cfg)
SVC_PROP_BOOL(svc_prop_cgroup_delegate, cgroup.delegate)
SVC_PROP_U32 (svc_prop_runtime_dir_mode, dir_mode[0])
SVC_PROP_U32 (svc_prop_state_dir_mode, dir_mode[1])
SVC_PROP_U32 (svc_prop_cache_dir_mode, dir_mode[2])
SVC_PROP_U32 (svc_prop_logs_dir_mode, dir_mode[3])
SVC_PROP_U32 (svc_prop_config_dir_mode, dir_mode[4])
SVC_PROP_STR (svc_prop_runtime_dir, runtime_dir)
SVC_PROP_STR (svc_prop_state_dir, state_dir)
SVC_PROP_STR (svc_prop_cache_dir, cache_dir)
SVC_PROP_STR (svc_prop_logs_dir, logs_dir)
SVC_PROP_STR (svc_prop_config_dir, config_dir)
SVC_PROP_STR (svc_prop_exec_start_pre, pre_script)
SVC_PROP_U32 (svc_prop_exec_start_pre_timeout, pre_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_start_ready, ready_script)
SVC_PROP_U32 (svc_prop_exec_start_ready_timeout, ready_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_stop, stop_script)
SVC_PROP_U32 (svc_prop_exec_stop_timeout, stop_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_stop_post, post_script)
SVC_PROP_U32 (svc_prop_exec_stop_post_timeout, post_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_reload, reload_script)
SVC_PROP_U32 (svc_prop_exec_reload_timeout, reload_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_cleanup, cleanup_script)
SVC_PROP_U32 (svc_prop_exec_cleanup_timeout, cleanup_tmo / 1000)
SVC_PROP_EXPR(svc_prop_notify, link_w_string, svc_notify_str(svc))
SVC_PROP_EXPR(svc_prop_stop_scope, link_w_string, svc_scope_str(svc->stop_scope))
SVC_PROP_EXPR(svc_prop_reload_signal, link_w_string, svc->sighup ? "SIGHUP" : "none")
SVC_PROP_EXPR(svc_prop_on_crash, link_w_string, svc_oncrash_str(svc))
SVC_PROP_EXPR(svc_prop_runtime_dir_preserve, link_w_string, svc_preserve_str(svc))
SVC_PROP_EXPR(svc_prop_log, link_w_bool, !svc_is_tty(svc) ? svc->log.enabled : 0)
SVC_PROP_EXPR(svc_prop_log_null, link_w_bool, !svc_is_tty(svc) ? svc->log.null : 0)
SVC_PROP_EXPR(svc_prop_log_console, link_w_bool, !svc_is_tty(svc) ? svc->log.console : 0)
SVC_PROP_EXPR(svc_prop_log_file, link_w_string, !svc_is_tty(svc) ? svc->log.file : "")
SVC_PROP_EXPR(svc_prop_log_priority, link_w_string, !svc_is_tty(svc) ? svc->log.prio : "")
SVC_PROP_EXPR(svc_prop_log_identity, link_w_string, !svc_is_tty(svc) ? svc->log.ident : "")
SVC_PROP_EXPR(svc_prop_tty_device, link_w_string, svc_is_tty(svc) ? svc->dev : "")
SVC_PROP_EXPR(svc_prop_tty_baud, link_w_string, svc_is_tty(svc) ? svc->baud : "")
SVC_PROP_EXPR(svc_prop_tty_term, link_w_string, svc_is_tty(svc) ? svc->term : "")
SVC_PROP_EXPR(svc_prop_tty_no_clear, link_w_bool, svc_is_tty(svc) ? svc->noclear : 0)
SVC_PROP_EXPR(svc_prop_tty_no_wait, link_w_bool, svc_is_tty(svc) ? svc->nowait : 0)
SVC_PROP_EXPR(svc_prop_tty_no_login, link_w_bool, svc_is_tty(svc) ? svc->nologin : 0)
SVC_PROP_EXPR(svc_prop_tty_no_tty, link_w_bool, svc_is_tty(svc) ? svc->notty : 0)
SVC_PROP_EXPR(svc_prop_tty_rescue, link_w_bool, svc_is_tty(svc) ? svc->rescue : 0)
static const link_property_t service_properties[] = {
{ .name = "Identity", .sig = "s", .getter = svc_prop_identity },
{ .name = "Name", .sig = "s", .getter = svc_prop_name },
@@ -823,10 +925,77 @@ static const link_property_t service_properties[] = {
{ .name = "ExitStatus", .sig = "u", .getter = svc_prop_exitstatus },
{ .name = "RestartsTotal",.sig = "u", .getter = svc_prop_restarts_tot },
{ .name = "RestartMax", .sig = "u", .getter = svc_prop_restart_max },
{ .name = "RestartDelay", .sig = "u", .getter = svc_prop_restart_delay },
{ .name = "RestartDelayMax", .sig = "u", .getter = svc_prop_restart_delay_max },
{ .name = "Starts", .sig = "u", .getter = svc_prop_starts },
{ .name = "ManualStart", .sig = "b", .getter = svc_prop_manual },
{ .name = "Forking", .sig = "b", .getter = svc_prop_forking },
{ .name = "Started", .sig = "b", .getter = svc_prop_started },
{ .name = "Notify", .sig = "s", .getter = svc_prop_notify },
{ .name = "Remain", .sig = "b", .getter = svc_prop_remain },
{ .name = "If", .sig = "s", .getter = svc_prop_if },
{ .name = "Provides", .sig = "s", .getter = svc_prop_provides },
{ .name = "Conflicts", .sig = "s", .getter = svc_prop_conflicts },
{ .name = "ExtraGroups", .sig = "s", .getter = svc_prop_extra_groups },
{ .name = "Capabilities", .sig = "s", .getter = svc_prop_capabilities },
{ .name = "Pam", .sig = "s", .getter = svc_prop_pam },
{ .name = "StopSignal", .sig = "s", .getter = svc_prop_stop_signal },
{ .name = "StopTimeout", .sig = "u", .getter = svc_prop_stop_timeout },
{ .name = "StopScope", .sig = "s", .getter = svc_prop_stop_scope },
{ .name = "ReloadSignal", .sig = "s", .getter = svc_prop_reload_signal },
{ .name = "RestartSec", .sig = "u", .getter = svc_prop_restart_sec },
{ .name = "Respawn", .sig = "b", .getter = svc_prop_respawn },
{ .name = "OnCrash", .sig = "s", .getter = svc_prop_on_crash },
{ .name = "RuntimeDir", .sig = "s", .getter = svc_prop_runtime_dir },
{ .name = "StateDir", .sig = "s", .getter = svc_prop_state_dir },
{ .name = "CacheDir", .sig = "s", .getter = svc_prop_cache_dir },
{ .name = "LogsDir", .sig = "s", .getter = svc_prop_logs_dir },
{ .name = "ConfigDir", .sig = "s", .getter = svc_prop_config_dir },
{ .name = "RuntimeDirPreserve", .sig = "s", .getter = svc_prop_runtime_dir_preserve },
{ .name = "RuntimeDirMode", .sig = "u", .getter = svc_prop_runtime_dir_mode },
{ .name = "StateDirMode", .sig = "u", .getter = svc_prop_state_dir_mode },
{ .name = "CacheDirMode", .sig = "u", .getter = svc_prop_cache_dir_mode },
{ .name = "LogsDirMode", .sig = "u", .getter = svc_prop_logs_dir_mode },
{ .name = "ConfigDirMode", .sig = "u", .getter = svc_prop_config_dir_mode },
{ .name = "Protected", .sig = "b", .getter = svc_prop_protected },
{ .name = "Id", .sig = "s", .getter = svc_prop_id },
{ .name = "Job", .sig = "u", .getter = svc_prop_job },
{ .name = "OldPid", .sig = "u", .getter = svc_prop_old_pid },
{ .name = "Dirty", .sig = "b", .getter = svc_prop_dirty },
{ .name = "Removed", .sig = "b", .getter = svc_prop_removed },
{ .name = "Starting", .sig = "b", .getter = svc_prop_starting },
{ .name = "NoWarn", .sig = "b", .getter = svc_prop_no_warn },
{ .name = "ReloadPropagate", .sig = "b", .getter = svc_prop_reload_propagate },
{ .name = "CgroupName", .sig = "s", .getter = svc_prop_cgroup_name },
{ .name = "CgroupConfig", .sig = "s", .getter = svc_prop_cgroup_config },
{ .name = "CgroupDelegate", .sig = "b", .getter = svc_prop_cgroup_delegate },
{ .name = "Rlimits", .sig = "s", .getter = svc_prop_rlimits },
{ .name = "ExecStartPre", .sig = "s", .getter = svc_prop_exec_start_pre },
{ .name = "ExecStartPreTimeout", .sig = "u", .getter = svc_prop_exec_start_pre_timeout },
{ .name = "ExecStartReady", .sig = "s", .getter = svc_prop_exec_start_ready },
{ .name = "ExecStartReadyTimeout", .sig = "u", .getter = svc_prop_exec_start_ready_timeout },
{ .name = "ExecStop", .sig = "s", .getter = svc_prop_exec_stop },
{ .name = "ExecStopTimeout", .sig = "u", .getter = svc_prop_exec_stop_timeout },
{ .name = "ExecStopPost", .sig = "s", .getter = svc_prop_exec_stop_post },
{ .name = "ExecStopPostTimeout", .sig = "u", .getter = svc_prop_exec_stop_post_timeout },
{ .name = "ExecReload", .sig = "s", .getter = svc_prop_exec_reload },
{ .name = "ExecReloadTimeout", .sig = "u", .getter = svc_prop_exec_reload_timeout },
{ .name = "ExecCleanup", .sig = "s", .getter = svc_prop_exec_cleanup },
{ .name = "ExecCleanupTimeout", .sig = "u", .getter = svc_prop_exec_cleanup_timeout },
{ .name = "Log", .sig = "b", .getter = svc_prop_log },
{ .name = "LogNull", .sig = "b", .getter = svc_prop_log_null },
{ .name = "LogConsole", .sig = "b", .getter = svc_prop_log_console },
{ .name = "LogFile", .sig = "s", .getter = svc_prop_log_file },
{ .name = "LogPriority", .sig = "s", .getter = svc_prop_log_priority },
{ .name = "LogIdentity", .sig = "s", .getter = svc_prop_log_identity },
{ .name = "TtyDevice", .sig = "s", .getter = svc_prop_tty_device },
{ .name = "TtyBaud", .sig = "s", .getter = svc_prop_tty_baud },
{ .name = "TtyTerm", .sig = "s", .getter = svc_prop_tty_term },
{ .name = "TtyNoClear", .sig = "b", .getter = svc_prop_tty_no_clear },
{ .name = "TtyNoWait", .sig = "b", .getter = svc_prop_tty_no_wait },
{ .name = "TtyNoLogin", .sig = "b", .getter = svc_prop_tty_no_login },
{ .name = "TtyNoTty", .sig = "b", .getter = svc_prop_tty_no_tty },
{ .name = "TtyRescue", .sig = "b", .getter = svc_prop_tty_rescue },
{ NULL, NULL, NULL }
};
+2
View File
@@ -100,6 +100,8 @@
#define INIT_CMD_POWEROFF 22
#define INIT_CMD_SUSPEND 23
#define INIT_CMD_SWITCH_ROOT 24 /* Switch to new root filesystem */
#define INIT_CMD_SHUTDOWN 25 /* runlevel: REBOOT/HALT/POWEROFF, sleeptime: sec, data: msg */
#define INIT_CMD_SHUTDOWN_CANCEL 26
#define INIT_CMD_WDOG_HELLO 128 /* Watchdog register and hello */
#define INIT_CMD_SVC_ITER 129
#define INIT_CMD_SVC_QUERY 130
+3 -12
View File
@@ -137,22 +137,13 @@ static inline char *fgetval(const char *line, const char *key, char *sep)
return NULL;
ptr = strsep(&str, sep);
if (ptr && strcmp(ptr, key)) {
fail:
if (!str || strcmp(ptr, key)) {
free(copy);
return NULL;
}
/*
* Check if we should strip optional separator, e.g.,
* 'foo = bar' => '= bar' should be stripped to 'bar'
*/
while (strchr(sep, str[0])) {
ptr = strsep(&str, sep);
if (!ptr)
goto fail;
}
ptr = str;
/* strip optional separators, e.g., 'foo = bar' => 'bar' */
ptr = str + strspn(str, sep);
if (*ptr == '"' || *ptr == '\'') {
char *end = &ptr[strlen(ptr) - 1];
+439 -10
View File
@@ -1090,6 +1090,36 @@ static int do_reboot_dbus(const char *method)
}
#endif
/* Scheduled shutdown, see issue #149, @cmd is INIT_CMD_REBOOT, _HALT or _POWEROFF */
int do_shutdown_at(int cmd, int sec, const char *msg)
{
struct init_request rq = {
.magic = INIT_MAGIC,
.cmd = INIT_CMD_SHUTDOWN,
.runlevel = cmd,
.sleeptime = sec,
};
strlcpy(rq.data, msg ? msg : "", sizeof(rq.data));
return client_send(&rq, sizeof(rq));
}
int do_shutdown_cancel(void)
{
struct init_request rq = {
.magic = INIT_MAGIC,
.cmd = INIT_CMD_SHUTDOWN_CANCEL,
};
if (client_send(&rq, sizeof(rq))) {
if (rq.cmd == INIT_CMD_NACK)
warnx("%s", rq.data);
return 1;
}
return 0;
}
int do_reboot (char *arg)
{
#ifdef HAVE_DBUS
@@ -1445,6 +1475,16 @@ static int svc_compare(svc_t *svc, char *arg)
* from a raw svc_t on the legacy socket path or from Service1
* properties on the D-Bus path, rendered by the same printers.
*/
/* In the order of the script[] and dir[] members of svc_row */
#define NUM_SCRIPTS 6
static const char *script_names[NUM_SCRIPTS] = {
"exec-start-pre", "exec-start-ready", "exec-stop",
"exec-stop-post", "exec-reload", "exec-cleanup",
};
static const char *dir_names[NUM_SVCDIRS] = {
"runtime", "state", "cache", "logs", "config",
};
struct svc_row {
char ident[MAX_IDENT_LEN];
char state[16];
@@ -1465,9 +1505,61 @@ struct svc_row {
int32_t restart_tot;
int32_t restart_cnt;
int32_t restart_max; /* -1 = restart:always */
uint32_t restart_delay; /* seconds, before the next restart */
uint32_t restart_delay_max; /* restart-max-sec, 0 = not set */
int manual;
int forking;
int started;
/* Settings, only in the JSON output */
char name[MAX_ARG_LEN];
char id[MAX_ID_LEN];
uint32_t job;
uint32_t oldpid;
int dirty;
int removed;
int starting;
char rlimits[1024]; /* name=soft:hard,... */
char cgroup_name[16];
char cgroup_cfg[128];
uint32_t dir_mode[NUM_SVCDIRS];
int cgroup_delegate;
int protect;
int nowarn;
int flux_reload;
char notify[8];
char ifstmt[MAX_IDENT_LEN];
char provides[MAX_NUM_PROVIDES * MAX_COND_LEN];
char conflicts[MAX_ARG_LEN];
char supgroups[MAX_SUPGROUPS_LEN];
char caps[MAX_CMD_LEN];
char pam[MAX_ARG_LEN];
char stop_signal[16];
char stop_scope[8];
char reload_signal[8];
char oncrash[8];
char dir[NUM_SVCDIRS][MAX_ARG_LEN];
char preserve[8];
char script[NUM_SCRIPTS][MAX_CMD_LEN];
uint32_t script_tmo[NUM_SCRIPTS]; /* seconds */
char log_file[64];
char log_prio[20];
char log_ident[20];
char tty_dev[32];
char tty_baud[10];
char tty_term[10];
uint32_t stop_timeout; /* seconds */
uint32_t restart_sec; /* restart-sec, 0 = not set */
int remain;
int respawn;
int log;
int log_null;
int log_console;
int tty_noclear;
int tty_nowait;
int tty_nologin;
int tty_notty;
int tty_rescue;
};
static void fill_row_from_svc(struct svc_row *r, svc_t *svc)
@@ -1495,9 +1587,78 @@ static void fill_row_from_svc(struct svc_row *r, svc_t *svc)
r->restart_tot = (int32_t)svc->restart_tot;
r->restart_cnt = (int32_t)svc->restart_cnt;
r->restart_max = (int32_t)svc->restart_max;
r->restart_delay = (uint32_t)svc->restart_tmo / 1000;
r->restart_delay_max = (uint32_t)svc->restart_tmo_max / 1000;
r->manual = svc->manual;
r->forking = svc->forking;
r->started = svc->started;
strlcpy(r->notify, svc_notify_str(svc), sizeof(r->notify));
r->remain = svc->remain;
strlcpy(r->ifstmt, svc->ifstmt, sizeof(r->ifstmt));
svc_provides_str(svc, r->provides, sizeof(r->provides));
strlcpy(r->conflicts, svc->conflict, sizeof(r->conflicts));
strlcpy(r->supgroups, svc->supgroups, sizeof(r->supgroups));
strlcpy(r->caps, svc->capabilities, sizeof(r->caps));
strlcpy(r->pam, svc->pam, sizeof(r->pam));
snprintf(r->stop_signal, sizeof(r->stop_signal), "SIG%s", sig2str(svc->sighalt));
r->stop_timeout = (uint32_t)(svc->killdelay / 1000);
strlcpy(r->stop_scope, svc_scope_str(svc->stop_scope), sizeof(r->stop_scope));
strlcpy(r->reload_signal, svc->sighup ? "SIGHUP" : "none", sizeof(r->reload_signal));
r->restart_sec = (uint32_t)(svc->restart_saved / 1000);
r->respawn = svc->respawn;
strlcpy(r->name, svc->name, sizeof(r->name));
strlcpy(r->id, svc->id, sizeof(r->id));
r->job = (uint32_t)svc->job;
r->oldpid = (uint32_t)svc->oldpid;
r->dirty = svc->dirty;
r->removed = svc->removed;
r->starting = svc->starting;
rlimits2str(svc->rlimit, r->rlimits, sizeof(r->rlimits));
strlcpy(r->cgroup_name, svc->cgroup.name, sizeof(r->cgroup_name));
strlcpy(r->cgroup_cfg, svc->cgroup.cfg, sizeof(r->cgroup_cfg));
r->cgroup_delegate = svc->cgroup.delegate;
for (int i = 0; i < NUM_SVCDIRS; i++)
r->dir_mode[i] = (uint32_t)svc->dir_mode[i];
r->protect = svc->protect;
r->nowarn = svc->nowarn;
r->flux_reload = svc->flux_reload;
strlcpy(r->oncrash, svc_oncrash_str(svc), sizeof(r->oncrash));
strlcpy(r->dir[0], svc->runtime_dir, sizeof(r->dir[0]));
strlcpy(r->dir[1], svc->state_dir, sizeof(r->dir[1]));
strlcpy(r->dir[2], svc->cache_dir, sizeof(r->dir[2]));
strlcpy(r->dir[3], svc->logs_dir, sizeof(r->dir[3]));
strlcpy(r->dir[4], svc->config_dir, sizeof(r->dir[4]));
strlcpy(r->preserve, svc_preserve_str(svc), sizeof(r->preserve));
strlcpy(r->script[0], svc->pre_script, sizeof(r->script[0]));
r->script_tmo[0] = (uint32_t)(svc->pre_tmo / 1000);
strlcpy(r->script[1], svc->ready_script, sizeof(r->script[1]));
r->script_tmo[1] = (uint32_t)(svc->ready_tmo / 1000);
strlcpy(r->script[2], svc->stop_script, sizeof(r->script[2]));
r->script_tmo[2] = (uint32_t)(svc->stop_tmo / 1000);
strlcpy(r->script[3], svc->post_script, sizeof(r->script[3]));
r->script_tmo[3] = (uint32_t)(svc->post_tmo / 1000);
strlcpy(r->script[4], svc->reload_script, sizeof(r->script[4]));
r->script_tmo[4] = (uint32_t)(svc->reload_tmo / 1000);
strlcpy(r->script[5], svc->cleanup_script, sizeof(r->script[5]));
r->script_tmo[5] = (uint32_t)(svc->cleanup_tmo / 1000);
if (svc_is_tty(svc)) {
strlcpy(r->tty_dev, svc->dev, sizeof(r->tty_dev));
strlcpy(r->tty_baud, svc->baud, sizeof(r->tty_baud));
strlcpy(r->tty_term, svc->term, sizeof(r->tty_term));
r->tty_noclear = svc->noclear;
r->tty_nowait = svc->nowait;
r->tty_nologin = svc->nologin;
r->tty_notty = svc->notty;
r->tty_rescue = svc->rescue;
} else {
r->log = svc->log.enabled;
r->log_null = svc->log.null;
r->log_console = svc->log.console;
strlcpy(r->log_file, svc->log.file, sizeof(r->log_file));
strlcpy(r->log_prio, svc->log.prio, sizeof(r->log_prio));
strlcpy(r->log_ident, svc->log.ident, sizeof(r->log_ident));
}
}
static const char *pidfile_str(struct svc_row *r)
@@ -1666,6 +1827,176 @@ static char *json_escape(const char *str)
return buf;
}
static const char *json_bool(int val)
{
return val ? "true" : "false";
}
/* "a,b" as [ "a", "b" ], nothing when the list is empty */
static void json_list(FILE *fp, const char *indent, const char *key, const char *list)
{
char *buf = strdupa(list), *tok, *ptr;
const char *sep = "";
if (!list[0])
return;
fprintf(fp, "%s \"%s\": [", indent, key);
for (tok = strtok_r(buf, ",", &ptr); tok; tok = strtok_r(NULL, ",", &ptr)) {
fprintf(fp, "%s \"%s\"", sep, json_escape(tok));
sep = ",";
}
fprintf(fp, " ],\n");
}
/* "nofile=1024:unlimited,..." from rlimits2str() as an object */
static void json_rlimits(FILE *fp, const char *indent, const char *rlimits)
{
char *buf = strdupa(rlimits), *tok, *ptr;
const char *sep = "";
fprintf(fp, "%s \"rlimits\": {", indent);
for (tok = strtok_r(buf, ",", &ptr); tok; tok = strtok_r(NULL, ",", &ptr)) {
char *soft = strchr(tok, '='), *hard;
const char *q[2];
if (!soft || !(hard = strchr(soft, ':')))
continue;
*soft++ = 0;
*hard++ = 0;
/* unlimited is the only value that is not a number */
q[0] = soft[0] == 'u' ? "\"" : "";
q[1] = hard[0] == 'u' ? "\"" : "";
fprintf(fp, "%s\n%s \"%s\": { \"soft\": %s%s%s, \"hard\": %s%s%s }",
sep, indent, tok, q[0], soft, q[0], q[1], hard, q[1]);
sep = ",";
}
if (sep[0])
fprintf(fp, "\n%s ", indent);
fprintf(fp, "},\n");
}
/* The settings of a service, what the plain view leaves out */
static void json_settings(FILE *fp, struct svc_row *r, const char *indent)
{
const char *sep = "";
int i;
fprintf(fp, "%s \"name\": \"%s\",\n", indent, json_escape(r->name));
fprintf(fp, "%s \"id\": \"%s\",\n", indent, json_escape(r->id));
fprintf(fp,
"%s \"internal\": {\n"
"%s \"job\": %u,\n"
"%s \"oldpid\": %u,\n"
"%s \"starting\": %s,\n"
"%s \"dirty\": %s,\n"
"%s \"removed\": %s\n"
"%s },\n",
indent,
indent, r->job,
indent, r->oldpid,
indent, json_bool(r->starting),
indent, json_bool(r->dirty),
indent, json_bool(r->removed),
indent);
fprintf(fp, "%s \"protected\": %s,\n", indent, json_bool(r->protect));
fprintf(fp, "%s \"nowarn\": %s,\n", indent, json_bool(r->nowarn));
fprintf(fp, "%s \"notify\": \"%s\",\n", indent, r->notify);
fprintf(fp, "%s \"remain\": %s,\n", indent, json_bool(r->remain));
if (r->ifstmt[0])
fprintf(fp, "%s \"if\": \"%s\",\n", indent, json_escape(r->ifstmt));
json_list(fp, indent, "provides", r->provides);
json_list(fp, indent, "conflicts", r->conflicts);
fprintf(fp,
"%s \"stop\": {\n"
"%s \"signal\": \"%s\",\n"
"%s \"timeout\": %u,\n"
"%s \"scope\": \"%s\"\n"
"%s },\n"
"%s \"reload\": {\n"
"%s \"signal\": \"%s\",\n"
"%s \"propagate\": %s\n"
"%s },\n",
indent,
indent, r->stop_signal,
indent, r->stop_timeout,
indent, r->stop_scope,
indent,
indent,
indent, r->reload_signal,
indent, json_bool(r->flux_reload),
indent);
fprintf(fp, "%s \"scripts\": {", indent);
for (i = 0; i < NUM_SCRIPTS; i++) {
if (!r->script[i][0])
continue;
fprintf(fp, "%s\n%s \"%s\": { \"command\": \"%s\", \"timeout\": %u }",
sep, indent, script_names[i], json_escape(r->script[i]), r->script_tmo[i]);
sep = ",";
}
if (sep[0])
fprintf(fp, "\n%s ", indent);
fprintf(fp, "},\n");
sep = "";
fprintf(fp, "%s \"directories\": {", indent);
for (i = 0; i < NUM_SVCDIRS; i++) {
if (!r->dir[i][0])
continue;
fprintf(fp, "%s\n%s \"%s\": { \"name\": \"%s\", \"mode\": \"%04o\" }",
sep, indent, dir_names[i], json_escape(r->dir[i]), r->dir_mode[i]);
sep = ",";
}
if (sep[0])
fprintf(fp, ",\n%s \"preserve\": \"%s\"\n%s ", indent, r->preserve, indent);
fprintf(fp, "},\n");
fprintf(fp, "%s \"cgroup-config\": {\n", indent);
fprintf(fp, "%s \"group\": \"%s\",\n", indent, json_escape(r->cgroup_name));
fprintf(fp, "%s \"config\": \"%s\",\n", indent, json_escape(r->cgroup_cfg));
fprintf(fp, "%s \"delegate\": %s\n%s },\n", indent, json_bool(r->cgroup_delegate), indent);
json_rlimits(fp, indent, r->rlimits);
if (!strcmp(r->type, "tty")) {
fprintf(fp, "%s \"tty\": {\n", indent);
fprintf(fp, "%s \"device\": \"%s\",\n", indent, json_escape(r->tty_dev));
fprintf(fp, "%s \"baud\": \"%s\",\n", indent, r->tty_baud);
fprintf(fp, "%s \"term\": \"%s\",\n", indent, json_escape(r->tty_term));
fprintf(fp,
"%s \"noclear\": %s,\n"
"%s \"nowait\": %s,\n"
"%s \"nologin\": %s,\n"
"%s \"notty\": %s,\n"
"%s \"rescue\": %s\n"
"%s },\n",
indent, json_bool(r->tty_noclear),
indent, json_bool(r->tty_nowait),
indent, json_bool(r->tty_nologin),
indent, json_bool(r->tty_notty),
indent, json_bool(r->tty_rescue),
indent);
} else {
fprintf(fp,
"%s \"log\": {\n"
"%s \"enabled\": %s,\n"
"%s \"null\": %s,\n"
"%s \"console\": %s,\n",
indent,
indent, json_bool(r->log),
indent, json_bool(r->log_null),
indent, json_bool(r->log_console));
fprintf(fp, "%s \"file\": \"%s\",\n", indent, json_escape(r->log_file));
fprintf(fp, "%s \"priority\": \"%s\",\n", indent, json_escape(r->log_prio));
fprintf(fp, "%s \"identity\": \"%s\"\n%s },\n", indent, json_escape(r->log_ident), indent);
}
}
static int json_status_one(FILE *fp, struct svc_row *r, char *indent, int prev)
{
const char *pidfn = pidfile_str(r);
@@ -1721,12 +2052,34 @@ static int json_status_one(FILE *fp, struct svc_row *r, char *indent, int prev)
fprintf(fp,
"%s \"condition\": %s,\n", indent, buf);
if (r->manual)
fprintf(fp,
"%s \"starts\": %u,\n", indent, r->starts);
fprintf(fp,
"%s \"restarts\": %d,\n", indent, r->restart_tot); /* XXX: add restart_cnt and restart_max */
"%s \"manual\": %s,\n"
"%s \"started\": %s,\n"
"%s \"starts\": %u,\n"
"%s \"restarts\": %d,\n"
"%s \"restart\": {\n"
"%s \"count\": %d,\n"
"%s \"max\": %d,\n"
"%s \"sec\": %u,\n"
"%s \"delay\": %u,\n"
"%s \"limit\": %u,\n"
"%s \"respawn\": %s,\n"
"%s \"oncrash\": \"%s\"\n"
"%s },\n",
indent, json_bool(r->manual),
indent, json_bool(r->started),
indent, r->starts,
indent, r->restart_tot,
indent,
indent, r->restart_cnt,
indent, r->restart_max,
indent, r->restart_sec,
indent, r->restart_delay,
indent, r->restart_delay_max,
indent, json_bool(r->respawn),
indent, r->oncrash,
indent);
json_settings(fp, r, indent);
/* Add memory and CPU information if cgroup support is available */
if (cgrp && r->pid > 1) {
@@ -1836,14 +2189,19 @@ static int json_status_one(FILE *fp, struct svc_row *r, char *indent, int prev)
"%s \"pidfile\": \"%s\",\n"
"%s \"pid\": %u,\n"
"%s \"user\": \"%s\",\n"
"%s \"group\": \"%s\",\n"
"%s \"uptime\": %ld,\n"
"%s \"runlevels\": %s\n"
"%s}",
"%s \"group\": \"%s\",\n",
indent, pidfn,
indent, r->pid,
indent, r->user,
indent, r->grp,
indent, r->grp);
json_list(fp, indent, "groups", r->supgroups);
json_list(fp, indent, "capabilities", r->caps);
if (r->pam[0])
fprintf(fp, "%s \"pam\": \"%s\",\n", indent, json_escape(r->pam));
fprintf(fp,
"%s \"uptime\": %ld,\n"
"%s \"runlevels\": %s\n"
"%s}",
indent, (long)r->uptime,
indent, runlevel_arr((int)r->runlevels),
indent);
@@ -1910,6 +2268,9 @@ static int show_one_row(struct svc_row *r)
printf(" Starts : %u\n", r->starts);
printf(" Restarts : %d (%d/%d)\n",
r->restart_tot, r->restart_cnt, r->restart_max);
if (r->restart_delay_max)
printf(" Restart in : %u sec (max %u)\n",
r->restart_delay, r->restart_delay_max);
printf(" Runlevels : %s\n",
runlevel_string(runlevel, (int)r->runlevels));
@@ -2025,9 +2386,77 @@ static const struct row_field {
ROW_U32 ("RestartsTotal", restart_tot),
ROW_U32 ("RestartCount", restart_cnt),
ROW_U32 ("RestartMax", restart_max),
ROW_U32 ("RestartDelay", restart_delay),
ROW_U32 ("RestartDelayMax", restart_delay_max),
ROW_BOOL("ManualStart", manual),
ROW_BOOL("Forking", forking),
ROW_BOOL("Started", started),
ROW_STR ("Notify", notify),
ROW_BOOL("Remain", remain),
ROW_STR ("If", ifstmt),
ROW_STR ("Provides", provides),
ROW_STR ("Conflicts", conflicts),
ROW_STR ("ExtraGroups", supgroups),
ROW_STR ("Capabilities", caps),
ROW_STR ("Pam", pam),
ROW_STR ("StopSignal", stop_signal),
ROW_U32 ("StopTimeout", stop_timeout),
ROW_STR ("StopScope", stop_scope),
ROW_STR ("ReloadSignal", reload_signal),
ROW_U32 ("RestartSec", restart_sec),
ROW_BOOL("Respawn", respawn),
ROW_STR ("Name", name),
ROW_STR ("Id", id),
ROW_U32 ("Job", job),
ROW_U32 ("OldPid", oldpid),
ROW_BOOL("Dirty", dirty),
ROW_BOOL("Removed", removed),
ROW_BOOL("Starting", starting),
ROW_STR ("Rlimits", rlimits),
ROW_STR ("CgroupName", cgroup_name),
ROW_STR ("CgroupConfig", cgroup_cfg),
ROW_BOOL("CgroupDelegate", cgroup_delegate),
ROW_U32 ("RuntimeDirMode", dir_mode[0]),
ROW_U32 ("StateDirMode", dir_mode[1]),
ROW_U32 ("CacheDirMode", dir_mode[2]),
ROW_U32 ("LogsDirMode", dir_mode[3]),
ROW_U32 ("ConfigDirMode", dir_mode[4]),
ROW_BOOL("Protected", protect),
ROW_BOOL("NoWarn", nowarn),
ROW_BOOL("ReloadPropagate", flux_reload),
ROW_STR ("OnCrash", oncrash),
ROW_STR ("RuntimeDir", dir[0]),
ROW_STR ("StateDir", dir[1]),
ROW_STR ("CacheDir", dir[2]),
ROW_STR ("LogsDir", dir[3]),
ROW_STR ("ConfigDir", dir[4]),
ROW_STR ("RuntimeDirPreserve", preserve),
ROW_STR ("ExecStartPre", script[0]),
ROW_U32 ("ExecStartPreTimeout", script_tmo[0]),
ROW_STR ("ExecStartReady", script[1]),
ROW_U32 ("ExecStartReadyTimeout", script_tmo[1]),
ROW_STR ("ExecStop", script[2]),
ROW_U32 ("ExecStopTimeout", script_tmo[2]),
ROW_STR ("ExecStopPost", script[3]),
ROW_U32 ("ExecStopPostTimeout", script_tmo[3]),
ROW_STR ("ExecReload", script[4]),
ROW_U32 ("ExecReloadTimeout", script_tmo[4]),
ROW_STR ("ExecCleanup", script[5]),
ROW_U32 ("ExecCleanupTimeout", script_tmo[5]),
ROW_BOOL("Log", log),
ROW_BOOL("LogNull", log_null),
ROW_BOOL("LogConsole", log_console),
ROW_STR ("LogFile", log_file),
ROW_STR ("LogPriority", log_prio),
ROW_STR ("LogIdentity", log_ident),
ROW_STR ("TtyDevice", tty_dev),
ROW_STR ("TtyBaud", tty_baud),
ROW_STR ("TtyTerm", tty_term),
ROW_BOOL("TtyNoClear", tty_noclear),
ROW_BOOL("TtyNoWait", tty_nowait),
ROW_BOOL("TtyNoLogin", tty_nologin),
ROW_BOOL("TtyNoTty", tty_notty),
ROW_BOOL("TtyRescue", tty_rescue),
{ NULL, 0, 0, 0 }
};
+107 -9
View File
@@ -28,15 +28,17 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "finit.h"
#include "util.h"
typedef enum {
CMD_UNKNOWN = -1,
CMD_REBOOT = 0,
CMD_HALT,
CMD_POWEROFF,
CMD_SUSPEND,
CMD_UNKNOWN = -1,
CMD_REBOOT = INIT_CMD_REBOOT,
CMD_HALT = INIT_CMD_HALT,
CMD_POWEROFF = INIT_CMD_POWEROFF,
CMD_SUSPEND = INIT_CMD_SUSPEND,
} cmd_t;
static cmd_t cmd = CMD_UNKNOWN;
@@ -49,6 +51,8 @@ extern int do_reboot (char *arg);
extern int do_halt (char *arg);
extern int do_poweroff(char *arg);
extern int do_suspend (char *arg);
extern int do_shutdown_at(int cmd, int sec, const char *msg);
extern int do_shutdown_cancel(void);
static void transform(char *nm)
@@ -101,18 +105,83 @@ static void do_kill(int signo, char *msg)
do_sleep(5);
}
#define MAX_MIN (365 * 24 * 60) /* Finit takes no more than a year */
/* now, +MIN, or HH:MM, as seconds from now, or -1 */
static int parse_time(const char *arg)
{
struct tm tm;
time_t t, at;
int hh, mm;
char *end;
long min;
char c;
if (!strcmp(arg, "now"))
return 0;
if (arg[0] == '+') {
min = strtol(&arg[1], &end, 10);
if (end == &arg[1] || *end || min < 0 || min > MAX_MIN)
return -1;
return (int)min * 60;
}
if (sscanf(arg, "%d:%d%c", &hh, &mm, &c) != 2 || hh < 0 || hh > 23 || mm < 0 || mm > 59)
return -1;
/* Next time the clock shows HH:MM, today or tomorrow */
t = time(NULL);
localtime_r(&t, &tm);
tm.tm_hour = hh;
tm.tm_min = mm;
tm.tm_sec = 0;
tm.tm_isdst = -1;
at = mktime(&tm);
if (at <= t) {
tm.tm_mday++;
tm.tm_isdst = -1;
at = mktime(&tm);
}
return (int)(at - t);
}
static int schedule(int sec, const char *text)
{
char tm[32];
time_t at;
if (do_shutdown_at(cmd, sec, text))
errx(1, "Failed scheduling %s.", msg);
if (sec > 0) {
at = time(NULL) + sec;
strftime(tm, sizeof(tm), "%a %Y-%m-%d %H:%M", localtime(&at));
printf("Scheduled %s at %s, use 'shutdown -c' to cancel.\n", msg, tm);
}
return 0;
}
static int usage(int rc)
{
fprintf(stderr, "Usage: %s [OPTIONS]\n\n"
int sd = !strcmp(prognm, "shutdown");
fprintf(stderr, "Usage: %s [OPTIONS]%s\n\n"
"Options:\n"
" -?, --help This help text\n"
" -c Cancel a scheduled shutdown\n"
" -f, --force Force unsafe %s now, do not contact the init system.\n"
" --halt Halt system, regardless of how the command is called.\n"
" -h Halt or power off after shutdown.\n"
" -P, --poweroff Power-off system, regardless of how the command is called.\n"
" -r, --reboot Reboot system, regardless of how the command is called.\n"
" -t, --timeout=SEC Force reboot/shutdown after a given timeout\n"
"\n", prognm, msg);
"\n", prognm, sd ? " [TIME [MESSAGE]]" : "", msg);
if (sd)
fprintf(stderr, "TIME is now, +MIN, or HH:MM. Logged-in users are sent MESSAGE as a\n"
"warning, and from five minutes before, new logins are refused.\n\n");
return rc;
}
@@ -128,17 +197,21 @@ int reboot_main(int argc, char *argv[])
{"timeout", 1, NULL, 't'},
{NULL, 0, NULL, 0}
};
int c, force = 0;
int c, force = 0, cancel = 0;
int tmp;
/* Initial command taken from program name */
transform(prognm);
while ((c = getopt_long(argc, argv, "h?fHPprt:", long_options, NULL)) != EOF) {
while ((c = getopt_long(argc, argv, "h?cfHPprt:", long_options, NULL)) != EOF) {
switch(c) {
case '?':
return usage(0);
case 'c':
cancel = 1;
break;
case 'f':
force = 1;
break;
@@ -176,6 +249,31 @@ int reboot_main(int argc, char *argv[])
if (getenv("SULOGIN"))
force = 1;
if (cancel)
return do_shutdown_cancel();
/* shutdown [opts] [TIME [MESSAGE]], see issue #149 */
if (!strcmp(prognm, "shutdown") && optind < argc) {
char text[256] = "";
int sec, i;
sec = parse_time(argv[optind]);
if (sec < 0)
errx(1, "Invalid time '%s', use now, +MIN, or HH:MM.", argv[optind]);
for (i = optind + 1; i < argc; i++) {
if (text[0])
strlcat(text, " ", sizeof(text));
strlcat(text, argv[i], sizeof(text));
}
if (sec > 0 || text[0]) {
if (force)
errx(1, "Cannot schedule a forced %s.", msg);
return schedule(sec, text);
}
}
if (force) {
sync();
+299 -105
View File
@@ -65,8 +65,6 @@
#include "utmp-api.h"
#include "schedule.h"
#define NOTIFY_PATH "@run/finit/notify/%d"
int logfile_size_max = 200000; /* 200 kB */
int logfile_count_max = 5;
@@ -653,7 +651,7 @@ static void service_mkdirs(svc_t *svc, uid_t uid, gid_t gid)
for (i = 0; i < NELEMS(svcdirs); i++) {
uid_t u = svcdirs[i].chown ? uid : (uid_t)-1;
gid_t g = svcdirs[i].chown ? gid : 0;
gid_t g = svcdirs[i].chown ? gid : (gid_t)-1;
struct stat st;
char *ptr;
@@ -780,20 +778,22 @@ static pid_t service_fork(svc_t *svc)
{
gid_t supgids[NGROUPS_MAX];
int ngroups = NGROUPS_MAX;
int i, j, n = 0;
char *sup, *ptr;
int j, n = 0;
/* Get user's supplementary groups from /etc/group */
if (getgrouplist(svc->username, gid, supgids, &ngroups) >= 0)
n = ngroups;
/* Add explicitly configured supplementary groups */
for (i = 0; i < svc->num_supgroups && n < NGROUPS_MAX; i++) {
int g = getgroup(svc->supgroups[i]);
for (sup = strtok_r(strdupa(svc->supgroups), ",", &ptr);
sup && n < NGROUPS_MAX; sup = strtok_r(NULL, ",", &ptr)) {
int g = getgroup(sup);
int found = 0;
if (g < 0) {
warn("%s: unknown supplementary group '%s'",
svc_ident(svc, NULL, 0), svc->supgroups[i]);
warnx("%s: unknown supplementary group '%s'",
svc_ident(svc, NULL, 0), sup);
continue;
}
/* Skip if already in list from /etc/group */
@@ -893,6 +893,26 @@ static int pam_refused(svc_t *svc)
return 1;
}
/*
* Bind the systemd notify socket before fork since the daemon may
* notify right away, see issue #505. The kernel picks a unique abstract
* address, which NOTIFY_SOCKET spells with a leading '@'.
*/
static int notify_bind(int sd, char *path, size_t len)
{
struct sockaddr_un sun = { .sun_family = AF_UNIX };
socklen_t slen = sizeof(sun);
if (bind(sd, (struct sockaddr *)&sun, sizeof(sa_family_t)) ||
getsockname(sd, (struct sockaddr *)&sun, &slen))
return -1;
slen -= offsetof(struct sockaddr_un, sun_path) + 1;
snprintf(path, len, "@%.*s", (int)slen, &sun.sun_path[1]);
return 0;
}
/**
* service_start - Start service
* @svc: Service to start
@@ -902,6 +922,7 @@ static int pam_refused(svc_t *svc)
*/
static int service_start(svc_t *svc)
{
char notify[sizeof(struct sockaddr_un)];
int result = 0, do_progress = 1;
char cmdline[CMD_SIZE] = "";
sigset_t nmask, omask;
@@ -985,6 +1006,12 @@ static int service_start(svc_t *svc)
svc_missing(svc);
return 1;
}
if (notify_bind(sd, notify, sizeof(notify))) {
err(1, "%s: failed binding to notify socket", svc_ident(svc, NULL, 0));
close(sd);
svc_missing(svc);
return 1;
}
break;
default:
break;
@@ -1023,31 +1050,16 @@ static int service_start(svc_t *svc)
result = -1;
goto fail;
} else if (pid > 0) {
struct sockaddr_un sun;
size_t len;
dbg("Starting %s as PID %d", svc_ident(svc, NULL, 0), pid);
svc->pid = pid;
svc->start_time = jiffies();
if (fd != -1)
close(fd); /* client-end of pipefd for s6 notify */
switch (svc->notify) {
case SVC_NOTIFY_SYSTEMD:
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
snprintf(sun.sun_path, sizeof(sun.sun_path), NOTIFY_PATH, pid);
len = strlen(sun.sun_path);
sun.sun_path[0] = 0;
result = bind(sd, (struct sockaddr *)&sun, offsetof(struct sockaddr_un, sun_path) + len);
if (result == -1) {
err(1, "%s: failed binding to notify socket", svc_ident(svc, NULL, 0));
close(sd);
break;
}
/* fallthrough */
case SVC_NOTIFY_S6:
if (svc->notify == SVC_NOTIFY_S6)
close(fd); /* client-end of pipefd for s6 notify */
result = uev_io_init(ctx, &svc->notify_watcher, service_notify_cb, svc, sd, UEV_READ);
if (result < 0) {
err(1, "%s: failed setting up notify callback", svc_ident(svc, NULL, 0));
@@ -1058,7 +1070,6 @@ static int service_start(svc_t *svc)
break;
}
} else { /* pid == 0 */
char str[strlen(NOTIFY_PATH) + 32];
char *args[MAX_NUM_SVC_ARGS + 3];
int status;
@@ -1067,8 +1078,7 @@ static int service_start(svc_t *svc)
switch (svc->notify) {
case SVC_NOTIFY_SYSTEMD:
snprintf(str, sizeof(str), NOTIFY_PATH, getpid());
setenv("NOTIFY_SOCKET", str, 1);
setenv("NOTIFY_SOCKET", notify, 1);
/* fallthrough */
case SVC_NOTIFY_S6:
close(sd);
@@ -1242,6 +1252,15 @@ fail:
return result;
}
/* The cgroup of the service, or the process group of its main PID */
static int service_signal_all(svc_t *svc, int sig)
{
if (svc_is_cgroup_scope(svc) && !cgroup_signal_svc(svc, sig))
return 0;
return kill(-svc->pid, sig);
}
/**
* service_kill - Forcefully terminate a service
* @param svc Service to kill
@@ -1485,8 +1504,11 @@ int service_stop(svc_t *svc)
* entire group. This gives the process time to properly stop
* and/or forward TERM to its children. If it does not respond
* in within a reasonable timeout we SIGKILL the entire group.
* With stop-scope cgroup, all of the cgroup gets SIGTERM,
* if the service has one.
*/
rc = kill(svc->pid, svc->sighalt);
if (svc->stop_scope != SVC_SCOPE_CGROUP || cgroup_signal_svc(svc, svc->sighalt))
rc = kill(svc->pid, svc->sighalt);
dbg("kill(%d, %d) => rc %d, errno %d", svc->pid, svc->sighalt, rc, errno);
/* PID lost or forking process never really started */
if (rc == -1 && (errno == ESRCH || errno == ENOENT))
@@ -1599,6 +1621,15 @@ int service_restart_now(svc_t *svc)
if (!svc)
return 1;
if (svc_is_runtask(svc) && svc_is_remain(svc) &&
svc->state == SVC_DONE_STATE) {
service_timeout_cancel(svc);
svc_restarting(svc);
service_step(svc);
return 0;
}
if (!svc_is_running(svc))
return service_start_now(svc);
@@ -1803,6 +1834,24 @@ static char *parse_args(char **line)
return NULL;
}
/*
* Match an option that takes a value, @opt on its own or followed by
* one of the characters in @sep, e.g. "log" and "log:/path". Returns
* the value, or NULL, so a command like logger or pidof is not taken
* for an option.
*/
static char *is_opt(char *tok, const char *opt, const char *sep)
{
size_t len = strlen(opt);
if (strncasecmp(tok, opt, len))
return NULL;
if (tok[len] && !strchr(sep, tok[len]))
return NULL;
return &tok[len];
}
/*
* log:/path/to/logfile,priority:facility.level,tag:ident
*/
@@ -1964,6 +2013,51 @@ static void parse_sighalt(svc_t *svc, char *arg)
svc->sighalt = signo;
}
static svc_scope_t parse_scope(svc_t *svc, const char *arg)
{
svc_scope_t i;
if (!arg)
return SVC_SCOPE_PGROUP;
for (i = SVC_SCOPE_PGROUP; i <= SVC_SCOPE_MIXED; i++) {
if (!strcmp(arg, svc_scope_str(i)))
return i;
}
warnx("%s: unknown stop-scope '%s', using pgroup", svc_ident(svc, NULL, 0), arg);
return SVC_SCOPE_PGROUP;
}
/*
* A cgroup scope also reaches other services sharing the cgroup.
* Only checked for a new or changed service, not on every reload.
*/
static void scope_check(svc_t *svc)
{
char a[MAX_ARG_LEN], b[MAX_ARG_LEN];
svc_t *s, *iter = NULL;
if (!svc_is_changed(svc) || !cgroup_svc_has(svc))
return;
cgroup_svc_name(svc, a, sizeof(a));
for (s = svc_iterator(&iter, 1); s; s = svc_iterator(&iter, 0)) {
svc_t *scoped = svc_is_cgroup_scope(svc) ? svc : s;
if (s == svc || !svc_is_cgroup_scope(scoped))
continue;
if (svc_is_tty(s) != svc_is_tty(svc) || strcmp(s->cgroup.name, svc->cgroup.name) ||
strcmp(cgroup_svc_name(s, b, sizeof(b)), a))
continue;
logit(LOG_WARNING, "%s: stop-scope %s also reaches %s, give it a cgroup name of its own",
svc_ident(scoped, a, sizeof(a)), svc_scope_str(scoped->stop_scope),
svc_ident(scoped == svc ? s : svc, b, sizeof(b)));
return;
}
}
static void parse_killdelay(svc_t *svc, char *delay)
{
const char *errstr;
@@ -2147,9 +2241,10 @@ static void parse_cmdline_args(svc_t *svc, char *cmd, char **args)
}
/**
* service_register - Register service, task or run commands
* service_register_desc - Register service, task or run commands
* @type: %SVC_TYPE_SERVICE(0), %SVC_TYPE_TASK(1), %SVC_TYPE_RUN(2)
* @cfg: Configuration, complete command, with -- for description text
* @cfg: Configuration, complete command, without description text
* @desc: Description text, or %NULL
* @rlimit: Limits for this service/task/run, may be global limits
* @file: The file name service was loaded from
*
@@ -2207,11 +2302,12 @@ static void parse_cmdline_args(svc_t *svc, char *cmd, char **args)
* skipped on purpose -- conditional loading, bootstrap over, nowarn --
* also returns %NULL, with @errno zero.
*/
svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
svc_t *service_register_desc(int type, char *cfg, const char *desc,
struct rlimit rlimit[], char *file)
{
char *cmd, *desc, *runlevels = NULL, *cond = NULL;
char *cmd, *runlevels = NULL, *cond = NULL;
char *username = NULL, *log = NULL, *pid = NULL;
char *name = NULL, *halt = NULL, *delay = NULL;
char *name = NULL, *halt = NULL, *delay = NULL, *scope = NULL;
char *id = NULL, *env = NULL, *cgroup = NULL;
char *pre_script = NULL, *post_script = NULL;
char *ready_script = NULL, *conflict = NULL;
@@ -2229,6 +2325,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
int forking = 0, manual = 0, remain = 0, nowarn = 0;
int restart_max = SVC_RESPAWN_MAX;
int restart_tmo = 0;
int restart_tmo_max = 0;
unsigned oncrash_action = SVC_ONCRASH_IGNORE;
char *line, *args;
svc_t *svc;
@@ -2245,24 +2342,6 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
return NULL;
}
desc = strstr(line, "-- ");
if (desc) {
*desc = 0;
desc += 3;
while (*desc && isblank(*desc))
desc++;
} else {
int pos;
/* Find "--\n" to denote empty/no description */
pos = (int)strlen(line) - 2;
if (pos > 0 && !strcmp(&line[pos], "--")) {
line[pos] = 0;
desc = &line[pos];
}
}
args = line;
cmd = parse_args(&args);
if (!cmd) {
@@ -2272,6 +2351,10 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
return NULL;
}
/*
* Options ending in ':' can be prefix matched, the rest must match
* the whole token or a command like logger is taken for one.
*/
while (cmd) {
char *arg;
@@ -2286,19 +2369,19 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
cond = &cmd[1];
else if (cmd[0] == ':') /* :ID */
id = &cmd[1];
else if (MATCH_CMD(cmd, "log", arg))
else if (is_opt(cmd, "log", ":"))
log = cmd;
else if (MATCH_CMD(cmd, "pid", arg))
else if (is_opt(cmd, "pid", ":"))
pid = cmd;
else if (MATCH_CMD(cmd, "name:", arg))
name = cmd;
else if (MATCH_CMD(cmd, "notify:", arg))
notify = arg;
else if (MATCH_CMD(cmd, "type:forking", arg))
else if (!strcasecmp(cmd, "type:forking"))
forking = 1;
else if (MATCH_CMD(cmd, "manual:yes", arg))
else if (!strcasecmp(cmd, "manual:yes"))
manual = 1;
else if (MATCH_CMD(cmd, "remain:yes", arg))
else if (!strcasecmp(cmd, "remain:yes"))
remain = 1;
else if (MATCH_CMD(cmd, "restart:", arg)) {
if (MATCH_CMD(arg, "always", arg))
@@ -2306,13 +2389,20 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
else
restart_max = atoi(arg);
}
else if (MATCH_CMD(cmd, "restarttmo:", arg)) /* compat alias */
else if (MATCH_CMD(cmd, "restart-sec:", arg) ||
MATCH_CMD(cmd, "restart_sec:", arg) || /* compat alias */
MATCH_CMD(cmd, "restarttmo:", arg)) /* compat alias */
restart_tmo = atoi(arg) * 1000;
else if (MATCH_CMD(cmd, "restart_sec:", arg))
restart_tmo = atoi(arg) * 1000;
else if (MATCH_CMD(cmd, "norestart", arg))
else if (MATCH_CMD(cmd, "restart-max-sec:", arg)) {
const char *errstr;
restart_tmo_max = (int)strtonum(arg, 0, 86400, &errstr) * 1000;
if (errstr)
warnx("restart-max-sec %s is %s (0-86400), ignoring", arg, errstr);
}
else if (!strcasecmp(cmd, "norestart"))
restart_max = 0;
else if (MATCH_CMD(cmd, "nowarn", arg))
else if (!strcasecmp(cmd, "nowarn"))
nowarn = 1;
else if (MATCH_CMD(cmd, "oncrash:", arg)) {
if (MATCH_CMD(arg, "reboot", arg))
@@ -2320,12 +2410,14 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
if (MATCH_CMD(arg, "script", arg))
oncrash_action = SVC_ONCRASH_SCRIPT;
}
else if (MATCH_CMD(cmd, "respawn", arg))
else if (!strcasecmp(cmd, "respawn"))
respawn = 1;
else if (MATCH_CMD(cmd, "halt:", arg))
halt = arg;
else if (MATCH_CMD(cmd, "kill:", arg))
delay = arg;
else if (MATCH_CMD(cmd, "stop-scope:", arg))
scope = arg;
else if (MATCH_CMD(cmd, "pre:", arg))
pre_script = arg;
else if (MATCH_CMD(cmd, "post:", arg))
@@ -2345,7 +2437,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
else if (MATCH_CMD(cmd, "tty:", arg))
ctty = arg;
/* catch both cgroup: and cgroup. handled in parse_cgroup() */
else if (MATCH_CMD(cmd, "cgroup", arg))
else if ((arg = is_opt(cmd, "cgroup", ".:")))
cgroup = arg;
else if (MATCH_CMD(cmd, "conflict:", arg))
conflict = arg;
@@ -2475,10 +2567,13 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
svc_unblock(svc);
}
svc->group[0] = 0;
svc->supgroups[0] = 0;
if (username) {
char *ptr = strchr(username, ':');
if (ptr) {
size_t len = sizeof(svc->supgroups);
char *sup;
*ptr++ = 0;
@@ -2486,20 +2581,15 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
sup = strchr(ptr, ',');
if (sup) {
*sup++ = 0;
svc->num_supgroups = 0;
while (sup) {
char *next = strchr(sup, ',');
if (next)
*next++ = 0;
if (svc->num_supgroups >= MAX_NUM_SUPGROUPS) {
warn("%s: too many supplementary groups, max %d",
svc->cmd, MAX_NUM_SUPGROUPS);
break;
}
strlcpy(svc->supgroups[svc->num_supgroups], sup,
sizeof(svc->supgroups[0]));
svc->num_supgroups++;
sup = next;
if (strlcpy(svc->supgroups, sup, len) >= len) {
/* Drop the cut-off name, it may match another group */
sup = strrchr(svc->supgroups, ',');
if (sup)
*sup = 0;
else
svc->supgroups[0] = 0;
warnx("%s: supplementary group list too long, max %zu characters",
svc->cmd, len - 1);
}
}
strlcpy(svc->group, ptr, sizeof(svc->group));
@@ -2548,6 +2638,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
parse_killdelay(svc, delay);
else
svc->killdelay = SVC_TERM_TIMEOUT;
svc->stop_scope = parse_scope(svc, scope);
if (pre_script)
parse_script(svc, "pre", pre_script, &svc->pre_tmo, svc->pre_script, sizeof(svc->pre_script));
else
@@ -2654,6 +2745,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
svc->forking = forking;
svc->restart_max = restart_max;
svc->restart_tmo = restart_tmo;
svc->restart_tmo_max = restart_tmo_max;
svc->oncrash_action = oncrash_action;
/* Decode any (optional) pid:/optional/path/to/file.pid */
@@ -2686,6 +2778,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
/* TTYs need a longer default to throttle errors (e.g., missing device) */
if (svc_is_tty(svc) && svc->restart_tmo == 0)
svc->restart_tmo = 2000;
svc->restart_saved = svc->restart_tmo;
/* Set configured limits */
memcpy(svc->rlimit, rlimit, sizeof(svc->rlimit));
@@ -2713,6 +2806,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
svc_mark_dirty(svc);
svc_enable(svc);
scope_check(svc);
/* for finit native services only, e.g. plugins/hotplug.c */
if (!file)
@@ -2730,6 +2824,45 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
return svc;
}
/**
* service_register - Register from a legacy one-liner
* @type: %SVC_TYPE_SERVICE(0), %SVC_TYPE_TASK(1), %SVC_TYPE_RUN(2)
* @cfg: Configuration, complete command, with -- for description text
* @rlimit: Limits for this service/task/run, may be global limits
* @file: The file name service was loaded from
*
* The first "-- " in @cfg starts the description, the rest is handed
* to service_register_desc().
*/
svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
{
char *line, *desc;
if (!cfg)
return service_register_desc(type, cfg, NULL, rlimit, file);
line = strdupa(cfg);
desc = strstr(line, "-- ");
if (desc) {
*desc = 0;
desc += 3;
while (*desc && isblank(*desc))
desc++;
} else {
int pos;
/* Find "--\n" to denote empty/no description */
pos = (int)strlen(line) - 2;
if (pos > 0 && !strcmp(&line[pos], "--")) {
line[pos] = 0;
desc = &line[pos];
}
}
return service_register_desc(type, line, desc, rlimit, file);
}
/*
* This function is called at the end of a runlevel change or reload
* command to delete all remnants of removed services.
@@ -2816,9 +2949,11 @@ void service_monitor(pid_t lost, int status)
logit(LOG_CONSOLE | LOG_NOTICE, "Stopped %s[%d]", svc_ident(svc, NULL, 0), lost);
}
/* Terminate any children in the same proess group, e.g. logit */
dbg("Killing lingering children in same process group ...");
kill(-svc->pid, SIGKILL);
/* Terminate lingering children, e.g. logit, unless stop-scope says not to */
if (svc->stop_scope != SVC_SCOPE_PROCESS) {
dbg("Killing lingering children ...");
service_signal_all(svc, SIGKILL);
}
/* Try removing PID file (in case service does not clean up after itself) */
if (svc_is_daemon(svc) || svc_is_tty(svc)) {
@@ -3132,10 +3267,61 @@ static void service_cleanup_script(svc_t *svc)
service_timeout_after(svc, svc->cleanup_tmo, service_kill_script);
}
/* Doubles with the instability index, up to restart-max-sec, issue #306 */
static int restart_backoff(svc_t *svc, int cnt)
{
int tmo = svc->restart_saved;
/* No restart-sec, the first restart was immediate */
if (tmo < 1000) {
tmo = 2000;
cnt--;
}
while (cnt-- > 0 && tmo < svc->restart_tmo_max)
tmo = tmo > svc->restart_tmo_max / 2 ? svc->restart_tmo_max : tmo * 2;
return tmo;
}
/* Delay before the next restart of a crashing service */
static int restart_delay(svc_t *svc)
{
int half;
if (svc->restart_tmo_max)
return restart_backoff(svc, svc->restart_cnt);
/* Wait 2s for the first half of the attempts, then back off to 5s */
half = (svc->restart_max == -1 ? SVC_RESPAWN_MAX : svc->restart_max) / 2;
/* If a longer timeout was specified in the conf, use that instead. */
return max(svc->restart_tmo, svc->restart_cnt <= half ? 2000 : 5000);
}
/*
* Saturates, restart always has no restart_max to stop the count.
* It stops where the back-off peaks, so aging soon brings it down.
*/
static void restart_cnt_inc(svc_t *svc)
{
int *restart_cnt = (int *)&svc->restart_cnt;
int limit = INT_MAX;
if (svc->restart_max == -1) {
if (!svc->restart_tmo_max)
limit = SVC_RESPAWN_MAX;
else if (*restart_cnt && restart_backoff(svc, *restart_cnt) >= svc->restart_tmo_max)
return;
}
if (*restart_cnt < limit)
(*restart_cnt)++;
}
static void service_retry(svc_t *svc)
{
char *restart_cnt = (char *)&svc->restart_cnt;
int timeout;
int *restart_cnt = (int *)&svc->restart_cnt;
service_timeout_cancel(svc);
@@ -3189,15 +3375,10 @@ static void service_retry(svc_t *svc)
return;
}
(*restart_cnt)++;
restart_cnt_inc(svc);
dbg("%s crashed, trying to start it again, attempt %d", svc_ident(svc, NULL, 0), *restart_cnt);
if ((*restart_cnt) == 1)
svc->restart_saved = svc->restart_tmo;
/* Wait 2s for the first 5 respawns, then back off to 5s */
timeout = ((*restart_cnt) <= (svc->restart_max / 2)) ? 2000 : 5000;
/* If a longer timeout was specified in the conf, use that instead. */
svc->restart_tmo = max(svc->restart_tmo, timeout);
svc->restart_tmo = restart_delay(svc);
if (WIFEXITED(svc->status))
logit(LOG_CONSOLE|LOG_WARNING,
"Service %s[%d] died (exit status: %d), restarting (retry in %d msec) (attempt: %d/%d)",
@@ -3298,16 +3479,26 @@ static void svc_set_state(svc_t *svc, svc_state_t new_state)
/*
* Called by pidfile plugin for forking services that have successfully started.
* We get here when the service_monitor() collects the PID, sets svc->pid to 0,
* and the state machine prepares for the worst bu setting state to HALTED.
* and the state machine prepares for the worst by setting state to HALTED.
*
* Returns 1 if the service is now running, 0 if it was stopped or disabled
* while waiting for its PID file, then the late daemon is stopped.
*/
void service_forked(svc_t *svc)
int service_forked(svc_t *svc)
{
/* Stop forking_retry() timer */
service_timeout_cancel(svc);
/* Not crashing, restore RUNNING state */
svc_unblock(svc);
/* Not crashing, restore RUNNING state, but keep a user stop */
if (!svc_is_stopped(svc))
svc_unblock(svc);
svc_set_state(svc, SVC_RUNNING_STATE);
/* Follow-up to issue #452, RUNNING and not enabled -> service_stop() */
if (!svc_enabled(svc))
service_step(svc);
return svc_is_running(svc);
}
/* Set or clear service/foo/ready condition for services and call optional ready:script */
@@ -3335,7 +3526,6 @@ void service_ready(svc_t *svc, int ready)
*/
int service_step(svc_t *svc)
{
char *restart_cnt = (char *)&svc->restart_cnt;
int changed = 0, waiting = 0;
svc_state_t old_state;
cond_state_t cond;
@@ -3378,8 +3568,8 @@ restart:
svc_set_state(svc, SVC_CLEANUP_STATE);
service_cleanup_script(svc);
} else {
/* Unblock remain tasks after post script so they can restart */
if (svc_is_remain(svc))
/* Restart remain tasks after runlevel/reload/restart teardown. */
if (svc_is_remain(svc) && svc_is_restart(svc))
svc_unblock(svc);
svc_set_state(svc, SVC_HALTED_STATE);
}
@@ -3398,13 +3588,17 @@ restart:
break;
case SVC_DONE_STATE:
/* Remain tasks: always run post script when stopped, even if config changed */
if (svc_is_runtask(svc) && svc_is_remain(svc) && svc_is_stopped(svc)) {
/* Remain tasks run post script before stopping or restarting. */
if (svc_is_runtask(svc) && svc_is_remain(svc) &&
(svc_is_stopped(svc) || svc_is_restart(svc))) {
if (svc_has_post(svc)) {
svc_set_state(svc, SVC_TEARDOWN_STATE);
service_post_script(svc);
} else
} else {
if (svc_is_restart(svc))
svc_unblock(svc);
svc_set_state(svc, SVC_HALTED_STATE);
}
} else if (svc_is_changed(svc))
svc_set_state(svc, SVC_HALTED_STATE);
else if (svc_is_runtask(svc) && svc_is_manual(svc) && enabled)
@@ -3522,7 +3716,7 @@ restart:
svc_set_state(svc, SVC_HALTED_STATE);
break;
}
(*restart_cnt)++;
restart_cnt_inc(svc);
break;
}
@@ -3626,7 +3820,7 @@ restart:
}
if (!svc->pid) {
(*restart_cnt)++;
restart_cnt_inc(svc);
svc_set_state(svc, SVC_WAITING_STATE);
break;
}
@@ -3727,7 +3921,7 @@ void service_runtask_clean(void)
/* Config changed or leaving runlevel: stop, run post, restart */
svc->once = 0;
svc_stop(svc);
svc_restarting(svc);
service_step(svc);
continue;
}
@@ -3950,7 +4144,7 @@ static void service_interval_cb(uev_t *w, void *arg, int events)
for (svc = svc_iterator(&iter, 1); svc; svc = svc_iterator(&iter, 0)) {
if (svc_is_daemon(svc)) {
char *restart_cnt = (char *)&svc->restart_cnt;
int *restart_cnt = (int *)&svc->restart_cnt;
if (!svc_is_running(svc))
continue;
+3 -1
View File
@@ -44,6 +44,8 @@ extern const struct svcdir svcdirs[NUM_SVCDIRS];
int service_set_dir (svc_t *svc, const struct svcdir *sd, const char *name);
svc_t *service_register (int type, char *line, struct rlimit rlimit[], char *file);
svc_t *service_register_desc (int type, char *line, const char *desc,
struct rlimit rlimit[], char *file);
void service_unregister (svc_t *svc);
void service_runtask_clean (void);
@@ -56,7 +58,7 @@ int service_timeout_after (svc_t *svc, int timeout, void (*cb)(svc_t *svc
int service_timeout_cancel (svc_t *svc);
void compose_cmdline (svc_t *svc, char *buf, size_t len);
void service_forked (svc_t *svc);
int service_forked (svc_t *svc);
void service_ready (svc_t *svc, int ready);
int service_stop (svc_t *svc);
+264
View File
@@ -0,0 +1,264 @@
/* Scheduled shutdown with wall messages and nologin, see issue #149
*
* Copyright (c) 2026 Joachim Wiberg <troglobit@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "config.h"
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <utmp.h>
#include "conf.h"
#include "finit.h"
#include "log.h"
#include "private.h"
#include "schedule.h"
#include "shutdown.h"
#include "sig.h"
#include "sm.h"
#include "util.h"
#include "utmp-api.h"
/* Minutes left at each warning, 0 is the deadline */
static const int warn_at[] = { 60, 30, 15, 10, 5, 4, 3, 2, 1, 0 };
#define NOLOGIN_MIN 5
#define MAX_WAIT 3600 /* sec, keeps the msec timer delay an int */
#define MAX_DELAY (365 * 24 * 3600)
static struct {
int cmd; /* INIT_CMD_REBOOT, _HALT, _POWEROFF, 0: none */
long when; /* Deadline, jiffies() */
int next; /* Minutes left at next warning */
int nologin; /* We created FINIT_NOLOGIN_PATH */
char msg[256];
struct wq work;
} sched;
static const char *action(int cmd)
{
switch (cmd) {
case INIT_CMD_REBOOT:
return "reboot";
case INIT_CMD_HALT:
return "halt";
default:
return "power-off";
}
}
/*
* Write @text to the terminal of every logged-in user. Done in a
* child, reading utmp may wait for its lock and closing a serial
* tty for its output to drain.
*/
static void wall(const char *text)
{
char host[64] = "", tm[32], hdr[160];
struct utmp *ut;
time_t t;
if (!has_utmp() || fork())
return;
t = time(NULL);
gethostname(host, sizeof(host) - 1);
strftime(tm, sizeof(tm), "%a %b %e %H:%M:%S %Y", localtime(&t));
snprintf(hdr, sizeof(hdr), "\r\nBroadcast message from root@%s (%s):\r\n\r\n", host, tm);
setutent();
while ((ut = getutent())) {
char tty[sizeof(ut->ut_line) + 6];
int fd;
if (ut->ut_type != USER_PROCESS || !ut->ut_line[0])
continue;
snprintf(tty, sizeof(tty), "/dev/%.*s", (int)sizeof(ut->ut_line), ut->ut_line);
if (strstr(tty, ".."))
continue;
/* utmp is not ours alone to write, make sure it is a tty */
fd = open(tty, O_WRONLY | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0)
continue;
if (isatty(fd) && write(fd, hdr, strlen(hdr)) > 0)
(void)!write(fd, text, strlen(text));
close(fd);
}
endutent();
_exit(0);
}
static void announce(int min)
{
char line[80], text[sizeof(sched.msg) + sizeof(line) + 8];
if (min > 0)
snprintf(line, sizeof(line), "The system is going DOWN for %s in %d minute%s!",
action(sched.cmd), min, min > 1 ? "s" : "");
else
snprintf(line, sizeof(line), "The system is going DOWN for %s NOW!", action(sched.cmd));
logit(LOG_CONSOLE | LOG_NOTICE, "%s", line);
snprintf(text, sizeof(text), "%s%s%s\r\n", sched.msg, sched.msg[0] ? "\r\n" : "", line);
wall(text);
}
/* Never touch an admin's nologin, only create and remove our own */
static void nologin(void)
{
FILE *fp;
if (fexist(FINIT_NOLOGIN_PATH))
return;
fp = fopen(FINIT_NOLOGIN_PATH, "w");
if (!fp) {
dbg("Failed creating %s: %s", FINIT_NOLOGIN_PATH, strerror(errno));
return;
}
fprintf(fp, "%s%sThe system is going down for %s.\n", sched.msg,
sched.msg[0] ? "\n" : "", action(sched.cmd));
fclose(fp);
sched.nologin = 1;
}
static void tick(void *arg)
{
long left, wait;
size_t i;
int min;
if (!sched.cmd || IS_RESERVED_RUNLEVEL(runlevel))
return;
left = sched.when - jiffies();
if (left <= 0) {
announce(0);
shutdown_now(sched.cmd, 0);
return;
}
min = (left + 59) / 60;
if (min <= NOLOGIN_MIN)
nologin();
if (min == sched.next)
announce(min);
for (i = 0; warn_at[i] >= min; i++)
;
sched.next = warn_at[i];
wait = left - sched.next * 60;
if (wait > MAX_WAIT)
wait = MAX_WAIT;
sched.work.delay = wait * 1000;
schedule_work(&sched.work);
}
/*
* Reboot, halt, or power off now, replacing any scheduled shutdown.
* A @timeout in seconds arms the emergency shutdown bypass, 0: none.
*/
int shutdown_now(int cmd, int timeout)
{
switch (cmd) {
case INIT_CMD_REBOOT:
halt = SHUT_REBOOT;
break;
case INIT_CMD_HALT:
halt = SHUT_HALT;
break;
case INIT_CMD_POWEROFF:
halt = SHUT_OFF;
break;
default:
return 1;
}
if (sched.cmd) {
sched.cmd = 0;
uev_timer_stop(&sched.work.watcher);
}
shutdown_bypass(timeout);
dbg("%s", action(cmd));
sm_runlevel(cmd == INIT_CMD_REBOOT ? 6 : 0);
return 0;
}
/* Replaces any already scheduled shutdown */
int shutdown_schedule(int cmd, int sec, const char *msg)
{
if (cmd != INIT_CMD_REBOOT && cmd != INIT_CMD_HALT && cmd != INIT_CMD_POWEROFF)
return 1;
if (sec < 0 || sec > MAX_DELAY)
return 1;
/* Our nologin belongs to the shutdown being replaced */
if (sched.nologin) {
erase(FINIT_NOLOGIN_PATH);
sched.nologin = 0;
}
sched.cmd = cmd;
sched.when = jiffies() + sec;
sched.next = (sec + 59) / 60; /* First tick warns */
strlcpy(sched.msg, msg ? msg : "", sizeof(sched.msg));
/* First tick right away, a zero delay would disarm the timer */
sched.work.cb = tick;
sched.work.delay = 1;
return schedule_work(&sched.work);
}
int shutdown_cancel(void)
{
if (!sched.cmd)
return 1;
sched.cmd = 0;
uev_timer_stop(&sched.work.watcher);
if (sched.nologin) {
erase(FINIT_NOLOGIN_PATH);
sched.nologin = 0;
}
logit(LOG_CONSOLE | LOG_NOTICE, "The system shutdown has been cancelled.");
wall("The system shutdown has been cancelled.\r\n");
return 0;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+31
View File
@@ -0,0 +1,31 @@
/* Scheduled shutdown, see issue #149
*
* Copyright (c) 2026 Joachim Wiberg <troglobit@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef FINIT_SHUTDOWN_H_
#define FINIT_SHUTDOWN_H_
int shutdown_now (int cmd, int timeout);
int shutdown_schedule(int cmd, int sec, const char *msg);
int shutdown_cancel (void);
#endif /* FINIT_SHUTDOWN_H_ */
+5 -2
View File
@@ -327,10 +327,13 @@ static char sm_rl2ch(int lvl)
*/
static void nologin(void)
{
/* Left by tmpfiles.d at boot */
if (prevlevel == INIT_LEVEL)
erase("/run/nologin");
if (runlevel == 1 || IS_RESERVED_RUNLEVEL(runlevel))
touch(FINIT_NOLOGIN_PATH);
if (prevlevel == 1 || IS_RESERVED_RUNLEVEL(prevlevel))
else if (prevlevel == 1 || IS_RESERVED_RUNLEVEL(prevlevel))
erase(FINIT_NOLOGIN_PATH);
}
+85 -4
View File
@@ -101,7 +101,7 @@ typedef enum {
#define MAX_STR_LEN 64
#define MAX_COND_LEN (MAX_ARG_LEN * 3)
#define MAX_USER_LEN MAX_ARG_LEN
#define MAX_NUM_SUPGROUPS 4
#define MAX_SUPGROUPS_LEN (MAX_CMD_LEN * 2)
#define MAX_NUM_PROVIDES 4
#define MAX_NUM_FDS 64 /* Max number of I/O plugins */
#define MAX_NUM_SVC_ARGS 64
@@ -112,6 +112,14 @@ typedef enum {
/* Prevent endless respawn of faulty services. */
#define SVC_RESPAWN_MAX 10
/* stop-scope, issue #413 */
typedef enum {
SVC_SCOPE_PGROUP = 0, /* Signal main PID, SIGKILL its process group */
SVC_SCOPE_PROCESS, /* Main PID only */
SVC_SCOPE_CGROUP, /* Signal all in cgroup, SIGKILL the rest */
SVC_SCOPE_MIXED, /* Signal main PID, SIGKILL rest of cgroup */
} svc_scope_t;
/*
* Default enable for all services, can be stopped by means
* of issuing an initctl call. E.g.
@@ -131,6 +139,7 @@ typedef struct svc {
/* Service details */
int sighalt; /* Signal to stop process, default: SIGTERM */
int killdelay; /* Delay in msec before sending SIGKILL */
svc_scope_t stop_scope; /* Which processes stop applies to */
pid_t oldpid, pid;
char pidfile[MAX_CMD_LEN];
long start_time; /* Start time, as seconds since boot, from sysinfo() */
@@ -168,9 +177,10 @@ typedef struct svc {
int restart_max; /* Maximum number of restarts allowed */
int restart_saved; /* INTERNAL, saved copy of .conf value */
int restart_tmo; /* Time before restarting a crashing service */
int restart_tmo_max;/* restart-max-sec, 0: fixed back-off, issue #306 */
unsigned char oncrash_action; /* Action to perform in crashed state. */
char respawn; /* ttys, or services with `respawn`, never increment restart_cnt */
const char restart_cnt; /* Incremented for each restart by service monitor. */
const int restart_cnt; /* Incremented for each restart by service monitor. */
union {
/* services we redirect stdout/stderr to syslog (not TTYs!) */
@@ -200,8 +210,7 @@ typedef struct svc {
/* Identity */
char username[MAX_USER_LEN];
char group[MAX_USER_LEN];
char supgroups[MAX_NUM_SUPGROUPS][MAX_USER_LEN];
int num_supgroups;
char supgroups[MAX_SUPGROUPS_LEN]; /* sup1,sup2,... */
char capabilities[MAX_CMD_LEN];
char pam[MAX_ARG_LEN]; /* /etc/pam.d/NAME, block format only */
@@ -325,6 +334,7 @@ static inline void svc_starting (svc_t *svc) { if (svc) svc->starting = 1;
static inline void svc_started (svc_t *svc) { if (svc) svc->starting = 0; }
static inline int svc_is_starting (svc_t *svc) { return svc && 0 != svc->starting; }
static inline int svc_is_running (svc_t *svc) { return svc && svc->state == SVC_RUNNING_STATE; }
static inline int svc_is_cgroup_scope(svc_t *svc) { return svc->stop_scope == SVC_SCOPE_CGROUP || svc->stop_scope == SVC_SCOPE_MIXED; }
static inline int svc_is_stopping (svc_t *svc) { return svc && svc->state == SVC_STOPPING_STATE; }
static inline int svc_is_stopped (svc_t *svc) { return svc && svc->block == SVC_BLOCK_USER; }
@@ -369,6 +379,77 @@ static inline int svc_has_cond(svc_t *svc)
return 0;
}
static inline const char *svc_scope_str(svc_scope_t scope)
{
switch (scope) {
case SVC_SCOPE_PGROUP:
return "pgroup";
case SVC_SCOPE_PROCESS:
return "process";
case SVC_SCOPE_CGROUP:
return "cgroup";
case SVC_SCOPE_MIXED:
return "mixed";
}
return "unknown";
}
static inline const char *svc_notify_str(svc_t *svc)
{
switch (svc->notify) {
case SVC_NOTIFY_NONE:
return "none";
case SVC_NOTIFY_PID:
return "pid";
case SVC_NOTIFY_SYSTEMD:
return "systemd";
case SVC_NOTIFY_S6:
return "s6";
}
return "unknown";
}
static inline const char *svc_oncrash_str(svc_t *svc)
{
switch (svc->oncrash_action) {
case SVC_ONCRASH_REBOOT:
return "reboot";
case SVC_ONCRASH_SCRIPT:
return "script";
}
return "ignore";
}
static inline const char *svc_preserve_str(svc_t *svc)
{
switch (svc->dir_preserve) {
case SVC_DIR_PRESERVE_RESTART:
return "restart";
case SVC_DIR_PRESERVE_YES:
return "yes";
}
return "no";
}
/* The conditions in provides, comma separated */
static inline char *svc_provides_str(svc_t *svc, char *buf, size_t len)
{
int i;
buf[0] = 0;
for (i = 0; i < svc->num_provides; i++) {
if (i)
strlcat(buf, ",", len);
strlcat(buf, svc->provides[i], len);
}
return buf;
}
static inline const char *svc_typestr(svc_t *svc)
{
switch (svc->type) {
+2150 -254
View File
File diff suppressed because it is too large. Load diff
+30 -18
View File
@@ -377,7 +377,8 @@ int rmrf(const char *path)
/*
* Set mode and owner on an open fd, only what differs is touched, the
* file may be immutable. mode 0 skips the chmod, uid -1 the chown.
* file may be immutable. mode 0 skips the chmod, uid and gid -1 keep
* the owner and the group.
*/
int fdperm(int fd, mode_t mode, uid_t uid, gid_t gid)
{
@@ -387,7 +388,8 @@ int fdperm(int fd, mode_t mode, uid_t uid, gid_t gid)
rc = fstat(fd, &st);
if (!rc && mode && (st.st_mode & 07777) != mode)
rc = fchmod(fd, mode);
if (!rc && uid != (uid_t)-1 && (st.st_uid != uid || st.st_gid != gid))
if (!rc && ((uid != (uid_t)-1 && st.st_uid != uid) ||
(gid != (gid_t)-1 && st.st_gid != gid)))
rc = fchown(fd, uid, gid);
return rc;
@@ -413,8 +415,8 @@ int dirperm(const char *path, mode_t mode, uid_t uid, gid_t gid)
}
/*
* Like mksubsys() but with the ids already resolved, uid -1 skips the
* chown. Parents are created 0755, only the leaf gets @mode.
* Create @dir with @mode and owner, -1 keeps the id the directory has.
* Parents are created 0755, only the leaf gets @mode.
*/
int mksubsysd(const char *dir, mode_t mode, uid_t uid, gid_t gid)
{
@@ -432,20 +434,6 @@ int mksubsysd(const char *dir, mode_t mode, uid_t uid, gid_t gid)
return rc;
}
int mksubsys(const char *dir, mode_t mode, char *user, char *group)
{
int uid, gid;
uid = getuser(user, NULL);
gid = getgroup(group);
if (gid < 0)
gid = 0;
if (uid < 0)
warnx("Cannot find user %s, %s is owned by root", user, dir);
return mksubsysd(dir, mode, uid < 0 ? (uid_t)-1 : (uid_t)uid, (gid_t)gid);
}
/*
* Read an open stream to EOF into a malloc()'ed, NUL terminated buffer.
*
@@ -722,6 +710,30 @@ char *rlim2str(int rlim)
return "unknown";
}
/* All of @rlimit as "name=soft:hard,...", a value is a number or unlimited */
char *rlimits2str(struct rlimit *rlimit, char *buf, size_t len)
{
const struct rlimit_name *rn;
size_t pos = 0;
buf[0] = 0;
for (rn = rlimit_names; rn->name && pos < len; rn++) {
rlim_t lim[2] = { rlimit[rn->val].rlim_cur, rlimit[rn->val].rlim_max };
int i;
pos += snprintf(&buf[pos], len - pos, "%s%s", pos ? "," : "", rn->name);
for (i = 0; i < 2 && pos < len; i++) {
if (lim[i] == RLIM_INFINITY)
pos += snprintf(&buf[pos], len - pos, "%cunlimited", i ? ':' : '=');
else
pos += snprintf(&buf[pos], len - pos, "%c%llu", i ? ':' : '=',
(unsigned long long)lim[i]);
}
}
return buf;
}
char *lim2str(struct rlimit *rlim)
{
char tmp[25];
+1 -1
View File
@@ -73,7 +73,6 @@ int getcgroup (char *buf, size_t len);
int fdperm (int fd, mode_t mode, uid_t uid, gid_t gid);
int dirperm (const char *path, mode_t mode, uid_t uid, gid_t gid);
int mksubsys (const char *dir, mode_t mode, char *user, char *group);
int mksubsysd (const char *dir, mode_t mode, uid_t uid, gid_t gid);
int chownr (const char *path, uid_t uid, gid_t gid);
int rmcontents (const char *path);
@@ -95,6 +94,7 @@ char *code2str (int code);
int str2rlim (char *str);
char *rlim2str (int rlim);
char *lim2str (struct rlimit *rlim);
char *rlimits2str (struct rlimit *rlimit, char *buf, size_t len);
void do_sleep (unsigned int sec);
void do_usleep (unsigned int usec);
+42
View File
@@ -38,6 +38,7 @@ EXTRA_DIST += conf-provides.sh
EXTRA_DIST += conf-tty.sh
EXTRA_DIST += conf-dup-title.sh
EXTRA_DIST += conf-dirs.sh
EXTRA_DIST += conf-groups.sh
EXTRA_DIST += conf-if.sh
EXTRA_DIST += conf-template.sh
EXTRA_DIST += script-timeout.sh
@@ -54,12 +55,17 @@ EXTRA_DIST += keventd.sh
EXTRA_DIST += notify.sh
EXTRA_DIST += pam-session.sh
EXTRA_DIST += pidfile.sh
EXTRA_DIST += pidfile-stopped.sh
EXTRA_DIST += stale-pidfile.sh
EXTRA_DIST += stop-scope.sh
EXTRA_DIST += shutdown-sched.sh
EXTRA_DIST += pre-post-serv.sh
EXTRA_DIST += pre-fail.sh
EXTRA_DIST += process-depends.sh
EXTRA_DIST += rclocal.sh
EXTRA_DIST += ready-serv.sh
EXTRA_DIST += remain-task-control.sh
EXTRA_DIST += restart-backoff.sh
EXTRA_DIST += restart-self.sh
EXTRA_DIST += runlevel.sh
EXTRA_DIST += run-restart-forever.sh
@@ -67,6 +73,7 @@ EXTRA_DIST += run-task-tricks.sh
EXTRA_DIST += runparts.sh
EXTRA_DIST += sysvparts.sh
EXTRA_DIST += start-stop-service.sh
EXTRA_DIST += status-json.sh
EXTRA_DIST += start-stop-service-sub-config.sh
EXTRA_DIST += start-kill-service.sh
EXTRA_DIST += start-kill-stop.sh
@@ -74,6 +81,20 @@ EXTRA_DIST += start-stop-sysv.sh
EXTRA_DIST += start-stop-serv.sh
EXTRA_DIST += signal-service.sh
EXTRA_DIST += testserv.sh
EXTRA_DIST += tmpfiles-acl.sh
EXTRA_DIST += tmpfiles-arg.sh
EXTRA_DIST += tmpfiles-attr.sh
EXTRA_DIST += tmpfiles-perm.sh
EXTRA_DIST += tmpfiles-purge.sh
EXTRA_DIST += tmpfiles-root.sh
EXTRA_DIST += tmpfiles-boot.sh
EXTRA_DIST += tmpfiles-clean.sh
EXTRA_DIST += tmpfiles-copy.sh
EXTRA_DIST += tmpfiles-files.sh
EXTRA_DIST += tmpfiles-match.sh
EXTRA_DIST += tmpfiles-order.sh
EXTRA_DIST += tmpfiles-specifier.sh
EXTRA_DIST += tmpfiles-unsupported.sh
EXTRA_DIST += unexpected-restart.sh
EXTRA_DIST += dbus-auth.sh
EXTRA_DIST += dbus-authz.sh
@@ -105,6 +126,7 @@ TESTS += conf-provides.sh
TESTS += conf-tty.sh
TESTS += conf-dup-title.sh
TESTS += conf-dirs.sh
TESTS += conf-groups.sh
TESTS += conf-if.sh
TESTS += conf-template.sh
TESTS += script-timeout.sh
@@ -123,12 +145,17 @@ endif
TESTS += notify.sh
TESTS += pam-session.sh
TESTS += pidfile.sh
TESTS += pidfile-stopped.sh
TESTS += stale-pidfile.sh
TESTS += stop-scope.sh
TESTS += shutdown-sched.sh
TESTS += pre-post-serv.sh
TESTS += pre-fail.sh
TESTS += process-depends.sh
TESTS += rclocal.sh
TESTS += ready-serv.sh
TESTS += remain-task-control.sh
TESTS += restart-backoff.sh
TESTS += restart-self.sh
TESTS += runlevel.sh
TESTS += sysvparts.sh
@@ -136,6 +163,7 @@ TESTS += run-restart-forever.sh
TESTS += run-task-tricks.sh
TESTS += runparts.sh
TESTS += start-stop-service.sh
TESTS += status-json.sh
TESTS += start-stop-service-sub-config.sh
TESTS += start-kill-service.sh
TESTS += start-kill-stop.sh
@@ -144,6 +172,20 @@ TESTS += start-stop-serv.sh
TESTS += signal-service.sh
if TESTSERV
TESTS += testserv.sh
TESTS += tmpfiles-acl.sh
TESTS += tmpfiles-arg.sh
TESTS += tmpfiles-attr.sh
TESTS += tmpfiles-perm.sh
TESTS += tmpfiles-purge.sh
TESTS += tmpfiles-root.sh
TESTS += tmpfiles-boot.sh
TESTS += tmpfiles-clean.sh
TESTS += tmpfiles-copy.sh
TESTS += tmpfiles-files.sh
TESTS += tmpfiles-match.sh
TESTS += tmpfiles-order.sh
TESTS += tmpfiles-specifier.sh
TESTS += tmpfiles-unsupported.sh
endif
TESTS += unexpected-restart.sh
if DBUS
+36
View File
@@ -11,6 +11,42 @@ directory it will be able to function properly without having any super user
privileges in the host environment.
Requirements
------------
On Debian, Ubuntu, and Linux Mint, install the build dependencies and
the tools the tests use:
sudo apt install build-essential autoconf automake libtool pkg-config \
libconfuse-dev libblkid-dev libcap-dev libpam0g-dev \
uidmap jq wget dbus shellcheck
* `uidmap` has `newuidmap` and `newgidmap`, which `unshare` needs to
set up the namespace of each test. Without it every test fails with
`unshare: failed to execute newuidmap`. Your user also needs a range
in `/etc/subuid` and `/etc/subgid`, which `adduser` sets up
* `jq` is used by the tests that read `initctl -j`
* `wget` fetches the BusyBox binary for the test root, on the first run
* `dbus` has the `dbus-daemon` and `dbus-send` that the D-Bus broker
test stages in the test root, without them that test is skipped
* `shellcheck` is used by the `checkself.sh` test, which checks the
test scripts themselves
* `libcap-dev` and `libpam0g-dev` are optional for Finit. Without
the latter the PAM session test is skipped
Finit also needs [libuEv][] v2.4.1 and [libite][] v2.6.1, or later. The
`libuev-dev` and `libite-dev` packages may be older, check with:
apt-cache policy libuev-dev libite-dev
In Ubuntu 24.04, `libuev-dev` is new enough but `libite-dev` is not, so
libite has to be built and installed from source, see the [build
instructions](../doc/build.md).
[libuEv]: https://github.com/troglobit/libuev
[libite]: https://github.com/troglobit/libite
Running tests
-------------
+24 -1
View File
@@ -76,6 +76,29 @@ retry 'assert_cmd pick "serv -np -i pick"'
assert_desc "Single command" pick
assert_num_children 1 serv
# The description has its own setting, so a -- in the command is an
# argument to it, see issue #512.
say 'A -- in the command is passed on to it'
run "echo 'service pick {' > $FINIT_CONF"
run "echo ' description = \"Dashes\"' >> $FINIT_CONF"
run "echo ' command = \"serv -np -i pick -- extra\"' >> $FINIT_CONF"
run "echo '}' >> $FINIT_CONF"
run "initctl reload"
retry 'assert_cmd pick "serv -np -i pick -- extra"'
assert_desc "Dashes" pick
assert_num_children 1 serv
# Options are matched as whole tokens, so a command that merely starts
# like one, pidof vs. pid, is still the command.
say 'A command named like an option is the command'
run "echo 'task lookalike {' > $FINIT_CONF"
run "echo ' command = \"pidof serv\"' >> $FINIT_CONF"
run "echo '}' >> $FINIT_CONF"
run "initctl reload"
retry 'assert_cmd lookalike "pidof serv"'
# A tty block takes the same list, its command is the getty to run.
# Asserting it is loaded is enough here, a getty in the test namespace
# has no terminal to attach to.
@@ -90,7 +113,7 @@ retry 'assert_cmd tty "serv -np -i ttypick"'
# Nothing resolves, so the block is skipped the same way a single
# missing command is. The leading - only decides whether that is
# quiet, service_register() bails before svc_new() either way.
# quiet, service_register_desc() bails before svc_new() either way.
say 'A block whose candidates are all missing is skipped'
run "echo 'service ghost {' > $FINIT_CONF"
run "echo ' command = { \"-/no/such/one\", \"-/no/such/two\" }' >> $FINIT_CONF"
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
# Verify group and extra-groups are set on the service, and that
# dropping either setting drops the group(s) too.
set -eu
TEST_DIR=$(dirname "$0")
# Optional arguments are the extra-groups list and the group
write_conf()
{
run "echo 'service grp {' > $FINIT_CONF"
run "echo ' user = \"root\"' >> $FINIT_CONF"
if [ -n "${2:-}" ]; then
run "echo ' group = \"$2\"' >> $FINIT_CONF"
fi
if [ -n "${1:-}" ]; then
run "echo ' extra-groups = { $1 }' >> $FINIT_CONF"
fi
run "echo ' command = \"serv -np -i grp\"' >> $FINIT_CONF"
run "echo '}' >> $FINIT_CONF"
}
# Kernel sorts the list, so it compares as a plain string.
assert_groups()
{
pid=$(texec initctl -j status grp | jq .pid)
assert "Service groups == $1" \
"$(texec cat "/proc/$pid/status" | sed -n 's/^Groups:[[:space:]]*//p' | xargs)" = "$1"
}
assert_gid()
{
pid=$(texec initctl -j status grp | jq .pid)
assert "Service gid == $1" \
"$(texec cat "/proc/$pid/status" | awk '/^Gid:/ {print $2}')" = "$1"
}
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
say 'Seven extra groups'
write_conf '"daemon", "bin", "sys", "adm", "tty", "disk", "dialout"' root
run "initctl reload"
retry 'assert_num_children 1 serv'
retry 'assert_groups "0 1 2 3 4 5 6 20"'
# The running process keeps its groups, the next start drops them
say 'Dropping extra-groups drops the groups'
write_conf
run "initctl reload"
run "initctl restart grp"
retry 'assert_groups "0"'
say 'Dropping group drops the group'
write_conf "" adm
run "initctl reload"
run "initctl restart grp"
retry 'assert_gid 4'
write_conf
run "initctl reload"
run "initctl restart grp"
retry 'assert_gid 0'
+8
View File
@@ -39,6 +39,14 @@ run "ip link del probe0"
sep "keventd readiness"
retry 'assert_ready "keventd"' 50 0.2
# Finit does not touch a daemon-owned pidfile, so keventd must do it
# after SIGHUP to reassert readiness, see issue #503. Signalled with
# kill to keep Finit out of it.
sep "keventd touches its pidfile on SIGHUP"
run "touch -d '2000-01-01 00:00' /run/keventd.pid"
run "kill -HUP $(texec cat /run/keventd.pid)"
retry "test \$(texec stat -c %Y /run/keventd.pid) -gt 1000000000" 10 0.2
sep "interface add asserts <class/net/dummy0>"
cat >> "$SYSROOT$FINIT_CONF" <<EOF
service serv {
+84
View File
@@ -0,0 +1,84 @@
#!/bin/sh
# Verify that a PID file written by someone else does not make a stopped
# or waiting service look started, see issue #452. E.g., a container
# started by hand with podman, outside of Finit.
set -eu
TEST_DIR=$(dirname "$0")
PIDFN=/run/ext.pid
# Stand-in for the process started outside of Finit
external()
{
say "Starting a process outside of Finit, it writes $PIDFN"
run "sh -c 'sleep 100 & echo \$! > $PIDFN'"
# Negative check, give the pidfile plugin time to (not) react
sleep 2
}
cleanup()
{
run "kill \$(cat $PIDFN 2>/dev/null) 2>/dev/null || true"
run "rm -f $PIDFN /bin/late.sh /tmp/late"
}
test_teardown()
{
say "Running test teardown."
cleanup
run "rm -f $FINIT_CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep
say 'A stopped forking service stays stopped'
run "echo 'service name:ext pid:!$PIDFN serv -p -P $PIDFN -- External' > $FINIT_CONF"
run "initctl reload"
retry 'assert_status ext running'
run "initctl stop ext"
retry 'assert_status ext stopped'
run "rm -f $PIDFN"
external
assert_status ext stopped
assert_nocond pid/ext
cleanup
sep
say 'A service waiting for its condition stays waiting'
run "echo 'service name:ext pid:!$PIDFN <usr/never> serv -p -P $PIDFN -- External' > $FINIT_CONF"
run "initctl reload"
retry 'assert_status ext waiting'
external
assert_status ext waiting
assert_nocond pid/ext
cleanup
# A forking daemon whose launcher exits before the daemon has written
# its PID file. A stop in that window must hold, and the daemon that
# shows up late must be stopped, not adopted as running.
sep
say 'A forking service stopped before its PID file appears stays stopped'
# Unquoted END, $PIDFN expands here. /tmp/late marks the daemon start
cat > "$SYSROOT/bin/late.sh" <<END
#!/bin/sh
( sleep 1; touch /tmp/late; exec serv -n -p -P $PIDFN ) &
END
chmod +x "$SYSROOT/bin/late.sh"
run "echo 'service name:ext pid:!$PIDFN late.sh -- Late' > $FINIT_CONF"
run "initctl reload"
run "initctl stop ext"
retry 'assert_file_exists /tmp/late'
# Negative check, give the pidfile plugin time to (not) react
sleep 1
assert_status ext stopped
assert_nocond pid/ext
assert_num_children 0 serv
+76
View File
@@ -0,0 +1,76 @@
#!/bin/sh
set -eu
TEST_DIR=$(dirname "$0")
TEST_CONF=/etc/finit.d/remain-task.conf
STATE=/run/remain-task.state
test_teardown()
{
run "rm -f $TEST_CONF $STATE"
}
assert_runs()
{
assert "Remain task has run $1 time(s)" \
"$(texec initctl -j status remain-task | jq -M .restarts)" -eq "$1"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
say 'Add remain task'
run "cat > $TEST_CONF" <<EOF
task remain-task {
description = "Remain task control"
runlevel = "2345"
remain-after-exit = true
command = "/bin/touch $STATE"
exec-stop-post = "/bin/rm -f $STATE"
}
EOF
run "initctl reload"
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
assert_runs 1
say 'Stop remain task'
run "initctl stop remain-task"
retry 'assert_status remain-task stopped'
assert "Post script removed state" \
"$(texec sh -c "[ ! -e '$STATE' ] && echo yes")" = yes
assert_runs 1
say 'Start remain task'
run "initctl start remain-task"
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
assert_runs 2
say 'Restart remain task'
run "initctl restart remain-task"
retry 'assert_runs 3'
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
say 'Reload changed remain task'
run "sed -i 's/Remain task control/Updated remain task control/' $TEST_CONF"
run "initctl reload"
retry 'assert_runs 4'
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
say 'Leave remain task runlevel'
run "initctl runlevel 1"
retry 'assert_status remain-task halted'
assert "Post script removed state" \
"$(texec sh -c "[ ! -e '$STATE' ] && echo yes")" = yes
assert_runs 4
say 'Re-enter remain task runlevel'
run "initctl runlevel 2"
retry 'assert_runs 5'
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
+89
View File
@@ -0,0 +1,89 @@
#!/bin/sh
# Verify the delay between restarts of a crashing service. It logs
# the uptime, in centiseconds, of each start and then exits.
set -eu
TEST_DIR=$(dirname "$0")
STARTS=/tmp/starts
# Wait for start $2, then check the delay since start $1, in sec
assert_delay()
{
retry "texec sh -c 'test \$(wc -l < $STARTS) -ge $2'" 150 0.1
# shellcheck disable=SC2016 # $1 is awk's field reference, not the shell's
delay=$(texec awk -v a="$1" -v b="$2" 'NR == a { t = $1 } NR == b { print $1 - t }' $STARTS)
assert "Delay between start $1 and $2 is $3-$4 sec" "$delay" -ge "$(($3 * 100))"
assert "Delay between start $1 and $2 is $3-$4 sec" "$delay" -le "$(($4 * 100))"
}
# Replace the service, settings in $1, and let it start crashing
crash()
{
run "rm -f $FINIT_CONF"
run "initctl reload"
run "rm -f $STARTS"
run "cat > $FINIT_CONF" <<CONF
service crash {
$1
command = "crash.sh"
}
CONF
run "initctl reload"
}
# Same, with the line-based format, options in $1
crash_line()
{
run "rm -f $FINIT_CONF"
run "initctl reload"
run "rm -f $STARTS"
run "echo 'service $1 crash.sh -- Crashing' > $FINIT_CONF"
run "initctl reload"
}
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_CONF $STARTS /bin/crash.sh"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
cat > "$SYSROOT/bin/crash.sh" <<SCRIPT
#!/bin/sh
tr -d . < /proc/uptime | cut -d' ' -f1 >> $STARTS
exit 1
SCRIPT
chmod +x "$SYSROOT/bin/crash.sh"
sep
say 'restart always, at once the first time, then every other second'
crash 'restart = "always"'
assert_delay 1 2 0 1
assert_delay 2 3 2 3
assert_delay 3 4 2 3
sep
say 'restart-max-sec, the delay doubles from restart-sec up to the limit'
crash 'restart = "always"
restart-sec = 1
restart-max-sec = 4'
assert_delay 1 2 1 2
assert_delay 2 3 2 3
assert_delay 3 4 4 5
assert_delay 4 5 4 5
say 'The restart counter stops where the delay peaks'
assert "Delay and limit in status" "$(texec initctl status crash | sed -n 's/.*Restart in : //p')" = "4 sec (max 4)"
run "initctl -j status crash"
assert "Same in JSON" "$(texec initctl -j status crash | jq -c .restart)" = '{"count":2,"max":-1,"sec":1,"delay":4,"limit":4,"respawn":false,"oncrash":"ignore"}'
assert "Restart counter is 2" "$(texec initctl status crash | awk '/Restarts/{ print $4 }')" = "(2/-1)"
sep
say 'restart-sec in the line-based format, and its old spelling'
crash_line 'restart:always restart-sec:3'
assert_delay 1 2 3 4
crash_line 'restart:always restart_sec:3'
assert_delay 1 2 3 4
+59
View File
@@ -0,0 +1,59 @@
#!/bin/sh
# Verify scheduled shutdown, see issue #149: shutdown TIME [MESSAGE]
# blocks new logins from five minutes before, and shutdown -c cancels
# it. The countdown never runs out here, it is always cancelled.
set -eu
TEST_DIR=$(dirname "$0")
NOLOGIN=/etc/nologin
# Assert that the command, run in the test namespace, fails
fails()
{
assert "$1 fails" "$(texec sh -c "$1 >/dev/null 2>&1 || echo fail")" = fail
}
test_teardown()
{
say "Running test teardown."
run "shutdown -c 2>/dev/null || true"
run "rm -f $NOLOGIN"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep
say 'Schedule a reboot in two minutes, within the nologin window'
run "shutdown -r +2 Testing scheduled reboot"
retry "assert_file_contains $NOLOGIN 'Testing scheduled reboot'"
say 'Cancel it, nologin is removed and the system stays up'
run "shutdown -c"
retry "texec sh -c '! test -e $NOLOGIN'"
assert "Still in runlevel 2" "$(texec initctl runlevel | awk '{print $2}')" = 2
sep
say 'Nothing to cancel'
fails "shutdown -c"
say 'An invalid time is refused'
fails "shutdown -r 25:00"
fails "shutdown -r +999999999"
sep
say 'A later shutdown replaces it, and its nologin'
run "shutdown -r +2 First"
retry "assert_file_contains $NOLOGIN First"
run "shutdown -r +120 Second"
retry "texec sh -c '! test -e $NOLOGIN'"
run "shutdown -c"
sep
say 'A nologin file of the admin is left alone'
run "echo 'Down for maintenance' > $NOLOGIN"
run "shutdown -h +2"
sleep 1 # first tick, where nologin would be written
run "shutdown -c"
assert_file_contains $NOLOGIN 'Down for maintenance'
+98
View File
@@ -0,0 +1,98 @@
#!/bin/sh
# Verify initctl -j status: it has the settings of a service, and gives
# the same over D-Bus as over the initctl socket.
set -eu
TEST_DIR=$(dirname "$0")
BUS=/run/finit/bus
# Check member $1 of the JSON status in $json
assert_json()
{
assert "$1 is $2" "$(echo "$json" | jq -c "$1")" = "$2"
}
test_teardown()
{
say "Running test teardown."
run "test -e $BUS.hidden && mv $BUS.hidden $BUS || true"
run "rm -f $FINIT_CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "cat > $FINIT_CONF" <<CONF
service json {
description = "JSON status"
notify = "pid"
stop-signal = "SIGINT"
stop-timeout = 5
stop-scope = "process"
restart-max = 3
restart-sec = 2
restart-max-sec = 8
oncrash = "script"
exec-stop-post = "/bin/true"
exec-stop-post-timeout = 7
runtime-dir = "json"
runtime-dir-mode = 0750
rlimit {
soft.nofile = 123
hard.nofile = 456
core = unlimited
}
cgroup maint { cpu.weight = 250 }
runtime-dir-preserve = "restart"
extra-groups = { "daemon", "bin" }
provides = { "usr/json-a", "usr/json-b" }
conflicts = { "nosuch" }
log {
identity = "jason"
}
command = "serv -np -i json"
}
CONF
run "initctl reload"
retry 'assert_status json running'
sep
say 'The settings of the service are in the JSON status'
run "initctl -j status json"
json=$(texec initctl -j status json)
assert_json .notify '"pid"'
assert_json .remain 'false'
assert_json .stop '{"signal":"SIGINT","timeout":5,"scope":"process"}'
assert_json .reload.signal '"SIGHUP"'
assert_json .restart.max '3'
assert_json .restart.sec '2'
assert_json .restart.limit '8'
assert_json .restart.respawn 'false'
assert_json .restart.oncrash '"script"'
assert_json .scripts '{"exec-stop-post":{"command":"/bin/true","timeout":7}}'
assert_json .directories '{"runtime":{"name":"json","mode":"0750"},"preserve":"restart"}'
assert_json .rlimits.nofile '{"soft":123,"hard":456}'
assert_json .rlimits.core '{"soft":"unlimited","hard":"unlimited"}'
assert_json '."cgroup-config"' '{"group":"maint","config":"cpu.weight:250","delegate":false}'
assert_json .name '"json"'
assert_json .protected 'false'
assert_json .id '""'
assert_json .internal.removed 'false'
assert_json .internal.oldpid '0'
assert_json .reload.propagate 'false'
assert_json .groups '["daemon","bin"]'
assert_json .provides '["usr/json-a","usr/json-b"]'
assert_json .conflicts '["nosuch"]'
assert_json .log.enabled 'true'
assert_json .log.identity '"jason"'
if texec test -e $BUS; then
sep
say 'Same over the initctl socket, with the bus hidden'
run "mv $BUS $BUS.hidden"
legacy=$(texec initctl -j status json)
run "mv $BUS.hidden $BUS"
assert "Same JSON from both" "$(echo "$json" | jq -cS 'del(.uptime)')" = "$(echo "$legacy" | jq -cS 'del(.uptime)')"
fi
+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
# Verify stop-scope, which processes a stop applies to, see issue #413.
# The service leaves a child behind in its process group, like the
# action script of avahi-autoipd. Cgroups are not available in the
# test namespace, so cgroup and mixed fall back to the process group.
set -eu
TEST_DIR=$(dirname "$0")
CHILD=/tmp/scope-child
# Start the service, stop it, and check if its child is still there.
# Optional second argument is the stop-scope.
stop_one()
{
sep
say "stop-scope ${2:-default}, child is left $1"
run "rm -f $CHILD"
run "cat > $FINIT_CONF" <<EOF
service scope {
${2:+stop-scope = "$2"}
command = "scope.sh"
}
EOF
run "initctl reload"
run "initctl start scope"
retry 'assert_status scope running'
retry "texec test -s $CHILD"
run "initctl stop scope"
retry 'assert_status scope stopped'
if [ "$1" = alive ]; then
assert "Child is alive" "$(texec sh -c "kill -0 \$(cat $CHILD) && echo yes")" = yes
run "kill \$(cat $CHILD)"
else
retry "texec sh -c '! kill -0 \$(cat $CHILD) 2>/dev/null'"
fi
}
test_teardown()
{
say "Running test teardown."
run "kill \$(cat $CHILD 2>/dev/null) 2>/dev/null || true"
run "rm -f $FINIT_CONF $CHILD /bin/scope.sh"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
cat > "$SYSROOT/bin/scope.sh" <<EOF
#!/bin/sh
sleep 100 &
echo \$! > $CHILD
exec serv -np -i scope
EOF
chmod +x "$SYSROOT/bin/scope.sh"
stop_one dead
stop_one dead pgroup
stop_one alive process
stop_one dead cgroup
stop_one dead mixed
+88
View File
@@ -0,0 +1,88 @@
#!/bin/sh
# Verify the a and A entries of tmpfiles, POSIX ACLs. The sysroot has
# no getfacl, so this looks at what an ACL does to the mode: the group
# bits show the mask, and a default ACL replaces the umask for what is
# created in the directory.
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/acl
CONF=/tmp/acl.conf
tmpfiles()
{
run "cat > $CONF"
run "/libexec/finit/tmpfiles --create $CONF"
}
assert_mode()
{
assert "Mode of $1 is $2" "$(texec stat -c %a "$1")" = "$2"
}
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep
say 'Default ACL on a directory, as in tpm2-tss-fapi.conf'
tmpfiles <<CONF
#Type Path Mode User Group Age Argument
d $DIR/keystore 2775 daemon daemon - -
a+ $DIR/keystore - - - - default:group:daemon:rwx
d $DIR/plain 2775 daemon daemon - -
CONF
run "umask 077; mkdir $DIR/keystore/sub $DIR/plain/sub; touch $DIR/keystore/file"
assert_mode $DIR/plain/sub 2700
assert_mode $DIR/keystore/sub 2775
assert_mode $DIR/keystore/file 664
sep
say 'a+ adds to the ACL of a file, a replaces it'
run "touch $DIR/file; chmod 600 $DIR/file"
tmpfiles <<CONF
a+ $DIR/file - - - - user:daemon:r--
CONF
assert_mode $DIR/file 640
tmpfiles <<CONF
a+ $DIR/file - - - - g:bin:rw-
CONF
assert_mode $DIR/file 660
tmpfiles <<CONF
a $DIR/file - - - - u:sys:--x
CONF
assert_mode $DIR/file 610
tmpfiles <<CONF
a+ $DIR/file - - - - m::r
CONF
assert_mode $DIR/file 640
sep
say 'An ACL can have many entries'
run "touch $DIR/many; chmod 600 $DIR/many"
tmpfiles <<CONF
a $DIR/many - - - - $(seq -s, -f 'u:%g:r' 2000 2039)
CONF
assert_mode $DIR/many 640
tmpfiles <<CONF
a+ $DIR/many - - - - u:2040:-w-
CONF
assert_mode $DIR/many 660
sep
say 'A is recursive, and X is x only for a directory or an executable'
run "mkdir -p $DIR/tree/sub; touch $DIR/tree/sub/file $DIR/tree/sub/prog"
run "chmod 700 $DIR/tree $DIR/tree/sub $DIR/tree/sub/prog; chmod 600 $DIR/tree/sub/file"
tmpfiles <<CONF
A $DIR/tree - - - - u:daemon:rwX
CONF
assert_mode $DIR/tree 770
assert_mode $DIR/tree/sub 770
assert_mode $DIR/tree/sub/prog 770
assert_mode $DIR/tree/sub/file 660
+131
View File
@@ -0,0 +1,131 @@
#!/bin/sh
# Verify how tmpfiles reads the argument, the last field of an entry
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/arg
CONF=/tmp/arg.conf
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "cat > $CONF" <<CONF
d $DIR - - - - -
L $DIR/aligned - - - - /dev/null
f $DIR/dash - - - - -
f $DIR/text - - - - two words
f^ $DIR/cred - - - - some.credential
CONF
run "/libexec/finit/tmpfiles --create $CONF"
say 'Space between the age and the argument is not part of the argument'
assert "Link target" "$(texec readlink $DIR/aligned)" = "/dev/null"
assert "File content" "$(texec cat $DIR/text)" = "two words"
say 'A lone - is no argument'
assert "Empty file" "$(texec stat -c %s $DIR/dash)" = "0"
say 'An entry that takes its argument from a credential is skipped'
assert "No file" "$(texec sh -c "ls $DIR | grep -c cred")" = "0"
sep
say 'L? only makes the link when what it points to is there'
run "cat > $CONF" <<CONF
L? $DIR/there - - - - /etc/passwd
L? $DIR/missing - - - - /no/such/file
CONF
run "/libexec/finit/tmpfiles --create $CONF"
assert "Link to a path that is there" "$(texec readlink $DIR/there)" = "/etc/passwd"
assert "No link to a missing path" "$(texec sh -c "ls $DIR | grep -c missing")" = "0"
sep
say 'With --prefix only the entries below it are run'
run "cat > $CONF" <<CONF
f $DIR/in/file
f $DIR/out/file
f $DIR/input
CONF
run "/libexec/finit/tmpfiles --create --prefix=$DIR/in $CONF"
assert "Only below the prefix" "$(texec sh -c "ls -d $DIR/in* $DIR/out* 2>/dev/null" | tr '\n' ' ')" = "$DIR/in "
sep
say 'w writes all of its argument to every path a glob matches'
run "touch $DIR/w1 $DIR/w2"
run "cat > $CONF" <<'CONF'
w /tmp/arg/w? - - - - one\ntwo
CONF
run "/libexec/finit/tmpfiles --create $CONF"
assert "First match" "$(texec cat $DIR/w1 | tr '\n' ' ')" = "one two"
assert "Second match" "$(texec cat $DIR/w2 | tr '\n' ' ')" = "one two"
sep
say 'w writes over the start of what is there, w+ adds to the end'
run "printf abcdef > $DIR/w1"
run "cat > $CONF" <<'CONF'
w /tmp/arg/w1 - - - - XY
w+ /tmp/arg/w1 - - - - Z
w+ /tmp/arg/w1 - - - - Z
CONF
run "/libexec/finit/tmpfiles --create $CONF"
assert "Written in place, added to by each w+" "$(texec cat $DIR/w1)" = "XYcdefZZ"
sep
say 'Escapes, and a # that is not at the start of the line'
run "cat > $CONF" <<'CONF'
# A comment
# and one more
f /tmp/arg/hex - - - - \x39\x41\x4a\x6b
f /tmp/arg/hash - - - - a#b c
CONF
run "/libexec/finit/tmpfiles --create $CONF"
assert "All hex digits" "$(texec cat $DIR/hex)" = "9AJk"
assert "No comment in line" "$(texec cat $DIR/hash)" = "a#b c"
sep
say 'A path can be quoted, and have escapes'
run "cat > $CONF" <<'CONF'
f "/tmp/arg/with space" - - - - double
f '/tmp/arg/single quote' - - - - single
f /tmp/arg/mid"dle sp"ace - - - - middle
f /tmp/arg/esc\x41\sped - - - - "kept as is"
f "/tmp/arg/open - - - - quote
f tmp/arg/relative - - - - path
CONF
run "cd /; /libexec/finit/tmpfiles --create $CONF"
assert "Double quotes" "$(texec cat "$DIR/with space")" = "double"
assert "Single quotes" "$(texec cat "$DIR/single quote")" = "single"
assert "Quotes in path" "$(texec cat "$DIR/middle space")" = "middle"
assert "Escapes in path" "$(texec cat "$DIR/escA ped")" = '"kept as is"'
assert "Skipped with a quote left open" "$(texec sh -c "ls $DIR | grep -c open")" = "0"
assert "Skipped when not absolute" "$(texec sh -c "ls $DIR | grep -c relative")" = "0"
sep
say 'With ~ the argument is Base64'
run "printf abcdef > $DIR/w1"
run "cat > $CONF" <<'CONF'
f~ /tmp/arg/b64 - - - - aGVsbG8gJXQK
f~ /tmp/arg/b64pad - - - - aGk=
f~ /tmp/arg/b64bad - - - - a!!!
w~ /tmp/arg/w1 - - - - WFk=
CONF
run "/libexec/finit/tmpfiles --create $CONF"
assert "Decoded, no specifiers" "$(texec cat $DIR/b64)" = "hello %t"
assert "Padded" "$(texec cat $DIR/b64pad)" = "hi"
assert "Written with w" "$(texec cat $DIR/w1)" = "XYcdef"
assert "Skipped when not Base64" "$(texec sh -c "ls $DIR | grep -c b64bad")" = "0"
sep
say '--cat-config shows the files that would be read'
assert "Files with their name" "$(texec /libexec/finit/tmpfiles --cat-config $CONF | head -2 | tr '\n' ' ')" = "# $CONF f~ /tmp/arg/b64 - - - - aGVsbG8gJXQK "
sep
say '--graceful is taken, and changes nothing'
run "rm $DIR/b64; /libexec/finit/tmpfiles --create --graceful $CONF"
assert "Runs with --graceful" "$(texec cat $DIR/b64)" = "hello %t"
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
# Verify the t and T entries of tmpfiles, extended attributes, and the
# h and H entries, file attributes. On the file system of the sysroot,
# not all attributes work on tmpfs.
set -eu
TEST_DIR=$(dirname "$0")
DIR=/attr-test
CONF=/tmp/attr.conf
tmpfiles()
{
run "cat > $CONF"
run "/libexec/finit/tmpfiles --create $CONF"
}
# The sysroot has setfattr but no getfattr, removing one that is not
# set fails
assert_xattr()
{
assert "$1 has $2" "$(texec sh -c "setfattr -x $2 $1 && echo yes || echo no")" = "yes"
}
assert_attr()
{
assert "Attributes of $1 have $2: $3" \
"$(texec sh -c "lsattr -d $1 | cut -d' ' -f1 | grep -q $2 && echo yes || echo no")" = "$3"
}
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "mkdir -p $DIR/tree/sub; touch $DIR/file $DIR/tree/sub/file"
sep
say 't sets extended attributes, T on everything below the path too'
tmpfiles <<CONF
t $DIR/file - - - - user.one=1 user.two="two words"
T $DIR/tree - - - - user.tree=yes
CONF
assert_xattr $DIR/file user.one
assert_xattr $DIR/file user.two
assert_xattr $DIR/tree user.tree
assert_xattr $DIR/tree/sub/file user.tree
sep
say 'h sets file attributes, H on everything below the path too'
tmpfiles <<CONF
h $DIR/file - - - - +dA
H $DIR/tree - - - - d
CONF
assert_attr $DIR/file d yes
assert_attr $DIR/file A yes
assert_attr $DIR/tree/sub/file d yes
say 'With - they are taken away, with = only those named are left'
tmpfiles <<CONF
h $DIR/file - - - - -d
H $DIR/tree - - - - =A
CONF
assert_attr $DIR/file d no
assert_attr $DIR/file A yes
assert_attr $DIR/tree/sub/file d no
assert_attr $DIR/tree/sub/file A yes
+73
View File
@@ -0,0 +1,73 @@
#!/bin/sh
# Verify that tmpfiles only runs the boot-only entries, the ones with
# a ! after the type, at boot or when called with --boot
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/boot
CONF=/tmp/boot.conf
tmpfiles()
{
run "/libexec/finit/tmpfiles $* $CONF"
}
assert_exists()
{
assert "$1 exists" "$(texec sh -c "test -e $1 && echo yes || echo no")" = "$2"
}
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF /fastboot"
rm -f "$NOLOGIN"
}
# Removed at boot by an r! entry in Finit's own legacy.conf
touch "${SYSROOT:-$(pwd)/$TEST_DIR/sysroot}/fastboot"
# What systemd's own tmpfiles.d has, logins are refused until boot is done
NOLOGIN="${SYSROOT:-$(pwd)/$TEST_DIR/sysroot}/etc/tmpfiles.d/nologin.conf"
mkdir -p "$(dirname "$NOLOGIN")"
echo 'f+! /run/nologin 0644 - - - "System is booting up."' > "$NOLOGIN"
echo 'f! /run/nologin-ran' >> "$NOLOGIN"
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep
say 'Finit runs the boot-only entries, and removes, at boot'
assert_exists /fastboot no
sep
say 'Logins are let in again when boot is done'
assert_exists /run/nologin-ran yes
assert_exists /run/nologin no
run "cat > $CONF" <<CONF
d $DIR
f $DIR/always
f! $DIR/boot
f+! $DIR/plus-boot - - - - text
f!+ $DIR/boot-plus - - - - text
r! $DIR/always
CONF
sep
say 'Without --boot they are skipped'
tmpfiles --create --remove
assert_exists $DIR/always yes
assert_exists $DIR/boot no
assert_exists $DIR/plus-boot no
assert_exists $DIR/boot-plus no
sep
say 'With --boot they run, remove before create'
tmpfiles --create --remove --boot
assert_exists $DIR/boot yes
assert "Modifiers in any order" "$(texec cat $DIR/plus-boot $DIR/boot-plus)" = "texttext"
assert_exists $DIR/always yes
tmpfiles --remove --boot
assert_exists $DIR/always no
+117
View File
@@ -0,0 +1,117 @@
#!/bin/sh
# Verify tmpfiles --clean, removing what is older than the age of an entry
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/clean
CONF=/tmp/clean.conf
clean()
{
run "cat > $CONF"
run "/libexec/finit/tmpfiles --clean $CONF"
}
assert_left()
{
assert "Left in $1: $2" "$(texec ls "$1" | tr '\n' ' ')" = "$2"
}
test_teardown()
{
say "Running test teardown."
run "umount $DIR/old/mnt 2>/dev/null; rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "mkdir -p $DIR/old/mnt $DIR/old/sub $DIR/young; touch $DIR/old/file $DIR/old/sub/file $DIR/young/file"
run "mount -t tmpfs none $DIR/old/mnt; touch $DIR/old/mnt/file"
sleep 2
sep
say 'Only what is older than the age is removed, and nothing on another file system'
clean <<CONF
d $DIR/old - - - 1s
d $DIR/young - - - 1h
CONF
assert_left $DIR/young "file "
assert_left $DIR/old "mnt "
assert_left $DIR/old/mnt "file "
sep
say 'x keeps a path and what is in it, X only the path itself'
run "mkdir -p $DIR/keep/all $DIR/keep/dir; touch $DIR/keep/file $DIR/keep/all/file $DIR/keep/dir/file"
sleep 2
clean <<CONF
d $DIR/keep - - - 1s
x $DIR/keep/a*
X $DIR/keep/dir/
CONF
assert_left $DIR/keep "all dir "
assert_left $DIR/keep/all "file "
assert_left $DIR/keep/dir ""
sep
say 'Age 0 removes everything, no age nothing'
run "mkdir -p $DIR/zero $DIR/none; touch $DIR/zero/file $DIR/none/file"
clean <<CONF
d $DIR/zero - - - 0
d $DIR/none - - - -
d $DIR/none
CONF
assert_left $DIR/zero ""
assert_left $DIR/none "file "
sep
say 'Ages with several units, ms, and what a path matched by e holds'
run "mkdir -p $DIR/units $DIR/msec $DIR/long $DIR/glob-1 $DIR/glob-2 $DIR/level/sub $DIR/by-all $DIR/by-m"
run "touch $DIR/units/file $DIR/msec/file $DIR/long/file $DIR/glob-1/file $DIR/glob-2/file"
run "touch $DIR/level/file $DIR/level/sub/file $DIR/by-all/file $DIR/by-m/file"
sleep 2
clean <<CONF
d $DIR/units - - - 0m1s
d $DIR/msec - - - 1500ms
d $DIR/long - - - 1h1s
e $DIR/glob-* - - - 1s
CONF
assert_left $DIR/units ""
assert_left $DIR/msec ""
assert_left $DIR/long "file "
assert_left $DIR/glob-1 ""
assert_left $DIR/glob-2 ""
sep
say 'With ~ what is right in the directory is kept'
clean <<CONF
d $DIR/level - - - ~1s
CONF
assert_left $DIR/level "file sub "
assert_left $DIR/level/sub ""
sep
say 'The timestamps to go by can be chosen, here not the change time'
run "cat > $CONF" <<CONF
d $DIR/by-all - - - 1s
d $DIR/by-m - - - am:1s
d $DIR/by-all - - - AM:1s
d $DIR/by-all - - - :1s
CONF
run "chmod 600 $DIR/by-all/file $DIR/by-m/file; /libexec/finit/tmpfiles --clean $CONF"
assert_left $DIR/by-all "file "
assert_left $DIR/by-m ""
sep
say 'An x entry with an age of its own has what it keeps cleaned by that age'
run "mkdir -p $DIR/own/keep $DIR/own/long; touch $DIR/own/file $DIR/own/keep/file $DIR/own/long/file"
sleep 2
clean <<CONF
d $DIR/own - - - 1s
x $DIR/own/keep - - - 1h
x $DIR/own/lon* - - - 1s
CONF
assert_left $DIR/own "keep long "
assert_left $DIR/own/keep "file "
assert_left $DIR/own/long ""
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
# Verify the C and C+ entries of tmpfiles, copy a file or a tree
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/copy
SRC=/tmp/copy-src
CONF=/tmp/copy.conf
content()
{
texec sh -c "cat $1 2>/dev/null || echo none"
}
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $SRC $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "mkdir -p $SRC/sub $DIR/empty $DIR/full/sub $DIR/merge/sub"
run "echo new > $SRC/file; echo new > $SRC/sub/file; echo new > $SRC/sub/other; ln -s file $SRC/link; chmod 640 $SRC/file"
run "echo old > $DIR/full/file; echo old > $DIR/merge/sub/file; echo old > $DIR/one-old"
run "mkdir $SRC/away $DIR/out; echo new > $SRC/away/file; ln -s ../out $DIR/merge/away"
run "cat > $CONF" <<CONF
C $DIR/tree - - - - $SRC
C $DIR/empty - - - - $SRC
C $DIR/full - - - - $SRC
C+ $DIR/merge - - - - $SRC
C $DIR/one 0600 - - - $SRC/file
C $DIR/one-old - - - - $SRC/file
C $DIR/missing - - - - /no/such/path
CONF
run "/libexec/finit/tmpfiles --create $CONF"
say 'C copies a tree, links are not followed'
assert "File" "$(content $DIR/tree/file)" = "new"
assert "File in subdir" "$(content $DIR/tree/sub/file)" = "new"
assert "Mode is kept" "$(texec stat -c %a $DIR/tree/file)" = "640"
assert "Link is a link" "$(texec readlink $DIR/tree/link)" = "file"
sep
say 'C fills a directory that is empty, and leaves one that is not'
assert "Empty directory" "$(content $DIR/empty/sub/file)" = "new"
assert "Existing file" "$(content $DIR/full/file)" = "old"
assert "Nothing added" "$(content $DIR/full/sub/file)" = "none"
sep
say 'C+ adds what is missing and overwrites nothing'
assert "Existing file" "$(content $DIR/merge/sub/file)" = "old"
assert "Missing file" "$(content $DIR/merge/sub/other)" = "new"
assert "Missing at top" "$(content $DIR/merge/file)" = "new"
assert "Not through a link" "$(content $DIR/out/file)" = "none"
sep
say 'C copies a file, unless it is there'
assert "New file" "$(content $DIR/one)" = "new"
assert "Mode of entry" "$(texec stat -c %a $DIR/one)" = "600"
assert "Existing file" "$(content $DIR/one-old)" = "old"
assert "No source" "$(texec sh -c "ls $DIR | grep -c missing")" = "0"
+69
View File
@@ -0,0 +1,69 @@
#!/bin/sh
# Verify which tmpfiles.d files are read, in what order, and that the
# first entry for a path is the one that counts
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/files
CONF=/tmp/files.conf
LIB=/usr/lib/tmpfiles.d
ETC=/etc/tmpfiles.d
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF $LIB/[0-9]0-test.conf $ETC/[0-9]0-test.conf"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "mkdir -p $LIB $ETC"
run "cat > $LIB/50-test.conf" <<CONF
f $DIR/same - - - - lib
f $DIR/masked - - - - lib
CONF
run "cat > $ETC/50-test.conf" <<CONF
f $DIR/same - - - - etc
CONF
run "cat > $LIB/10-test.conf" <<CONF
f $DIR/first - - - - one
CONF
run "cat > $ETC/20-test.conf" <<CONF
f $DIR/first - - - - two
f $DIR/second - - - - two
w+ $DIR/first - - - - +three
w+ $DIR/first - - - - +four
CONF
run "/libexec/finit/tmpfiles --create --prefix=$DIR"
say 'A file in /etc is read in place of one of the same name in /usr/lib'
assert "Entry from /etc" "$(texec cat $DIR/same)" = "etc"
assert "None from /usr/lib" "$(texec sh -c "ls $DIR | grep -c masked")" = "0"
sep
say 'Files are read by name, and the first entry for a path counts'
assert "First by file name" "$(texec cat $DIR/first)" = "one+three+four"
assert "Told about in a dry run" \
"$(texec sh -c "/libexec/finit/tmpfiles -n --create --prefix=$DIR 2>&1 | grep -c 'already has an entry'")" = "1"
sep
say 'With --replace a file on the command line is read as if it was the one named'
run "cat > $CONF" <<CONF
f $DIR/replace - - - - new
f $DIR/first - - - - new
f $DIR/second - - - - new
CONF
run "rm -rf $DIR; /libexec/finit/tmpfiles --create --prefix=$DIR --replace=$LIB/15-test.conf $CONF"
assert "Read" "$(texec cat $DIR/replace)" = "new"
assert "After the files before its name" "$(texec cat $DIR/first)" = "one+three+four"
assert "Before the ones after it" "$(texec cat $DIR/second)" = "new"
assert "With the other files" "$(texec cat $DIR/same)" = "etc"
run "rm -rf $DIR; /libexec/finit/tmpfiles --create --prefix=$DIR --replace=$LIB/50-test.conf $CONF"
assert "Not when /etc has that name" "$(texec sh -c "ls $DIR | grep -c replace")" = "0"
sep
say 'A file named - is read from standard input'
run "echo 'f $DIR/stdin' | /libexec/finit/tmpfiles --create -"
assert "Entry on stdin" "$(texec sh -c "ls $DIR | grep -c stdin")" = "1"
+63
View File
@@ -0,0 +1,63 @@
#!/bin/sh
# Verify the = modifier of tmpfiles, what is of another kind than the
# entry makes is removed first
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/match
CONF=/tmp/match.conf
kind()
{
texec stat -c %F "$1"
}
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
setup()
{
run "rm -rf $DIR; mkdir -p $DIR/dir/sub $DIR/same; mkfifo $DIR/fifo $DIR/parent; echo old > $DIR/file; echo old > $DIR/keep; echo old > $DIR/link; echo same > $DIR/same/file"
}
conf()
{
run "cat > $CONF" <<CONF
d$1 $DIR/fifo
f$1 $DIR/dir - - - - new
d$1 $DIR/file
f$1 $DIR/parent/file - - - - new
p$1 $DIR/keep
L$1 $DIR/link - - - - /dev/null
d$1 $DIR/same
f$1 $DIR/same/file
CONF
run "/libexec/finit/tmpfiles --create $CONF"
}
setup
conf ""
say 'Without = a path of another kind is left alone'
assert "Pipe for d" "$(kind $DIR/fifo)" = "fifo"
assert "Directory for f" "$(kind $DIR/dir)" = "directory"
assert "File for d" "$(kind $DIR/file)" = "regular file"
assert "Pipe as parent" "$(kind $DIR/parent)" = "fifo"
setup
conf "="
sep
say 'With = it is removed, and made anew'
assert "Pipe for d" "$(kind $DIR/fifo)" = "directory"
assert "Directory for f" "$(texec cat $DIR/dir)" = "new"
assert "File for d" "$(kind $DIR/file)" = "directory"
assert "Pipe as parent" "$(texec cat $DIR/parent/file)" = "new"
assert "File for p" "$(kind $DIR/keep)" = "fifo"
assert "File for L" "$(texec readlink $DIR/link)" = "/dev/null"
assert "Same kind is left alone" "$(texec cat $DIR/same/file)" = "same"
+51
View File
@@ -0,0 +1,51 @@
#!/bin/sh
# Verify the order tmpfiles runs the entries in
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/order
CONF=/tmp/order.conf
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "cat > $CONF" <<CONF
d $DIR
f $DIR/file - - - - new
r $DIR/file
CONF
run "mkdir $DIR; echo old > $DIR/file"
run "/libexec/finit/tmpfiles --create --remove $CONF"
assert "The old file is removed, a new one created" "$(texec cat $DIR/file)" = "new"
sep
say 'With --dry-run it only tells what it would do, in that order'
run "cat > $CONF" <<CONF
f $DIR/dry - - - - text
r $DIR/file
d $DIR/sub - - - 1d
CONF
out=$(texec /libexec/finit/tmpfiles --dry-run --create --remove --clean "$CONF")
assert "What it would do" "$(echo "$out" | tr '\n' ';')" = "clean d $DIR/sub, older than 1d;remove r $DIR/file;create f $DIR/dry text;create d $DIR/sub;"
assert "Nothing is done" "$(texec ls $DIR)" = "file"
sep
say 'A path is made after the one above it, wherever in the file they are'
run "cat > $CONF" <<CONF
w $DIR/real/file - - - - XY
d $DIR/real
f $DIR/link/file - - - - text
L $DIR/link - - - - real
CONF
run "/libexec/finit/tmpfiles --create $CONF"
assert "Link before the file below it" "$(texec readlink $DIR/link)" = "real"
say 'An entry that takes a glob, like w, is run after the others'
assert "File before it is written to" "$(texec cat $DIR/real/file)" = "XYxt"
+130
View File
@@ -0,0 +1,130 @@
#!/bin/sh
# Verify that tmpfiles leaves the mode and owner of an existing
# directory alone when the entry does not give them, issue #523
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/perm
CONF=/tmp/perm.conf
# Run tmpfiles with entry $1, then check mode $2 and owner $3 of $DIR
assert_perm()
{
run "echo '$1' > $CONF"
run "/libexec/finit/tmpfiles --create $CONF"
assert "Entry '$1' gives $2 $3" "$(texec stat -c '%a %U:%G' $DIR)" = "$2 $3"
}
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep
say 'A new directory gets the default mode and owner'
assert_perm "d $DIR" 755 root:root
sep
say 'An existing directory keeps what the entry does not give'
run "chmod 1777 $DIR; chown daemon:daemon $DIR"
assert_perm "d $DIR" 1777 daemon:daemon
assert_perm "d $DIR - - -" 1777 daemon:daemon
assert_perm "d $DIR 0750" 750 daemon:daemon
assert_perm "d $DIR - bin" 750 bin:daemon
assert_perm "d $DIR - - sys" 750 bin:sys
assert_perm "e $DIR" 750 bin:sys
assert_perm "d $DIR 1777 root root" 1777 root:root
sep
say 'An unknown user skips the entry, an unknown group only the group'
run "cat > $CONF" <<CONF
d $DIR/user 0755 nosuchuser
f $DIR/file 0644 nosuchuser
d $DIR/group 0750 bin nosuchgroup
CONF
run "/libexec/finit/tmpfiles --create $CONF"
assert "Only the entry with a known user is created" "$(texec ls $DIR)" = "group"
assert "With its mode and user" "$(texec stat -c '%a %U:%G' $DIR/group)" = "750 bin:root"
sep
say 'With : mode and owner are only for a path the entry creates'
run "rm -rf $DIR; mkdir $DIR; chmod 1777 $DIR"
assert_perm "d $DIR :0700 :bin :bin" 1777 root:root
run "rmdir $DIR"
assert_perm "d $DIR :0700 :bin :bin" 700 bin:bin
sep
say 'With ~ the mode loses what no one has on the path'
run "chmod 500 $DIR"
assert_perm "e $DIR ~0777" 555 bin:bin
assert_perm "e $DIR :~0700 :sys" 555 bin:bin
sep
say 'Mode and owner of an f entry are set on an existing file too'
run "echo keep > $DIR/file; chmod 600 $DIR/file"
run "echo 'f $DIR/file 0644 bin sys - new' > $CONF; /libexec/finit/tmpfiles --create $CONF"
assert "Mode and owner" "$(texec stat -c '%a %U:%G' $DIR/file)" = "644 bin:sys"
assert "Content is kept" "$(texec cat $DIR/file)" = "keep"
sep
say 'Mode and owner of p, C, z, and Z entries'
run "mkdir -p $DIR/tree/sub; touch $DIR/tree/sub/file"
run "cat > $CONF" <<CONF
p $DIR/fifo 0660 bin sys
C $DIR/copy 0600 bin sys - /etc/group
z $DIR/file 0600 sys bin
Z $DIR/tree - bin sys
CONF
run "umask 077; /libexec/finit/tmpfiles --create $CONF"
assert "p" "$(texec stat -c '%a %U:%G' $DIR/fifo)" = "660 bin:sys"
assert "C" "$(texec stat -c '%a %U:%G' $DIR/copy)" = "600 bin:sys"
assert "z" "$(texec stat -c '%a %U:%G' $DIR/file)" = "600 sys:bin"
assert "Z" "$(texec stat -c '%U:%G' $DIR/tree/sub/file)" = "bin:sys"
sep
say 'A p entry leaves a path that is not a fifo alone'
run "echo 'p $DIR/file 0644 root root' > $CONF; /libexec/finit/tmpfiles --create $CONF"
assert "Not a fifo" "$(texec stat -c '%a %U:%G' $DIR/file)" = "600 sys:bin"
sep
say 'Setuid survives a change of owner, and ~ can take every bit'
run "touch $DIR/suid $DIR/none; chmod 4755 $DIR/suid; chmod 111 $DIR/none"
run "cat > $CONF" <<CONF
f $DIR/suid 4755 bin sys
f $DIR/keep - sys bin
f $DIR/none ~0600
CONF
run "touch $DIR/keep; chmod 2755 $DIR/keep; /libexec/finit/tmpfiles --create $CONF"
assert "Mode given" "$(texec stat -c '%a %U:%G' $DIR/suid)" = "4755 bin:sys"
assert "Mode not given" "$(texec stat -c '%a %U:%G' $DIR/keep)" = "2755 sys:bin"
assert "Masked to 0" "$(texec stat -c '%a' $DIR/none)" = "0"
sep
say 'v, q, and Q entries make a plain directory, like d'
run "cat > $CONF" <<CONF
v $DIR/v 0750 bin sys
q $DIR/q 0700 sys bin
Q $DIR/Q
CONF
run "/libexec/finit/tmpfiles --create $CONF"
assert "v" "$(texec stat -c '%F %a %U:%G' $DIR/v)" = "directory 750 bin:sys"
assert "q" "$(texec stat -c '%F %a %U:%G' $DIR/q)" = "directory 700 sys:bin"
assert "Q" "$(texec stat -c '%F %a %U:%G' $DIR/Q)" = "directory 755 root:root"
sep
say 'A new file without a mode is 0644, whatever the umask'
run "echo 'f $DIR/default' > $CONF; umask 077; /libexec/finit/tmpfiles --create $CONF"
assert "Default mode" "$(texec stat -c '%a' $DIR/default)" = "644"
sep
say 'A link to a directory is left alone, without complaints'
run "mkdir $DIR/real; chmod 700 $DIR/real; ln -s real $DIR/link"
run "printf 'd $DIR/link 0755\ne $DIR/link 0755\n' > $CONF"
msg=$(texec sh -c "/libexec/finit/tmpfiles --create $CONF 2>&1")
assert "No warning" "$msg" = ""
assert "Directory as it was" "$(texec stat -c '%a' $DIR/real)" = "700"
+47
View File
@@ -0,0 +1,47 @@
#!/bin/sh
# Verify tmpfiles --purge, which removes what the entries marked with a
# $ make, for when a package is uninstalled
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/purge
CONF=/tmp/purge.conf
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "cat > $CONF" <<CONF
d $DIR
d\$ $DIR/state
f\$ $DIR/state/file - - - - text
f\$ $DIR/file
L\$ $DIR/link - - - - file
e\$ $DIR/glob-*
d $DIR/kept
f $DIR/kept/file
r\$ $DIR/other
CONF
run "/libexec/finit/tmpfiles --create $CONF"
run "mkdir $DIR/glob-1 $DIR/glob-2 $DIR/state/more; touch $DIR/other"
say 'Only tells what it would do with --dry-run'
out=$(texec /libexec/finit/tmpfiles --dry-run --purge "$CONF")
assert "Entries with a \$, a path before the one above it" "$(echo "$out" | tr '\n' ';')" \
= "purge f\$ $DIR/state/file;purge d\$ $DIR/state;purge f\$ $DIR/file;purge L\$ $DIR/link;purge e\$ $DIR/glob-*;"
sep
say 'Removes what the entries with a $ make, and nothing else'
run "/libexec/finit/tmpfiles --purge $CONF"
assert "What is left" "$(texec ls $DIR | tr '\n' ' ')" = "kept other "
assert "And in it" "$(texec ls $DIR/kept)" = "file"
sep
say 'Needs a file, it is not for all of the tmpfiles.d files'
assert "Refused without one" "$(texec sh -c "/libexec/finit/tmpfiles --purge >/dev/null 2>&1; echo \$?")" = "1"
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
# Verify tmpfiles --root, which runs on the system below a directory:
# its tmpfiles.d files, its users, and its paths
set -eu
TEST_DIR=$(dirname "$0")
ROOT=/tmp/root
CONF=/tmp/root.conf
assert_stat()
{
assert "$1 is $2" "$(texec stat -c '%a %u %g' "$ROOT$1")" = "$2"
}
test_teardown()
{
say "Running test teardown."
run "rm -rf $ROOT $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "mkdir -p $ROOT/etc/tmpfiles.d $ROOT/usr/share/factory/etc"
run "echo 'app:x:1:1::/:/bin/sh' > $ROOT/etc/passwd"
run "echo 'grp:x:2:' > $ROOT/etc/group"
run "echo factory > $ROOT/usr/share/factory/etc/issue"
run "cat > $ROOT/etc/tmpfiles.d/root.conf" <<CONF
d /var/lib/root-test 0750 app grp
f /var/lib/root-test/file 0600 - - - inside
f /var/lib/root-test/other 0600
z /var/lib/root-test/other 0644
L /link - - - - /var/lib/root-test
f /link/through 0640
C /etc/issue
C /etc/outside - - - - ../../../etc/passwd
d /skipped 0700 daemon
CONF
run "echo 'd /from/cmdline 0711' > $CONF"
# The leak check of a sanitizer build needs /proc, the root has none
tmpfiles()
{
run "ASAN_OPTIONS=detect_leaks=0 /libexec/finit/tmpfiles --create --root=$ROOT $*"
}
tmpfiles
say 'The tmpfiles.d files, users, and groups are those below the root'
assert_stat /var/lib/root-test "750 1 2"
assert "File content" "$(texec cat $ROOT/var/lib/root-test/file)" = "inside"
assert "No user daemon there" "$(texec sh -c "ls $ROOT | grep -c skipped")" = "0"
sep
say 'So are the paths, also what a link points to'
assert_stat /var/lib/root-test/other "644 0 0"
assert_stat /var/lib/root-test/through "640 0 0"
assert "Copied from its factory" "$(texec cat $ROOT/etc/issue)" = "factory"
assert "No copy from outside it" "$(texec sh -c "ls $ROOT/etc | grep -c outside")" = "0"
assert "Nothing outside it" "$(texec sh -c "ls /var/lib | grep -c root-test")" = "0"
sep
say 'A file on the command line is not below the root'
tmpfiles $CONF
assert_stat /from/cmdline "711 0 0"
+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
# Verify the % specifiers of tmpfiles.d(5), in the path and the argument
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/specifier
CONF=/tmp/specifier.conf
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF /etc/os-release"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "cat > /etc/os-release" <<OS
NAME="Finit Test"
ID=finit-test
VERSION_ID="1.2"
OS
run "cat > $CONF" <<CONF
d $DIR
f $DIR/os-%o-%w
f $DIR/arch-%a
f $DIR/variant-%W
f $DIR/host-%H
f $DIR/kernel-%v
f $DIR/machine-%m
f $DIR/boot-%b
f $DIR/100%%
f $DIR/end%
f $DIR/unknown - - - - %!
f $DIR/arg - - - - %T %V %t %S %C %L %h %u %U %g %G %l
CONF
run "/libexec/finit/tmpfiles --create $CONF"
host=$(texec hostname)
assert "Hostname" "$(texec ls $DIR/host-"$host")" = "$DIR/host-$host"
assert "Kernel release" "$(texec ls $DIR/kernel-"$(texec uname -r)")" = "$DIR/kernel-$(texec uname -r)"
assert "Machine ID" "$(texec ls $DIR/machine-"$(texec cat /etc/machine-id)")" = "$DIR/machine-$(texec cat /etc/machine-id)"
boot=$(texec cat /proc/sys/kernel/random/boot_id | tr -d -)
assert "Boot ID" "$(texec ls $DIR/boot-"$boot")" = "$DIR/boot-$boot"
assert "Percent" "$(texec ls $DIR/100%)" = "$DIR/100%"
assert "In the argument" "$(texec cat $DIR/arg)" = "/tmp /var/tmp /run /var/lib /var/cache /var/log /root root 0 root 0 ${host%%.*}"
assert "Skipped: a lone % and an unknown specifier" "$(texec sh -c "ls $DIR | grep -c -e end -e unknown")" = "0"
assert "OS ID and version" "$(texec ls $DIR/os-finit-test-1.2)" = "$DIR/os-finit-test-1.2"
assert "Architecture" "$(texec sh -c "ls $DIR | grep -c '^arch-.'")" = "1"
assert "Empty when not in os-release" "$(texec ls $DIR/variant-)" = "$DIR/variant-"
sep
say "%T and %V follow \$TMPDIR when it is a directory"
run "cat > $CONF" <<CONF
f $DIR/tmpdir - - - - %T %V
CONF
run "TMPDIR=$DIR /libexec/finit/tmpfiles --create $CONF"
assert "From the environment" "$(texec cat $DIR/tmpdir)" = "$DIR $DIR"
run "rm $DIR/tmpdir; TMPDIR=/no/such/dir /libexec/finit/tmpfiles --create $CONF"
assert "Not a directory" "$(texec cat $DIR/tmpdir)" = "/tmp /var/tmp"
+36
View File
@@ -0,0 +1,36 @@
#!/bin/sh
# Verify that tmpfiles skips an entry it does not support, and goes on
# with the rest
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/unsupported
CONF=/tmp/unsupported.conf
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "cat > $CONF" <<CONF
d $DIR
y $DIR - - - - +i
f $DIR/%!
f $DIR/after
CONF
say 'Create only'
msg=$(texec sh -c "/libexec/finit/tmpfiles --create $CONF 2>&1")
assert "The entry after is created" "$(texec ls $DIR)" = "after"
assert "Each is reported once" "$(echo "$msg" | grep -c skipping)" -eq 2
say 'Remove and create, two passes'
run "rm $DIR/after"
msg=$(texec sh -c "/libexec/finit/tmpfiles --create --remove $CONF 2>&1")
assert "The entry after is created" "$(texec ls $DIR)" = "after"
assert "Each is reported once" "$(echo "$msg" | grep -c skipping)" -eq 2
+1 -5
View File
@@ -1,8 +1,4 @@
d /run/lock 0755 root root -
L /var/lock - - - - ../run/lock
d /run/lock/subsys 0755 root root -
# For /run/lock and /var/lock, see var.conf
L /run/shm - - - - ../dev/shm
# These are not supported by Finit, see command line options
+1 -3
View File
@@ -19,8 +19,7 @@ f /run/console/console.lock 0644 - - - nobody
d /run/lock 0777 - - -
d /run/lock/subsys 0755 - - -
# Compat symlink to new /run ramdisk
L /var/run - - - - ../run
# Compat symlink to new /run ramdisk, for /var/run see finit.conf
L /var/lock - - - - ../run/lock
# Needed by Debian/Ubuntu ifupdown
@@ -35,7 +34,6 @@ d /var/empty 0755 - - -
d /var/log 0755 - - -
d /var/mail 0755 - - -
d /var/opt 0755 - - -
d /var/spool 0755 - - -
d /var/spool/cron 0755 - - -
# UTMP actually needs multiple db files