Compare commits

...
24 Commits
Author SHA1 Message Date
Joachim Wiberg 513f47813e tmpfiles: keep the mode of an existing directory when none is given
A d entry without a mode reset an existing directory to 0755.  On
finix a bare "d /tmp" line took the sticky bit and the write
permission for others off the /tmp mount, so nobody but root could
create files there:

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

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

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

Fixes #523

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
(cherry picked from commit 94bdccd2002d8847736743cb31e9b7bd56bdcada)
2026-11-20 17:51:40 +01:00
Joachim Wiberg 90523404b3 tmpfiles: free the glob result of an e entry
An e entry leaked the path list from glob().  tmpfiles exits right
after, so it only shows in a build with the address sanitizer, where
LeakSanitizer makes tmpfiles exit with an error:

    tmpfiles --create e.conf

Free the list when the entry is done.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
(cherry picked from commit 73ebc7fb365cab993bc4f2cf4066f0865c99b14b)
2026-11-20 17:51:33 +01:00
Joachim Wiberg 0f01284ff2 doc: ChangeLog entry for the fgetval() crash fix
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 17:26:46 +01:00
Joachim Wiberg b5d8c2b16b plugins: fix leak of unknown 'set' command in modules-load
An unknown 'set foo' line in modules-load.d leaks the string returned
by fgetval().  Free it before skipping the line.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 17:16:15 +01:00
Joachim Wiberg f8c2927672 helpers: fix fgetval() crash on empty value
getty crashes reading /etc/os-release when a key it looks for has no
value, e.g.:

    VERSION=

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

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

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

Reported-by: Tobias Waldekranz <tobias@waldekranz.com>
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 17:16:15 +01:00
Joachim Wiberg 8a5102e714 service: drop a service's group when the configuration drops it
Changing a service from @alice:wheel to @alice 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>
(cherry picked from commit bf42811a13)
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 08:03:50 +01:00
Joachim Wiberg 5049c32c35 service: lift the limit of four supplementary groups
A service listing more than four supplementary groups, as in
@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>
(cherry picked from commit de73b06415)
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 08:02:42 +01:00
Joachim Wiberg 66b62cbd45 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, and cgroupfs-mount.

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>
(cherry picked from commit f15e95d1cc)
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 08:01:11 +01:00
Joachim Wiberg fe59fd5dc7 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>
(cherry picked from commit 35c313c2fa)
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 07:50:18 +01:00
Joachim Wiberg 341c8ece2d 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>
(cherry picked from commit a1706e8ebd)
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 07:50:08 +01:00
Basil Zubko f105ba4bb6 fix static build dropping all built-in plugins
(cherry picked from commit 1efd50191c)
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-10-27 12:31:08 +01:00
Anees Rehman 70a44d3860 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-10-12 09:39:03 +02:00
Joachim Wiberg f29a3db86c doc: ChangeLog entry for the lost reload fix
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-27 18:56:00 +02:00
Joachim Wiberg f6b394e0a2 service: keep a pending reload across a second conf reload
A service whose condition goes into flux during a reload is paused
with its reload still pending.  If another reload was requested in
the meantime, re-parsing its unchanged .conf file cleared the pending
mark, so the service was resumed without ever being reloaded.  Seen
with sshd <pid/syslogd> on Infix, where a configuration change that
touched both landed as two reloads in a row and sshd kept its old
listen addresses.

The mark is only ever cleared once the change has been applied, so a
mark that is still set when the file is parsed again means exactly
that: not applied yet.  Leave it alone.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-27 18:40:44 +02:00
Joachim Wiberg ccaa4caf48 Bump version and update ChangeLog for 4.18
Covers the longer user and group names, the tmpfiles mode and owner
work, the shutdown remount order, and the script timeout crash.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-27 18:03:24 +02:00
Anees Rehman 77d199f1a4 sig: avoid reading fstab during shutdown
Only fall back to the regular mount invocation when both
fstab-independent root remount attempts fail.
This avoids reading an encrypted fstab during a normal shutdown.

Signed-off-by: Anees Rehman <anees.rehman@atlascopco.com>
(cherry picked from commit 263ea929fd)
2026-09-27 17:59:15 +02:00
Anees Rehman 0448151c0a svc: allow longer user and group names
Service user and group names are stored in 16-byte buffers, limiting
them to 15 characters. This silently truncates longer names before
getpwnam() and getgrnam(), preventing services configured with valid
longer account names from starting.

Increase the buffers to match the existing maximum configuration
argument length.

Signed-off-by: Anees Rehman <anees.rehman@atlascopco.com>
2026-09-27 17:43:11 +02:00
Joachim Wiberg 75739fbeef tmpfiles: apply mode and owner of e and f/F entries through an fd
Same treatment as d/D got: e went through fisdir() and a path based
chmod/chown, f/F did the chmod/chown by path after closing the file.
Both now work on the open fd, so the mode and owner end up on the
directory or file that was just checked or written.  f/F use open(2)
directly, which lets a plain f rely on O_EXCL for create-if-missing
instead of the earlier stat().

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-27 17:29:51 +02:00
Sam Brkopac 3a72d1263c tmpfiles: set mode and owner of d/D directories through an fd
makedir() swallows EEXIST, so the chmod branch for directories that
already existed never ran, while chown() ran every time.  On finix
/var/empty is immutable, which gave a warning on every boot even
though the owner was already correct.

mksubsys() is the original of this code and has the same shape, the
dbus plugin uses it for /tmp/dbus.  Both now go through dirperm(),
which opens the directory and uses fstat/fchmod/fchown on the fd,
changing only what differs.  A failed chown in mksubsys() is a warning
now rather than err(1), PID 1 should not exit over a directory it
cannot adjust.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-27 17:25:50 +02:00
Joachim Wiberg 7e2b154f9b .github: update actions to Node.js 24
All workflow runs now warn:

    Node.js 20 is deprecated. The following actions target Node.js 20
    but are being forced to run on Node.js 24.

Update the actions/* dependencies to their current major versions,
all of which target Node.js 24: checkout v7, upload-artifact v7,
download-artifact v8, setup-python v7, and cache v6.  The release
action tracks the floating v1 tag and updates on its own.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-07-30 15:09:36 +02:00
Joachim Wiberg 547e59b2ad .github: allow building and releasing from maintenance branches
With 5.0 on master, maintenance releases move to a 4.x branch: run
push builds, docs deploy, and weekly distcheck for any N.x branch,
and mark only the highest stable tag as the latest release.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-07-30 14:45:11 +02:00
Joachim Wiberg 7f37d0c4e9 test: refuse to run against a stale sysroot binary
'make check' refreshes the sysroot through the setup-chroot rule, but
running a test script by hand does not, so the test exercises whichever
finit was installed last and reports on code that is no longer there.
Both a passing and a failing run are then meaningless, and nothing says
so.

Compare the built binary against the installed one at startup and fail
with the command that fixes it.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-07-30 14:17:04 +02:00
Joachim Wiberg dd77f63ad3 service: do not let a script timeout take PID 1 with it
A stop: or reload: script written with a timeout killed Finit at
config load:

    service stop:5,/bin/true service.sh -- Boom

parse_script() takes the timeout as a pointer and the caller decides
whether it wants one.  However, both stop: and reload: scripts so far
have no timeout, i.e., NULL.  Guard the branch that reads a leading
number.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-07-30 14:16:50 +02:00
Joachim Wiberg e0f9df1f27 test: reap the watchdog's sleep in wdkill()
Every test left a stray `sleep 300` behind, reparented to PID 1, where
it lingered for up to five minutes after the test had finished.

wdstart() runs the watchdog in a subshell, so $! is the pid of the
subshell, not of the sleep it forks.  wdkill() killed the subshell and
orphaned the sleep.

Kill the child first, killing the subshell puts the sleep beyond the
reach of pkill -P.  Neither kill is sure to match, and wdkill() runs
from the EXIT trap under set -e, so both must tolerate failure.  Also
return early when wdpid is unset, for failures before wdstart() runs.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-07-30 14:15:22 +02:00
28 changed files with 653 additions and 149 deletions

No files matched your search

+7 -8
View File
@@ -1,12 +1,13 @@
name: Bob the Builder name: Bob the Builder
# Run on all branches, including all pull requests, except the 'dev' # Run on push to release branches (master and maintenance N.x), and
# branch since that's where we run Coverity Scan (limited tokens/day) # on all pull requests. The 'dev' branch is where we run Coverity
# Scan (limited tokens/day)
on: on:
push: push:
branches: branches:
- '**' - master
- '!dev' - '[0-9]+.x'
pull_request: pull_request:
types: [opened, synchronize, reopened, labeled] types: [opened, synchronize, reopened, labeled]
@@ -22,8 +23,6 @@ jobs:
# Verify we can build on latest Ubuntu with both gcc and clang # Verify we can build on latest Ubuntu with both gcc and clang
name: ${{ matrix.compiler }} name: ${{ matrix.compiler }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
# Skip redundant builds for PRs - prefer PR builds over push builds
if: github.event_name != 'push' || github.ref == 'refs/heads/master'
strategy: strategy:
matrix: matrix:
compiler: [gcc, clang] compiler: [gcc, clang]
@@ -43,7 +42,7 @@ jobs:
(cd libuev-2.4.1 && ./configure && make -j9 && sudo make install-strip) (cd libuev-2.4.1 && ./configure && make -j9 && sudo make install-strip)
(cd libite-2.6.2 && ./configure && make -j9 && sudo make install-strip) (cd libite-2.6.2 && ./configure && make -j9 && sudo make install-strip)
sudo ldconfig sudo ldconfig
- uses: actions/checkout@v4 - uses: actions/checkout@v7
- name: Static Finit - name: Static Finit
run: | run: |
./autogen.sh ./autogen.sh
@@ -81,7 +80,7 @@ jobs:
make -j1 check || (cat test/test-suite.log; false) make -j1 check || (cat test/test-suite.log; false)
- name: Upload Test Results - name: Upload Test Results
if: always() if: always()
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v7
with: with:
name: finit-test-${{ matrix.compiler }} name: finit-test-${{ matrix.compiler }}
path: test/*.log path: test/*.log
+3 -3
View File
@@ -19,7 +19,7 @@ jobs:
coverity: coverity:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v7
- name: Fetch latest Coverity Scan MD5 - name: Fetch latest Coverity Scan MD5
id: var id: var
env: env:
@@ -29,7 +29,7 @@ jobs:
--post-data "token=$TOKEN&project=${COVERITY_PROJ}&md5=1" \ --post-data "token=$TOKEN&project=${COVERITY_PROJ}&md5=1" \
-O coverity-latest.tar.gz.md5 -O coverity-latest.tar.gz.md5
echo "md5=$(cat coverity-latest.tar.gz.md5)" | tee -a $GITHUB_OUTPUT echo "md5=$(cat coverity-latest.tar.gz.md5)" | tee -a $GITHUB_OUTPUT
- uses: actions/cache@v4 - uses: actions/cache@v6
id: cache id: cache
with: with:
path: coverity-latest.tar.gz path: coverity-latest.tar.gz
@@ -86,7 +86,7 @@ jobs:
--form description="${PROJECT_NAME} $(git rev-parse HEAD)" \ --form description="${PROJECT_NAME} $(git rev-parse HEAD)" \
https://scan.coverity.com/builds?project=${COVERITY_PROJ} https://scan.coverity.com/builds?project=${COVERITY_PROJ}
- name: Upload build.log - name: Upload build.log
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v7
with: with:
name: coverity-build.log name: coverity-build.log
path: cov-int/build-log.txt path: cov-int/build-log.txt
+6 -6
View File
@@ -4,7 +4,7 @@ on:
push: push:
branches: branches:
- master - master
- 4.x - '[0-9]+.x'
paths: paths:
- 'doc/**' - 'doc/**'
- 'README.md' - 'README.md'
@@ -30,7 +30,7 @@ jobs:
version: ${{ steps.version.outputs.version }} version: ${{ steps.version.outputs.version }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v7
with: with:
fetch-depth: 0 # Needed for git-revision-date-localized plugin fetch-depth: 0 # Needed for git-revision-date-localized plugin
@@ -42,7 +42,7 @@ jobs:
echo "version=$version" >> $GITHUB_OUTPUT echo "version=$version" >> $GITHUB_OUTPUT
- name: Setup Python - name: Setup Python
uses: actions/setup-python@v4 uses: actions/setup-python@v7
with: with:
python-version: '3.x' python-version: '3.x'
@@ -58,7 +58,7 @@ jobs:
run: mkdocs build --clean run: mkdocs build --clean
- name: Upload site artifact - name: Upload site artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v7
with: with:
name: site name: site
path: site/ path: site/
@@ -72,13 +72,13 @@ jobs:
steps: steps:
- name: Download site artifact - name: Download site artifact
uses: actions/download-artifact@v4 uses: actions/download-artifact@v8
with: with:
name: site name: site
path: site/ path: site/
- name: Checkout pages repo - name: Checkout pages repo
uses: actions/checkout@v4 uses: actions/checkout@v7
with: with:
repository: finit-project/finit-project.github.io repository: finit-project/finit-project.github.io
path: pages path: pages
+9 -4
View File
@@ -14,7 +14,7 @@ jobs:
if: startsWith(github.ref, 'refs/tags/') if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v7
- name: Installing dependencies ... - name: Installing dependencies ...
run: | run: |
sudo apt-get -y update sudo apt-get -y update
@@ -31,12 +31,17 @@ jobs:
run: | run: |
ver=${GITHUB_REF#refs/tags/} ver=${GITHUB_REF#refs/tags/}
echo "ver=${ver}" >> $GITHUB_OUTPUT echo "ver=${ver}" >> $GITHUB_OUTPUT
if echo $ver | grep -qE '^[0-9]+\.[0-9]+(\.[0-9]+)?(-alpha|-beta|-rc)[0-9]*$'; then stable='[0-9]+\.[0-9]+(\.[0-9]+)?'
if echo $ver | grep -qE "^${stable}(-alpha|-beta|-rc)[0-9]*$"; then
echo "pre=true" >> $GITHUB_OUTPUT echo "pre=true" >> $GITHUB_OUTPUT
else else
echo "pre=false" >> $GITHUB_OUTPUT echo "pre=false" >> $GITHUB_OUTPUT
fi fi
if echo $ver | grep -qE '^[0-9.]+\.[0-9.]+(\.[0-9]+)?$'; then # Mark as latest release only if this is the highest stable
# tag, so a 4.x maintenance release doesn't outrank 5.x
newest=$(git ls-remote --tags --refs origin | awk -F/ '{print $NF}' \
| grep -E "^${stable}$" | sort -V | tail -1)
if [ "$ver" = "$newest" ]; then
echo "latest=true" >> $GITHUB_OUTPUT echo "latest=true" >> $GITHUB_OUTPUT
else else
echo "latest=false" >> $GITHUB_OUTPUT echo "latest=false" >> $GITHUB_OUTPUT
@@ -64,7 +69,7 @@ jobs:
mv ../*.tar.* artifacts/ mv ../*.tar.* artifacts/
- name: Upload Test Results - name: Upload Test Results
if: always() if: always()
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v7
with: with:
name: finit-release-test-logs name: finit-release-test-logs
path: finit-*/_build/sub/test/*.log path: finit-*/_build/sub/test/*.log
+22 -11
View File
@@ -14,22 +14,31 @@ jobs:
schedule: schedule:
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs: outputs:
run: ${{ steps.schedule.outputs.run }} branches: ${{ steps.schedule.outputs.branches }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v7
- name: Check for any commits since last week with:
fetch-depth: 0
- name: Check for branches with no commits since last week
id: schedule id: schedule
run: | run: |
commits="$(git log --format=%H --since='1 week ago')" branches=
maint=$(git branch -r --format='%(refname:lstrip=3)' | grep -E '^[0-9]+\.x$')
for branch in master $maint; do
commits="$(git log --format=%H --since='1 week ago' origin/$branch)"
if [ -z "$commits" ]; then if [ -z "$commits" ]; then
echo "run=true" >> $GITHUB_OUTPUT branches="$branches\"$branch\","
else
echo "run=false" >> $GITHUB_OUTPUT
fi fi
done
echo "branches=[${branches%,}]" >> $GITHUB_OUTPUT
distcheck: distcheck:
needs: schedule needs: schedule
if: ${{ needs.schedule.outputs.run == 'true' }} if: ${{ needs.schedule.outputs.branches != '[]' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
branch: ${{ fromJSON(needs.schedule.outputs.branches) }}
fail-fast: false
steps: steps:
- name: Install dependencies - name: Install dependencies
run: | run: |
@@ -42,7 +51,9 @@ jobs:
(cd libuev-2.4.1 && ./configure && make -j9 && sudo make install-strip) (cd libuev-2.4.1 && ./configure && make -j9 && sudo make install-strip)
(cd libite-2.6.2 && ./configure && make -j9 && sudo make install-strip) (cd libite-2.6.2 && ./configure && make -j9 && sudo make install-strip)
sudo ldconfig sudo ldconfig
- uses: actions/checkout@v4 - uses: actions/checkout@v7
with:
ref: ${{ matrix.branch }}
- name: Base run - name: Base run
run: | run: |
./autogen.sh ./autogen.sh
@@ -61,7 +72,7 @@ jobs:
make -j1 distcheck || (cat $dir/test/test-suite.log; false) make -j1 distcheck || (cat $dir/test/test-suite.log; false)
- name: Upload Test Results - name: Upload Test Results
if: always() if: always()
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v7
with: with:
name: finit-weekly-test-logs name: finit-weekly-test-logs-${{ matrix.branch }}
path: finit-*/_build/sub/test/*.log path: finit-*/_build/sub/test/*.log
+1 -1
View File
@@ -1,4 +1,4 @@
AC_INIT([Finit], [4.17], [https://github.com/finit-project/finit/issues], AC_INIT([Finit], [4.18-pre], [https://github.com/finit-project/finit/issues],
[finit], [https://http://finit-project.github.io/]) [finit], [https://http://finit-project.github.io/])
AC_CONFIG_AUX_DIR(aux) AC_CONFIG_AUX_DIR(aux)
AM_INIT_AUTOMAKE([1.11 foreign subdir-objects]) AM_INIT_AUTOMAKE([1.11 foreign subdir-objects])
+47
View File
@@ -12,9 +12,36 @@ All relevant changes are documented in this file.
e.g. `killed by SIGKILL` or `killed by SIGSEGV, core dumped`, in e.g. `killed by SIGKILL` or `killed by SIGSEGV, core dumped`, in
place of the bare numeric `by signal: N`. Gives operators a much place of the bare numeric `by signal: N`. Gives operators a much
stronger breadcrumb when a daemon dies unexpectedly stronger breadcrumb when a daemon dies unexpectedly
- 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
- Shutdown now stops after the first successful remount of `/` read
only. The plain `mount -n -o remount,ro /`, which reads
`/etc/fstab`, is only used when both device-agnostic forms fail,
the same order as Debian's `umountroot`. By Anees Rehman
### Fixes ### Fixes
- 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 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)
- A service can have more than four supplementary groups, as in
`@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
- Remove stale daemon-owned (`pid:!`) pidfiles after unclean exits. - Remove stale daemon-owned (`pid:!`) pidfiles after unclean exits.
When a daemon dies via SIGKILL/OOM/segfault, or exits early during When a daemon dies via SIGKILL/OOM/segfault, or exits early during
startup, its pidfile lingers and can prevent the next instance from startup, its pidfile lingers and can prevent the next instance from
@@ -27,6 +54,26 @@ All relevant changes are documented in this file.
- Fix misspelled `SIGUNKOWN` returned by `sig_name()` for unknown - Fix misspelled `SIGUNKOWN` returned by `sig_name()` for unknown
signal numbers, now spelled correctly as `SIGUNKNOWN`. Surfaced by signal numbers, now spelled correctly as `SIGUNKNOWN`. Surfaced by
the new restart log above the new restart log above
- Fix mode of existing `d`/`D` directories in tmpfiles when the entry
gives one, the chmod branch never ran because the directory creation
swallowed `EEXIST`. Mode and owner of `d`/`D`, `e`, and `f`/`F`
entries, and of the directories `mksubsys()` creates for the dbus
plugin, are now set through an open fd and only when they differ, so
an immutable directory like `/var/empty` no longer warns on every
boot. By Sam Brkopac
- Fix crash at config load for a `stop:` or `reload:` script written
with a timeout, e.g. `stop:5,/bin/true`, which took PID 1 down
- Fix a lost reload for a service paused mid-reload by a condition in
flux. A second reload arriving meanwhile re-parsed the unchanged .conf
and cleared the pending mark, so the service resumed without ever being
reloaded. Seen on Infix, where sshd kept its old listen addresses after
a change that landed as two reloads in a row
- Fix crash on a line with a key but no value, or no separator at all.
A `VERSION=` line in `/etc/os-release` crashed getty, the same in
`.initrc` crashed `initctl`, and a bare `set` or `set index=` line in
a `modules-load.d` file crashed the `modules-load` plugin, taking down
PID 1. An unknown `set` line there also leaked memory. Found by
Tobias Waldekranz
[4.17][] - 2026-04-28 [4.17][] - 2026-04-28
--------------------- ---------------------
+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) AM_CPPFLAGS += -D__FINIT__ $(lite_CFLAGS) $(uev_CFLAGS)
if STATIC if STATIC
noinst_LTLIBRARIES = libplug.la noinst_LIBRARIES = libplug.a
libplug_la_SOURCES = bootmisc.c pidfile.c procps.c sys.c usr.c libplug_a_SOURCES = bootmisc.c pidfile.c procps.c sys.c usr.c
libplug_a_CFLAGS = $(AM_CFLAGS)
if BUILD_ALSA_UTILS_PLUGIN if BUILD_ALSA_UTILS_PLUGIN
libplug_la_SOURCES += alsa-utils.c libplug_a_SOURCES += alsa-utils.c
endif endif
if BUILD_DBUS_PLUGIN 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 endif
if BUILD_MODULES_LOAD_PLUGIN if BUILD_MODULES_LOAD_PLUGIN
libplug_la_SOURCES += modules-load.c libplug_a_SOURCES += modules-load.c
endif endif
if BUILD_MODPROBE_PLUGIN if BUILD_MODPROBE_PLUGIN
libplug_la_SOURCES += modprobe.c libplug_a_SOURCES += modprobe.c
endif endif
if BUILD_NETLINK_PLUGIN if BUILD_NETLINK_PLUGIN
libplug_la_SOURCES += netlink.c libplug_a_SOURCES += netlink.c
endif endif
if BUILD_PLYMOUTH_PLUGIN if BUILD_PLYMOUTH_PLUGIN
libplug_la_SOURCES += plymouth.c libplug_a_SOURCES += plymouth.c
endif endif
if BUILD_RESOLVCONF_PLUGIN if BUILD_RESOLVCONF_PLUGIN
libplug_la_SOURCES += resolvconf.c libplug_a_SOURCES += resolvconf.c
endif endif
if BUILD_RTC_PLUGIN if BUILD_RTC_PLUGIN
libplug_la_SOURCES += rtc.c libplug_a_SOURCES += rtc.c
endif endif
if BUILD_TTY_PLUGIN if BUILD_TTY_PLUGIN
libplug_la_SOURCES += tty.c libplug_a_SOURCES += tty.c
endif endif
if BUILD_URANDOM_PLUGIN if BUILD_URANDOM_PLUGIN
libplug_la_SOURCES += urandom.c libplug_a_SOURCES += urandom.c
endif endif
if BUILD_X11_COMMON_PLUGIN if BUILD_X11_COMMON_PLUGIN
libplug_la_SOURCES += x11-common.c libplug_a_SOURCES += x11-common.c
endif endif
else else
+1
View File
@@ -156,6 +156,7 @@ static int modules_load(const char *file, int index)
} }
/* unknown 'set' command, ignore. */ /* unknown 'set' command, ignore. */
free(set);
goto next; goto next;
} }
+10 -3
View File
@@ -109,6 +109,12 @@ static void pidfile_update_conds(char *dir, char *name, uint32_t mask)
} }
if (mask & (IN_CLOSE_WRITE | IN_ATTRIB | IN_MODIFY | IN_MOVED_TO)) { 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 * only mark native services as started, the s6 and
* systemd style services rely on their respective * systemd style services rely on their respective
@@ -133,9 +139,6 @@ static void pidfile_update_conds(char *dir, char *name, uint32_t mask)
return; return;
} }
/* Service is not crashing, let's tell state machine! */
service_forked(svc);
if (pid != svc->pid) { if (pid != svc->pid) {
dbg("Forking service %s (cmd %s) changed PID from %d to %d", dbg("Forking service %s (cmd %s) changed PID from %d to %d",
svc_ident(svc, NULL, 0), svc->cmd, svc->pid, pid); 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); logit(LOG_CONSOLE | LOG_NOTICE, "Started %s[%d]", svc_ident(svc, NULL, 0), pid);
cgroup_move_svc(svc); cgroup_move_svc(svc);
} }
/* Service is not crashing, let's tell state machine! */
if (!service_forked(svc))
return;
} }
if (svc->notify == SVC_NOTIFY_PID) if (svc->notify == SVC_NOTIFY_PID)
+3 -1
View File
@@ -88,8 +88,10 @@ finit_CPPFLAGS = $(AM_CPPFLAGS) -D__FINIT__
finit_CFLAGS = -W -Wall -Wextra -Wno-unused-parameter -std=gnu99 finit_CFLAGS = -W -Wall -Wextra -Wno-unused-parameter -std=gnu99
finit_CFLAGS += $(lite_CFLAGS) $(uev_CFLAGS) finit_CFLAGS += $(lite_CFLAGS) $(uev_CFLAGS)
finit_LDADD = $(lite_LIBS) $(uev_LIBS) finit_LDADD = $(lite_LIBS) $(uev_LIBS)
finit_LDFLAGS = $(AM_LDFLAGS)
if STATIC if STATIC
finit_LDADD += ../plugins/libplug.la finit_LDADD += ../plugins/libplug.a
finit_LDFLAGS += -Wl,--whole-archive,../plugins/libplug.a,--no-whole-archive
else else
finit_LDADD += -ldl finit_LDADD += -ldl
endif endif
+3 -12
View File
@@ -123,22 +123,13 @@ static inline char *fgetval(const char *line, const char *key, char *sep)
return NULL; return NULL;
ptr = strsep(&str, sep); ptr = strsep(&str, sep);
if (ptr && strcmp(ptr, key)) { if (!str || strcmp(ptr, key)) {
fail:
free(copy); free(copy);
return NULL; return NULL;
} }
/* /* strip optional separators, e.g., 'foo = bar' => 'bar' */
* Check if we should strip optional separator, e.g., ptr = str + strspn(str, sep);
* 'foo = bar' => '= bar' should be stripped to 'bar'
*/
while (strchr(sep, str[0])) {
ptr = strsep(&str, sep);
if (!ptr)
goto fail;
}
ptr = str;
if (*ptr == '"' || *ptr == '\'') { if (*ptr == '"' || *ptr == '\'') {
char *end = &ptr[strlen(ptr) - 1]; char *end = &ptr[strlen(ptr) - 1];
+6 -2
View File
@@ -121,15 +121,19 @@ void unmount_tmpfs(void)
} }
} }
void unmount_regular(void) int unmount_regular(void)
{ {
const struct mntent *mnt; const struct mntent *mnt;
FILE *fp = NULL; FILE *fp = NULL;
int rc = 0;
while ((mnt = iterator("/proc/mounts", &fp))) { while ((mnt = iterator("/proc/mounts", &fp))) {
if (!unmount(mnt->mnt_dir)) rc = unmount(mnt->mnt_dir);
if (!rc)
iterator_end(&fp); /* Restart iteration */ iterator_end(&fp); /* Restart iteration */
} }
return !!rc;
} }
/** /**
+70 -34
View File
@@ -625,20 +625,22 @@ static pid_t service_fork(svc_t *svc)
{ {
gid_t supgids[NGROUPS_MAX]; gid_t supgids[NGROUPS_MAX];
int ngroups = 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 */ /* Get user's supplementary groups from /etc/group */
if (getgrouplist(svc->username, gid, supgids, &ngroups) >= 0) if (getgrouplist(svc->username, gid, supgids, &ngroups) >= 0)
n = ngroups; n = ngroups;
/* Add explicitly configured supplementary groups */ /* Add explicitly configured supplementary groups */
for (i = 0; i < svc->num_supgroups && n < NGROUPS_MAX; i++) { for (sup = strtok_r(strdupa(svc->supgroups), ",", &ptr);
int g = getgroup(svc->supgroups[i]); sup && n < NGROUPS_MAX; sup = strtok_r(NULL, ",", &ptr)) {
int g = getgroup(sup);
int found = 0; int found = 0;
if (g < 0) { if (g < 0) {
warn("%s: unknown supplementary group '%s'", warnx("%s: unknown supplementary group '%s'",
svc_ident(svc, NULL, 0), svc->supgroups[i]); svc_ident(svc, NULL, 0), sup);
continue; continue;
} }
/* Skip if already in list from /etc/group */ /* Skip if already in list from /etc/group */
@@ -1473,6 +1475,24 @@ static char *parse_args(char **line)
return NULL; 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 * log:/path/to/logfile,priority:facility.level,tag:ident
*/ */
@@ -1654,6 +1674,7 @@ static void parse_script(svc_t *svc, char *type, char *script, int *tmo, char *b
script, errstr); script, errstr);
goto err; goto err;
} }
if (tmo)
*tmo = (int)(sec * 1000); *tmo = (int)(sec * 1000);
} else { } else {
path = script; path = script;
@@ -1920,6 +1941,10 @@ int service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
return errno = ENOENT; return errno = ENOENT;
} }
/*
* 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) { while (cmd) {
char *arg; char *arg;
@@ -1934,19 +1959,19 @@ int service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
cond = &cmd[1]; cond = &cmd[1];
else if (cmd[0] == ':') /* :ID */ else if (cmd[0] == ':') /* :ID */
id = &cmd[1]; id = &cmd[1];
else if (MATCH_CMD(cmd, "log", arg)) else if (is_opt(cmd, "log", ":"))
log = cmd; log = cmd;
else if (MATCH_CMD(cmd, "pid", arg)) else if (is_opt(cmd, "pid", ":"))
pid = cmd; pid = cmd;
else if (MATCH_CMD(cmd, "name:", arg)) else if (MATCH_CMD(cmd, "name:", arg))
name = cmd; name = cmd;
else if (MATCH_CMD(cmd, "notify:", arg)) else if (MATCH_CMD(cmd, "notify:", arg))
notify = arg; notify = arg;
else if (MATCH_CMD(cmd, "type:forking", arg)) else if (!strcasecmp(cmd, "type:forking"))
forking = 1; forking = 1;
else if (MATCH_CMD(cmd, "manual:yes", arg)) else if (!strcasecmp(cmd, "manual:yes"))
manual = 1; manual = 1;
else if (MATCH_CMD(cmd, "remain:yes", arg)) else if (!strcasecmp(cmd, "remain:yes"))
remain = 1; remain = 1;
else if (MATCH_CMD(cmd, "restart:", arg)) { else if (MATCH_CMD(cmd, "restart:", arg)) {
if (MATCH_CMD(arg, "always", arg)) if (MATCH_CMD(arg, "always", arg))
@@ -1958,9 +1983,9 @@ int service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
restart_tmo = atoi(arg) * 1000; restart_tmo = atoi(arg) * 1000;
else if (MATCH_CMD(cmd, "restart_sec:", arg)) else if (MATCH_CMD(cmd, "restart_sec:", arg))
restart_tmo = atoi(arg) * 1000; restart_tmo = atoi(arg) * 1000;
else if (MATCH_CMD(cmd, "norestart", arg)) else if (!strcasecmp(cmd, "norestart"))
restart_max = 0; restart_max = 0;
else if (MATCH_CMD(cmd, "nowarn", arg)) else if (!strcasecmp(cmd, "nowarn"))
nowarn = 1; nowarn = 1;
else if (MATCH_CMD(cmd, "oncrash:", arg)) { else if (MATCH_CMD(cmd, "oncrash:", arg)) {
if (MATCH_CMD(arg, "reboot", arg)) if (MATCH_CMD(arg, "reboot", arg))
@@ -1968,7 +1993,7 @@ int service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
if (MATCH_CMD(arg, "script", arg)) if (MATCH_CMD(arg, "script", arg))
oncrash_action = SVC_ONCRASH_SCRIPT; oncrash_action = SVC_ONCRASH_SCRIPT;
} }
else if (MATCH_CMD(cmd, "respawn", arg)) else if (!strcasecmp(cmd, "respawn"))
respawn = 1; respawn = 1;
else if (MATCH_CMD(cmd, "halt:", arg)) else if (MATCH_CMD(cmd, "halt:", arg))
halt = arg; halt = arg;
@@ -1993,7 +2018,7 @@ int service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
else if (MATCH_CMD(cmd, "tty:", arg)) else if (MATCH_CMD(cmd, "tty:", arg))
ctty = arg; ctty = arg;
/* catch both cgroup: and cgroup. handled in parse_cgroup() */ /* 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; cgroup = arg;
else if (MATCH_CMD(cmd, "conflict:", arg)) else if (MATCH_CMD(cmd, "conflict:", arg))
conflict = arg; conflict = arg;
@@ -2117,10 +2142,13 @@ int service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
svc_unblock(svc); svc_unblock(svc);
} }
svc->group[0] = 0;
svc->supgroups[0] = 0;
if (username) { if (username) {
char *ptr = strchr(username, ':'); char *ptr = strchr(username, ':');
if (ptr) { if (ptr) {
size_t len = sizeof(svc->supgroups);
char *sup; char *sup;
*ptr++ = 0; *ptr++ = 0;
@@ -2128,20 +2156,15 @@ int service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
sup = strchr(ptr, ','); sup = strchr(ptr, ',');
if (sup) { if (sup) {
*sup++ = 0; *sup++ = 0;
svc->num_supgroups = 0; if (strlcpy(svc->supgroups, sup, len) >= len) {
while (sup) { /* Drop the cut-off name, it may match another group */
char *next = strchr(sup, ','); sup = strrchr(svc->supgroups, ',');
if (next) if (sup)
*next++ = 0; *sup = 0;
if (svc->num_supgroups >= MAX_NUM_SUPGROUPS) { else
warn("%s: too many supplementary groups, max %d", svc->supgroups[0] = 0;
svc->cmd, MAX_NUM_SUPGROUPS); warnx("%s: supplementary group list too long, max %zu characters",
break; svc->cmd, len - 1);
}
strlcpy(svc->supgroups[svc->num_supgroups], sup,
sizeof(svc->supgroups[0]));
svc->num_supgroups++;
sup = next;
} }
} }
strlcpy(svc->group, ptr, sizeof(svc->group)); strlcpy(svc->group, ptr, sizeof(svc->group));
@@ -2336,11 +2359,14 @@ int service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
if (cgroup) if (cgroup)
parse_cgroup(svc, cgroup); parse_cgroup(svc, cgroup);
/* New, recently modified or unchanged ... used on reload. */ /*
* New or modified since the last reload. The mark is cleared when
* the change has been applied, on start or reload, so one that is
* still set here is a change that has not been applied yet, e.g.
* the service is paused waiting for a condition. Leave it.
*/
if ((file && conf_changed(file)) || conf_changed(svc_getenv(svc)) || svc->args_dirty) if ((file && conf_changed(file)) || conf_changed(svc_getenv(svc)) || svc->args_dirty)
svc_mark_dirty(svc); svc_mark_dirty(svc);
else
svc_mark_clean(svc);
svc_enable(svc); svc_enable(svc);
@@ -2914,16 +2940,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. * 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, * 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 */ /* Stop forking_retry() timer */
service_timeout_cancel(svc); service_timeout_cancel(svc);
/* Not crashing, restore RUNNING state */ /* Not crashing, restore RUNNING state, but keep a user stop */
if (!svc_is_stopped(svc))
svc_unblock(svc); svc_unblock(svc);
svc_set_state(svc, SVC_RUNNING_STATE); 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 */ /* Set or clear service/foo/ready condition for services and call optional ready:script */
+1 -1
View File
@@ -39,7 +39,7 @@ void service_ready_script (svc_t *svc); /* XXX: only for pidfile plugin b
int service_timeout_after (svc_t *svc, int timeout, void (*cb)(svc_t *svc)); int service_timeout_after (svc_t *svc, int timeout, void (*cb)(svc_t *svc));
int service_timeout_cancel (svc_t *svc); int service_timeout_cancel (svc_t *svc);
void service_forked (svc_t *svc); int service_forked (svc_t *svc);
void service_ready (svc_t *svc, int ready); void service_ready (svc_t *svc, int ready);
int service_stop (svc_t *svc); int service_stop (svc_t *svc);
+7 -5
View File
@@ -170,7 +170,7 @@ static struct sigmap {
void mdadm_wait(void); void mdadm_wait(void);
void unmount_tmpfs(void); void unmount_tmpfs(void);
void unmount_regular(void); int unmount_regular(void);
static void fs_swapoff(void) static void fs_swapoff(void)
{ {
@@ -302,6 +302,7 @@ void do_shutdown(shutop_t op)
struct sched_param sched_param = { .sched_priority = 99 }; struct sched_param sched_param = { .sched_priority = 99 };
int in_cont = in_container(); int in_cont = in_container();
int signo = SIGTERM; int signo = SIGTERM;
int rc;
if (SHUTDOWN_DEBUG) cprintf("do_shutdown: entered, op=%d\n", op); if (SHUTDOWN_DEBUG) cprintf("do_shutdown: entered, op=%d\n", op);
@@ -372,12 +373,13 @@ void do_shutdown(shutop_t op)
} }
/* Unmount any tmpfs before unmounting swap ... */ /* Unmount any tmpfs before unmounting swap ... */
print(0, "Unmounting filesystems ..."); print(-1, "Unmounting filesystems ...");
unmount_tmpfs(); unmount_tmpfs();
fs_swapoff(); fs_swapoff();
/* ... unmount remaining regular file systems. */ /* ... 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! * We sit on / so we must remount it ro, try all the things!
@@ -386,8 +388,8 @@ void do_shutdown(shutop_t op)
* - https://bugs.launchpad.net/ubuntu/+source/util-linux/+bug/29187 * - https://bugs.launchpad.net/ubuntu/+source/util-linux/+bug/29187
*/ */
sync(); sync();
run("mount -n -o remount,ro -t dummytype dummydev /", NULL); if (run("mount -n -o remount,ro -t dummytype dummydev /", NULL) &&
run("mount -n -o remount,ro dummydev /", NULL); run("mount -n -o remount,ro dummydev /", NULL))
run("mount -n -o remount,ro /", "mount"); run("mount -n -o remount,ro /", "mount");
/* Call mdadm to mark any RAID array(s) as clean before halting. */ /* Call mdadm to mark any RAID array(s) as clean before halting. */
+3 -4
View File
@@ -100,8 +100,8 @@ typedef enum {
#define MAX_IDENT_LEN (MAX_ARG_LEN + MAX_ID_LEN + 1) #define MAX_IDENT_LEN (MAX_ARG_LEN + MAX_ID_LEN + 1)
#define MAX_STR_LEN 64 #define MAX_STR_LEN 64
#define MAX_COND_LEN (MAX_ARG_LEN * 3) #define MAX_COND_LEN (MAX_ARG_LEN * 3)
#define MAX_USER_LEN 16 #define MAX_USER_LEN MAX_ARG_LEN
#define MAX_NUM_SUPGROUPS 4 #define MAX_SUPGROUPS_LEN (MAX_CMD_LEN * 2)
#define MAX_NUM_FDS 64 /* Max number of I/O plugins */ #define MAX_NUM_FDS 64 /* Max number of I/O plugins */
#define MAX_NUM_SVC_ARGS 64 #define MAX_NUM_SVC_ARGS 64
@@ -195,8 +195,7 @@ typedef struct svc {
/* Identity */ /* Identity */
char username[MAX_USER_LEN]; char username[MAX_USER_LEN];
char group[MAX_USER_LEN]; char group[MAX_USER_LEN];
char supgroups[MAX_NUM_SUPGROUPS][MAX_USER_LEN]; char supgroups[MAX_SUPGROUPS_LEN]; /* sup1,sup2,... */
int num_supgroups;
char capabilities[MAX_CMD_LEN]; char capabilities[MAX_CMD_LEN];
/* Command, arguments and service description */ /* Command, arguments and service description */
+42 -35
View File
@@ -24,6 +24,7 @@
#include "config.h" /* Generated by configure script */ #include "config.h" /* Generated by configure script */
#include <dirent.h> #include <dirent.h>
#include <fcntl.h>
#include <ftw.h> #include <ftw.h>
#include <getopt.h> #include <getopt.h>
#include <glob.h> #include <glob.h>
@@ -587,66 +588,72 @@ static void tmpfiles(char *line)
gid = 0; gid = 0;
rc = makedir(path, mode ?: 0755); rc = makedir(path, mode ?: 0755);
if (rc && errno == EEXIST) if (!rc && dirperm(path, mode, uid, gid))
rc = chmod(path, mode ?: 0755); warn("Failed setting mode/owner on %s", path);
if (chown(path, uid, gid))
warn("Failed chown(%s, %d, %d)", path, uid, gid);
} }
umask(omask); umask(omask);
break; break;
} }
case 'e': case 'e': {
int uid, gid;
if (glob(path, GLOB_NOESCAPE, NULL, &gl)) if (glob(path, GLOB_NOESCAPE, NULL, &gl))
break; break;
uid = parse_uid(user);
gid = parse_gid(group);
if (gid < 0)
gid = 0;
for (size_t i = 0; i < gl.gl_pathc; i++) { for (size_t i = 0; i < gl.gl_pathc; i++) {
char *p = gl.gl_pathv[i]; char *p = gl.gl_pathv[i];
int uid, gid;
/* e only adjusts existing directories */ /* skip non-directories */
if (!fisdir(p)) if (dirperm(p, mode, uid, gid) && errno != ENOTDIR)
continue; warn("Failed setting mode/owner on %s", p);
uid = parse_uid(user);
gid = parse_gid(group);
if (gid < 0)
gid = 0;
if (mode)
chmod(p, mode);
if (uid >= 0 && chown(p, uid, gid))
warn("Failed chown(%s, %d, %d)", p, uid, gid);
} }
globfree(&gl);
break; break;
}
case 'f': case 'f':
case 'F': case 'F': {
mkparent(path, 0755); int flags = O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC;
int fd, uid, gid;
if (type[1] == '+' || type[0] == 'F') { if (type[1] == '+' || type[0] == 'F') {
/* f+/F will create or truncate the file */ flags |= O_TRUNC; /* create or truncate */
fp = fopen(path, "w+");
} else { } else {
/* f will create the file if it doesn't exist */ if (!strc)
if (strc) break; /* create only if missing */
fp = fopen(path, "w"); flags |= O_EXCL;
} }
if (fp) { mkparent(path, 0755);
int uid, gid; fd = open(path, flags, 0666);
if (fd < 0) {
if (errno != EEXIST)
warn("Failed creating %s", path);
break;
}
fp = fdopen(fd, "w");
if (!fp) {
close(fd);
break;
}
write_arg(fp, arg); write_arg(fp, arg);
rc = fclose(fp);
/* Apply mode and ownership */
if (mode)
chmod(path, mode);
uid = parse_uid(user); uid = parse_uid(user);
gid = parse_gid(group); gid = parse_gid(group);
if (gid < 0) if (gid < 0)
gid = 0; gid = 0;
if (uid >= 0 && chown(path, uid, gid)) if (fdperm(fd, mode, uid, gid))
warn("Failed chown(%s, %d, %d)", path, uid, gid); warn("Failed setting mode/owner on %s", path);
}
rc = fclose(fp);
break; break;
}
case 'l': /* Finit extension, like 'L' but only if target exists */ case 'l': /* Finit extension, like 'L' but only if target exists */
if (!arg) { if (!arg) {
paste(buf, sizeof(buf), "/usr/share/factory", path); paste(buf, sizeof(buf), "/usr/share/factory", path);
+40 -4
View File
@@ -25,6 +25,7 @@
#include <ctype.h> /* isprint() */ #include <ctype.h> /* isprint() */
#include <errno.h> #include <errno.h>
#include <fcntl.h>
#include <grp.h> #include <grp.h>
#include <pwd.h> #include <pwd.h>
#ifdef HAVE_MNTENT_H #ifdef HAVE_MNTENT_H
@@ -280,6 +281,43 @@ int getcgroup(char *buf, size_t len)
return 0; return 0;
} }
/*
* Set mode and owner on an open fd, only what differs is touched, the
* file may be immutable. mode 0 skips the chmod, uid -1 the chown.
*/
int fdperm(int fd, mode_t mode, uid_t uid, gid_t gid)
{
struct stat st;
int rc;
rc = fstat(fd, &st);
if (!rc && mode && (st.st_mode & 07777) != mode)
rc = fchmod(fd, mode);
if (!rc && uid != (uid_t)-1 && (st.st_uid != uid || st.st_gid != gid))
rc = fchown(fd, uid, gid);
return rc;
}
/*
* Same for a directory that may already exist. Opened with
* O_NOFOLLOW | O_DIRECTORY, so the change lands on the directory
* itself and not on whatever a link at @path points to.
*/
int dirperm(const char *path, mode_t mode, uid_t uid, gid_t gid)
{
int fd, rc;
fd = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0)
return -1;
rc = fdperm(fd, mode, uid, gid);
close(fd);
return rc;
}
int mksubsys(const char *dir, mode_t mode, char *user, char *group) int mksubsys(const char *dir, mode_t mode, char *user, char *group)
{ {
mode_t omask; mode_t omask;
@@ -295,10 +333,8 @@ int mksubsys(const char *dir, mode_t mode, char *user, char *group)
gid = 0; gid = 0;
rc = makedir(dir, mode); rc = makedir(dir, mode);
if (rc && errno == EEXIST) if (!rc && dirperm(dir, mode, uid, gid))
rc = chmod(dir, mode); warn("Failed setting mode/owner on %s", dir);
if (chown(dir, uid, gid))
err(1, "Failed chown(%s, %d, %d)", dir, uid, gid);
} }
umask(omask); umask(omask);
+2
View File
@@ -68,6 +68,8 @@ int getgroup (const char *group);
int getcuser (char *buf, size_t len); int getcuser (char *buf, size_t len);
int getcgroup (char *buf, size_t len); int getcgroup (char *buf, size_t len);
int fdperm (int fd, mode_t mode, uid_t uid, gid_t gid);
int dirperm (const char *path, mode_t mode, uid_t uid, gid_t gid);
int mksubsys (const char *dir, mode_t mode, char *user, char *group); int mksubsys (const char *dir, mode_t mode, char *user, char *group);
int fnread (char *buf, size_t len, char *fmt, ...) __attribute__ ((format (printf, 3, 4))); int fnread (char *buf, size_t len, char *fmt, ...) __attribute__ ((format (printf, 3, 4)));
+12 -1
View File
@@ -30,9 +30,10 @@ EXTRA_DIST += setup-sysroot.sh
EXTRA_DIST += add-remove-dynamic-service.sh EXTRA_DIST += add-remove-dynamic-service.sh
EXTRA_DIST += add-remove-dynamic-service-sub-config.sh EXTRA_DIST += add-remove-dynamic-service-sub-config.sh
EXTRA_DIST += bootstrap-crash.sh EXTRA_DIST += bootstrap-crash.sh
EXTRA_DIST += cond-start-task.sh EXTRA_DIST += script-timeout.sh
EXTRA_DIST += crashing.sh EXTRA_DIST += crashing.sh
EXTRA_DIST += dep-chain-reload.sh EXTRA_DIST += dep-chain-reload.sh
EXTRA_DIST += reload-while-paused.sh
EXTRA_DIST += depserv.sh EXTRA_DIST += depserv.sh
EXTRA_DIST += devmon.sh EXTRA_DIST += devmon.sh
EXTRA_DIST += failing-sysv.sh EXTRA_DIST += failing-sysv.sh
@@ -41,6 +42,9 @@ EXTRA_DIST += global-envs.sh
EXTRA_DIST += initctl-status-subset.sh EXTRA_DIST += initctl-status-subset.sh
EXTRA_DIST += notify.sh EXTRA_DIST += notify.sh
EXTRA_DIST += pidfile.sh EXTRA_DIST += pidfile.sh
EXTRA_DIST += conf-groups.sh
EXTRA_DIST += option-lookalike.sh
EXTRA_DIST += pidfile-stopped.sh
EXTRA_DIST += stale-pidfile.sh EXTRA_DIST += stale-pidfile.sh
EXTRA_DIST += pre-post-serv.sh EXTRA_DIST += pre-post-serv.sh
EXTRA_DIST += pre-fail.sh EXTRA_DIST += pre-fail.sh
@@ -61,6 +65,7 @@ EXTRA_DIST += start-stop-sysv.sh
EXTRA_DIST += start-stop-serv.sh EXTRA_DIST += start-stop-serv.sh
EXTRA_DIST += signal-service.sh EXTRA_DIST += signal-service.sh
EXTRA_DIST += testserv.sh EXTRA_DIST += testserv.sh
EXTRA_DIST += tmpfiles-perm.sh
EXTRA_DIST += unexpected-restart.sh EXTRA_DIST += unexpected-restart.sh
AM_TESTS_ENVIRONMENT = SYSROOT='$(abs_builddir)/sysroot/'; AM_TESTS_ENVIRONMENT = SYSROOT='$(abs_builddir)/sysroot/';
@@ -75,8 +80,10 @@ TESTS += add-remove-dynamic-service.sh
TESTS += add-remove-dynamic-service-sub-config.sh TESTS += add-remove-dynamic-service-sub-config.sh
TESTS += bootstrap-crash.sh TESTS += bootstrap-crash.sh
TESTS += cond-start-task.sh TESTS += cond-start-task.sh
TESTS += script-timeout.sh
TESTS += crashing.sh TESTS += crashing.sh
TESTS += dep-chain-reload.sh TESTS += dep-chain-reload.sh
TESTS += reload-while-paused.sh
TESTS += depserv.sh TESTS += depserv.sh
TESTS += devmon.sh TESTS += devmon.sh
TESTS += failing-sysv.sh TESTS += failing-sysv.sh
@@ -85,6 +92,9 @@ TESTS += global-envs.sh
TESTS += initctl-status-subset.sh TESTS += initctl-status-subset.sh
TESTS += notify.sh TESTS += notify.sh
TESTS += pidfile.sh TESTS += pidfile.sh
TESTS += conf-groups.sh
TESTS += option-lookalike.sh
TESTS += pidfile-stopped.sh
TESTS += stale-pidfile.sh TESTS += stale-pidfile.sh
TESTS += pre-post-serv.sh TESTS += pre-post-serv.sh
TESTS += pre-fail.sh TESTS += pre-fail.sh
@@ -106,6 +116,7 @@ TESTS += start-stop-serv.sh
TESTS += signal-service.sh TESTS += signal-service.sh
if TESTSERV if TESTSERV
TESTS += testserv.sh TESTS += testserv.sh
TESTS += tmpfiles-perm.sh
endif endif
TESTS += unexpected-restart.sh TESTS += unexpected-restart.sh
+67
View File
@@ -0,0 +1,67 @@
#!/bin/sh
# Verify group and supplementary groups, @user:group,sup1,sup2,..., are
# set on the service, and that dropping either drops the group(s) too.
set -eu
TEST_DIR=$(dirname "$0")
# Optional arguments are the group and the supplementary group list,
# ",sup1,sup2,...", the latter requires a group
write_conf()
{
user="@root"
if [ -n "${1:-}" ]; then
user="@root:$1${2:-}"
fi
run "echo 'service $user name:grp serv -np -i grp -- Groups' > $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 supplementary groups'
write_conf root ',daemon,bin,sys,adm,tty,disk,dialout'
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 supplementary groups drops the groups'
write_conf root
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'
+17 -1
View File
@@ -255,8 +255,12 @@ wdstart()
wdkill() wdkill()
{ {
[ -n "${wdpid:-}" ] || return 0
say "Stopping test watchdog, pid $wdpid" say "Stopping test watchdog, pid $wdpid"
kill -KILL $wdpid # Reap the sleep first, killing its subshell orphans it to PID 1.
pkill -KILL -P "$wdpid" 2>/dev/null || true
kill -KILL "$wdpid" 2>/dev/null || true
} }
teardown() teardown()
@@ -305,6 +309,18 @@ trap teardown EXIT
SYSROOT="${SYSROOT:-$(pwd)/${TEST_DIR}/sysroot}" SYSROOT="${SYSROOT:-$(pwd)/${TEST_DIR}/sysroot}"
export SYSROOT export SYSROOT
# 'make check' refreshes the sysroot through the setup-chroot rule, but
# running a test script by hand does not, and then the test silently
# exercises whatever finit was installed last. Compare and refuse.
top_builddir="${top_builddir:-$TEST_DIR/..}"
sysroot_finit="$SYSROOT/sbin/finit"
built_finit="$top_builddir/src/finit"
[ -x "$top_builddir/src/.libs/finit" ] && built_finit="$top_builddir/src/.libs/finit"
if [ -x "$built_finit" ] && [ -e "$sysroot_finit" ] && ! cmp -s "$built_finit" "$sysroot_finit"; then
fail "Stale $sysroot_finit, run 'make -C test setup-chroot' or use 'make check'"
fi
TEST_TIMEOUT=300 TEST_TIMEOUT=300
# shellcheck source=/dev/null # shellcheck source=/dev/null
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# Verify that a command which starts like a service option, e.g. pidof
# vs. pid, is still taken as the command.
set -eu
TEST_DIR=$(dirname "$0")
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
say 'A command named like an option is the command'
run "echo 'task [2345] name:lookalike pidof serv -- Lookalike' > $FINIT_CONF"
run "initctl reload"
retry "test \"\$(texec initctl -p status lookalike | sed -n 's/.*Command : //p')\" = 'pidof 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 'texec test -e /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
# A reload must not be lost on a service paused by a condition
#
# svc_s writes its PID file one second after a SIGHUP, so a service
# with <pid/svc_s> is paused for that second whenever svc_s reloads.
# svc_x counts the SIGHUPs it gets. Both .conf files are touched and
# two reloads are requested back to back, so the second one arrives
# while svc_x is paused with its own reload still pending. svc_x must
# get exactly one SIGHUP and keep its PID.
set -eu
TEST_DIR=$(dirname "$0")
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_RCSD/svc_s.conf $FINIT_RCSD/svc_x.conf /tmp/hup.sh /tmp/hup.log"
}
pidof()
{
texec initctl -j status "$1" | jq .pid
}
test_setup()
{
run "cat > /tmp/hup.sh" <<EOF
#!/bin/sh
trap 'echo HUP >> /tmp/hup.log' HUP
trap 'exit 0' TERM
while true; do
sleep 1
done
EOF
run "cat > $FINIT_RCSD/svc_s.conf" <<EOF
service log:stdout notify:pid pid:!/run/service.pid name:svc_s service.sh -- Slow to reassert
EOF
run "cat > $FINIT_RCSD/svc_x.conf" <<EOF
service log:stdout <pid/svc_s> name:svc_x /bin/sh /tmp/hup.sh -- Paused while svc_s reloads
EOF
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep "Configuration"
run "cat $FINIT_RCSD/svc_s.conf"
run "cat $FINIT_RCSD/svc_x.conf"
say "Reload Finit to start both services"
run "initctl reload"
retry 'assert_status "svc_x" "running"' 10 1
pid_x=$(pidof svc_x)
say "svc_x PID before: $pid_x"
sep "Touch both, reload twice"
run "rm -f /tmp/hup.log"
run "initctl touch svc_s.conf"
run "initctl touch svc_x.conf"
run "initctl reload"
run "initctl reload"
say "Wait for services to settle"
retry 'assert_status "svc_x" "running"' 15 1
run "initctl status"
# shellcheck disable=SC2016
retry 'assert "svc_x got its SIGHUP" "$(texec sh -c "cat /tmp/hup.log 2>/dev/null | wc -l")" -eq 1' 10 1
new_pid_x=$(pidof svc_x)
# shellcheck disable=SC2086
assert "svc_x was not restarted" $new_pid_x -eq $pid_x
return 0
+36
View File
@@ -0,0 +1,36 @@
#!/bin/sh
# A timeout on a stop: or reload: script must not take PID 1 with it.
# Those two hooks passed a NULL timeout pointer to parse_script(),
# which wrote through it whenever the script was prefixed with a
# valid number. Only a valid number reached the store, so
# 'stop:abc,/bin/true' was harmless while 'stop:5,/bin/true' was not.
set -eu
TEST_DIR=$(dirname "$0")
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
# shellcheck disable=SC2154
assert_alive()
{
assert "Finit survived $1" "$(kill -0 "$finit_pid" 2>/dev/null && echo yes)" = "yes"
}
for hook in stop reload post pre; do
say "Timeout on a $hook: script"
run "echo 'service $hook:5,/bin/true service.sh -- Timeout test' > $FINIT_CONF"
run "initctl reload" || true
assert_alive "$hook:5,/bin/true"
done
say 'The service still runs afterwards'
run "echo 'service stop:5,/bin/true service.sh -- Timeout test' > $FINIT_CONF"
run "initctl reload"
retry 'assert_num_children 1 service.sh'
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# Verify that tmpfiles leaves the mode of an existing directory alone
# when the entry does not give one, issue #523
set -eu
TEST_DIR=$(dirname "$0")
DIR=/tmp/perm
CONF=/tmp/perm.conf
# Run tmpfiles with entry $1, then check mode $2 and owner $3 of $DIR
assert_perm()
{
run "echo '$1' > $CONF"
run "/libexec/finit/tmpfiles --create $CONF"
assert "Entry '$1' gives $2 $3" "$(texec stat -c '%a %U:%G' $DIR)" = "$2 $3"
}
test_teardown()
{
say "Running test teardown."
run "rm -rf $DIR $CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep
say 'A new directory gets the default mode and owner'
assert_perm "d $DIR" 755 root:root
sep
say 'An existing directory keeps its mode when the entry gives none'
run "chmod 1777 $DIR"
assert_perm "d $DIR" 1777 root:root
assert_perm "d $DIR - - -" 1777 root:root
assert_perm "d $DIR 0750" 750 root:root
assert_perm "e $DIR" 750 root:root
assert_perm "d $DIR 1777 root root" 1777 root:root