exit() will run all atexit registered functions and flush the standard
streams. When a process fork()s but does not exec(), doing so in the
child can clean up something the parent process does not expect, hence
_exit() is usually used instead.
This patch fixes duplicated prints to stdout, which broke the Weston
test suite. The test suite prints a TAP report to stdout in parts. The
child process in libseat gets a copy of the buffered stdout on fork().
Closing the libseat session flushed stdout with a partial TAP report in
the child, corrupting the final TAP report.
Signed-off-by: Pekka Paalanen <pekka.paalanen@collabora.com>
vt_close is the cleanup counterpart to vt_open. vt_open correctly
sets VT_PROCESS mode so that seatd can manage VT switching via signals.
However, vt_close was also setting VT_PROCESS (passing true to
terminal_set_process_switching), leaving the VT controlled by seatd for
no reason.
Pass false to restore VT_AUTO mode, letting the kernel manage VT
switching again after seatd releases it.
Signed-off-by: Quentin THÉBAULT <quentin.thebault@defenso.fr>
When a client is removed while a VT switch is in progress,
seat->cur_vt may be -1 (set by seat_vt_release before the client
acknowledges the disable request). If the client crashes or is
killed in this window, seat_remove_client calls vt_close(-1),
which fails to open the terminal and skips all cleanup. On
FreeBSD, this leaves the keyboard in K_RAW mode permanently,
as the kernel does not reset vw_kbdmode when the owning process
dies.
Use client->session instead, which always holds the correct VT
number for the departing client regardless of the seat's
transient state.
Signed-off-by: Quentin THÉBAULT <quentin.thebault@defenso.fr>
If the seat opening failed at the end because we could not send the
enable message, we would still leave the state as activated. Reorganize
things a bit so that the activation is rolled back.
Previously, session numbers would increase forever until wraparound,
which is highly inconvenient for session switching and may technically
lead to issues if the system runs for very, very long.
Switch to allocating the lowest available session ID.
If the same device is attempted opened twice, we increase the refcount
of the old device. However, we were accidentally returning new and
uninitialized device instead of the old one.
Return the right value and move the device declaration down to the point
of allocation for clarity.
If the inner decoding loop in handle_properties_changed failed, the
shadowed ret would lead to the error not being logged. Remove
unnecessary shadowing declaration.
The first time set_error is called it will perform cleanup that could
clobber errno. As this is often called in error paths, retain errno for
convenience.
Most of the user-facing functions now contain some last-minute
housekeeping. These calls may have internal errors that do not bubble
up, clobbering the errno we return to our caller.
Record the errno we want to return at the time of failure, and set errno
at the end of the function.
If we cannot allocate the backend struct, we have nothing to destroy.
Attempting to do so would lead to NULL-pointer dereferences.
Just close the fd and return immediately.
sd_bus calls return errno-style errors as negative return values, which
must be converted to errno to match with the rest of our error handling.
A few places were missing this conversion, so add it.
Using goto's for error handling with incremental cleanup is preferred,
but here there is nothing to clean up and at most two such failure paths
from a single opcode handler.
Just do the error handling inline.
seat_close_device cannot fail, and might be called in error handling
paths. Ensure that it does not clobber errno even if some of its
housekeeping fails.
In the property change handler, the variable `s` is read using:
ret = sd_bus_message_read_basic(msg, 's', &s);
However, after further calls like:
ret = sd_bus_message_read_basic(msg, 'b', &value);
the contents of `s` may become invalid or corrupted. This is because
string-like values returned by sd_bus_message_read_basic() point to
internal memory owned by the message and are only valid until the
next read or until the message is released.
To ensure correctness, this patch copies the string into a local
buffer immediately after reading. This avoids referencing stale or
invalid memory when logging or comparing the property key.
Reference:
https://www.freedesktop.org/software/systemd/man/sd_bus_message_read_basic.html
Signed-off-by: Hongfei Shang <shanghongfei@kylinos.cn>
Signed-off-by: Hongfei Shang <shanghongfei@zohomail.com>
Compile on PPC64 fails with error:
../common/evdev.c: In function 'evdev_revoke':
../common/evdev.c:26:26: error: overflow in conversion from 'long unsigned int' to 'int' changes value from '2147763601' to '-2147203695' [-Werror=overflow]
26 | return ioctl(fd, EVIOCREVOKE, NULL);
Prevent overflow warning by using explicit cast to int.
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
Some messages were allowed to contain trailing data.
This converts all comparisions to equal, thereby disallowing unexpected
trailing data after the message.
The seat_name and device path are supposed to be null termiated strings.
This adds validation that the strings actually end in a null byte and
contain no interior null byte.
seatd did send the seat_name without a null byte.
libseat/seatd handles this gracefully by appending the missing null byte
if required.
An overuse of goto's had lead to some code duplication. Rely on a
variable containing the return value instead of distinct branches, and
avoid checking pending events on protocol errors.
When sending a request and awaiting a response, the client will read
data into the ringbuffer and queue events until the response is found.
Normally we would not have received any events, but if we did, we issue
a ping request to seatd so that the libseat caller will be woken up for
a dedicated dispatch.
If an event is received immediately after the response such that we will
read both into ringbuffer at the same time, but we stop reading the
ringubffer to queue events once we hit the response. As such, the event
will not be queued and we will not attempt a ping to ensure an explicit
dispatch occurs. At this point we are deadlocked, as the libseat caller
is unaware that an explicit dispatch is needed to process events already
read from the socket.
Before checking if any events are queued, read any remaining events and
queue them so that we do not leave full messages in the ring buffer.
This should fix an issue where when switching session, the libseat
client sometimes fails to see the disable_seat event.
By having read_and_queue error out on its own if it sees non-background
opcode when the opcode pointer is NULL, we can reasonably do away with
read_and_exeecute, which was one read_* function too many.
Linux 6.12 adds support for revocation of hidraw devices, making room
for seatd-mediated access. Add support for opening hidraw devices when
the revocation ioctl is present.
References: https://lore.kernel.org/all/20240812052753.GA478917@quokka/
The smoketest was fragile, relying on private systemd state - they
technically only set that we should not parse it, not that we should not
write it - and is now broken. Get rid of it to let CI pass for now.
Tying the session state to active drm devices is fragile and does not
make sense. Instead, rely mainly on PropertiesChanged for the session
state. The session is also suspended on the first gentle device pause as
these must be acked.
This also removes the need for listening to device resume, as the
PropertiesChanged handler takes care of re-activation.
Instead of stopping when we see the first Active value, iterate through
the entire PropertiesChanged message. This is not expected to cause any
functional differences, as logind only sets Active once, and only in
argument 2.
While we were listening for changes on the seat object, our logic did
not look for properties that would be present on the seat object.
As the signal has no effect, and as we know everything we need to know
from our session object, remove the seat object listener.
When the logic to activate the current session was removed, the logic to
check the current state of the session was lost with it. This meant that
the libseat seat was never activated.
Check the session state after we find the path to the session.
Not all function names are equally obvious, and some caveats details and
caveats are worth documenting.
I would normally put this documentation in a header, but some important
functions are static and so I placed it together with the implementation
for consistency.
The only user of seat_close_client was seat_remove_client. Merge the two
into a single seat_remove_client. To fix dependencies, move
seat_activate up above seat_remove_client.
Convert seat_remove_client to void while we're at it as it cannot fail.
The original logind implementation in wlroots performed an activation
followed by a check whether the session became active.
This does not appear to be necessary. Skipping activation also mean that
users that have a systemd built for polkit support, but without polkit
installed, can open a seat with logind at the time of writing.
Other functionality like SwitchTo will still fail, and no guarantees as
to whether open seat will continue to work in the future can be made. If
a user does not want polkit installed, they should build systemd without
polkit support.
The dispatch implementation for the seatd backend had not been correctly
adjusted. Local builds might erroneously have resolved this to the
logind implementation so that it did not lead to a compilation error.
When linked_list entries are removed they become uninitialized, and
further removal will fail on an assert. client_destroy may currently end
up removing a client link twice: once directly, and once in
seat_remove_client.
Instead, make seat_remove_client re-init the link so client_destroy can
call remove afterwards. This is necessary as the client might still be
in the original idle list.
linked_list_insert originally asserted two things:
1. That the list that is being inserted into is initialized, which
indicated that the list is active.
2. That the element that was inserted was *not* initialized which
indicated that it was not intended to be a list, and that it was
instead a fresh or removed element.
Initializing a list element allows it to later be safely, blindly
removed without knowing if it would still be a member of a list. Change
the element assert to just check that the element isn't a member of a
list already.
Session switch and disable seat did not have a return value, and so the
client did not dispatch anything. They could still, however, still
trigger an error response.
The libseat seatd backend would not dispatch error responses in the
background, allowing the connection buffer to fill up until further
reads failed on the buffer being full.
The various dispatch utility functions were named in a confusing manner.
Make "dispatch" the implementation of libseat_dispatch, and use "read"
for the functions that do not dispatch background events.
Responses are read immediately by functions sending the respective
request, so we only ever expect to see events during dispatch. Error out
if an unexpected response is received.
- Restrict access to block devices to the service process by creating a
whitelist.
- As a result, the service will only have write access to what it
needs--drm, input, tty, console and /dev/null.
- Restrict the capabilities of the service process by creating a
whitelist of caps and sockets.
- Also, further restrict it by denying realtime scheduling and the
ability to change memory mappings.
- Deny access to the kernel log ring buffer and ability to load kernel
modules for the service process.
- Also, prevent the kernel execution domain from being changed or a
personality from being selected.
- Whitelist system calls to systemd's recommended predefined set and
limit the CPU architectures of the service process to the system's
native ABI.
- In effect, the service will only have access to system calls that
require super-user capabilities via the @privileged set and will only
be able invoke native system calls.
- Protect /home and mount the entire filesystem hierarchy as read-only
with the exception of /dev for the service process.
- In addition, give the service its own private /tmp, make processes
owned by other users invisible and make all files created accessible
only to the service's user.
terminal_current_vt closes the file handle passed to it which is
incosistent with the other terminal functions and was actually hiding a
double close bug in seat_update_vt. Remove the calls to close and leave
the responsibility to the caller.
Signed-off-by: Jack Mitchell <ml@embed.me.uk>
The drm-kmod drivers use linuxkpi and end up with /dev/drm being the
canonical path for the devices, but the drm-subtree drivers use drmkpi
which has them appear under /dev/dri like Linux. Thus, adapt path_is_drm
to recognise both on FreeBSD.
Matching the functionallity by the seatd open call. O_NONBLOCK is
specially important for libseat, otherwise it hangs while trying to
drain all events from an input device fd.
Signed-off-by: Anna (navi) Figueiredo Gomes <navi@vlhl.dev>
wlroots' libinput backend expects the name of the seat to either match
ID_SEAT from udev, or in case ID_SEAT returns nothing, match seat0. As
noop has no seat switching, always returning seat0 as the session name
fixes that.
Signed-off-by: Anna (navi) Figueiredo Gomes <navi@vlhl.dev>
Quoting the Meson documentation:
> Note that the value returned for built-in options that end in `dir`
> such as `bindir` and `libdir` is usually a path relative to (and
> inside) the `prefix` but you should not rely on that, as it can also
> be an absolute path [in some cases](Builtin-options.md#universal-options).
> [`install_dir` arguments](Installing.md) handle that as expected
> but if you need an absolute path, e.g. to use in a define etc.,
> you should use the path concatenation operator like this:
> `get_option('prefix') / get_option('localstatedir')`.
> Never manually join paths as if they were strings.
The concatenation of two absolute paths caused seatd-launch in Nixpkgs
to try to launch e.g.
/nix/store/43wyk9s2l2z8cparnshbf24d39vm5272-seatd-0.7.0//nix/store/j9a7k4qqwc3byyfmpqwg46shmh6g82yf-seatd-0.7.0-bin/bin/seatd.
This function is only used for logind, which is Linux-specific, but the
presence in common/drm.c suggested that it had to be portable.
Move it to the logind backend for now.
4ad48cb305 introduced support for NetBSD,
which modified a number of our ifdefs. In that process, FreeBSD was
accidentally excluded from an important code path that controls keyboard
usage on the kernel console.
Revert part of that change to restore FreeBSD behavior.
Configurable socket paths exist mainly to facilitate multiple parallel
seatd instances. However, the only valid use-case for running multiple
instances of seatd is testing during development, which can just as well
be done by changing SEATD_DEFAULTPATH at compile-time for test builds.
Remove the command-line argument in seatd for runtime configuration of
socket path, hardcode the socket path in seatd-launch, and change seatd
unlink/chmod/chown code to not run when started by seatd-launch.
This means that seatd-launch will now fail to start seatd if another
seatd instance is already running. The unlink code still runs when seatd
is started normally to assist in system crash recovery, but this may be
removed later if we deem it unnecessary.
SEATD_LOGLEVEL was used to set the loglevel despite already having
getopt in place. Remove the environment variable and make a command-line
argument for it instead.
This should not need to be configured, so remove the argument. If
downstream prefers a different folder, the location can be made
compile-time configurable like for seatd itself.
SOCK_PATH is made redundant by the -s command-line argument added in
a98e0c4ce9. Support was originally left
behind for short-term compatibility, but it should be fine to remove.
Previous socket cleanup is changed to run unconditionally. The cleanup
now fails if the existing file is not a socket.
sd_bus_call_method may have read and queued our ping response, so we
cannot assume that a previous ping will make the socket readable.
Instead, always send a ping if read or write queues are not empty, even
if a ping has already been sent.
This allows downstream users to write:
dependency('libseat', fallback: 'seatd')
instead of having to rely on the seatd/meson.build's variable name:
dependency('libseat', fallback: ['seatd', 'libseat'])
This reduces the boilerplate a bit. Use logind.name() instead of
having a separate source of truth. Requires adapting the checks a
bit because the dep name has a "lib" prefix.
If the compiler errors out on some -DXXX flag, then we're in
trouble. Avoid using cc.get_supported_arguments for defines we
require. Only use it for detecting support for warning flags.
The smoketest script has gotten significantly simpler, and can simply be
inlined into the build scripts if we don't care about running the tests
twice.
This should fix CI for mailing list patches.
sd_bus_call drains received messages into the receive queue, and peeks
for its own return value. It does not dispatch the receive queue.
As the socket is drained, the caller will not wake from a poll and have
no reason to dispatch libseat. This has gone unnoticed largely due to
logind sending an event for every device, making it unlikely that no
unread message will be left on the socket.
Like we have done for seatd, we fix this by sending a "ping" request to
logind if anything is left in our receive queue as reported by
sd_bus_get_events. The response to this will wake us up and ensure that
dispatch is called.
When device open or close messages are sent to seatd, libseat must read
messages from the socket until it sees the associated response message.
This means that it may drain enable/disable seat events from the socket,
queueing them internally for deferred processing.
As the socket is drained, the caller will not wake from a poll and have
no reason to dispatch libseat. To ensure that these messages would not
be left in the queue, 6fa82930d0 made it
so that open/close calls would execute all queued events just before
returning.
Unfortunately, this had the side-effect of having events fire from the
stack of libseat_open_device or libseat_close_device, which we now see
cause problems in compositors. Specifically, an issue has been observed
where libinput end up calling libseat_close_device, which in turn
dispatch a disable seat event that calls libinput_suspend. libinput does
not like this.
Instead, remove the execution from libseat_open_device and
libseat_close_device, and instead make a "ping" request to seatd if
events have been queued. The response to this will wake us up and ensure
that dispatch is called.
The parent environment might contain nasty things. Create a new
environment for the seatd process containing only the environment
variables we care about. For now, that's only SEATD_LOGLEVEL.
We previously used execlp to execute seatd, which had the effect of
searching PATH for the executable. This allowed the caller to control
what executable was run, which is bad if SUID has been set.
Instead, expose the absolute install path for seatd from meason as a
define, and use that in a call to execv.
Mimick shells and exit with a status >128 if our child has been
signalled. Exiting with 128 + signal number is what most shells do
(POSIX only requires them to exit with >128).
The command indexing had not been updated afer the introduction of
getopt, so combining a command with flags would fail.
Add error handling for if no command was specified while we're at it.
Instead of relying on seatd's user/group arguments, which require
turning our UID back into a username, just chmod/chown the socket
ourselves once seatd is ready.
We also reduce the permissions to just user access, instead of user and
group like seatd specifies.
New clients could only be added to a VT bound seat if there were no
"active" client, regardless of its actual state. This meant that if one
switched from an "active" VT to an "inactive" VT, the seat would be
blocked while the "active" client was in CLIENT_PENDING_DISABLE, causing
new clients to possibly fail should the old client take its time with
the ack.
Instead, allow new clients to also be added if there is an active client
whose state is CLIENT_PENDING_DISABLE, and there is no client with the
new VT as its session ID.
The kernel Secure Attention Key killer, triggered by SysRq+k, kills all
processes that hold an fd referencing the tty.
To avoid its attention, we stop storing the fd for the currently active
VT in seat state. This has the added benefit of simplifying state a bit.
This reverts commit 1ae6c3b3dd.
A user might want to run the builtin server as non root, if they have
permission to use the devices.
The check was originally copied from wlroots's direct backend. It was reverted
in fa05d3cde68d with a detailed explanation of why root priviledges are not
always necessary to use the DRM device.
c8b3a22d4e snuck in a change which
converts chown/chmod to fchown/fchmod using the socket fd. This appears
to succeed under Linux, but fails with EINVAL on FreeBSD. As the error
handling in this area was flawed, CI failed to catch the regression.
Partially revert c8b3a22d4e to fix the
regression on FreeBSD.
The UID/GID defaulted to 0, which results in trying to chown to root
when a UID or GID isn't requested. Instead, deafult to -1 so that the
unspecified values are left intact.
This adds the ability to specify the number of an fd that is inherited
by the process as open. Once seatd is read to serve requests, it will
write a single newline and close the fd.
This handler returns the number of dispatched or executed events, or -1
if dispatch_pending failed.
This helper is used to clean up dispatch_background, which now ensures
that all events are executed before we read or poll the connection, and
have improved error handling in the corner case where the second
dispatch_pending failed.
Dispatch needs to report if something has happened, which includes
events executed from the queue as these could have lead to additional
dispatch and queuing.
The option names are a little bit confusing, because it's not clear
which ones toggle libseat features, and which ones toggle seatd
features.
Add a "libseat-" prefix to libseat-specific features, to make it
more obvious that they only are about the library.
The builtin backend relies on the seatd backend implementation. When
builtin was enabled without seatd, compilation would fail due to the
implementation not being included.
Include the implementation if either seatd or builtin is enabled.
The socket is expected not to be found if seatd is not running.
In general other backends will be attempted after seatd. There is
already an error message in case no backend can be started.
"video" was used for convenience in the example, but a dedicated group
is preferable so that a user does not gain the ability to bypass the
seat manager and open devices directly.
This allows libseat users to e.g. advise people to chmod a+s the
executable if libseat is built with the builtin backend.
While bumping the Meson version, adjust the scdoc logic to avoid
the following warnings:
WARNING: Project targeting '>=0.56.0' but tried to use feature deprecated since '0.56.0': Dependency.get_pkgconfig_variable. use Dependency.get_variable(pkgconfig : ...) instead
WARNING: Project targeting '>=0.56.0' but tried to use feature deprecated since '0.55.0': ExternalProgram.path. use ExternalProgram.full_path() instead
Setting auto_features=disabled is supposed to disable all optional
dependencies. Since we aren't using a feature option here, we need
to manually add logic to disable logind in this case.
If -Dlogind=auto but systemd/elogind isn't available,
logind_provider would get set to the last item of the foreach loop.
This would incorrectly report "systemd: YES".
Allow package maintainers to explicitly select a logind provider
by passing -Dlogind=systemd or -Dlogind=elogind. In case both are
available (e.g. for distributions which support both), this makes
it possible to gte deterministic behavior.
By default, auto-detect the logind provider. That way, users which
have systemd or elogind installed get the backend built by default.
clang-format wants to put the terminating NULLs on the same line as the
noop backend when it doens't have any immediate non-NULL neighbors.
Add a newline to stop it.
This is useful for headless testing, for instance with VKMS:
modprobe vkms
export WLR_DRM_DEVICES=/dev/dri/card1
export WLR_BACKENDS=drm
export LIBSEAT_BACKEND=noop
sway
We don't need any of the VT handling in this case.
If a client closed while it was disabled, the VT would not be torn down.
If the user navigated back to the VT it belonged to, they would be
stuck.
When a client is disabled, open the fd for the VT it belonged to and
perform regular teardown on it.
This is not strictly speaking necessary as detaching from the bus should
trigger this automatically, but elogind apparently has issues with this.
Doing this explicitly does no harm, so let's just do that.
The most common pain point I've seen with people trying out seat is
forgetting to add themselves to whatever group the distro has chosen
to own the socket.
Logging this error and path of the socket should make it easier to tell
why things aren't working.
Linux only requires acking release and ignores ack of acquire, but
FreeBSD is more stringent and will patiently wait for both to be acked.
Implement proper acking for both events.
FreeBSD adds one to the VT number returned by the GET_ACTIVE ioctl, so
to match things up, the wrapper here subtracted by one. This lead to
ttyv0 being named VT 0. This had the side-effect of VT numbering not
matching expectations, and switching not behaving as intended.
Align numbers with expectations, and move the required subtraction to
terminal_open, so that VT 1 matches ttyv0.
Path check was done on /dev/dri/card and /dev/dri/renderD. However,
/dev/dri/by-path is a thing, and on FreeBSD, /dev/dri/ symlinks to
/dev/drm/.
Relax Linux check to /dev/dri/, and add FreeBSD check for /dev/drm/.
If a background event was queued during call dispatch, and no unread
data was left on the socket, there would be no incentive for the user to
call dispatch, and as a result, the events would never be executed.
Execute events at the end of IPC calls that read from the socket to
avoid stalls.
Dispatch on IPC call only dispatched until the first message was
successfully processed. This could lead to premature dispatch
termination if a background event was received during an IPC call.
Instead, continue dispatching until a non-bg opcode is reported or an
error is received.
Only if a device had an fd and was active would an fd be closed. As
devices are deactivated early on session switch, this lead to fd
leakage.
Close fds regardless of active state.
The seat activation logic did not correctly handle VT switching and
switching between multiple sessions.
Session switching on VT-bound seats is now performed using a VT switch,
taking advantage of VT signals to perform the actual switch. This
simplifies switching logic and makes it more robust.
Signal handling relied on poll(2) being interrupted by signals, followed
by a check for signal handlers flagging a signal as received. This only
allowed signals that were received during poll(2) to be handled
correctly.
Implement the usual self-pipe implementation, where signal handlers
write an arbitrary byte to a polled file descriptor to ensure proper
level-triggered signal handling.
test_run and test_assert replaces regular assert with better logging
which include the currently running test name. The tests can now also be
built without DEBUG.
Add helpers around connection access to have all logging centralized and
reduce code duplication. Improve existing helpers to further reduce code
duplication.
The seatd backend should have much better logging after this.
FreeBSD TTY paths are contructed in the kernel using the %r formatter,
which in this case ends up being a base 32 encoding.
The base 32 implementation is taken more or less directly from wlroots
commit fc6c0ca12e94.
Taken from X11, weston and consolekit2 ports for FreeBSD.
Setting just K_CODE as done before makes input seemingly have no ill
effects, but it is still buffered and possibly send to the terminal
after application exit if stdin is never drained. Setting raw mode
appears to be needed to solve that issue.
A K_OFF-like VT keyboard setting like Linux has would seem more
appropriate, but that is not currently available to us on FreeBSD.
elogind provides a libsystemd wrapper which is packaged by some distros.
For whatever reason using this wrapper instead of libelogind directly
causes compiler warnings to pop up. Checking for libelogind first
ensures that this wrapper is not used.
VTs were being cleaned up the active client of a VT went away, or if we
were acking a kernel VT switch request. However, no cleanup was done if
the user had reqested a session switch to a different VT.
Duplicate the VT cleanup to the VT switch condition.
Previously, seatd would not deactivate devices until the client had
acked the disable. In once instance, this lead to libinput spending
significant time checking and closing each input device.
As a workaround, mimick logind's behavior of deactivating devices first.
The original behavior can be reintroduced if the client-side problem is
fixed.
Closes: https://todo.sr.ht/~kennylevinsen/seatd/5
The VT and KD ioctl's are picky about the tty fd used. In order to
satisfy these, and to improve state cleanup, we now only and store the
current tty when opening a client, and use this fd to perform teardown
later. The presence of the fd is also used to signal that teardown is
needed.
FreeBSD device numbers cannot be used to check the type of a device, as
they are merely unique filesystem IDs.
As the paths we use have been sanitized with realpath, we can simply use
the path to check if a requested file is an evdev or drm device. This
also allows us to make the check before the file is opened.