Compare commits

..
31 Commits
Author SHA1 Message Date
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
Joachim Wiberg 59a2f69345 Merge pull request #515 from augustebaum/patch-1
docs: Fix nested bulleted list
2026-11-09 17:14:29 +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
Auguste Baum cbd5f79ffd docs: Fix nested bulleted list 2026-10-30 12:13:23 +01:00
Joachim Wiberg a220e0fa9b Merge pull request #514 from vazub/static-fix
Fix static build dropping all built-in plugins
2026-10-27 12:24:28 +01:00
Basil Zubko 1efd50191c fix static build dropping all built-in plugins 2026-10-24 15:13:10 +02:00
Joachim Wiberg 096e6337c5 Merge pull request #513 from vazub/keventd-input
keventd: fix ENV{} match on unset properties
2026-10-24 12:33:46 +02:00
Basil Zubko 02cd1bac42 keventd: fix ENV{} match on unset properties 2026-10-24 09:06:23 +00: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
Joachim Wiberg 530d6703f1 Merge pull request #509 from anees-r3hman/umount-rc
mount: report unmount failures
2026-10-12 09:38:08 +02:00
Anees Rehman c016965371 mount: report unmount failures
Return a failure status from unmount_regular() when filesystems remain
mounted, and use it to report the final shutdown unmount result.

Signed-off-by: Anees Rehman <anees.rehman@atlascopco.com>
2026-09-25 21:20:02 +02:00
38 changed files with 1544 additions and 236 deletions

No files matched your search

+35
View File
@@ -8,6 +8,12 @@ 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
- 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 +149,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 +166,28 @@ 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)
- 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,
+10
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
@@ -37,6 +41,7 @@ version of the above mentioned libraries. Currently required versions:
- libuEv v2.2.0, 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
+1
View File
@@ -69,6 +69,7 @@ Service options
| `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` |
+21
View File
@@ -259,6 +259,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:
+6 -6
View File
@@ -3,15 +3,15 @@ Starting & Monitoring
Finit can start and monitor the following types of daemons:
* Forks to background, creates a PID file
* Runs in foreground and signals ready by:
- creating a PID file
- does not create a PID file -- Finit can create it for you (optional)
- [other mechanism][1] (systemd, s6)
* Forks to background, creates a PID file
* Runs in foreground and signals ready by:
- creating a PID file
- does not create a PID file -- Finit can create it for you (optional)
- [other mechanism][1] (systemd, s6)
Finit can *not* start and monitor a daemon that:
* Forks to background and does *not* create a PID file
* Forks to background and does *not* create a PID file
| | Forking | Creates PID File | Finit creates PID File |
|---|---------|------------------|------------------------|
+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);
}
+36 -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 */
@@ -1045,6 +1073,8 @@ static int match_key(const struct rule *r, const struct rule_key *k,
if (!k->attr)
return (k->op == OP_MATCH_NE);
subject = uevent_getenv(ev, k->attr);
if (!subject)
subject = "";
break;
case KEY_CONST: {
if (!k->attr) {
@@ -1099,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];
@@ -1625,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 ?: "");
+12
View File
@@ -470,6 +470,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
+18 -13
View File
@@ -6,51 +6,56 @@ AM_CPPFLAGS += -D_XOPEN_SOURCE=600 -D_BSD_SOURCE -D_GNU_SOURCE -D_DEFAULT
AM_CPPFLAGS += -D__FINIT__ $(lite_CFLAGS) $(uev_CFLAGS)
if STATIC
noinst_LTLIBRARIES = libplug.la
libplug_la_SOURCES = bootmisc.c pidfile.c procps.c sys.c usr.c
noinst_LIBRARIES = libplug.a
libplug_a_SOURCES = bootmisc.c pidfile.c procps.c sys.c usr.c
libplug_a_CFLAGS = $(AM_CFLAGS)
if BUILD_ALSA_UTILS_PLUGIN
libplug_la_SOURCES += alsa-utils.c
libplug_a_SOURCES += alsa-utils.c
endif
if BUILD_DBUS_PLUGIN
libplug_la_SOURCES += dbus.c
libplug_a_SOURCES += dbus.c
endif
if BUILD_HOOK_SCRIPTS_PLUGIN
libplug_a_SOURCES += hook-scripts.c
endif
if BUILD_MODULES_LOAD_PLUGIN
libplug_la_SOURCES += modules-load.c
libplug_a_SOURCES += modules-load.c
endif
if BUILD_MODPROBE_PLUGIN
libplug_la_SOURCES += modprobe.c
libplug_a_SOURCES += modprobe.c
endif
if BUILD_NETLINK_PLUGIN
libplug_la_SOURCES += netlink.c
libplug_a_SOURCES += netlink.c
endif
if BUILD_PLYMOUTH_PLUGIN
libplug_la_SOURCES += plymouth.c
libplug_a_SOURCES += plymouth.c
endif
if BUILD_RESOLVCONF_PLUGIN
libplug_la_SOURCES += resolvconf.c
libplug_a_SOURCES += resolvconf.c
endif
if BUILD_RTC_PLUGIN
libplug_la_SOURCES += rtc.c
libplug_a_SOURCES += rtc.c
endif
if BUILD_TTY_PLUGIN
libplug_la_SOURCES += tty.c
libplug_a_SOURCES += tty.c
endif
if BUILD_URANDOM_PLUGIN
libplug_la_SOURCES += urandom.c
libplug_a_SOURCES += urandom.c
endif
if BUILD_X11_COMMON_PLUGIN
libplug_la_SOURCES += x11-common.c
libplug_a_SOURCES += x11-common.c
endif
else
+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)
+4 -1
View File
@@ -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 \
@@ -87,8 +88,10 @@ finit_CPPFLAGS = $(AM_CPPFLAGS) -D__FINIT__
finit_CFLAGS = -W -Wall -Wextra -Wno-unused-parameter -std=gnu99
finit_CFLAGS += $(lite_CFLAGS) $(uev_CFLAGS) $(confuse_CFLAGS)
finit_LDADD = $(lite_LIBS) $(uev_LIBS) $(confuse_LIBS)
finit_LDFLAGS = $(AM_LDFLAGS)
if STATIC
finit_LDADD += ../plugins/libplug.la
finit_LDADD += ../plugins/libplug.a
finit_LDFLAGS += -Wl,--whole-archive,../plugins/libplug.a,--no-whole-archive
else
finit_LDADD += -ldl
endif
+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);
+11 -7
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"
@@ -265,6 +268,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 +1127,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 +1444,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)
{
@@ -1671,6 +1675,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 +1731,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 +1808,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);
}
/*
+6 -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)
{
+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
+30
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
+6 -2
View File
@@ -121,15 +121,19 @@ void unmount_tmpfs(void)
}
}
void unmount_regular(void)
int unmount_regular(void)
{
const struct mntent *mnt;
FILE *fp = NULL;
int rc = 0;
while ((mnt = iterator("/proc/mounts", &fp))) {
if (!unmount(mnt->mnt_dir))
rc = unmount(mnt->mnt_dir);
if (!rc)
iterator_end(&fp); /* Restart iteration */
}
return !!rc;
}
/**
+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();
+234 -88
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;
@@ -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,58 @@ static void parse_sighalt(svc_t *svc, char *arg)
svc->sighalt = signo;
}
static const char *scopes[] = {
[SVC_SCOPE_PGROUP] = "pgroup",
[SVC_SCOPE_PROCESS] = "process",
[SVC_SCOPE_CGROUP] = "cgroup",
[SVC_SCOPE_MIXED] = "mixed",
};
static svc_scope_t parse_scope(svc_t *svc, const char *arg)
{
size_t i;
if (!arg)
return SVC_SCOPE_PGROUP;
for (i = 0; i < NELEMS(scopes); i++) {
if (!strcmp(arg, scopes[i]))
return (svc_scope_t)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)), scopes[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 +2248,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 +2309,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;
@@ -2245,24 +2348,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 +2357,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 +2375,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))
@@ -2310,9 +2399,9 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
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 (!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 +2409,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 +2436,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 +2566,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 +2580,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 +2637,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
@@ -2713,6 +2803,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 +2821,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 +2946,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)) {
@@ -3298,16 +3430,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 */
@@ -3378,8 +3520,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 +3540,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)
@@ -3727,7 +3873,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;
}
+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 -3
View File
@@ -170,7 +170,7 @@ static struct sigmap {
void mdadm_wait(void);
void unmount_tmpfs(void);
void unmount_regular(void);
int unmount_regular(void);
static void fs_swapoff(void)
{
@@ -302,6 +302,7 @@ void do_shutdown(shutop_t op)
struct sched_param sched_param = { .sched_priority = 99 };
int in_cont = in_container();
int signo = SIGTERM;
int rc;
if (SHUTDOWN_DEBUG) cprintf("do_shutdown: entered, op=%d\n", op);
@@ -377,12 +378,13 @@ void do_shutdown(shutop_t op)
}
/* Unmount any tmpfs before unmounting swap ... */
print(0, "Unmounting filesystems ...");
print(-1, "Unmounting filesystems ...");
unmount_tmpfs();
fs_swapoff();
/* ... unmount remaining regular file systems. */
unmount_regular();
rc = unmount_regular();
print(rc, NULL);
/*
* We sit on / so we must remount it ro, try all the things!
+12 -3
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() */
@@ -200,8 +209,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 +333,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; }
+10
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,16 @@ 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-self.sh
EXTRA_DIST += runlevel.sh
EXTRA_DIST += run-restart-forever.sh
@@ -105,6 +110,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 +129,16 @@ 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-self.sh
TESTS += runlevel.sh
TESTS += sysvparts.sh
+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"
+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'
+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