From 326f9c66ae15f79de4bcb730377202d4c3a5c7bf Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Thu, 3 Dec 2026 07:54:11 +0800 Subject: [PATCH 1/2] fix(compat): restore systemd logging and shutdown ABI --- .../en/LC_MESSAGES/userspace-api/abi.po | 20 ++ .../userspace-api/device-filesystems.po | 16 ++ .../ja/LC_MESSAGES/userspace-api/abi.po | 20 ++ .../userspace-api/device-filesystems.po | 16 ++ Documentation/userspace-api/abi.rst | 18 ++ .../userspace-api/device-filesystems.rst | 13 + arch/x86_64/interrupt/irq.c | 2 + drivers/console/Kbuild | 2 +- drivers/console/kmsg.c | 176 ++++++++++++++ drivers/console/log.c | 21 +- fs/cgroup/filesystem.c | 11 +- fs/exfat/native.c | 6 +- fs/ext_common/Kbuild | 2 +- fs/ext_common/acl.c | 222 ++++++++++++++++++ fs/ext_common/dir.c | 13 +- fs/ext_common/format.c | 3 + fs/ext_common/internal.h | 20 +- fs/ext_common/native.c | 79 ++++++- fs/ext_common/storage_ext4_types.h | 2 + fs/ext_common/xattr.c | 162 +++++++++++-- fs/fat/native.c | 6 +- fs/operations.h | 8 +- fs/security/access.c | 83 ++++++- fs/tmpfs/native.c | 9 +- fs/vfs/attributes.c | 10 + fs/vfs/file.c | 20 +- fs/vfs/storage_backend.c | 22 +- fs/vfs/storage_backend.h | 8 +- fs/vfs/storage_create.c | 22 +- fs/vfs/xattr.c | 23 +- include/reliefnt/console.h | 4 +- include/reliefnt/kmsg.h | 54 +++++ include/reliefnt/mount.h | 31 ++- include/reliefnt/posix_acl.h | 40 ++++ include/reliefnt/sched.h | 8 + kernel/sched/signal.c | 45 +++- kernel/syscall/device/device_io.c | 30 ++- kernel/syscall/device/device_open.c | 2 + kernel/syscall/entry.c | 1 + kernel/syscall/event/epoll.c | 3 + kernel/syscall/event/poll.c | 7 +- kernel/syscall/fd/open.c | 4 +- kernel/syscall/fs/create.c | 10 +- kernel/syscall/fs/xattr.c | 81 ++++++- kernel/syscall/internal.h | 3 +- kernel/syscall/io/io.c | 3 + kernel/syscall/io/legacy_io.c | 3 +- kernel/syscall/io/seek.c | 14 +- kernel/syscall/io/vector.c | 29 +++ kernel/syscall/ipc/unix_path.c | 3 +- kernel/syscall/process/process.c | 5 +- tools/test_ext4_dir.py | 2 +- tools/test_mount_backend.py | 1 + tools/tests/epoll_capacity_test.c | 1 + tools/tests/ext4_metadata_api_test.py | 11 +- tools/tests/ext4_xattr_test.c | 17 +- tools/tests/inotify_vfs_test.c | 7 +- tools/tests/modules/console.h | 1 + tools/tests/modules/kmsg.h | 5 + tools/tests/modules/syscall_dispatch.h | 1 + tools/tests/mount_backend_test.c | 9 +- tools/tests/permission_graph_fixture.h | 6 +- tools/tests/select_bitmap_test.c | 1 + tools/tests/storage_mkdir_mount_test.c | 1 + tools/tests/storage_rename_test.c | 1 + tools/tests/systemd_compat_runtime_probe.c | 181 ++++++++++++++ tools/tests/task8_epoll_user_test.c | 1 + .../task8_host_stubs/descriptor_unreached.c | 1 + tools/tests/vt_console_test.c | 4 + 69 files changed, 1531 insertions(+), 135 deletions(-) create mode 100644 drivers/console/kmsg.c create mode 100644 fs/ext_common/acl.c create mode 100644 include/reliefnt/kmsg.h create mode 100644 include/reliefnt/posix_acl.h create mode 100644 tools/tests/modules/kmsg.h create mode 100644 tools/tests/systemd_compat_runtime_probe.c diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 335ec0c6..53f59211 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -1076,3 +1076,23 @@ msgstr "" "skipped when AVX is disabled. Applications and glibc versions outside " "this coverage still require individual validation. VMware validation is " "incomplete, and physical hardware has not been validated." + +msgid "广播进程信号" +msgstr "Broadcast process signals" + +msgid "" +"``kill(-1, sig)`` 按 Linux 语义遍历每个用户进程一次。PID 1 和调用者的整个线程组 跳过,其他进程分别检查 " +"UID、目标用户空间的 ``CAP_KILL`` 以及同会话 ``SIGCONT`` 权限。信号 0 只作探测。信号携带 " +"``SI_USER``、发送进程 ID 和按接收者用户空间 映射的发送者真实 UID。没有候选进程时返回 ``ESRCH``。" +msgstr "``kill(-1, sig)`` visits each userspace process once using Linux semantics. PID 1 and the caller's entire thread group are skipped. Each remaining process is checked against UID permissions, ``CAP_KILL`` in its user namespace, and the same-session rule for ``SIGCONT``. Signal 0 is a probe. Signals carry ``SI_USER``, the sender's process ID, and the sender's real UID mapped into the recipient's user namespace. If there are no candidates, the call returns ``ESRCH``." + +msgid "ext 文件系统 ACL" +msgstr "ACLs on ext filesystems" + +msgid "" +"ext2、ext3 和 ext4 支持 ``system.posix_acl_access`` 与 " +"``system.posix_acl_default``。路径和描述符的 xattr 调用使用 Linux ACL 编码。 " +"文件所有者或具有相应权限的进程可以设置和删除 ACL。访问检查应用命名用户、 命名组、补充组和 ACL 掩码。``chmod`` 同步调整访问 " +"ACL 的权限类别。 新 inode 从父目录继承默认 ACL,并按请求的模式限制权限。父目录没有默认 ACL 时,inode 创建使用调用者的 " +"``umask``。新目录同时继承默认 ACL。" +msgstr "ext2, ext3, and ext4 support ``system.posix_acl_access`` and ``system.posix_acl_default``. Path- and descriptor-based xattr calls use Linux ACL encoding. The inode owner or a privileged caller can set and remove ACLs. Access checks apply named users, named groups, supplementary groups, and the ACL mask. ``chmod`` updates the access ACL's permission classes. A new inode inherits its parent's default ACL with permissions limited by the requested mode. Without a default ACL, inode creation applies the caller's ``umask``. New directories also inherit the default ACL." diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po index 0b83f0ba..50cff4cb 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/device-filesystems.po @@ -377,3 +377,19 @@ msgstr "Opening a writable control checks permissions on its exact inode; a succ msgid "文本虚拟终端的 ``K_XLATE`` 和 ``K_UNICODE`` 键盘模式均支持 ``Ctrl+Alt+F1`` 至 ``Ctrl+Alt+F6`` 切换,遵循既有终端交接流程。Unicode 模式保留 UTF-8 输入。" msgstr "Text virtual terminals support switching with ``Ctrl+Alt+F1`` through ``Ctrl+Alt+F6`` in both ``K_XLATE`` and ``K_UNICODE`` keyboard modes, using the existing terminal handoff protocol. Unicode mode preserves UTF-8 input." + +msgid "内核日志设备" +msgstr "Kernel log device" + +msgid "" +"``/dev/kmsg`` 以 Linux 的字符设备号 ``1:11`` 提供内核日志。每次打开独立记录 读取位置,``dup`` 和 " +"``fork`` 共享打开描述的游标。每次读取返回一条包含优先级、 序号和启动后微秒时间的完整记录。缓冲区无新记录时,阻塞读取可被信号中断, " +"非阻塞读取返回 ``EAGAIN``。读取落后于日志环时返回 ``EPIPE`` 并定位到最旧 的可读记录。poll 和 epoll " +"可等待新记录并报告溢出。" +msgstr "``/dev/kmsg`` exposes the kernel log through Linux character device number ``1:11``. Each open has an independent read position. Descriptors inherited through ``dup`` or ``fork`` share the cursor of the open file description. Each read returns one record containing its priority, sequence, and time in microseconds since boot. When no record is available, blocking reads can be interrupted by a signal and nonblocking reads return ``EAGAIN``. A reader overtaken by the ring returns ``EPIPE`` and advances to the oldest readable record. poll and epoll wait for new records and report overruns." + +msgid "" +"``lseek(fd, 0, SEEK_SET)`` 定位到最旧记录,``SEEK_END`` 定位到当前末尾, ``SEEK_DATA`` " +"定位到初始序号。用户态每次 ``write`` 或 ``writev`` 写入一条 记录,可带 syslog 的 ``<优先级>`` " +"前缀。用户态记录使用非内核 facility。" +msgstr "``lseek(fd, 0, SEEK_SET)`` selects the oldest record, ``SEEK_END`` selects the current tail, and ``SEEK_DATA`` selects the initial sequence. Each userspace ``write`` or ``writev`` appends one record and may supply a syslog ```` prefix. Userspace records use a nonkernel facility." diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index 10ac9da6..e8b8a08c 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -903,3 +903,23 @@ msgstr "" "ELF、pthread/TLS、``posix_spawn``、``dlopen/dlsym``、localhost NSS、通常の robust" " ミューテックスも実行しました。AVX が無効な場合は AVX 固有の検査をスキップします。この範囲外のアプリケーションと glibc " "バージョンは個別の検証が必要です。VMware での検証は未完了で、実機ハードウェアは未検証です。" + +msgid "广播进程信号" +msgstr "プロセスへのシグナルの一斉送信" + +msgid "" +"``kill(-1, sig)`` 按 Linux 语义遍历每个用户进程一次。PID 1 和调用者的整个线程组 跳过,其他进程分别检查 " +"UID、目标用户空间的 ``CAP_KILL`` 以及同会话 ``SIGCONT`` 权限。信号 0 只作探测。信号携带 " +"``SI_USER``、发送进程 ID 和按接收者用户空间 映射的发送者真实 UID。没有候选进程时返回 ``ESRCH``。" +msgstr "``kill(-1, sig)`` は Linux の動作に従い、各ユーザープロセスを一度ずつ処理します。PID 1 と呼び出し元のスレッドグループ全体を除外します。残りの各プロセスについて UID、対象のユーザー名前空間の ``CAP_KILL``、および ``SIGCONT`` の同一セッション条件を確認します。シグナル 0 は確認にのみ使います。シグナルには ``SI_USER``、送信元のプロセス ID、受信側のユーザー名前空間にマップされた送信元の実 UID を含めます。候補がなければ ``ESRCH`` を返します。" + +msgid "ext 文件系统 ACL" +msgstr "ext ファイルシステムの ACL" + +msgid "" +"ext2、ext3 和 ext4 支持 ``system.posix_acl_access`` 与 " +"``system.posix_acl_default``。路径和描述符的 xattr 调用使用 Linux ACL 编码。 " +"文件所有者或具有相应权限的进程可以设置和删除 ACL。访问检查应用命名用户、 命名组、补充组和 ACL 掩码。``chmod`` 同步调整访问 " +"ACL 的权限类别。 新 inode 从父目录继承默认 ACL,并按请求的模式限制权限。父目录没有默认 ACL 时,inode 创建使用调用者的 " +"``umask``。新目录同时继承默认 ACL。" +msgstr "ext2、ext3、ext4 は ``system.posix_acl_access`` と ``system.posix_acl_default`` をサポートします。パスやファイル記述子を指定する xattr 呼び出しは Linux の ACL 形式を使用します。inode の所有者または権限のある呼び出し元が ACL を設定、削除できます。アクセス判定には名前付きユーザー、名前付きグループ、補助グループ、ACL マスクが適用されます。``chmod`` はアクセス ACL の権限クラスも更新します。新しい inode は親ディレクトリのデフォルト ACL を継承し、要求されたモードで権限を制限します。デフォルト ACL がない場合は、呼び出し元の ``umask`` を適用します。新しいディレクトリにはデフォルト ACL 自体も継承されます。" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po index adab9c6f..9a79bef5 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/device-filesystems.po @@ -334,3 +334,19 @@ msgstr "書き込み可能な制御ファイルを開くと、対象 inode の msgid "文本虚拟终端的 ``K_XLATE`` 和 ``K_UNICODE`` 键盘模式均支持 ``Ctrl+Alt+F1`` 至 ``Ctrl+Alt+F6`` 切换,遵循既有终端交接流程。Unicode 模式保留 UTF-8 输入。" msgstr "テキスト仮想端末は ``K_XLATE`` と ``K_UNICODE`` の両キーボードモードで、既存の端末引き渡し手順に従い ``Ctrl+Alt+F1`` から ``Ctrl+Alt+F6`` による切り替えに対応します。Unicode モードでは UTF-8 入力を維持します。" + +msgid "内核日志设备" +msgstr "カーネルログデバイス" + +msgid "" +"``/dev/kmsg`` 以 Linux 的字符设备号 ``1:11`` 提供内核日志。每次打开独立记录 读取位置,``dup`` 和 " +"``fork`` 共享打开描述的游标。每次读取返回一条包含优先级、 序号和启动后微秒时间的完整记录。缓冲区无新记录时,阻塞读取可被信号中断, " +"非阻塞读取返回 ``EAGAIN``。读取落后于日志环时返回 ``EPIPE`` 并定位到最旧 的可读记录。poll 和 epoll " +"可等待新记录并报告溢出。" +msgstr "``/dev/kmsg`` は Linux のキャラクターデバイス番号 ``1:11`` でカーネルログを公開します。開くたびに独立した読み取り位置が割り当てられ、``dup`` または ``fork`` で共有されたファイル記述は同じ位置を使います。読み取りは優先度、シーケンス番号、起動からのマイクロ秒を含むレコードを一件ずつ返します。新しい記録がない場合、ブロッキング読み取りはシグナルで中断でき、非ブロッキング読み取りは ``EAGAIN`` を返します。読み取りがリングの上書きに追い越されると ``EPIPE`` を返し、読み取れる最も古い記録へ進みます。poll と epoll で新しい記録やオーバーランを待機できます。" + +msgid "" +"``lseek(fd, 0, SEEK_SET)`` 定位到最旧记录,``SEEK_END`` 定位到当前末尾, ``SEEK_DATA`` " +"定位到初始序号。用户态每次 ``write`` 或 ``writev`` 写入一条 记录,可带 syslog 的 ``<优先级>`` " +"前缀。用户态记录使用非内核 facility。" +msgstr "``lseek(fd, 0, SEEK_SET)`` は最も古い記録を、``SEEK_END`` は現在の末尾を、``SEEK_DATA`` は初期シーケンスを選びます。ユーザー空間の ``write`` または ``writev`` は一件の記録を追加し、syslog の ``<優先度>`` プレフィックスを指定できます。ユーザー空間の記録にはカーネル用以外のファシリティを使います。" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 976a7818..bc6fcb4c 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -61,6 +61,24 @@ fork、vfork、clone 复制调用任务的选择,exec 保留选择。已经存 没有这种祖先则回退到 PID 1。新父进程可等待被接管的子进程,并按 SIGCHLD 规则 接收退出通知。当前不提供独立的 PID 命名空间。 +广播进程信号 +============ + +``kill(-1, sig)`` 按 Linux 语义遍历每个用户进程一次。PID 1 和调用者的整个线程组 +跳过,其他进程分别检查 UID、目标用户空间的 ``CAP_KILL`` 以及同会话 ``SIGCONT`` +权限。信号 0 只作探测。信号携带 ``SI_USER``、发送进程 ID 和按接收者用户空间 +映射的发送者真实 UID。没有候选进程时返回 ``ESRCH``。 + +ext 文件系统 ACL +================ + +ext2、ext3 和 ext4 支持 ``system.posix_acl_access`` 与 +``system.posix_acl_default``。路径和描述符的 xattr 调用使用 Linux ACL 编码。 +文件所有者或具有相应权限的进程可以设置和删除 ACL。访问检查应用命名用户、 +命名组、补充组和 ACL 掩码。``chmod`` 同步调整访问 ACL 的权限类别。 +新 inode 从父目录继承默认 ACL,并按请求的模式限制权限。父目录没有默认 ACL +时,inode 创建使用调用者的 ``umask``。新目录同时继承默认 ACL。 + 创建挂载命名空间 ================ diff --git a/Documentation/userspace-api/device-filesystems.rst b/Documentation/userspace-api/device-filesystems.rst index 8bd6fc56..c58c205a 100644 --- a/Documentation/userspace-api/device-filesystems.rst +++ b/Documentation/userspace-api/device-filesystems.rst @@ -112,6 +112,19 @@ devpts 挂载选项 权限决定是否可打开。找不到有效的 devpts 多路复用器时沿用启动阶段的旧 PTY 分配;其他查找错误则返回调用方。 +内核日志设备 +============ + +``/dev/kmsg`` 以 Linux 的字符设备号 ``1:11`` 提供内核日志。每次打开独立记录 +读取位置,``dup`` 和 ``fork`` 共享打开描述的游标。每次读取返回一条包含优先级、 +序号和启动后微秒时间的完整记录。缓冲区无新记录时,阻塞读取可被信号中断, +非阻塞读取返回 ``EAGAIN``。读取落后于日志环时返回 ``EPIPE`` 并定位到最旧 +的可读记录。poll 和 epoll 可等待新记录并报告溢出。 + +``lseek(fd, 0, SEEK_SET)`` 定位到最旧记录,``SEEK_END`` 定位到当前末尾, +``SEEK_DATA`` 定位到初始序号。用户态每次 ``write`` 或 ``writev`` 写入一条 +记录,可带 syslog 的 ``<优先级>`` 前缀。用户态记录使用非内核 facility。 + 前台虚拟终端 ============ diff --git a/arch/x86_64/interrupt/irq.c b/arch/x86_64/interrupt/irq.c index 69d6a60a..fbca19a4 100644 --- a/arch/x86_64/interrupt/irq.c +++ b/arch/x86_64/interrupt/irq.c @@ -4,6 +4,7 @@ * Routes timer, input, storage, and device interrupts to kernel subsystems. */ #include +#include #include #include #include @@ -201,6 +202,7 @@ struct task *irq_dispatch(struct trap_frame *frame) if (vector == 0x20) { time_on_tick(); serial_tx_tick(); + kmsg_notify_readers(); if (from_user) { uint8_t byte; if (keyboard_led_next(&keyboard_led, input_caps_lock_active() ? 4U : 0U, diff --git a/drivers/console/Kbuild b/drivers/console/Kbuild index 152433a4..8ae866f6 100644 --- a/drivers/console/Kbuild +++ b/drivers/console/Kbuild @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 -obj-y := ansi.o core.o log.o panic.o render.o vt.o vga_console.o vga_terminal.o vga_ansi.o +obj-y := ansi.o core.o kmsg.o log.o panic.o render.o vt.o vga_console.o vga_terminal.o vga_ansi.o include $(srctree)/scripts/Makefile.module diff --git a/drivers/console/kmsg.c b/drivers/console/kmsg.c new file mode 100644 index 00000000..7ee687a4 --- /dev/null +++ b/drivers/console/kmsg.c @@ -0,0 +1,176 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include +#include +#include +#include +#include +#include +#include + +#define KMSG_RECORDS 512u + +struct kmsg_record { + uint64_t timestamp; + uint16_t length; + uint16_t priority; + char text[KMSG_MESSAGE_MAX]; +}; + +static struct kmsg_record records[KMSG_RECORDS]; +static struct kernel_spinlock ring_lock = KERNEL_SPINLOCK_INIT; +static uint64_t next_sequence; +static uint64_t notified_sequence; + +/** @brief Compute the oldest live record from a single sequence snapshot. */ +static uint64_t oldest(uint64_t next) +{ + return next > KMSG_RECORDS ? next - KMSG_RECORDS : 0; +} + +/** @copydoc kmsg_append */ +void kmsg_append(unsigned priority, uint64_t timestamp, const char *text, size_t length) +{ + uint64_t flags; + kernel_spin_lock_irqsave(&ring_lock, &flags); + uint64_t next = __atomic_load_n(&next_sequence, __ATOMIC_RELAXED); + struct kmsg_record *record = &records[next % KMSG_RECORDS]; + if (next && timestamp < records[(next - 1) % KMSG_RECORDS].timestamp) + timestamp = records[(next - 1) % KMSG_RECORDS].timestamp; + if (length > sizeof(record->text)) length = sizeof(record->text); + record->timestamp = timestamp; + record->length = (uint16_t)length; + record->priority = (uint16_t)priority; + __builtin_memcpy(record->text, text, length); + __atomic_store_n(&next_sequence, next + 1, __ATOMIC_RELEASE); + kernel_spin_unlock_irqrestore(&ring_lock, flags); +} + +/** @copydoc kmsg_next_sequence */ +uint64_t kmsg_next_sequence(void) +{ + return __atomic_load_n(&next_sequence, __ATOMIC_ACQUIRE); +} + +/** @copydoc kmsg_first_sequence */ +uint64_t kmsg_first_sequence(void) +{ + return oldest(kmsg_next_sequence()); +} + +/** @copydoc kmsg_readiness */ +short kmsg_readiness(uint64_t sequence) +{ + uint64_t next = kmsg_next_sequence(); + if (sequence >= next) return 0; + return POLLIN | POLLRDNORM | (sequence < oldest(next) ? POLLERR | POLLPRI : 0); +} + +/** @brief Write a decimal field and its separator into the bounded header. + * @param cursor Next output byte, with room for a uint64_t and a comma. + * @param value Field value. @return Position immediately after the comma. + */ +static char *decimal_field(char *cursor, uint64_t value) +{ + char digits[20]; + size_t count = 0; + do { + digits[count++] = (char)('0' + value % 10); + value /= 10; + } while (value); + while (count) *cursor++ = digits[--count]; + *cursor++ = ','; + return cursor; +} + +/** @brief Determine whether the kmsg record format escapes this byte. */ +static bool escape_byte(unsigned char ch) +{ + return ch < 32 || ch >= 127 || ch == '\\'; +} + +/** @copydoc kmsg_read_record */ +int kmsg_read_record(uint64_t *sequence, char *buffer, size_t capacity) +{ + uint64_t flags, cursor = *sequence; + struct kmsg_record record; + kernel_spin_lock_irqsave(&ring_lock, &flags); + uint64_t next = __atomic_load_n(&next_sequence, __ATOMIC_RELAXED); + uint64_t first = oldest(next); + if (cursor < first) { + *sequence = first; + kernel_spin_unlock_irqrestore(&ring_lock, flags); + return -EPIPE; + } + if (cursor >= next) { + kernel_spin_unlock_irqrestore(&ring_lock, flags); + return -EAGAIN; + } + record = records[cursor % KMSG_RECORDS]; + *sequence = cursor + 1; + kernel_spin_unlock_irqrestore(&ring_lock, flags); + + char header[64]; + char *end = decimal_field(header, record.priority); + end = decimal_field(end, cursor); + end = decimal_field(end, record.timestamp); + *end++ = '-'; + *end++ = ';'; + size_t header_length = (size_t)(end - header); + size_t length = header_length + 1; /* Final newline. */ + for (size_t i = 0; i < record.length; ++i) + length += escape_byte((unsigned char)record.text[i]) ? 4u : 1u; + if (length > capacity) return -EINVAL; + __builtin_memcpy(buffer, header, header_length); + end = buffer + header_length; + static const char hex[] = "0123456789abcdef"; + for (size_t i = 0; i < record.length; ++i) { + unsigned char ch = (unsigned char)record.text[i]; + if (escape_byte(ch)) { + *end++ = '\\'; + *end++ = 'x'; + *end++ = hex[ch >> 4]; + *end++ = hex[ch & 15u]; + } else { + *end++ = (char)ch; + } + } + *end = '\n'; + return (int)length; +} + +/** @copydoc kmsg_write_record */ +int kmsg_write_record(const char *buffer, size_t length) +{ + if (length > KMSG_MESSAGE_MAX) return -EINVAL; + if (!length) return 0; + char text[KMSG_MESSAGE_MAX]; + __builtin_memcpy(text, buffer, length); + size_t end = 0, start = 0; + while (end < length && text[end]) ++end; + uint32_t priority = 12; /* LOG_USER | LOG_WARNING. */ + if (end > 1 && text[0] == '<') { + size_t i = 1; + uint32_t prefix = 0; + while (i < end && text[i] >= '0' && text[i] <= '9') + prefix = prefix * 10u + (unsigned)(text[i++] - '0'); + if (i < end && text[i] == '>') { + priority = prefix & 0x7ffu; + if (!(priority >> 3)) priority |= 8u; + start = i + 1; + } + } + if (end > start && text[end - 1] == '\n') --end; + kmsg_append(priority, time_uptime_us(), text + start, end - start); + if ((priority & 7u) != 7u) console_write_len(text + start, end - start); + return (int)length; +} + +/** @copydoc kmsg_notify_readers */ +void kmsg_notify_readers(void) +{ + uint64_t next = kmsg_next_sequence(); + if (next != notified_sequence) { + notified_sequence = next; + kernel_poll_readiness_notify(); + } +} diff --git a/drivers/console/log.c b/drivers/console/log.c index 66a159f3..521ea1d1 100644 --- a/drivers/console/log.c +++ b/drivers/console/log.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "internal.h" #include +#include #include #define CONSOLE_LOG_MESSAGE_BYTES 768u @@ -279,9 +280,17 @@ static void publish_line(enum console_log_level level, uint64_t uptime, } } -static void console_publish(enum console_log_level level, const char *text, size_t length) +/** @brief Publish formatted lines to the kernel log and enabled display sinks. + * @param level Native log severity. @param text Borrowed formatted bytes. + * @param length Number of formatted bytes. @param kernel_record Retain native + * records in kmsg even when quiet. Userspace writes already have a record. + */ +static void console_publish(enum console_log_level level, const char *text, size_t length, + bool kernel_record) { uint64_t uptime = time_uptime_us(); + bool display = console_log_enabled(level); + if (!display && !kernel_record) return; uint64_t flags = kernel_irq_save(); uint32_t cpu = smp_current_cpu(); bool acquired = false; @@ -304,7 +313,8 @@ static void console_publish(enum console_log_level level, const char *text, size while (end < length && text[end] != '\n') ++end; size_t line_length = end - from; if (line_length && text[end - 1u] == '\r') --line_length; - publish_line(level, uptime, text + from, line_length, owned); + if (kernel_record && owned) kmsg_append(priorities[level], uptime, text + from, line_length); + if (display) publish_line(level, uptime, text + from, line_length, owned); from = end + 1u; } if (acquired) __atomic_store_n(&console_log_owner, UINT32_MAX, __ATOMIC_RELEASE); @@ -313,16 +323,15 @@ static void console_publish(enum console_log_level level, const char *text, size void console_vlog(enum console_log_level level, const char *fmt, va_list arguments) { - if (!console_log_enabled(level) || !fmt || !*fmt) return; + if (!fmt || !*fmt) return; char message[CONSOLE_LOG_MESSAGE_BYTES]; struct log_format output = {.data = message, .capacity = sizeof(message)}; format_message(&output, fmt, arguments); - console_publish(normalize_level(level), message, output.length); + console_publish(normalize_level(level), message, output.length, true); } void console_log(enum console_log_level level, const char *fmt, ...) { - if (!console_log_enabled(level)) return; va_list arguments; va_start(arguments, fmt); console_vlog(level, fmt, arguments); @@ -363,7 +372,7 @@ void console_write_len(const char *text, size_t length) while (length) { size_t chunk = length < sizeof(data) ? length : sizeof(data); __builtin_memcpy(data, text, chunk); - console_publish(CONSOLE_LOG_INFO, data, chunk); + console_publish(CONSOLE_LOG_INFO, data, chunk, false); text += chunk; length -= chunk; } diff --git a/fs/cgroup/filesystem.c b/fs/cgroup/filesystem.c index 944283f5..1e2b2844 100644 --- a/fs/cgroup/filesystem.c +++ b/fs/cgroup/filesystem.c @@ -282,11 +282,16 @@ static int cgroup_statfs(void *context, const struct storage_node *node, struct } /** @brief Publish a child only with write/search DAC on the actual parent. + * @param context Borrowed cgroup filesystem context. @param parent Retained directory. + * @param name Literal component. @param type Requested Linux inode type. + * @param mode Borrowed creation metadata. @param target Unused symlink target. + * @param umask Process creation mask. @param out Receives the new node. + * @param pin Optional owned backing reference. @return Zero or negative errno. * The backend enforces parent DAC even for internal callers without a * pathname permission walk, and reserves disabled control names. */ static int cgroup_create(void *context, const struct storage_node *parent, const char *name, uint32_t type, - const struct reliefos_permissions *mode, const char *target, + const struct reliefos_permissions *mode, const char *target, uint32_t umask, struct storage_node *out, void **pin) { (void)context; (void)target; @@ -300,7 +305,9 @@ static int cgroup_create(void *context, const struct storage_node *parent, const for (enum cgroup_file file = CG_PROCS; file < CG_FILE_COUNT; ++file) if (!__builtin_strcmp(controls[file].name, name)) return -EEXIST; struct cgroup *g = NULL; - rc = cgroup_mkdir(group, name, mode, &g); + struct reliefos_permissions masked = *mode; + masked.mode &= ~umask; + rc = cgroup_mkdir(group, name, &masked, &g); if (rc) return rc; *out = cgroup_node(g, CG_DIR, 0); return pin ? cgroup_retain(context, out, pin) : 0; diff --git a/fs/exfat/native.c b/fs/exfat/native.c index 10f4a3d3..570771a6 100644 --- a/fs/exfat/native.c +++ b/fs/exfat/native.c @@ -288,15 +288,17 @@ static const struct storage_cluster_ops exfat_native_clusters={ * @param volume Borrowed selected/pinned instance. @param parent Actual directory. * @param name Validated literal component. @param mode Authorized type/mode. * @param value Borrowed authorized ownership/mode. @param target Optional symlink target. + * @param umask Mask already applied by the storage backend. * @param out Required created metadata output. * @return Zero or native validation/allocation/I/O errno. Execution/mutation * admission required; no callback lock. Core stores sidecar attributes and * acquires publication pins before the new VFS dentry becomes observable. */ static int exfat_native_create(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, - const struct reliefos_permissions *value,const char *target,struct storage_node *out) + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out) { - (void)value;(void)target; + (void)value;(void)target;(void)umask; if(parent->type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; if((mode&LINUX_S_IFMT)==LINUX_S_IFREG) { int rc=exfat_native_lookup(volume,parent,name,out); diff --git a/fs/ext_common/Kbuild b/fs/ext_common/Kbuild index a2121624..c89ab9e9 100644 --- a/fs/ext_common/Kbuild +++ b/fs/ext_common/Kbuild @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 obj-$(CONFIG_EXT_FS_COMMON) := ext_common.o -ext_common-y := alloc.o cache.o checksum.o dir.o extent.o format.o journal.o mount.o ops.o vfs.o xattr.o +ext_common-y := acl.o alloc.o cache.o checksum.o dir.o extent.o format.o journal.o mount.o ops.o vfs.o xattr.o ext_common-y += native.o sync.o mkfs.o ext2.o ext2_cache.o ext2_write.o init.o include $(srctree)/scripts/Makefile.module diff --git a/fs/ext_common/acl.c b/fs/ext_common/acl.c new file mode 100644 index 00000000..8d51593a --- /dev/null +++ b/fs/ext_common/acl.c @@ -0,0 +1,222 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "../../block/core/storage_internal.h" +#include +#include + +#define EXT_ACL_VERSION 1u + +/** @brief Validate canonical ACL entry order, qualifiers and permissions. + * @param entries Borrowed ordered entries with globally mapped qualifiers. + * @param count Number of entries. @return True for a valid nonempty ACL. + */ +static bool acl_valid(const struct posix_acl_entry *entries, unsigned count) +{ + if (count < 3 || entries[0].tag != ACL_USER_OBJ || entries[count - 1].tag != ACL_OTHER) + return false; + unsigned seen = 0; + for (unsigned i = 0; i < count; ++i) { + const struct posix_acl_entry *entry = &entries[i]; + switch (entry->tag) { + case ACL_USER_OBJ: case ACL_USER: case ACL_GROUP_OBJ: + case ACL_GROUP: case ACL_MASK: case ACL_OTHER: break; + default: return false; + } + if (entry->perm > 7 || (i && entry->tag < entries[i - 1].tag)) return false; + if (posix_acl_named(entry->tag)) { + if (entry->id == UINT32_MAX) return false; + } else if (seen & entry->tag) { + return false; + } + seen |= entry->tag; + } + return (seen & ACL_GROUP_OBJ) && (!(seen & (ACL_USER | ACL_GROUP)) || (seen & ACL_MASK)); +} + +/** @brief Decode ext's version-1 compact entries into the Linux xattr format. + * @param raw Borrowed on-disk ACL bytes. @param size Number of bytes. + * @param result Receives an allocation owned by the caller. + * @param count Receives the number of validated entries. + * @return Zero or negative format/allocation errno. + */ +static int acl_decode(const void *raw, uint32_t size, struct posix_acl_xattr **result, + unsigned *count) +{ + const uint8_t *start = raw; + if (size < 4 || ext4_get_le32(start) != EXT_ACL_VERSION) return -EIO; + unsigned max_entries = (size - 4) / 4; + struct posix_acl_xattr *acl = kernel_malloc(sizeof(*acl) + + max_entries * sizeof(acl->entries[0])); + if (!acl) return -ENOMEM; + acl->version = POSIX_ACL_XATTR_VERSION; + unsigned n = 0; + uint32_t offset = 4; + while (size - offset >= 4) { + uint16_t tag = ext4_get_le16(start + offset); + unsigned width = posix_acl_named(tag) ? 8 : 4; + if (width > size - offset) break; + acl->entries[n++] = (struct posix_acl_entry){tag, ext4_get_le16(start + offset + 2), + width == 8 ? ext4_get_le32(start + offset + 4) : UINT32_MAX}; + offset += width; + } + if (offset != size || !acl_valid(acl->entries, n)) { + kernel_free(acl); + return -EIO; + } + *result = acl; + *count = n; + return 0; +} + +/** @brief Load and decode an access or default ACL for a retained ext inode. */ +static int acl_read(struct storage_volume *v, uint64_t ino, const struct ext4_inode_view *in, + bool is_default, struct posix_acl_xattr **acl, unsigned *count) +{ + void *raw; + uint32_t length; + int rc = storage_ext4_read_acl(v, ino, in, is_default, &raw, &length); + if (!rc) rc = acl_decode(raw, length, acl, count); + kernel_free(raw); + return rc; +} + +/** @brief Encode ordered Linux ACL entries and commit them with optional mode bits. */ +static int acl_write(struct storage_volume *v, uint64_t ino, bool is_default, + const struct posix_acl_entry *entries, unsigned count, + const uint16_t *mode) +{ + if (!count) return storage_ext4_write_acl(v, ino, is_default, NULL, 0, mode); + uint8_t *raw = kernel_malloc(4 + 8 * count); + if (!raw) return -ENOMEM; + uint32_t size = 4; + ext4_put_le32(raw, EXT_ACL_VERSION); + for (unsigned i = 0; i < count; ++i) { + ext4_put_le16(raw + size, entries[i].tag); + ext4_put_le16(raw + size + 2, entries[i].perm); + size += 4; + if (posix_acl_named(entries[i].tag)) { + ext4_put_le32(raw + size, entries[i].id); + size += 4; + } + } + int rc = storage_ext4_write_acl(v, ino, is_default, raw, size, mode); + kernel_free(raw); + return rc; +} + +/** @brief Project owner, mask (or owning group) and other entries into st_mode. */ +static uint16_t acl_mode(const struct posix_acl_entry *entries, unsigned count, uint16_t mode) +{ + mode &= ~0777u; + unsigned group = 0; + for (unsigned i = 0; i < count; ++i) { + const struct posix_acl_entry *entry = &entries[i]; + switch (entry->tag) { + case ACL_USER_OBJ: mode |= entry->perm << 6; break; + case ACL_GROUP_OBJ: case ACL_MASK: group = entry->perm; break; + case ACL_OTHER: mode |= entry->perm; break; + } + } + return mode | (uint16_t)(group << 3); +} + +/** @brief Apply a mode to the ACL classes, preserving the named entries. + * @param entries Valid mutable entries. @param count Entry count. + * @param mode Permission bits to take or intersect. + * @param intersect True for creation; false to replace affected chmod fields. + */ +static void acl_apply_mode(struct posix_acl_entry *entries, unsigned count, uint16_t mode, + bool intersect) +{ + bool masked = entries[count - 2].tag == ACL_MASK; + for (unsigned i = 0; i < count; ++i) { + unsigned perm; + switch (entries[i].tag) { + case ACL_USER_OBJ: perm = (mode >> 6) & 7; break; + case ACL_GROUP_OBJ: + if (masked) continue; + /* fall through */ + case ACL_MASK: perm = (mode >> 3) & 7; break; + case ACL_OTHER: perm = mode & 7; break; + default: continue; + } + if (intersect) entries[i].perm &= perm; + else entries[i].perm = perm; + } +} + +/** @copydoc storage_ext4_get_acl */ +int storage_ext4_get_acl(struct storage_volume *v, uint64_t ino, const struct ext4_inode_view *in, + bool is_default, void *value, uint32_t capacity, uint32_t *length) +{ + struct posix_acl_xattr *acl; + unsigned count; + if ((in->mode & LINUX_S_IFMT) == LINUX_S_IFLNK) return -EOPNOTSUPP; + int rc = acl_read(v, ino, in, is_default, &acl, &count); + if (rc) return rc; + *length = sizeof(*acl) + count * sizeof(acl->entries[0]); + if (capacity && capacity < *length) rc = -ERANGE; + else if (capacity) storage_memcpy(value, acl, *length); + kernel_free(acl); + return rc; +} + +/** @copydoc storage_ext4_set_acl */ +int storage_ext4_set_acl(struct storage_volume *v, uint64_t ino, const struct ext4_inode_view *in, + bool is_default, const void *value, uint32_t length, bool clear_setgid) +{ + const struct posix_acl_xattr *acl = value; + if ((in->mode & LINUX_S_IFMT) == LINUX_S_IFLNK) return -EOPNOTSUPP; + if (length && (length < sizeof(*acl) || (length - sizeof(*acl)) % sizeof(acl->entries[0]) || + acl->version != POSIX_ACL_XATTR_VERSION)) return -EINVAL; + unsigned count = length ? (length - sizeof(*acl)) / sizeof(acl->entries[0]) : 0; + if (count && !acl_valid(acl->entries, count)) return -EINVAL; + if (is_default && (in->mode & LINUX_S_IFMT) != LINUX_S_IFDIR) return count ? -EACCES : 0; + if (!count && !in->inline_xattrs && !in->file_acl) return 0; + if (!count || is_default) return acl_write(v, ino, is_default, count ? acl->entries : NULL, count, NULL); + uint16_t mode = acl_mode(acl->entries, count, in->mode); + if (clear_setgid) mode &= ~02000u; + /* Three base entries are completely represented by mode bits. */ + return acl_write(v, ino, false, acl->entries, count == 3 ? 0 : count, &mode); +} + +/** @copydoc storage_ext4_chmod_acl */ +int storage_ext4_chmod_acl(struct storage_volume *v, uint64_t ino, const struct ext4_inode_view *in, + uint16_t mode) +{ + struct posix_acl_xattr *acl; + unsigned count; + int rc = acl_read(v, ino, in, false, &acl, &count); + if (rc) return rc; + acl_apply_mode(acl->entries, count, mode, false); + rc = acl_write(v, ino, false, acl->entries, count, &mode); + kernel_free(acl); + return rc; +} + +/** @copydoc storage_ext4_init_acl */ +int storage_ext4_init_acl(struct storage_volume *v, uint64_t parent, const struct ext4_inode_view *dir, + uint64_t ino, struct ext4_inode_view *in, uint32_t umask) +{ + if ((in->mode & LINUX_S_IFMT) == LINUX_S_IFLNK) + return storage_ext4_write_inode(v, ino, in); + struct posix_acl_xattr *acl; + unsigned count; + int rc = acl_read(v, parent, dir, true, &acl, &count); + if (rc == -ENODATA) { + in->mode &= ~(umask & 0777u); + return storage_ext4_write_inode(v, ino, in); + } + if (rc) return rc; + uint16_t requested = in->mode; + in->mode = (requested & ~0777u) | (acl_mode(acl->entries, count, requested) & requested & 0777u); + rc = storage_ext4_write_inode(v, ino, in); + bool directory = (in->mode & LINUX_S_IFMT) == LINUX_S_IFDIR; + if (!rc && directory) rc = acl_write(v, ino, true, acl->entries, count, NULL); + if (!rc && count > 3) { + acl_apply_mode(acl->entries, count, requested, true); + rc = acl_write(v, ino, false, acl->entries, count, NULL); + } + if (!rc && (directory || count > 3)) rc = storage_ext4_read_inode(v, ino, in); + kernel_free(acl); + return rc; +} diff --git a/fs/ext_common/dir.c b/fs/ext_common/dir.c index 748310d6..3fc0018a 100644 --- a/fs/ext_common/dir.c +++ b/fs/ext_common/dir.c @@ -500,7 +500,8 @@ uint8_t ed_type(uint16_t mode) case 0020000:return 3; case 0060000:return 4; case 0010000:return 5; case 0140000:return 6; default:return 1; } } static int ed_create(struct storage_volume *v,uint64_t parent,const char *name,uint16_t mode, - uint32_t uid,uint32_t gid,const char *target,uint32_t device,uint64_t *out,struct storage_node *created) + uint32_t uid,uint32_t gid,const char *target,uint32_t device,uint32_t umask, + uint64_t *out,struct storage_node *created) { int ret=ed_name(name,true); if (ret<0 || (!out && !created)) return ret<0?ret:-RELIEFOS_EINVAL; if (((mode&EXT2_S_IFMT)==EXT2_S_IFLNK)!=!!target || (target && !target[0])) return -RELIEFOS_EINVAL; @@ -524,7 +525,7 @@ static int ed_create(struct storage_volume *v,uint64_t parent,const char *name,u if (target && target_len<60) { in.size=target_len; storage_memcpy(in.i_block_raw,target,target_len); } if ((mode&EXT2_S_IFMT)==0020000 || (mode&EXT2_S_IFMT)==0060000) ext4_put_le32(in.i_block_raw+4,device); - ret=storage_ext4_write_inode(v,ino,&in); if (ret<0) goto done; + ret=storage_ext4_init_acl(v,parent,&par,ino,&in,umask); if (ret<0) goto done; if (dir) { uint64_t logical; uint8_t *buf=kernel_malloc(v->ext4.block_size); if (!buf) { ret=-RELIEFOS_ENOMEM; goto done; } ret=ed_append(v,ino,&in,&logical); @@ -553,7 +554,7 @@ static int ed_create(struct storage_volume *v,uint64_t parent,const char *name,u } int storage_ext4_create(struct storage_volume *v,uint64_t parent,const char *name,uint16_t mode, uint32_t uid,uint32_t gid,const char *target,uint64_t *out) -{return !out ? -RELIEFOS_EINVAL : ed_create(v,parent,name,mode,uid,gid,target,0,out,NULL);} +{return !out ? -RELIEFOS_EINVAL : ed_create(v,parent,name,mode,uid,gid,target,0,0,out,NULL);} /** @brief Return created inode identity from the same directory transaction. * @param v Borrowed selected filesystem under execution ownership. @@ -564,14 +565,16 @@ int storage_ext4_create(struct storage_volume *v,uint64_t parent,const char *nam * @param gid Final group ID. * @param target Borrowed symlink target, NULL for other types. * @param device Encoded Linux device number for character/block inodes. + * @param umask Mask applied when the parent has no default ACL. * @param out Required borrowed metadata result; no inode reference transferred. * @return Zero or negative errno. No metadata lookup/allocation follows a * successful directory transaction, so publication cannot be reported as * failure merely because a second metadata read runs out of memory. */ int storage_ext4_create_node(struct storage_volume *v,uint64_t parent,const char *name,uint16_t mode, - uint32_t uid,uint32_t gid,const char *target,uint32_t device,struct storage_node *out) -{return !out ? -RELIEFOS_EINVAL : ed_create(v,parent,name,mode,uid,gid,target,device,NULL,out);} + uint32_t uid,uint32_t gid,const char *target,uint32_t device, + uint32_t umask,struct storage_node *out) +{return !out ? -RELIEFOS_EINVAL : ed_create(v,parent,name,mode,uid,gid,target,device,umask,NULL,out);} int storage_ext4_link(struct storage_volume *v,uint64_t parent,const char *name,uint64_t ino) { struct storage_ext4_handle h; int ret=storage_ext4_journal_start(v,EXT4_JOURNAL_CREDITS,&h); if (ret<0) return ret; diff --git a/fs/ext_common/format.c b/fs/ext_common/format.c index e5c35b03..83b4cd8d 100644 --- a/fs/ext_common/format.c +++ b/fs/ext_common/format.c @@ -305,6 +305,9 @@ int storage_ext4_parse_inode(const uint8_t *raw, uint32_t raw_len, out->extra_isize = ext4_get_le16(raw + 128); if (out->extra_isize > raw_len - 128 || (out->extra_isize & 3)) return -RELIEFOS_EINVAL; + unsigned body = 128u + out->extra_isize; + out->inline_xattrs = body + 8 <= raw_len && + ext4_get_le32(raw + body) == EXT4_XATTR_MAGIC; } for (uint32_t i = 0; i < 60; ++i) out->i_block_raw[i] = raw[40 + i]; return 0; diff --git a/fs/ext_common/internal.h b/fs/ext_common/internal.h index 58d1af56..29a0e7d2 100644 --- a/fs/ext_common/internal.h +++ b/fs/ext_common/internal.h @@ -103,6 +103,24 @@ int storage_ext4_destroy_inode(struct storage_volume *, uint64_t); int storage_ext4_getxattr(struct storage_volume *,uint64_t,const char *,void *,uint32_t,uint32_t *); int storage_ext4_setxattr(struct storage_volume *,uint64_t,const char *,const void *,uint32_t,uint32_t); int storage_ext4_removexattr(struct storage_volume *,uint64_t,const char *); +/** @brief List exposed user and ACL names, or report their byte count. */ +int storage_ext4_listxattr(struct storage_volume *,uint64_t,void *,uint32_t,uint32_t *); +/** @brief Allocate the compact on-disk ACL for a known inode, or return ENODATA. */ +int storage_ext4_read_acl(struct storage_volume *,uint64_t,const struct ext4_inode_view *, + bool,void **,uint32_t *); +/** @brief Commit a compact ACL (or remove it) together with an optional new inode mode. */ +int storage_ext4_write_acl(struct storage_volume *,uint64_t,bool,const void *,uint32_t,const uint16_t *); +/** @brief Read a native ACL and export it in Linux's userspace xattr format. */ +int storage_ext4_get_acl(struct storage_volume *,uint64_t,const struct ext4_inode_view *, + bool,void *,uint32_t,uint32_t *); +/** @brief Validate and store a Linux ACL; update mode atomically for access ACLs. */ +int storage_ext4_set_acl(struct storage_volume *,uint64_t,const struct ext4_inode_view *, + bool,const void *,uint32_t,bool); +/** @brief Adjust an existing access ACL for chmod, or return ENODATA if absent. */ +int storage_ext4_chmod_acl(struct storage_volume *,uint64_t,const struct ext4_inode_view *,uint16_t); +/** @brief Store a new inode using a default ACL or umask in its creation transaction. */ +int storage_ext4_init_acl(struct storage_volume *,uint64_t,const struct ext4_inode_view *, + uint64_t,struct ext4_inode_view *,uint32_t); int storage_ext4_drop_xattrs(struct storage_volume *,uint64_t,struct ext4_inode_view *); int storage_ext4_recover_orphans(struct storage_volume *); int storage_ext4_fallocate(struct storage_volume *, uint64_t, uint32_t, uint64_t, uint64_t); @@ -187,7 +205,7 @@ int storage_ext4_dir_lookup_prepared(struct storage_volume *v,uint64_t ino,const int storage_ext4_dir_insert(struct storage_volume *,uint64_t,const char *,uint64_t,uint8_t); int storage_ext4_dir_remove(struct storage_volume *,uint64_t,const char *,uint64_t *); int storage_ext4_create(struct storage_volume *,uint64_t,const char *,uint16_t,uint32_t,uint32_t,const char *,uint64_t *); -int storage_ext4_create_node(struct storage_volume *,uint64_t,const char *,uint16_t,uint32_t,uint32_t,const char *,uint32_t,struct storage_node *); +int storage_ext4_create_node(struct storage_volume *,uint64_t,const char *,uint16_t,uint32_t,uint32_t,const char *,uint32_t,uint32_t,struct storage_node *); int storage_ext4_link(struct storage_volume *,uint64_t,const char *,uint64_t); int storage_ext4_unlink(struct storage_volume *,uint64_t,const char *,bool); int storage_ext4_rename(struct storage_volume *,uint64_t,const char *,uint64_t,const char *); diff --git a/fs/ext_common/native.c b/fs/ext_common/native.c index 7e75547b..28f04ef4 100644 --- a/fs/ext_common/native.c +++ b/fs/ext_common/native.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -144,9 +145,15 @@ static int ext_native_permissions(struct storage_volume *volume,const struct sto ret = storage_ext4_check_node(volume, node, &inode); if (ret < 0) return ret; if (write) { + uint16_t mode = (inode.mode & LINUX_S_IFMT) | (value->mode & 07777u); + if (((inode.mode ^ mode) & 0777u) && inode.uid == value->uid && inode.gid == value->gid && + (inode.inline_xattrs || inode.file_acl)) { + ret = storage_ext4_chmod_acl(volume,node->first_cluster,&inode,mode); + if (ret != -ENODATA) return ret; + } struct reliefos_time_info now; if (time_wall_clock(&now) == 0) inode.ctime = (uint32_t)now.unix_seconds; - inode.mode = (inode.mode & 0170000u) | (value->mode & 07777u); + inode.mode = mode; inode.uid = value->uid; inode.gid = value->gid; ret = ext_native_store_inode(volume, node->first_cluster, &inode); @@ -310,38 +317,95 @@ static int ext_native_truncate(struct storage_volume *volume,struct storage_node * @param volume Borrowed selected/pinned instance. @param parent Actual directory. * @param name Validated literal component. @param mode Authorized type/mode. * @param value Borrowed authorized ownership/mode. @param target Optional symlink target. + * @param umask Mask applied if the directory has no default ACL. * @param out Required created metadata output. * @return Zero or native validation/allocation/I/O errno. Execution/mutation * admission required; no callback lock. Core stores sidecar attributes and * acquires publication pins before the new VFS dentry becomes observable. */ static int ext_native_create(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, - const struct reliefos_permissions *value,const char *target,struct storage_node *out) + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out) { struct ext4_inode_view directory;int rc=storage_ext4_check_node(volume,parent,&directory); if(!rc && (directory.mode&LINUX_S_IFMT)!=LINUX_S_IFDIR)rc=-ENOTDIR; if(!rc && !directory.links_count)rc=-ENOENT; - if(!rc)rc=storage_ext4_create_node(volume,parent->first_cluster,name,(uint16_t)mode,value->uid,value->gid,target,0,out); + if(!rc)rc=storage_ext4_create_node(volume,parent->first_cluster,name,(uint16_t)mode,value->uid,value->gid, + target,0,umask,out); return rc; } /** @brief Create a device inode and store its rdev in the creation transaction. * @param volume Borrowed selected instance. @param parent Actual directory. * @param name Literal component. @param mode Authorized type and permissions. * @param value Authorized ownership. @param device Encoded Linux rdev. + * @param umask Mask applied if the directory has no default ACL. * @param out Required metadata result. * @return Zero or native errno. Execution/mutation admission is required; * device metadata is written before the directory transaction commits. */ static int ext_native_create_device(struct storage_volume *volume,const struct storage_node *parent,const char *name, - uint32_t mode,const struct reliefos_permissions *value,uint32_t device, + uint32_t mode,const struct reliefos_permissions *value,uint32_t device,uint32_t umask, struct storage_node *out) { struct ext4_inode_view directory;int rc=storage_ext4_check_node(volume,parent,&directory); if(!rc && (directory.mode&LINUX_S_IFMT)!=LINUX_S_IFDIR)rc=-ENOTDIR; if(!rc && !directory.links_count)rc=-ENOENT; - if(!rc)rc=storage_ext4_create_node(volume,parent->first_cluster,name,(uint16_t)mode,value->uid,value->gid,NULL,device,out); + if(!rc)rc=storage_ext4_create_node(volume,parent->first_cluster,name,(uint16_t)mode,value->uid,value->gid, + NULL,device,umask,out); return rc; } + +/** @brief Read an exposed extended attribute from the exact held ext inode. + * @param volume Selected volume. @param node Retained inode identity. + * @param name Linux attribute name. @param value Writable output if capacity is nonzero. + * @param capacity Output size or zero for a size query. @param length Result size. + * @return Zero or a negative provider error, including ERANGE for a short buffer. + */ +static int ext_native_getxattr(struct storage_volume *volume,const struct storage_node *node, + const char *name,void *value,uint32_t capacity,uint32_t *length) +{ + struct ext4_inode_view inode; + int rc=storage_ext4_check_node(volume,node,&inode); + if(rc)return rc; + if(posix_acl_name(name)) + return storage_ext4_get_acl(volume,node->first_cluster,&inode, + !__builtin_strcmp(name,POSIX_ACL_DEFAULT_NAME),value,capacity,length); + return storage_ext4_getxattr(volume,node->first_cluster,name,value,capacity,length); +} + +/** @brief List ext user and ACL attributes for the retained inode. + * @param volume Selected volume. @param node Retained inode identity. + * @param names Writable output if capacity is nonzero. + * @param capacity Output size or zero for a size query. @param length Result size. + * @param include_trusted Unused because this provider only exposes user and ACL names. + * @return Zero or negative errno. + */ +static int ext_native_listxattr(struct storage_volume *volume,const struct storage_node *node, + void *names,uint32_t capacity,uint32_t *length,bool include_trusted) +{ + (void)include_trusted; + struct ext4_inode_view inode; + int rc=storage_ext4_check_node(volume,node,&inode); + if(rc)return rc; + return storage_ext4_listxattr(volume,node->first_cluster,names,capacity,length); +} + +/** @brief Set or remove an authorized ACL on the exact held ext inode. + * @param volume Selected volume. @param node Retained inode identity. + * @param name Recognized Linux ACL xattr name. @param value Borrowed ACL bytes. + * @param length ACL byte count or zero to remove. + * @param clear_setgid Whether the caller lacks permission to retain setgid. + * @return Zero or negative errno; mode changes are part of the ACL transaction. + */ +static int ext_native_set_acl(struct storage_volume *volume,const struct storage_node *node, + const char *name,const void *value,uint32_t length,bool clear_setgid) +{ + struct ext4_inode_view inode; + int rc=storage_ext4_check_node(volume,node,&inode); + if(rc)return rc; + return storage_ext4_set_acl(volume,node->first_cluster,&inode, + !__builtin_strcmp(name,POSIX_ACL_DEFAULT_NAME),value,length,clear_setgid); +} /** @brief Remove the exact verified native member, retaining open inode backing. * @param volume Borrowed selected/pinned instance. @param parent Actual directory. * @param name Literal component. @param node Verified victim metadata. @@ -534,7 +598,10 @@ const struct storage_filesystem_ops storage_ext_ops={ .readdir=ext_native_readdir, .root=ext_native_root, .lookup=ext_native_lookup, - .readlink=ext_native_readlink + .readlink=ext_native_readlink, + .getxattr=ext_native_getxattr, + .listxattr=ext_native_listxattr, + .set_acl=ext_native_set_acl }; diff --git a/fs/ext_common/storage_ext4_types.h b/fs/ext_common/storage_ext4_types.h index 5159ca1b..301239e9 100644 --- a/fs/ext_common/storage_ext4_types.h +++ b/fs/ext_common/storage_ext4_types.h @@ -33,6 +33,7 @@ #define EXT4_SUPERBLOCK_OFFSET 1024u #define EXT4_SUPERBLOCK_SIZE 1024u +#define EXT4_XATTR_MAGIC 0xea020000u /* On-disk offset of s_checksum_seed (linux/fs/ext4/ext4.h:1369). Named * here so storage_ext4_parse_super and the host tests share one spelling; * keep the replacement list token-identical to the tests' local copy. */ @@ -203,6 +204,7 @@ struct ext4_inode_view { uint32_t uid, gid, flags, generation; uint32_t atime, ctime, mtime, dtime; uint16_t mode, links_count, extra_isize; + bool inline_xattrs; uint8_t i_block_raw[60]; }; struct storage_ext4_map_result { diff --git a/fs/ext_common/xattr.c b/fs/ext_common/xattr.c index 55d0bdf3..f36fd289 100644 --- a/fs/ext_common/xattr.c +++ b/fs/ext_common/xattr.c @@ -1,8 +1,14 @@ /* Inline and single-block ext4 extended attributes, including shared-block - * copy-on-write. Namespace authorization belongs to the VFS/LSM owner; this - * backend exposes user.* and preserves other on-disk namespaces unchanged. */ + * copy-on-write. The syscall layer authorizes user.* queries and ACL changes. */ #include "../../block/core/storage_internal.h" -#define AX_MAGIC 0xea020000u +#include +#include + +#define AX_USER 1u +#define AX_ACL_ACCESS 2u +#define AX_ACL_DEFAULT 3u +#define AX_REMOVE 4u +#define AX_REMOVE_IF_PRESENT 8u struct ax_item { const uint8_t *name,*value; uint32_t size; uint8_t index,len; }; struct ax_context { struct ext4_inode_view in; @@ -50,9 +56,20 @@ static int ax_parse(struct storage_volume *v,struct ax_context *c,const uint8_t } return 0; } -static int ax_load(struct storage_volume *v,uint64_t ino,struct ax_context *c) +/** @brief Load and parse the attributes of an inode under storage ownership. + * @param v Selected volume. @param ino Inode number. + * @param c Output context; always release with ax_free. + * @param inode Optional previously read inode view from the same transaction. + * @return Zero or negative metadata/I/O errno. + */ +static int ax_load(struct storage_volume *v,uint64_t ino,struct ax_context *c, + const struct ext4_inode_view *inode) { - *c=(struct ax_context){0}; int ret=storage_ext4_read_inode(v,ino,&c->in); if (ret<0) return ret; + *c=(struct ax_context){0}; + int ret=0; + if (inode) c->in=*inode; + else ret=storage_ext4_read_inode(v,ino,&c->in); + if (ret<0) return ret; unsigned size=v->ext4.inode_size,bs=v->ext4.block_size; c->capacity=(size+bs)/16+1; c->raw=kernel_malloc(size); c->external=kernel_malloc(bs); c->items=kernel_malloc(c->capacity*sizeof(*c->items)); @@ -69,13 +86,13 @@ static int ax_load(struct storage_volume *v,uint64_t ino,struct ax_context *c) storage_memcpy(c->raw+first,data,size-first); } c->body=128+c->in.extra_isize; - if (c->body+8<=size && ext4_get_le32(c->raw+c->body)==AX_MAGIC) { + if (c->in.inline_xattrs) { ret=ax_parse(v,c,c->raw,size,c->body+4,c->body+4); if (ret<0) return ret; } if (c->in.file_acl) { if (c->in.file_acl<=v->ext4.first_data_block || c->in.file_acl>=v->ext4.blocks_count) return ax_bad(v); ret=storage_ext4_cache_read_blocks(v,c->in.file_acl,1,c->external); if (ret<0) return ret; - if (ext4_get_le32(c->external)!=AX_MAGIC || !ext4_get_le32(c->external+4) || + if (ext4_get_le32(c->external)!=EXT4_XATTR_MAGIC || !ext4_get_le32(c->external+4) || ext4_get_le32(c->external+4)>1024 || ext4_get_le32(c->external+8)!=1) return ax_bad(v); if ((v->ext4.super_view.feature_ro_compat&EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) && ax_block_checksum(v,c->in.file_acl,c->external)!=ext4_get_le32(c->external+16)) return ax_bad(v); @@ -93,18 +110,19 @@ static int ax_name(const char *name,unsigned *len) } static bool ax_equal(const uint8_t *a,const uint8_t *b,unsigned n) { for (unsigned i=0;icount;i++) if (c->items[i].index==1 && c->items[i].len==len && - ax_equal(c->items[i].name,(const uint8_t *)name+5,len)) return (int)i; + for (unsigned i=0;icount;i++) if (c->items[i].index==index && c->items[i].len==len && + ax_equal(c->items[i].name,(const uint8_t *)name,len)) return (int)i; return -1; } int storage_ext4_getxattr(struct storage_volume *v,uint64_t ino,const char *name,void *value,uint32_t size,uint32_t *len) { unsigned n; int ret=ax_name(name,&n); if (ret<0 || !len) return ret<0?ret:-RELIEFOS_EINVAL; - *len=0; struct ax_context c; ret=ax_load(v,ino,&c); + *len=0; struct ax_context c; ret=ax_load(v,ino,&c,NULL); if (!ret) { - int i=ax_find(&c,name,n); + int i=ax_find(&c,AX_USER,name+5,n); if (i<0) ret=-61; else { *len=c.items[i].size; @@ -144,6 +162,7 @@ static int ax_write_inode(struct storage_volume *v,uint64_t ino,struct ax_contex { unsigned size=v->ext4.inode_size,bs=v->ext4.block_size,first=sizeoffset?size:bs-c->offset; uint64_t blocks=c->in.blocks; if (c->in.flags&EXT4_HUGE_FILE_FL) blocks/=bs/512; + ext4_put_le16(raw,c->in.mode); ext4_put_le32(raw+104,c->in.file_acl); ext4_put_le16(raw+118,c->in.file_acl>>32); ext4_put_le32(raw+28,blocks); ext4_put_le16(raw+116,blocks>>32); struct reliefos_time_info now; if (!time_wall_clock(&now)) ext4_put_le32(raw+12,now.unix_seconds); @@ -156,19 +175,30 @@ static int ax_write_inode(struct storage_volume *v,uint64_t ino,struct ax_contex } return ret; } -static int ax_set(struct storage_volume *v,uint64_t ino,const char *name,const void *value,uint32_t size,uint32_t flags) +/** @brief Change one xattr and optionally the inode mode in one transaction. + * @param v Selected volume. @param ino Inode number. + * @param item Borrowed namespace, short name and new value. + * @param flags Create/replace or internal remove action. + * @param mode Optional replacement inode type and mode. + * @return Zero or negative errno; failed journaled updates roll back together. + */ +static int ax_set(struct storage_volume *v,uint64_t ino,struct ax_item item,uint32_t flags, + const uint16_t *mode) { - unsigned n; int ret=ax_name(name,&n); if (ret<0) return ret; - if ((flags&~7u) || flags==3 || ((flags&4) && flags!=4) || (size && !value)) return -RELIEFOS_EINVAL; - if (size>v->ext4.block_size) return -RELIEFOS_ENOSPC; - struct storage_ext4_handle h; ret=storage_ext4_journal_start(v,EXT4_JOURNAL_CREDITS,&h); if (ret<0) return ret; - struct ax_context c; ret=ax_load(v,ino,&c); uint8_t *packed=NULL; + if (flags==3 || (item.size && !item.value)) return -RELIEFOS_EINVAL; + if (item.size>v->ext4.block_size) return -RELIEFOS_ENOSPC; + struct storage_ext4_handle h; + int ret=storage_ext4_journal_start(v,EXT4_JOURNAL_CREDITS,&h); if (ret<0) return ret; + struct ax_context c; ret=ax_load(v,ino,&c,NULL); uint8_t *packed=NULL; if (ret<0) goto done; - int found=ax_find(&c,name,n); + int found=ax_find(&c,item.index,(const char *)item.name,item.len); + bool remove=flags==AX_REMOVE || flags==AX_REMOVE_IF_PRESENT; if (found>=0 && flags==1) { ret=-17; goto done; } - if (found<0 && (flags==2 || flags==4)) { ret=-61; goto done; } + if (found<0 && (flags==2 || flags==AX_REMOVE)) { ret=-ENODATA; goto done; } + if (found<0 && remove && !mode) goto done; + if (mode) c.in.mode=*mode; if (found>=0) { for (unsigned i=found;i+1index) { + case AX_USER: prefix="user."; break; + case AX_ACL_ACCESS: prefix=POSIX_ACL_ACCESS_NAME; break; + case AX_ACL_DEFAULT: prefix=POSIX_ACL_DEFAULT_NAME; break; + default: continue; + } + size_t prefix_length=__builtin_strlen(prefix); + uint32_t bytes=(uint32_t)prefix_length+item->len+1; + if (capacity && bytes>capacity-*length) { rc=-ERANGE; break; } + if (capacity) { + char *name=(char *)names+*length; + storage_memcpy(name,prefix,prefix_length); + storage_memcpy(name+prefix_length,item->name,item->len); + name[bytes-1]=0; + } + *length+=bytes; + } + ax_free(&ctx); + return rc; +} + +/** @copydoc storage_ext4_read_acl */ +int storage_ext4_read_acl(struct storage_volume *v,uint64_t ino, + const struct ext4_inode_view *in,bool is_default, + void **value,uint32_t *length) +{ + *value=NULL; + *length=0; + if (!in->inline_xattrs && !in->file_acl) return -ENODATA; + struct ax_context ctx; + int rc=ax_load(v,ino,&ctx,in); + if (!rc) { + int index=ax_find(&ctx,is_default ? AX_ACL_DEFAULT : AX_ACL_ACCESS,"",0); + if (index<0) rc=-ENODATA; + else { + *length=ctx.items[index].size; + if (!*length) rc=-EIO; + else { + *value=kernel_malloc(*length); + if (!*value) rc=-ENOMEM; + else storage_memcpy(*value,ctx.items[index].value,*length); + } + } + } + ax_free(&ctx); + return rc; +} + +/** @copydoc storage_ext4_write_acl */ +int storage_ext4_write_acl(struct storage_volume *v,uint64_t ino,bool is_default, + const void *value,uint32_t length,const uint16_t *mode) +{ + struct ax_item item={.name=(const uint8_t *)"",.value=value,.size=length, + .index=is_default ? AX_ACL_DEFAULT : AX_ACL_ACCESS}; + return ax_set(v,ino,item,value ? 0 : AX_REMOVE_IF_PRESENT,mode); +} + int storage_ext4_drop_xattrs(struct storage_volume *v,uint64_t ino,struct ext4_inode_view *in) { if (!in->file_acl) return 0; - struct ax_context c; int ret=ax_load(v,ino,&c); + struct ax_context c; int ret=ax_load(v,ino,&c,in); if (!ret) { if (in->blocksext4.block_size/512) ret=ax_bad(v); else { diff --git a/fs/fat/native.c b/fs/fat/native.c index a1b92173..3233a77c 100644 --- a/fs/fat/native.c +++ b/fs/fat/native.c @@ -420,15 +420,17 @@ static const struct storage_cluster_ops fat_native_clusters={ * @param volume Borrowed selected/pinned instance. @param parent Actual directory. * @param name Validated literal component. @param mode Authorized type/mode. * @param value Borrowed authorized ownership/mode. @param target Optional symlink target. + * @param umask Mask already applied by the storage backend. * @param out Required created metadata output. * @return Zero or native validation/allocation/I/O errno. Execution/mutation * admission required; no callback lock. Core stores sidecar attributes and * acquires publication pins before the new VFS dentry becomes observable. */ static int fat_native_create(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, - const struct reliefos_permissions *value,const char *target,struct storage_node *out) + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out) { - (void)value;(void)target; + (void)value;(void)target;(void)umask; if(parent->type!=RELIEFOS_FS_TYPE_DIR)return -ENOTDIR; if((mode&LINUX_S_IFMT)==LINUX_S_IFREG) { int rc=fat_native_lookup(volume,parent,name,out); diff --git a/fs/operations.h b/fs/operations.h index eb243291..9c47ef90 100644 --- a/fs/operations.h +++ b/fs/operations.h @@ -64,10 +64,12 @@ struct storage_filesystem_ops { const void *bytes,uint32_t length,uint32_t *written); int (*truncate)(struct storage_volume *volume,struct storage_node *node,uint64_t length); int (*create)(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, - const struct reliefos_permissions *value,const char *target,struct storage_node *out); + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out); /* Device creation follows create's atomic-publication contract. */ int (*create_device)(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, - const struct reliefos_permissions *value,uint32_t device,struct storage_node *out); + const struct reliefos_permissions *value,uint32_t device,uint32_t umask, + struct storage_node *out); int (*remove)(struct storage_volume *volume,const struct storage_node *parent,const char *name, const struct storage_node *node,bool directory); int (*rename)(struct storage_volume *volume,const struct storage_rename_args *args); @@ -96,6 +98,8 @@ struct storage_filesystem_ops { const char *name,void *value,uint32_t capacity,uint32_t *length); int (*listxattr)(struct storage_volume *volume,const struct storage_node *node, void *names,uint32_t capacity,uint32_t *length,bool include_trusted); + int (*set_acl)(struct storage_volume *volume,const struct storage_node *node,const char *name, + const void *value,uint32_t length,bool clear_setgid); int (*readdir_name)(struct storage_volume *volume,const struct storage_node *node, uint64_t *cursor,char *name,size_t capacity,uint64_t mount_flags); }; diff --git a/fs/security/access.c b/fs/security/access.c index a7a2cf84..0857c24e 100644 --- a/fs/security/access.c +++ b/fs/security/access.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -131,7 +132,8 @@ static int device_metadata(const struct storage_node *node, } if (!write) { uint32_t mode = node->type == RELIEFOS_FS_TYPE_DIR ? 0755 : 0666; - if (node->flags & STORAGE_NODE_FLAG_DEV_BLOCK) mode = 0600; + if ((node->flags & STORAGE_NODE_FLAG_DEV_BLOCK) || + node->first_cluster == STORAGE_DEV_KIND_KMSG) mode = 0600; uint32_t gid = 0; if (node->first_cluster == STORAGE_DEV_KIND_DRM_CARD0) { mode = 0660; @@ -197,20 +199,80 @@ struct fs_access_cred fs_access_credentials(const struct task *task,bool real_id .caps=real_ids ? ((task->user_ns || task->uid) ? 0 : task->cap_permitted) : task_initial_capabilities(task)}; } +/** @brief Check DAC override capabilities after ordinary permission denial. */ +static bool fs_permissions_override(const struct fs_access_cred *cred,bool directory, + uint32_t mode,uint32_t access) +{ + if ((cred->caps & (1ULL << CAP_DAC_OVERRIDE)) && + (!(access & FS_ACCESS_EXEC) || directory || (mode & 0111u))) return true; + return (cred->caps & (1ULL << CAP_DAC_READ_SEARCH)) && + (directory ? !(access & FS_ACCESS_WRITE) : access == FS_ACCESS_READ); +} + /** @copydoc fs_permissions_check_mode */ int fs_permissions_check_mode(const struct fs_access_cred *cred,bool directory, const struct reliefos_permissions *value,uint32_t access) { uint32_t shift=cred->uid==value->uid ? 6 : cred->gid==value->gid || group_list_contains(cred->groups,value->gid) ? 3 : 0; - if (((value->mode >> shift) & access) == access) return 0; - if ((cred->caps & (1ULL << CAP_DAC_OVERRIDE)) && - (!(access & FS_ACCESS_EXEC) || directory || (value->mode & 0111u))) return 0; - if ((cred->caps & (1ULL << CAP_DAC_READ_SEARCH)) && - (directory ? !(access & FS_ACCESS_WRITE) : access == FS_ACCESS_READ)) return 0; + if (((value->mode >> shift) & access) == access || + fs_permissions_override(cred,directory,value->mode,access)) return 0; return -RELIEFOS_EACCES; } +/** @brief Enforce an access ACL for a caller outside the owning-user class. + * @param acl Validated provider ACL. @param length Size of the xattr. + * @param cred Stable effective or real DAC credentials. + * @param value Inode ownership and mode. @param access Requested rwx bits. + * @return Zero on grant; EACCES on denial. + */ +static int fs_acl_permission(const struct posix_acl_xattr *acl,uint32_t length, + const struct fs_access_cred *cred,const struct reliefos_permissions *value, + uint32_t access) +{ + uint32_t count=(length-sizeof(*acl))/sizeof(acl->entries[0]); + unsigned mask=(value->mode>>3)&7u; + bool group_found=false; + for(uint32_t i=1;ientries[i]; + if(entry->tag==ACL_USER && entry->id==cred->uid) + return ((entry->perm&mask)&access)==access ? 0 : -RELIEFOS_EACCES; + if(entry->tag==ACL_GROUP_OBJ || entry->tag==ACL_GROUP) { + uint32_t group=entry->tag==ACL_GROUP_OBJ ? value->gid : entry->id; + if(group==cred->gid || group_list_contains(cred->groups,group)) { + group_found=true; + if(((entry->perm&mask)&access)==access)return 0; + } + } + if(entry->tag==ACL_OTHER) + return !group_found && (entry->perm&access)==access ? 0 : -RELIEFOS_EACCES; + } + return -RELIEFOS_EIO; +} + +/** @brief Read and check the native access ACL when it can affect DAC. + * @return Zero or negative errno. ENODATA means to use ordinary mode bits. + */ +static int fs_check_access_acl(const struct vfs_path *path,const struct fs_access_cred *cred, + const struct reliefos_permissions *value,uint32_t access) +{ + uint32_t small[33],length=0; + void *acl=small; + int rc=vfs_path_getxattr(path,POSIX_ACL_ACCESS_NAME,acl,sizeof(small),&length); + if(rc==-LINUX_ERANGE && length>sizeof(small)) { + acl=kernel_malloc(length); + if(!acl)return -RELIEFOS_ENOMEM; + rc=vfs_path_getxattr(path,POSIX_ACL_ACCESS_NAME,acl,length,&length); + } + if(!rc) { + if(lengthtype==RELIEFOS_FS_TYPE_DIR,&value,access); + bool directory=node->type==RELIEFOS_FS_TYPE_DIR; + if(access && cred.uid!=value.uid && (value.mode&0070u) && + (node->flags&STORAGE_NODE_FLAG_EXT_FAMILY) && node->type!=RELIEFOS_FS_TYPE_SYMLINK) { + ret=fs_check_access_acl(path,&cred,&value,access); + if(ret==-RELIEFOS_EACCES && fs_permissions_override(&cred,directory,value.mode,access))return 0; + if(ret!=-LINUX_ENODATA && ret!=-RELIEFOS_EOPNOTSUPP)return ret; + } + return fs_permissions_check_mode(&cred,directory,&value,access); } /** @brief Apply the common chmod policy without performing metadata I/O. diff --git a/fs/tmpfs/native.c b/fs/tmpfs/native.c index bc5a6dc7..c6317517 100644 --- a/fs/tmpfs/native.c +++ b/fs/tmpfs/native.c @@ -150,28 +150,33 @@ static int tmpfs_native_truncate(struct storage_volume *volume,struct storage_no * @param volume Borrowed selected/pinned instance. @param parent Actual directory. * @param name Validated literal component. @param mode Authorized type/mode. * @param value Borrowed authorized ownership/mode. @param target Optional symlink target. + * @param umask Mask already applied by the storage backend. * @param out Required created metadata output. * @return Zero or native validation/allocation/I/O errno. Execution/mutation * admission required; no callback lock. Core stores sidecar attributes and * acquires publication pins before the new VFS dentry becomes observable. */ static int tmpfs_native_create(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, - const struct reliefos_permissions *value,const char *target,struct storage_node *out) + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out) { + (void)umask; return tmpfs_create_child(volume->tmpfs,parent->first_cluster,name,mode,target,value,out); } /** @brief Create a tmpfs character or block inode with its final device number. * @param volume Borrowed selected instance. @param parent Actual directory. * @param name Literal component. @param mode Authorized type and permissions. * @param value Authorized ownership. @param device Encoded Linux rdev. + * @param umask Mask already applied by the storage backend. * @param out Required metadata result. * @return Zero or native errno. Execution and mutation admission are required; * failed creation publishes no inode. */ static int tmpfs_native_create_device(struct storage_volume *volume,const struct storage_node *parent,const char *name, - uint32_t mode,const struct reliefos_permissions *value,uint32_t device, + uint32_t mode,const struct reliefos_permissions *value,uint32_t device,uint32_t umask, struct storage_node *out) { + (void)umask; return tmpfs_mknod_child(volume->tmpfs,parent->first_cluster,name,mode,device,value,out); } /** @brief Remove the exact verified native member, retaining open inode backing. diff --git a/fs/vfs/attributes.c b/fs/vfs/attributes.c index 29b9484f..71a28e54 100644 --- a/fs/vfs/attributes.c +++ b/fs/vfs/attributes.c @@ -10,6 +10,16 @@ int vfs_path_access(const struct vfs_path *path,const struct task *task,uint32_t return ops->access ? ops->access(path->mount->context, path, task, access) : -EOPNOTSUPP; } +/** @copydoc vfs_path_getxattr */ +int vfs_path_getxattr(const struct vfs_path *path,const char *name,void *value, + uint32_t capacity,uint32_t *length) +{ + if (!vfs_path_valid(path) || !name || !length || (capacity && !value)) return -EINVAL; + const struct vfs_mount *mount=path->mount; + if (!mount->ops->getxattr) return -EOPNOTSUPP; + return mount->ops->getxattr(mount->context,&path->dentry->node,name,value,capacity,length); +} + int vfs_stat_basic(const struct storage_node *node,struct linux_stat_abi *out) { if(node->size>INT64_MAX)return -EOVERFLOW; diff --git a/fs/vfs/file.c b/fs/vfs/file.c index 099d36b0..e4b8f699 100644 --- a/fs/vfs/file.c +++ b/fs/vfs/file.c @@ -248,13 +248,14 @@ int vfs_path_new_file(const struct vfs_path *parent,const char *name, * @param type Linux inode type. @param value Final ownership and permissions. * @param target Symlink target, otherwise NULL. @param device Encoded rdev. * @param create_device Select device creation and validate its inode type. + * @param umask Mask applied when there is no inherited ACL. * @param out Optional retained created path. * @return Zero or negative errno. Reserve publication state before mutation; * failures leave no dentry and provider pin failures roll back the inode. */ static int vfs_create_member(const struct vfs_path *parent,const char *name,uint32_t type, const struct reliefos_permissions *value,const char *target, - uint32_t device,bool create_device,struct vfs_path *out) + uint32_t device,bool create_device,uint32_t umask,struct vfs_path *out) { if(out)*out=(struct vfs_path){0}; if(!vfs_path_valid(parent) || !name || !name[0] || !value || @@ -286,8 +287,8 @@ static int vfs_create_member(const struct vfs_path *parent,const char *name,uint } struct storage_node node;void *pin=NULL; int rc=special ? parent->mount->ops->create_device(parent->mount->context,&parent->dentry->node, - name,type,value,device,&node,reserved ? &pin : NULL) : - parent->mount->ops->create_node(parent->mount->context,&parent->dentry->node,name,type,value,target,&node, + name,type,value,device,umask,&node,reserved ? &pin : NULL) : + parent->mount->ops->create_node(parent->mount->context,&parent->dentry->node,name,type,value,target,umask,&node, reserved ? &pin : NULL); if(rc) { if(reserved){kernel_free(reserved->name);kernel_free(reserved);} @@ -311,7 +312,7 @@ static int vfs_create_member(const struct vfs_path *parent,const char *name,uint int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t type, const struct reliefos_permissions *value,const char *target,struct vfs_path *out) { - return vfs_create_member(parent,name,type,value,target,0,false,out); + return vfs_create_member(parent,name,type,value,target,0,false,0,out); } /** @brief Create a character or block member through the retained parent. @@ -323,5 +324,14 @@ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t int vfs_path_create_device(const struct vfs_path *parent,const char *name,uint32_t type, const struct reliefos_permissions *value,uint32_t device,struct vfs_path *out) { - return vfs_create_member(parent,name,type,value,NULL,device,true,out); + return vfs_create_member(parent,name,type,value,NULL,device,true,0,out); +} + +/** @copydoc vfs_path_create_masked */ +int vfs_path_create_masked(const struct vfs_path *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,const char *target, + uint32_t device,uint32_t umask,struct vfs_path *out) +{ + bool special=type==LINUX_S_IFCHR || type==LINUX_S_IFBLK; + return vfs_create_member(parent,name,type,value,target,device,special,umask&0777u,out); } diff --git a/fs/vfs/storage_backend.c b/fs/vfs/storage_backend.c index ee54b575..81c19089 100644 --- a/fs/vfs/storage_backend.c +++ b/fs/vfs/storage_backend.c @@ -281,6 +281,26 @@ static int storage_vfs_listxattr(void *context,const struct storage_node *node,v return rc; } +/** @brief Apply an authorized ACL through the held native provider. + * @param context Pinned volume. @param node Retained inode. + * @param name Linux ACL attribute. @param value Borrowed ACL bytes or NULL. + * @param length Byte count, with zero indicating removal. + * @param clear_setgid Whether to clear setgid with a new access ACL. + * @return Zero or negative selection/provider errno. + */ +static int storage_vfs_set_acl(void *context,const struct storage_node *node,const char *name, + const void *value,uint32_t length,bool clear_setgid) +{ + struct storage_volume *volume=context,*previous=NULL; + if(node->volume_id!=volume->volume_id)return -EINVAL; + int rc=storage_select_node_volume(node,&previous); + if(rc)return rc; + const struct storage_filesystem_ops *ops=volume->fs_ops; + rc=ops && ops->set_acl ? ops->set_acl(volume,node,name,value,length,clear_setgid) : -EOPNOTSUPP; + storage_restore_volume(previous); + return rc; +} + static const struct vfs_backend_ops storage_vfs_ops={ .lookup_generation=storage_vfs_lookup_generation, .lookup=storage_backend_lookup_vfs,.retain=storage_vfs_retain,.release=storage_vfs_release, @@ -290,7 +310,7 @@ static const struct vfs_backend_ops storage_vfs_ops={ .read=storage_vfs_read,.read_cursor=storage_vfs_read_cursor,.readdir=storage_vfs_readdir,.permissions=storage_backend_permissions, .mount_flags=storage_vfs_flags,.create_node=storage_backend_create_node,.create_device=storage_backend_create_device, .getattr=storage_backend_getattr,.statfs=storage_backend_statfs, - .getxattr=storage_vfs_getxattr,.listxattr=storage_vfs_listxattr, + .getxattr=storage_vfs_getxattr,.listxattr=storage_vfs_listxattr,.set_acl=storage_vfs_set_acl, .readdir_name=storage_vfs_readdir_name, .write=storage_backend_write,.truncate=storage_backend_truncate,.utimens=storage_backend_utimens, .fallocate=storage_backend_fallocate,.sync=storage_backend_sync, diff --git a/fs/vfs/storage_backend.h b/fs/vfs/storage_backend.h index efe2ac07..7727a34b 100644 --- a/fs/vfs/storage_backend.h +++ b/fs/vfs/storage_backend.h @@ -71,23 +71,27 @@ int storage_backend_store_child(struct storage_volume *volume,const struct stora * @param context Borrowed pinned instance. @param parent Actual directory. * @param name Validated component. @param type Authorized Linux inode type. * @param value Borrowed authorized ownership/mode. @param target Optional symlink target. + * @param umask Creation mask when no default ACL applies. * @param out Required node output. @param pin Optional owned inode-pin output. * @return Zero or input/readonly/native/metadata errno. Execution ownership * required; creation, sidecar and publication-pin failures roll back before * exposing a dentry; no graph/module lock spans provider I/O. */ int storage_backend_create_node(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,const char *target,struct storage_node *out,void **pin); + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out,void **pin); /** @brief Create an authorized device inode with the normal publication rollback. * @param context Borrowed native instance. @param parent Actual directory. * @param name Validated component. @param type S_IFCHR or S_IFBLK. * @param value Final owner/mode. @param device Encoded Linux rdev. + * @param umask Creation mask when no default ACL applies. * @param out Required created node. @param pin Optional owned inode pin. * @return Zero or negative errno. Execution ownership is required, and no * graph lock spans provider I/O. Failure rolls back an unpublished member. */ int storage_backend_create_device(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,uint32_t device,struct storage_node *out,void **pin); + const struct reliefos_permissions *value,uint32_t device,uint32_t umask, + struct storage_node *out,void **pin); /** * @brief Best-effort native disk access-time update for this exact attachment. * @param context Borrowed live native storage instance pinned by its mount. diff --git a/fs/vfs/storage_create.c b/fs/vfs/storage_create.c index 148f5a75..0d689b6e 100644 --- a/fs/vfs/storage_create.c +++ b/fs/vfs/storage_create.c @@ -52,13 +52,14 @@ int storage_cluster_drop_new(struct storage_volume *volume,const struct storage_ * @param name Validated literal component. @param type Authorized Linux inode type. * @param value Borrowed authorized ownership/mode. @param target Optional symlink target. * @param device Encoded device number for a character or block inode. + * @param umask Creation mask for files without an inherited ACL. * @param out Required native node output. @param pin Optional owned inode-pin output. * @return Zero or input/readonly/provider/metadata errno. Execution ownership * required. Provider creation, sidecar persistence and final publication pins * roll back before exposing a VFS dentry; no graph/module lock spans native I/O. */ static int storage_backend_create_member(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,const char *target,uint32_t device, + const struct reliefos_permissions *value,const char *target,uint32_t device,uint32_t umask, struct storage_node *out,void **pin) { if(pin)*pin=NULL; @@ -69,14 +70,17 @@ static int storage_backend_create_member(void *context,const struct storage_node bool special=type==LINUX_S_IFCHR || type==LINUX_S_IFBLK; if(!ops || (special ? !ops->create_device : !ops->create))return -EOPNOTSUPP; bool sidecar=ops->flags&STORAGE_FS_SIDECAR; + struct reliefos_permissions metadata=*value; + if(!ops->set_acl && type!=LINUX_S_IFLNK)metadata.mode&=~umask; + value=&metadata; if(sidecar && type!=LINUX_S_IFREG && type!=LINUX_S_IFDIR)return -EOPNOTSUPP; if(sidecar && storage_text_eq_ci(name,"LEONACL.SYS"))return -EPERM; struct storage_node directory=*parent;int rc=storage_inode_refresh(&directory);if(rc)return rc; parent=&directory; struct storage_volume *previous=NULL;rc=storage_select_node_volume(parent,&previous);if(rc)return rc; storage_begin_mutation(); - rc=special ? ops->create_device(volume,parent,name,type|(value->mode&07777),value,device,out) : - ops->create(volume,parent,name,type|(value->mode&07777),value,target,out); + rc=special ? ops->create_device(volume,parent,name,type|(value->mode&07777),value,device,umask,out) : + ops->create(volume,parent,name,type|(value->mode&07777),value,target,umask,out); if(!rc && sidecar) { struct storage_inode_ref *metadata_pin=NULL;rc=storage_inode_get(out,&metadata_pin); if(!rc)rc=storage_backend_store_child(volume,parent,name,value); @@ -100,24 +104,28 @@ static int storage_backend_create_member(void *context,const struct storage_node * @param context Borrowed native instance. @param parent Actual directory. * @param name Literal component. @param type Linux inode type. * @param value Final permissions. @param target Symlink target, otherwise NULL. + * @param umask Creation mask for files without an inherited ACL. * @param out Required node output. @param pin Optional owned inode pin. * @return Zero or negative errno. Failed publication rolls back the member. */ int storage_backend_create_node(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,const char *target,struct storage_node *out,void **pin) + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out,void **pin) { - return storage_backend_create_member(context,parent,name,type,value,target,0,out,pin); + return storage_backend_create_member(context,parent,name,type,value,target,0,umask,out,pin); } /** @brief Create a device native member with publication rollback. * @param context Borrowed native instance. @param parent Actual directory. * @param name Literal component. @param type Linux device inode type. * @param value Final permissions. @param device Encoded Linux rdev. + * @param umask Creation mask for files without an inherited ACL. * @param out Required node output. @param pin Optional owned inode pin. * @return Zero or negative errno. Failed publication rolls back the member. */ int storage_backend_create_device(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,uint32_t device,struct storage_node *out,void **pin) + const struct reliefos_permissions *value,uint32_t device,uint32_t umask, + struct storage_node *out,void **pin) { - return storage_backend_create_member(context,parent,name,type,value,NULL,device,out,pin); + return storage_backend_create_member(context,parent,name,type,value,NULL,device,umask,out,pin); } diff --git a/fs/vfs/xattr.c b/fs/vfs/xattr.c index 5d3a2c6a..216ce900 100644 --- a/fs/vfs/xattr.c +++ b/fs/vfs/xattr.c @@ -1,14 +1,6 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "mount_internal.h" - -int vfs_path_getxattr(const struct vfs_path *path,const char *name,void *value, - uint32_t capacity,uint32_t *length) -{ - if (!vfs_path_valid(path) || !name || !length || (capacity && !value)) return -EINVAL; - const struct vfs_mount *mount=path->mount; - if (!mount->ops->getxattr) return -EOPNOTSUPP; - return mount->ops->getxattr(mount->context,&path->dentry->node,name,value,capacity,length); -} +#include int vfs_path_listxattr(const struct vfs_path *path,void *names,uint32_t capacity, uint32_t *length,bool include_trusted) @@ -18,3 +10,16 @@ int vfs_path_listxattr(const struct vfs_path *path,void *names,uint32_t capacity if (!mount->ops->listxattr) return -EOPNOTSUPP; return mount->ops->listxattr(mount->context,&path->dentry->node,names,capacity,length,include_trusted); } + +/** @copydoc vfs_path_set_acl */ +int vfs_path_set_acl(const struct vfs_path *path,const char *name,const void *value, + uint32_t length,bool clear_setgid) +{ + if (!vfs_path_valid(path) || !name || (length && !value)) return -EINVAL; + if (vfs_path_mount_flags(path)&MS_RDONLY) return -EROFS; + const struct vfs_mount *mount=path->mount; + if (!mount->ops->set_acl) return -EOPNOTSUPP; + int rc=mount->ops->set_acl(mount->context,&path->dentry->node,name,value,length,clear_setgid); + if (!rc && vfs_notify_event) vfs_notify_event(path,IN_ATTRIB); + return rc; +} diff --git a/include/reliefnt/console.h b/include/reliefnt/console.h index aefc63cb..cbaf536c 100644 --- a/include/reliefnt/console.h +++ b/include/reliefnt/console.h @@ -13,7 +13,7 @@ */ void console_init(void); /** - * @brief Append length-delimited input as INFO records in the kernel log. + * @brief Mirror length-delimited diagnostic input to the console sinks. * @param s Bytes to write; need not be NUL-terminated. * @param len Number of bytes to write. */ @@ -83,7 +83,7 @@ void console_printf(const char *fmt, ...); void console_log_configure(const char *cmdline); /** @brief Check the immutable boot logging policy without taking a lock. * @param level Severity of the proposed record. - * @return True when the record should be formatted. + * @return True when the severity is enabled for console presentation. */ bool console_log_enabled(enum console_log_level level); /** @brief Format and publish bounded kernel records to enabled sinks. diff --git a/include/reliefnt/kmsg.h b/include/reliefnt/kmsg.h new file mode 100644 index 00000000..a966603a --- /dev/null +++ b/include/reliefnt/kmsg.h @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_KMSG_H +#define RELIEFNT_KMSG_H + +#include + +#define KMSG_MESSAGE_MAX 1024u + +/** @brief Append one complete kernel or userspace record to the shared log. + * @param priority Syslog facility and priority byte. + * @param timestamp Monotonic microseconds since boot. + * @param text Borrowed kernel buffer. + * @param length Message length, excluding the record terminator. + * IRQ safe. Readers are notified from the timer so this path can run with + * scheduler and driver locks held. + */ +void kmsg_append(unsigned priority, uint64_t timestamp, const char *text, size_t length); + +/** @brief Snapshot the head of the log. + * @return Sequence of the oldest retained record, or the tail if empty. + */ +uint64_t kmsg_first_sequence(void); + +/** @brief Snapshot the tail of the log. + * @return Sequence where the next record will be appended. + */ +uint64_t kmsg_next_sequence(void); + +/** @brief Snapshot Linux poll bits for a reader sequence. + * @param sequence Next sequence belonging to the open file description. + * @return Readable when a record is available, with error/priority on overrun. + */ +short kmsg_readiness(uint64_t sequence); + +/** @brief Read and advance one shared open-file log cursor. + * @param sequence In/out next sequence, serialized by the caller. + * @param buffer Validated writable buffer, accessed outside the ring lock. + * @param capacity Available bytes. + * @return Complete ABI record length, EAGAIN when empty, EPIPE on overrun, + * or EINVAL if the consumed record exceeds the supplied capacity. + */ +int kmsg_read_record(uint64_t *sequence, char *buffer, size_t capacity); + +/** @brief Mirror a write from a validated user buffer into the log. + * @param buffer Validated readable source. + * @param length Original byte count. + * @return Accepted count or EINVAL for a message exceeding the device limit. + */ +int kmsg_write_record(const char *buffer, size_t length); + +/** @brief Publish any accumulated log readiness changes from the boot CPU timer. */ +void kmsg_notify_readers(void); + +#endif diff --git a/include/reliefnt/mount.h b/include/reliefnt/mount.h index 0453fa61..86f449cf 100644 --- a/include/reliefnt/mount.h +++ b/include/reliefnt/mount.h @@ -171,15 +171,18 @@ struct vfs_backend_ops { /* Pure shared-state query. Initial creation also snapshots legacy/default * attachment bits once; later policy queries use only shared flags. */ uint64_t (*mount_flags)(void *context); - /* Create one member with final type/metadata before returning. Optional + /* Create one member with final type/metadata before returning. Apply + * the supplied umask unless inheriting an ACL (symlinks keep 0777). Optional * pin receives one owned native retain, or the new member is rolled back * on failure. No namespace routing or EAGAIN after mutation commits. */ int (*create_node)(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,const char *target,struct storage_node *out,void **pin); + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out,void **pin); /* Create a character/block inode with its independent Linux device number. * The same publication and rollback contract as create_node applies. */ int (*create_device)(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,uint32_t device,struct storage_node *out,void **pin); + const struct reliefos_permissions *value,uint32_t device,uint32_t umask, + struct storage_node *out,void **pin); int (*getattr)(void *context,const struct vfs_path *path,struct linux_stat_abi *out); int (*statfs)(void *context,const struct storage_node *node,struct linux_statfs_abi *out); int (*write)(void *context,struct storage_node *node,uint64_t offset, @@ -208,6 +211,8 @@ struct vfs_backend_ops { void *value,uint32_t capacity,uint32_t *length); int (*listxattr)(void *context,const struct storage_node *node,void *names, uint32_t capacity,uint32_t *length,bool include_trusted); + int (*set_acl)(void *context,const struct storage_node *node,const char *name, + const void *value,uint32_t length,bool clear_setgid); /* Linux getdents accepts up to NAME_MAX bytes regardless of the legacy ABI. */ int (*readdir_name)(void *context,const struct storage_node *node,uint64_t *cursor, char *name,size_t capacity,uint64_t mount_flags); @@ -934,6 +939,15 @@ int vfs_path_getxattr(const struct vfs_path *path,const char *name,void *value, */ int vfs_path_listxattr(const struct vfs_path *path,void *names,uint32_t capacity, uint32_t *length,bool include_trusted); +/** @brief Set a Linux ACL using authorized, namespace-translated xattr bytes. + * @param path Held actual inode. @param name Borrowed Linux ACL attribute. + * @param value Borrowed ACL bytes, optional when removing. + * @param length ACL length, zero for removal. + * @param clear_setgid Clear setgid when setting a new access ACL. + * @return Zero or negative errno. Readonly mounts reject changes. + */ +int vfs_path_set_acl(const struct vfs_path *path,const char *name,const void *value, + uint32_t length,bool clear_setgid); /** @brief Query or update metadata through an owned filesystem object. * @param path Borrowed retained path; its provider stays pinned. * @param value Writable result or borrowed new mode/uid/gid. @@ -998,6 +1012,17 @@ int vfs_path_create_node(const struct vfs_path *parent,const char *name,uint32_t */ int vfs_path_create_device(const struct vfs_path *parent,const char *name,uint32_t type, const struct reliefos_permissions *value,uint32_t device,struct vfs_path *out); +/** @brief Create an authorized member with its umask and parent ACL policy. + * @param parent Held actual directory. @param name Literal child component. + * @param type Linux inode type. @param value Requested mode and authorized IDs. + * @param target Symlink target or NULL. @param device Encoded rdev for device types. + * @param umask Mask for backends or parents without ACL inheritance. + * @param out Optional retained created path. + * @return Zero on publication or negative errno on failure. + */ +int vfs_path_create_masked(const struct vfs_path *parent,const char *name,uint32_t type, + const struct reliefos_permissions *value,const char *target, + uint32_t device,uint32_t umask,struct vfs_path *out); /** @brief Unlink/rmdir the exact retained directory member. * @param ns Borrowed shared namespace under execution ownership. * @param path Borrowed victim path retaining its parent, inode and provider. diff --git a/include/reliefnt/posix_acl.h b/include/reliefnt/posix_acl.h new file mode 100644 index 00000000..69e410b4 --- /dev/null +++ b/include/reliefnt/posix_acl.h @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef RELIEFNT_POSIX_ACL_H +#define RELIEFNT_POSIX_ACL_H + +#include + +#define POSIX_ACL_ACCESS_NAME "system.posix_acl_access" +#define POSIX_ACL_DEFAULT_NAME "system.posix_acl_default" +#define POSIX_ACL_XATTR_VERSION 2u + +/* Linux's little-endian xattr ABI, native on ReliefNT's x86-64 targets. */ +enum posix_acl_tag { + ACL_USER_OBJ = 1, ACL_USER = 2, ACL_GROUP_OBJ = 4, ACL_GROUP = 8, + ACL_MASK = 16, ACL_OTHER = 32 +}; + +struct posix_acl_entry { + uint16_t tag, perm; + uint32_t id; +}; + +struct posix_acl_xattr { + uint32_t version; + struct posix_acl_entry entries[]; +}; + +/** @brief Recognize the two Linux POSIX ACL extended attributes. */ +static inline bool posix_acl_name(const char *name) +{ + return !__builtin_strcmp(name, POSIX_ACL_ACCESS_NAME) || + !__builtin_strcmp(name, POSIX_ACL_DEFAULT_NAME); +} + +/** @brief Return whether the entry requires a UID or GID qualifier. */ +static inline bool posix_acl_named(uint16_t tag) +{ + return tag == ACL_USER || tag == ACL_GROUP; +} + +#endif diff --git a/include/reliefnt/sched.h b/include/reliefnt/sched.h index cfc119bc..9e9e4fab 100644 --- a/include/reliefnt/sched.h +++ b/include/reliefnt/sched.h @@ -461,6 +461,14 @@ int sched_signal_action(uint32_t pid, int signal_number, uint32_t operation, */ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, int signal_number); +/** + * @brief Broadcast a kill(2) signal to eligible user processes once per group. + * @param sender Calling task retained under execution ownership. + * @param signal_number Valid Linux signal number or zero for a probe. + * @return Linux kill(-1) result, including ESRCH when there are no candidates. + * The sender's thread group and PID 1 are excluded; per-target DAC still applies. + */ +int sched_signal_broadcast(struct task *sender, int signal_number); /* Terminal-generated signals originate in the kernel, independent of UID. */ int sched_signal_kernel_group(uint32_t process_group, int signal_number); int64_t sched_process_group_session(uint32_t process_group); diff --git a/kernel/sched/signal.c b/kernel/sched/signal.c index ff415183..86d502cd 100644 --- a/kernel/sched/signal.c +++ b/kernel/sched/signal.c @@ -315,6 +315,40 @@ int sched_signal_kernel_group(uint32_t process_group, int signal_number) return count ? count : -LINUX_ESRCH; } +/** @brief Send SI_USER siginfo to an eligible process using the sender's real UID. + * @param sender Borrowed caller with stable execution ownership. + * @param target Borrowed process leader whose namespace governs permission. + * @param signum Valid Linux signal number or zero. + * @return Zero on acceptance, EPERM for denied sends, or the queue error. + */ +static int signal_user_from(struct task *sender, struct task *target, int signum) +{ + if (!kernel_signal_may_send(sender, target, signum)) return -LINUX_EPERM; + struct linux_siginfo info = {.signo = signum, .code = LINUX_SI_USER, + .fields.sender = {.pid = (int32_t)sched_task_tgid(sender), + .uid = user_namespace_id_from_kernel_munged(target->user_ns, false, sender->uid)}}; + return sched_signal_user_process_target(target, signum, &info); +} + +/** @copydoc sched_signal_broadcast */ +int sched_signal_broadcast(struct task *sender, int signal_number) +{ + uint32_t tgid = sched_task_tgid(sender); + bool found = false; + int result = 0; + for (uint32_t i = 0; i < task_count; ++i) { + struct task *task = tasks[i]; + if (!task || task->kind != TASK_KIND_USER || task->pid <= 1 || task->pid == tgid || + task->pid != sched_task_tgid(task) || + (task->state == TASK_EXITED && !(task->flags & TASK_FLAG_WAITABLE_CHILD))) continue; + int rc = signal_user_from(sender, task, signal_number); + found = true; + /* Linux broadcast ignores individual permission denials. */ + if (rc != -LINUX_EPERM) result = rc; + } + return found ? result : -LINUX_ESRCH; +} + /** @copydoc sched_signal_process_group */ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, int signal_number) @@ -328,18 +362,11 @@ int sched_signal_process_group(uint32_t sender_pid, uint32_t process_group, if (!task || !task->pid || task->kind != TASK_KIND_USER || task->process_group != process_group || task->pid != sched_task_tgid(task) || (task->state == TASK_EXITED && !(task->flags & TASK_FLAG_WAITABLE_CHILD))) continue; - if (sched_task_tgid(sender) != sched_task_tgid(task) && - !task_ns_capable(sender, task->user_ns, CAP_KILL) && - sender->uid != task->uid && sender->uid != task->suid && - sender->euid != task->uid && sender->euid != task->suid && - !(signal_number == 18 && sender->process_session == task->process_session)) { + int result = signal_user_from(sender, task, signal_number); + if (result == -LINUX_EPERM) { if (error == -LINUX_ESRCH) error = -LINUX_EPERM; continue; } - struct linux_siginfo info = {.signo = signal_number, .code = LINUX_SI_USER, - .fields.sender = {.pid = (int32_t)sched_task_tgid(sender), - .uid = user_namespace_id_from_kernel_munged(task->user_ns, false, sender->uid)}}; - int result = sched_signal_user_process_info(task->pid, signal_number, &info); if (result >= 0) ++count; else error = result; } diff --git a/kernel/syscall/device/device_io.c b/kernel/syscall/device/device_io.c index 8b64e89e..71e3bc55 100644 --- a/kernel/syscall/device/device_io.c +++ b/kernel/syscall/device/device_io.c @@ -1,4 +1,5 @@ #include +#include #include "../internal.h" @@ -27,6 +28,26 @@ int task_block_device(const struct task_file *file, uint32_t *disk_id, return 1; } +/** @brief Read one kernel log record, with interruptible wait at the tail. + * @param task Current task. @param file Retained log OFD. + * @param buffer Validated output. @param length Available bytes. + * @return Whole record, negative errno or the dispatcher blocking sentinel. + */ +static int device_read_kmsg(struct task *task, struct task_file *file, char *buffer, + uint32_t length) +{ + kernel_poll_wait_remove(task); + for (;;) { + uint64_t generation = kernel_poll_readiness_generation(); + int rc = kmsg_read_record(&file->aux, buffer, length); + if (rc != -LINUX_EAGAIN || (file->flags & LINUX_O_NONBLOCK)) return rc; + if (sched_task_pending(task) & ~task->blocked_signals) return -LINUX_EINTR; + int parked = kernel_poll_wait_current(generation, 0); + if (parked > 0) return KERNEL_SYSCALL_BLOCKED; + if (parked < 0) return -LINUX_EAGAIN; + } +} + /** * @brief Read an opened device; block descriptors use Linux open-time DAC checks. * @param task Current task, required for device context. @@ -34,7 +55,8 @@ int task_block_device(const struct task_file *file, uint32_t *disk_id, * @param buffer Validated writable destination of length bytes. * @param length Maximum byte count to read. * @return Bytes read, negative errno, or KERNEL_SYSCALL_BLOCKED for terminal - * job control; an empty nonblocking console returns negative EAGAIN. + * job control and interruptible log waits. An empty nonblocking console or + * kmsg reader returns negative EAGAIN. */ int task_device_read(struct task *task, struct task_file *file, void *buffer, uint32_t length) @@ -53,6 +75,8 @@ int task_device_read(struct task *task, struct task_file *file, if (task_device_is(file, STORAGE_DEV_KIND_NULL) || task_device_is(file, STORAGE_DEV_KIND_FULL) || task_device_is(file, STORAGE_DEV_KIND_SERIAL)) return 0; + if (task_device_is(file, STORAGE_DEV_KIND_KMSG)) + return device_read_kmsg(task, file, buffer, length); if (task_device_is(file, STORAGE_DEV_KIND_CONSOLE)) { uint32_t terminal = (uint32_t)file->aux; if (!terminal || !pty_is_active(terminal)) return -RELIEFOS_ENODEV; @@ -153,9 +177,7 @@ int task_device_write(struct task *task, struct task_file *file, return (int)result; } if (task_device_is(file, STORAGE_DEV_KIND_KMSG)) { - if (!buffer) return -RELIEFOS_EFAULT; - console_write_len((const char *)buffer, length); - return (int)length; + return kmsg_write_record(buffer, length); } if (task_device_is(file, STORAGE_DEV_KIND_SERIAL)) { if (!length) return 0; diff --git a/kernel/syscall/device/device_open.c b/kernel/syscall/device/device_open.c index 283abf47..35d8fa66 100644 --- a/kernel/syscall/device/device_open.c +++ b/kernel/syscall/device/device_open.c @@ -2,6 +2,7 @@ #include "../internal.h" #include #include +#include /** @brief Bind a newly created PTY description to its held device path. * @param task Current fd-table owner under execution ownership. @@ -135,6 +136,7 @@ int task_open_device_path(struct task *task,const struct vfs_path *path,uint32_t if(!rc)rc=character_file_open(status.st_rdev,task,file,&file->character_file); } if(!rc && node->first_cluster==STORAGE_DEV_KIND_SHM)rc=task_shm_attach(file,0); + if(!rc && node->first_cluster==STORAGE_DEV_KIND_KMSG)file->aux=kmsg_first_sequence(); if(!rc && (node->first_cluster==STORAGE_DEV_KIND_KEYBOARD || node->first_cluster==STORAGE_DEV_KIND_MOUSE)) { file->aux=input_evdev_cursor_now();file->input_vt=task_evdev_vt_hint(task); } diff --git a/kernel/syscall/entry.c b/kernel/syscall/entry.c index a1f17593..e2b56bb1 100644 --- a/kernel/syscall/entry.c +++ b/kernel/syscall/entry.c @@ -107,6 +107,7 @@ static int syscall_eagain_is_nonblocking_device(struct task *task, (task_device_is(file, STORAGE_DEV_KIND_KEYBOARD) || task_device_is(file, STORAGE_DEV_KIND_MOUSE) || task_device_is(file, STORAGE_DEV_KIND_CONSOLE) || + task_device_is(file, STORAGE_DEV_KIND_KMSG) || task_device_is(file, STORAGE_DEV_KIND_SERIAL) || task_device_is(file, STORAGE_DEV_KIND_AUDIO) || (file->node.flags & (STORAGE_NODE_FLAG_AUDIO_CONTROL | diff --git a/kernel/syscall/event/epoll.c b/kernel/syscall/event/epoll.c index 419a6c31..5bce09bd 100644 --- a/kernel/syscall/event/epoll.c +++ b/kernel/syscall/event/epoll.c @@ -1,4 +1,5 @@ #include "../internal.h" +#include #include /** @@ -24,6 +25,8 @@ static uint64_t epoll_event_generation(const struct task_file *file, uint32_t *p file->node.first_cluster == STORAGE_DEV_KIND_KEYBOARD)) return input_evdev_event_generation_vt(file->node.first_cluster, file->aux2, file->input_vt); + if (file && (file->flags & TASK_FILE_FLAG_DEV_NODE) && + file->node.first_cluster == STORAGE_DEV_KIND_KMSG) return kmsg_next_sequence(); return task_socket_event_generation(file); } diff --git a/kernel/syscall/event/poll.c b/kernel/syscall/event/poll.c index 9d860e48..823ac893 100644 --- a/kernel/syscall/event/poll.c +++ b/kernel/syscall/event/poll.c @@ -1,4 +1,5 @@ #include +#include #include #include "../internal.h" #include @@ -123,7 +124,11 @@ static int64_t syscall_poll_impl_core(struct task *task, struct pollfd *fds, } else if (file && file->character_file) { revents=character_file_poll(file->character_file,file,events); } else if (file && (file->flags & TASK_FILE_FLAG_DEV_NODE)) { - if (task_device_is(file, STORAGE_DEV_KIND_SERIAL)) { + if (task_device_is(file, STORAGE_DEV_KIND_KMSG)) { + fds[i].revents = kmsg_readiness(file->aux) & (events | POLLERR); + if (fds[i].revents) ++ready; + continue; + } else if (task_device_is(file, STORAGE_DEV_KIND_SERIAL)) { if (!serial_com1_available()) revents |= POLLERR; else { /* This diagnostic device has no receive path. A read diff --git a/kernel/syscall/fd/open.c b/kernel/syscall/fd/open.c index 92e08dc7..7b2cd479 100644 --- a/kernel/syscall/fd/open.c +++ b/kernel/syscall/fd/open.c @@ -118,7 +118,9 @@ int64_t syscall_open_object(struct vfs_namespace *ns,struct task *task,int32_t d if(found.trailing)rc=-RELIEFOS_EISDIR; else rc=syscall_creation_mode(task,&found.path,LINUX_S_IFREG,mode,&value); if(!rc) { - struct vfs_path file={0};rc=vfs_path_new_file(&found.path,found.last,&value,&file); + struct vfs_path file={0}; + rc=vfs_path_create_masked(&found.path,found.last,LINUX_S_IFREG,&value,NULL,0, + *sched_task_umask(task),&file); if(!rc){vfs_path_put(&found.path);found.path=file;created=true;} } } else if(exclusive)rc=-RELIEFOS_EEXIST; diff --git a/kernel/syscall/fs/create.c b/kernel/syscall/fs/create.c index 7d66403e..e80c25b3 100644 --- a/kernel/syscall/fs/create.c +++ b/kernel/syscall/fs/create.c @@ -1,13 +1,13 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" -/** @brief Derive final creation metadata from the actual authorized parent. +/** @brief Derive authorized creation metadata from the actual parent. * @param task Borrowed caller and stable filesystem credentials. * @param parent Held parent retaining the provider through metadata I/O. * @param type Full Linux S_IF* inode type. * @param mode Requested permission/special bits. * @param out Receives final mode, fsuid and inherited/default group. - * @return Zero or negative errno. Applies umask, directory SGID inheritance, + * @return Zero or negative errno. Applies directory SGID inheritance, * non-directory CAP_FSETID/group rules and symlink0777. No locks span I/O. * An override of setgid clearing requires initial user namespace CAP_FSETID. */ @@ -19,7 +19,7 @@ int syscall_creation_mode(struct task *task,const struct vfs_path *parent,uint32 struct reliefos_permissions inherited; if(!rc)rc=vfs_path_permissions(parent,&inherited,false); if(rc)return rc; - *out=(struct reliefos_permissions){type==LINUX_S_IFLNK ? 0777 : (mode&07777)&~*sched_task_umask(task), + *out=(struct reliefos_permissions){type==LINUX_S_IFLNK ? 0777 : mode&07777, task->fsuid,task->fsgid}; if(inherited.mode&02000) { out->gid=inherited.gid; @@ -68,8 +68,8 @@ static int64_t syscall_create_member(struct vfs_namespace *ns,struct task *task, if(!rc)rc=syscall_creation_mode(task,&parent.path,type,mode,&value); if(!rc && special && !(type==LINUX_S_IFCHR && !device) && !(task_initial_capabilities(task)&(1ULL< #include +#include #include #include @@ -19,6 +21,7 @@ static int xattr_get_permission(struct task *task,const struct vfs_path *path, { if (!__builtin_strncmp(name,"trusted.",8)) return privileged ? 0 : -LINUX_ENODATA; if (!__builtin_strncmp(name,"security.",9)) return 0; + if (posix_acl_name(name)) return 0; if (__builtin_strncmp(name,"user.",5)) return -RELIEFOS_EOPNOTSUPP; const struct storage_node *node=vfs_path_node(path); if (node->type!=RELIEFOS_FS_TYPE_FILE && node->type!=RELIEFOS_FS_TYPE_DIR) @@ -26,6 +29,47 @@ static int xattr_get_permission(struct task *task,const struct vfs_path *path, return fs_permissions_check_path(task,path,4,false); } +/** @brief Translate named ACL IDs between the caller and the filesystem. + * @param task Caller with stable user namespace. @param bytes Owned ACL value. + * @param length Exact xattr length. @param import True for syscall input. + * @return Zero or EINVAL for malformed data or an unmapped input qualifier. + */ +static int xattr_map_acl(struct task *task,void *bytes,uint32_t length,bool import) +{ + struct posix_acl_xattr *acl=bytes; + if(lengthentries[0]) || + acl->version!=POSIX_ACL_XATTR_VERSION)return -RELIEFOS_EINVAL; + uint32_t count=(length-sizeof(*acl))/sizeof(acl->entries[0]); + for(uint32_t i=0;ientries[i]; + if(!posix_acl_named(entry->tag))continue; + bool group=entry->tag==ACL_GROUP; + if(import) { + entry->id=user_namespace_id_to_kernel(task->user_ns,group,entry->id); + if(entry->id==UINT32_MAX)return -RELIEFOS_EINVAL; + } else { + entry->id=user_namespace_id_from_kernel(task->user_ns,group,entry->id); + } + } + return 0; +} + +/** @brief Grant ACL changes to the inode owner or a privileged caller. + * @param task Caller with stable filesystem credentials. + * @param path Actual retained inode. @param clear_setgid Receives setgid policy. + * @return Zero on authorization, or negative metadata/permission errno. + */ +static int xattr_acl_permission(struct task *task,const struct vfs_path *path,bool *clear_setgid) +{ + struct reliefos_permissions metadata; + int rc=vfs_path_permissions(path,&metadata,false); + if(rc)return rc; + uint64_t caps=task_initial_capabilities(task); + if(task->fsuid!=metadata.uid && !(caps&(1ull<XATTR_BUFFER_MAX ? XATTR_BUFFER_MAX : (uint32_t)size; uint32_t length=0; void *buffer=NULL; bool privileged=(task_initial_capabilities(task)&(1ull<pid); } if (!rc && capacity && length) { diff --git a/kernel/syscall/internal.h b/kernel/syscall/internal.h index 33dc1260..d88caa57 100644 --- a/kernel/syscall/internal.h +++ b/kernel/syscall/internal.h @@ -1203,7 +1203,8 @@ int resolve_user_object_at_flags(struct vfs_namespace *ns,struct task *task,int3 * @param task Borrowed current task and stable filesystem credentials. * @param parent Borrowed retained directory, never resolved by display name. * @param type Linux S_IF* inode type. - * @param mode Requested permissions, subject to umask and set-ID policy. + * @param mode Requested permissions subject to set-ID policy. The creation + * provider applies the caller's umask or the parent's default ACL. * @param out Required metadata output on success. * @return Zero or negative errno. Checks parent write/search, fsuid/fsgid, * SGID inheritance and capabilities; symlinks keep0777. No graph lock spans I/O. diff --git a/kernel/syscall/io/io.c b/kernel/syscall/io/io.c index 4f52235d..a251a6e2 100644 --- a/kernel/syscall/io/io.c +++ b/kernel/syscall/io/io.c @@ -1,5 +1,6 @@ #include "../internal.h" #include +#include #include #include #include @@ -127,6 +128,8 @@ int64_t syscall_io_write(uint64_t a0, uint64_t a1, uint64_t a2) if (signal_file && (signal_file->kind == TASK_FILE_KIND_SIGNALFD || signal_file->kind == TASK_FILE_KIND_PIDFD)) return -LINUX_EINVAL; if (signal_file && signal_file->kind == TASK_FILE_KIND_INOTIFY) return -LINUX_EBADF; + if (task_device_is(signal_file, STORAGE_DEV_KIND_KMSG) && a2 > KMSG_MESSAGE_MAX) + return file_can_write(signal_file) ? -LINUX_EINVAL : -LINUX_EBADF; #ifdef CONFIG_SWAP if(signal_file && (signal_file->flags & TASK_FILE_FLAG_SOCKET_UNIX)) { if(!scalar_address_valid(a1,a2))return -RELIEFOS_EFAULT; diff --git a/kernel/syscall/io/legacy_io.c b/kernel/syscall/io/legacy_io.c index b897dd43..74b8ba52 100644 --- a/kernel/syscall/io/legacy_io.c +++ b/kernel/syscall/io/legacy_io.c @@ -106,7 +106,8 @@ int64_t syscall_legacy_io(uint64_t number, uint64_t a0, uint64_t a1, uint64_t a2 if (task_device_is(file, STORAGE_DEV_KIND_CONSOLE)) return -LINUX_ESPIPE; if (file->io_owner && file->io_owner != task->pid) return -RELIEFOS_EAGAIN; if (file->kind == TASK_FILE_KIND_SIGNALFD) return (uint32_t)a2 > 4 ? -LINUX_EINVAL : (int64_t)file->offset; - if (file->node.type == RELIEFOS_FS_TYPE_FILE || file->node.type == RELIEFOS_FS_TYPE_DIR) + if (task_device_is(file, STORAGE_DEV_KIND_KMSG) || + file->node.type == RELIEFOS_FS_TYPE_FILE || file->node.type == RELIEFOS_FS_TYPE_DIR) return syscall_seek_object(task,(int32_t)a0,offset,(uint32_t)a2); if (file->flags & TASK_FILE_FLAG_DEV_BLOCK) { /* Block devices are seekable byte streams. GPT editors and diff --git a/kernel/syscall/io/seek.c b/kernel/syscall/io/seek.c index a4cead1a..458ff322 100644 --- a/kernel/syscall/io/seek.c +++ b/kernel/syscall/io/seek.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" +#include /** @brief Seek one admitted ordinary inode using its shared OFD position. * @param task Execution-owned caller retaining the admitted OFD until cleanup. @@ -7,7 +8,8 @@ * @param offset Signed Linux byte offset or opaque directory position cookie. * @param whence Linux SEEK_SET/CUR/END/DATA/HOLE selector, low 32 bits. * @return New position, negative errno or internal metadata retry. Namespace - * handles return ESPIPE for valid whence. Directories + * handles return ESPIPE for valid whence. The kmsg stream selects a record + * cursor with zero-offset SET, END or DATA. Directories * preserve backend cookies without record-size conversion. Ordinary END/DATA/ * HOLE use fresh actual-provider metadata, with the conservative permitted * all-data/EOF-hole interpretation. The OFD position is reserved before any @@ -19,6 +21,16 @@ int64_t syscall_seek_object(struct task *task,int32_t fd,int64_t offset,uint32_t struct task_file *file=task_file_for_io(task,fd); if(!task || !file || (file->flags&TASK_FILE_FLAG_PATH) || task->syscall_file!=file || task->syscall_file_number!=LINUX_SYS_LSEEK)return -RELIEFOS_EBADF; + if(task_device_is(file,STORAGE_DEV_KIND_KMSG)) { + if(whence>4)return -LINUX_EINVAL; + if(offset)return -LINUX_ESPIPE; + switch(whence) { + case RELIEFOS_SEEK_SET: file->aux=kmsg_first_sequence();return 0; + case RELIEFOS_SEEK_END: file->aux=kmsg_next_sequence();return 0; + case 3: file->aux=0;return 0; /* SEEK_DATA: no SYSLOG_ACTION_CLEAR has occurred. */ + default: return -LINUX_EINVAL; + } + } bool directory=file->node.type==RELIEFOS_FS_TYPE_DIR; if(!directory && file->node.type!=RELIEFOS_FS_TYPE_FILE)return -LINUX_ESPIPE; if(whence>4 || (directory && whence>RELIEFOS_SEEK_CUR))return -RELIEFOS_EINVAL; diff --git a/kernel/syscall/io/vector.c b/kernel/syscall/io/vector.c index 18f5a34a..de059df0 100644 --- a/kernel/syscall/io/vector.c +++ b/kernel/syscall/io/vector.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: Apache-2.0 */ #include "../internal.h" #include "vector_internal.h" +#include #include #include #include @@ -8,6 +9,30 @@ /* Standalone vector fixtures may omit the anonymous inotify provider. */ extern short task_inotify_poll(const struct task_file *) __attribute__((weak)); + +/** @brief Gather a kmsg writev into one record before publishing it. + * @param task Borrowed caller under execution ownership. + * @param iov Imported vector. @param count Number of elements. + * @param length Sum of the component byte counts. + * @return Accepted bytes or a validation/import errno; no partial records. + */ +static int64_t write_kmsg_vector(struct task *task,const struct iovec *iov, + uint32_t count,uint64_t length) +{ + if(length>KMSG_MESSAGE_MAX)return -LINUX_EINVAL; + char record[KMSG_MESSAGE_MAX]; + size_t at=0; + for(uint32_t i=0;icharacter_file,task,file,iov,a2, positional && !current_position,position,positional_flags); if (!requested) return 0; + if (writing && task_device_is(file,STORAGE_DEV_KIND_KMSG)) { + if (positional && !current_position) return -LINUX_ESPIPE; + return write_kmsg_vector(task,iov,(uint32_t)a2,requested); + } if (positional && !current_position) { if (!file) return -RELIEFOS_EINVAL; if (file->node.type != RELIEFOS_FS_TYPE_FILE) return -RELIEFOS_ESPIPE; diff --git a/kernel/syscall/ipc/unix_path.c b/kernel/syscall/ipc/unix_path.c index 13be4b0c..ffb9a9cb 100644 --- a/kernel/syscall/ipc/unix_path.c +++ b/kernel/syscall/ipc/unix_path.c @@ -32,7 +32,8 @@ int syscall_unix_path(struct vfs_namespace *ns,struct task *task,const char *nam vfs_path_put(&existing); struct reliefos_permissions mode; if(!rc)rc=syscall_creation_mode(task,&found.path,LINUX_S_IFSOCK,0777,&mode); - if(!rc)rc=vfs_path_create_node(&found.path,found.last,LINUX_S_IFSOCK,&mode,NULL,out); + if(!rc)rc=vfs_path_create_masked(&found.path,found.last,LINUX_S_IFSOCK,&mode,NULL,0, + *sched_task_umask(task),out); if(rc==-RELIEFOS_EEXIST)rc=-RELIEFOS_EADDRINUSE; } else { rc=fs_permissions_check_path(task,&found.path,FS_ACCESS_WRITE,false); diff --git a/kernel/syscall/process/process.c b/kernel/syscall/process/process.c index 8e72910d..c40c80e3 100644 --- a/kernel/syscall/process/process.c +++ b/kernel/syscall/process/process.c @@ -1205,9 +1205,8 @@ int64_t syscall_process_control(uint64_t number, uint64_t a0, int32_t requested_pid = (int32_t)a0; struct task *target; if (signal_number < 0 || signal_number >= LINUX_NSIG) return -RELIEFOS_EINVAL; - if (!current || requested_pid == -1) { - return -RELIEFOS_EINVAL; - } + if (!current) return -LINUX_ESRCH; + if (requested_pid == -1) return sched_signal_broadcast(current, signal_number); if (requested_pid <= 0) { uint32_t process_group = requested_pid == 0 ? current->process_group diff --git a/tools/test_ext4_dir.py b/tools/test_ext4_dir.py index cedab4fc..9f555d6b 100644 --- a/tools/test_ext4_dir.py +++ b/tools/test_ext4_dir.py @@ -17,7 +17,7 @@ def main(): "-Iinclude/uapi","-Iinclude", "-include",str(STORAGE/"core/storage_internal.h"),"tools/tests/ext4_dir_test.c", *[str(FS/f"ext_common/{n}.c") for n in - ("format","checksum","cache","alloc","extent","ops","xattr","journal","dir")],"-lext2fs","-o",str(binary)]) + ("format","checksum","cache","alloc","extent","ops","xattr","journal","dir","acl")],"-lext2fs","-o",str(binary)]) stage=work/"stage"; (stage/"linux").mkdir(parents=True) for i in range(1000): (stage/"linux"/f"linux-file-{i:05d}").touch() for bs in (1024,4096): diff --git a/tools/test_mount_backend.py b/tools/test_mount_backend.py index 2e306999..e276d1d2 100644 --- a/tools/test_mount_backend.py +++ b/tools/test_mount_backend.py @@ -26,6 +26,7 @@ def test_real_tmpfs_without_text_routing(self): "kernel/init/uts.c", "net/namespace/namespace.c", "net/ipv6/state.c", "kernel/syscall/dispatch.c", "kernel/syscall/io/legacy_io.c", "kernel/syscall/io/io.c", "kernel/syscall/io/file_io.c", "kernel/syscall/io/seek.c", "kernel/syscall/io/transfer.c", + "drivers/console/kmsg.c", "kernel/syscall/io/directory.c", "kernel/syscall/fs/metadata.c", "tools/tests/mount_backend_io_boundaries.c", "tools/tests/task8_host_stubs/device_page_unreached.c", "tools/tests/task8_host_stubs/writable_alias_model.c", diff --git a/tools/tests/epoll_capacity_test.c b/tools/tests/epoll_capacity_test.c index c8669dfe..f2aba630 100644 --- a/tools/tests/epoll_capacity_test.c +++ b/tools/tests/epoll_capacity_test.c @@ -6,6 +6,7 @@ #include #include "../../kernel/syscall/event/epoll.c" +#include "modules/kmsg.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include "../../drivers/tty/input/input.c" diff --git a/tools/tests/ext4_metadata_api_test.py b/tools/tests/ext4_metadata_api_test.py index 82b58b4a..f8322e00 100644 --- a/tools/tests/ext4_metadata_api_test.py +++ b/tools/tests/ext4_metadata_api_test.py @@ -3,6 +3,7 @@ from pathlib import Path import re import subprocess +import struct import tempfile import sys sys.path.insert(0,str(Path(__file__).resolve().parents[1])) @@ -17,7 +18,7 @@ def main(): "-Iinclude/uapi","-Iinclude", "-include",str(STORAGE/"core/storage_internal.h"),"tools/tests/ext4_xattr_test.c", *[str(FS/"ext_common"/f"{n}.c") for n in - ("format","checksum","cache","alloc","extent","ops","journal","dir","xattr")],"-o",str(binary)]) + ("format","checksum","cache","alloc","extent","ops","journal","dir","xattr","acl")],"-o",str(binary)]) for bs in (1024,4096): for kind,features in (("ext2","none,filetype,ext_attr"), ("ext4","none,filetype,extents,64bit,metadata_csum,extra_isize,ext_attr,has_journal")): @@ -35,6 +36,14 @@ def main(): value.unlink() run(["debugfs","-R",f"ea_get -f {value} /payload user.linux",str(result)],capture_output=True) assert value.read_bytes()==b"replaced" + value.unlink() + run(["debugfs","-R",f"ea_get -f {value} /payload system.posix_acl_access",str(result)],capture_output=True) + observed=value.read_bytes() + # debugfs fills unused qualifiers with zero when exporting an ACL. + expected=struct.pack(" int main(int argc,char **argv) { assert(argc==4); init_volume(argv[1]); uint64_t ino=strtoull(argv[2],NULL,10); @@ -39,6 +40,20 @@ int main(int argc,char **argv) check(storage_ext4_removexattr(&volume,ino,"user.small")); assert(storage_ext4_getxattr(&volume,ino,"user.small",small,sizeof(small),&len)==-61); check(storage_ext4_setxattr(&volume,ino,"user.linux","replaced",8,2)); + const struct { + uint32_t version; + struct posix_acl_entry entries[5]; + } acl = {POSIX_ACL_XATTR_VERSION, { + {ACL_USER_OBJ, 6, UINT32_MAX}, {ACL_USER, 4, 1000}, + {ACL_GROUP_OBJ, 0, UINT32_MAX}, {ACL_MASK, 4, UINT32_MAX}, {ACL_OTHER, 0, UINT32_MAX} + }}; + check(storage_ext4_read_inode(&volume,ino,&first)); + check(storage_ext4_set_acl(&volume,ino,&first,false,&acl,sizeof(acl),false)); + sync_image(); invalidate(); + check(storage_ext4_read_inode(&volume,ino,&first)); + assert((first.mode&0777)==0640); + check(storage_ext4_get_acl(&volume,ino,&first,false,small,sizeof(small),&len)); + assert(len==sizeof(acl) && !memcmp(small,&acl,len)); volume.read_only_reason=1; assert(storage_ext4_setxattr(&volume,ino,"user.ro","x",1,0)==-RELIEFOS_EROFS); volume.read_only_reason=0; sync_image(); @@ -50,5 +65,5 @@ int main(int argc,char **argv) } FILE *f=fopen(argv[3],"wb"); assert(f); assert(fwrite(disk,1,disk_len,f)==disk_len); fclose(f); storage_ext4_journal_close(&volume); invalidate(); free(disk); free(big); free(out); - puts("PASS Linux/native inline/external user xattrs, create/replace/remove/errors/reload"); return 0; + puts("PASS Linux/native user xattrs and access ACL persistence"); return 0; } diff --git a/tools/tests/inotify_vfs_test.c b/tools/tests/inotify_vfs_test.c index f6452128..e5266b92 100644 --- a/tools/tests/inotify_vfs_test.c +++ b/tools/tests/inotify_vfs_test.c @@ -69,9 +69,12 @@ static int getattr(void *ctx,const struct vfs_path *path,struct linux_stat_abi * return tmpfs_stat(ctx,vfs_path_node(path)->first_cluster,out); } static int create(void *ctx,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *p,const char *target,struct storage_node *out,void **pin) + const struct reliefos_permissions *p,const char *target,uint32_t umask, + struct storage_node *out,void **pin) { - int rc=tmpfs_create_child(ctx,parent->first_cluster,name,type|(p->mode&07777),target,p,out); + struct reliefos_permissions value=*p; + if(type!=LINUX_S_IFLNK)value.mode&=~umask; + int rc=tmpfs_create_child(ctx,parent->first_cluster,name,type|(value.mode&07777),target,&value,out); if(!rc && pin)rc=retain(ctx,out,pin); return rc; } diff --git a/tools/tests/modules/console.h b/tools/tests/modules/console.h index 8cc1b5c7..f2ad103f 100644 --- a/tools/tests/modules/console.h +++ b/tools/tests/modules/console.h @@ -38,6 +38,7 @@ void serial_panic_quiesce(void) {} #include "../../../drivers/console/render.c" #include "../../../drivers/console/vt.c" #include "../../../drivers/console/log.c" +#include "kmsg.h" #include "../../../drivers/console/ansi.c" #include "../../../drivers/console/core.c" #include "../../../drivers/console/panic.c" diff --git a/tools/tests/modules/kmsg.h b/tools/tests/modules/kmsg.h new file mode 100644 index 00000000..a01734a2 --- /dev/null +++ b/tools/tests/modules/kmsg.h @@ -0,0 +1,5 @@ +/* Test-only white-box composition of the production record buffer. */ +#ifndef RELIEFNT_TEST_MODULE_KMSG_H +#define RELIEFNT_TEST_MODULE_KMSG_H +#include "../../../drivers/console/kmsg.c" +#endif diff --git a/tools/tests/modules/syscall_dispatch.h b/tools/tests/modules/syscall_dispatch.h index fc33e8a5..b6ffc75e 100644 --- a/tools/tests/modules/syscall_dispatch.h +++ b/tools/tests/modules/syscall_dispatch.h @@ -1,6 +1,7 @@ /* Test-only white-box composition of the separately built production units. */ #ifndef RELIEFNT_TEST_MODULE_SYSCALL_DISPATCH_H #define RELIEFNT_TEST_MODULE_SYSCALL_DISPATCH_H +#include "../../../drivers/console/kmsg.c" #include "../../../kernel/device/character.c" #include "../../../kernel/syscall/event/epoll.c" #include "../../../kernel/syscall/fs/stat.c" diff --git a/tools/tests/mount_backend_test.c b/tools/tests/mount_backend_test.c index 12a57dcb..d8e644fc 100644 --- a/tools/tests/mount_backend_test.c +++ b/tools/tests/mount_backend_test.c @@ -66,6 +66,10 @@ static void runtime_block_mount_api(const uint8_t *bytes, uint32_t sectors, cons int sound_service_card_index(uint32_t token) {(void)token;return -19;} +/** @brief Provide a deterministic timestamp for the storage fixture. */ +uint64_t time_uptime_us(void) +{return 0;} + static const struct storage_filesystem_ops *counted_provider; static unsigned provider_roots,provider_lookups,provider_reads,provider_directories; static unsigned provider_stats,provider_permissions,provider_times,provider_statfs; @@ -109,8 +113,9 @@ static int counted_write(struct storage_volume *volume,struct storage_node *node static int counted_truncate(struct storage_volume *volume,struct storage_node *node,uint64_t length) { ++provider_truncates;return counted_provider->truncate(volume,node,length); } static int counted_create(struct storage_volume *volume,const struct storage_node *parent,const char *name,uint32_t mode, - const struct reliefos_permissions *value,const char *target,struct storage_node *out) -{ ++provider_creates;return counted_provider->create(volume,parent,name,mode,value,target,out); } + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out) +{ ++provider_creates;return counted_provider->create(volume,parent,name,mode,value,target,umask,out); } static int counted_remove(struct storage_volume *volume,const struct storage_node *parent,const char *name, const struct storage_node *node,bool directory) { ++provider_removes;return counted_provider->remove(volume,parent,name,node,directory); } diff --git a/tools/tests/permission_graph_fixture.h b/tools/tests/permission_graph_fixture.h index 3025c360..4aecbe48 100644 --- a/tools/tests/permission_graph_fixture.h +++ b/tools/tests/permission_graph_fixture.h @@ -85,13 +85,15 @@ static int fixture_link_bytes(void *context,const struct storage_node *node,char static int fixture_remount(void *context,uint64_t flags) {assert(context==entries);(void)flags;return 0;} static int fixture_create(void *context,const struct storage_node *parent,const char *name,uint32_t type, - const struct reliefos_permissions *value,const char *target,struct storage_node *out,void **pin) + const struct reliefos_permissions *value,const char *target,uint32_t umask, + struct storage_node *out,void **pin) { assert(context==entries);struct storage_node existing; if(!fixture_lookup(context,parent,name,&existing))return -EEXIST; if(entry_count==sizeof(entries)/sizeof(entries[0]))return -ENOSPC; unsigned index=entry_count++;struct fixture *f=&entries[index]; *f=(struct fixture){.parent=parent->inode_generation,.value=*value,.target=target}; + if(type!=LINUX_S_IFLNK)f->value.mode&=~umask; f->type=type==LINUX_S_IFDIR ? RELIEFOS_FS_TYPE_DIR : type==LINUX_S_IFLNK ? RELIEFOS_FS_TYPE_SYMLINK : RELIEFOS_FS_TYPE_FILE; assert(strlen(name)name));strcpy(f->name,name);*out=entry_node(index); @@ -185,6 +187,6 @@ static int create_file(struct task *task,const char *name,uint32_t type,uint32_t { struct vfs_lookup_result parent={0};int rc=file_resolve(task,"/",name,false,VFS_LOOKUP_PARENT,&parent); struct reliefos_permissions value;if(!rc)rc=syscall_creation_mode(task,&parent.path,type,mode,&value); - if(!rc)rc=vfs_path_create_node(&parent.path,parent.last,type,&value,target,NULL); + if(!rc)rc=vfs_path_create_masked(&parent.path,parent.last,type,&value,target,0,*sched_task_umask(task),NULL); vfs_path_put(&parent.path);return rc; } diff --git a/tools/tests/select_bitmap_test.c b/tools/tests/select_bitmap_test.c index 5aabb0a8..950d9187 100644 --- a/tools/tests/select_bitmap_test.c +++ b/tools/tests/select_bitmap_test.c @@ -6,6 +6,7 @@ #include #include "../../kernel/syscall/event/poll.c" +#include "modules/kmsg.h" #define TEST_FD_MAX 4096u #define HIGH_READY_FD 1100u diff --git a/tools/tests/storage_mkdir_mount_test.c b/tools/tests/storage_mkdir_mount_test.c index 5a844b31..17479663 100644 --- a/tools/tests/storage_mkdir_mount_test.c +++ b/tools/tests/storage_mkdir_mount_test.c @@ -50,6 +50,7 @@ #include "../../fs/ext_common/extent.c" #include "../../fs/ext_common/ops.c" #include "../../fs/ext_common/xattr.c" +#include "../../fs/ext_common/acl.c" #ifndef RELIEFNT_FIXTURE_SEPARATE_JOURNAL #include "../../fs/ext_common/journal.c" #endif diff --git a/tools/tests/storage_rename_test.c b/tools/tests/storage_rename_test.c index 6fe7f497..0229bc3c 100644 --- a/tools/tests/storage_rename_test.c +++ b/tools/tests/storage_rename_test.c @@ -151,6 +151,7 @@ int storage_ext4_device_flush(const struct storage_volume *v) { (void)v; return #include "../../fs/ext_common/extent.c" #include "../../fs/ext_common/ops.c" #include "../../fs/ext_common/xattr.c" +#include "../../fs/ext_common/acl.c" #include "../../fs/ext_common/journal.c" #include "../../fs/ext_common/dir.c" #include "../../fs/ext_common/mount.c" diff --git a/tools/tests/systemd_compat_runtime_probe.c b/tools/tests/systemd_compat_runtime_probe.c new file mode 100644 index 00000000..bbf4a0f4 --- /dev/null +++ b/tools/tests/systemd_compat_runtime_probe.c @@ -0,0 +1,181 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(condition) do { if (!(condition)) { \ + fprintf(stderr, "[systemd-compat] %s:%d: %s (errno=%d)\n", \ + __func__, __LINE__, #condition, errno); return 1; \ +} } while (0) + +static int kmsg(void) +{ + int reader = open("/dev/kmsg", O_RDONLY | O_NONBLOCK); + int other = open("/dev/kmsg", O_RDONLY | O_NONBLOCK); + int writer = open("/dev/kmsg", O_WRONLY | O_NONBLOCK); + CHECK(reader >= 0 && other >= 0 && writer >= 0); + char line[8192], same[8192]; + ssize_t size = read(reader, line, sizeof(line) - 1); + CHECK(size > 0 && read(other, same, sizeof(same)) == size); + CHECK(!memcmp(line, same, size) && line[size - 1] == '\n'); + line[size] = 0; + unsigned priority; + unsigned long long first_sequence, timestamp; + CHECK(sscanf(line, "%u,%llu,%llu,", &priority, &first_sequence, ×tamp) == 3); + CHECK(lseek(reader, 0, SEEK_END) == 0 && lseek(other, 0, SEEK_END) == 0); + CHECK(read(reader, line, sizeof(line)) < 0 && errno == EAGAIN); + CHECK(lseek(reader, 1, SEEK_SET) < 0 && errno == ESPIPE); + CHECK(lseek(reader, 0, SEEK_CUR) < 0 && errno == EINVAL); + struct pollfd descriptor = {.fd = reader, .events = POLLIN}; + CHECK(poll(&descriptor, 1, 0) == 0); + int epoll = epoll_create1(EPOLL_CLOEXEC); + struct epoll_event event = {.events = EPOLLIN, .data.fd = reader}; + CHECK(epoll >= 0 && epoll_ctl(epoll, EPOLL_CTL_ADD, reader, &event) == 0); + char prefix[] = "<7>", message[] = "reliefnt kmsg probe\\byte\n"; + struct iovec vector[] = {{prefix, sizeof(prefix) - 1}, {message, sizeof(message) - 1}}; + CHECK(writev(writer, vector, 2) == sizeof(prefix) + sizeof(message) - 2); + CHECK(epoll_wait(epoll, &event, 1, 2000) == 1 && (event.events & EPOLLIN)); + int shared = dup(reader); + CHECK(shared >= 0); + unsigned long long sequence; + do { + size = read(shared, line, sizeof(line) - 1); + CHECK(size > 0); + line[size] = 0; + } while (!strstr(line, "reliefnt kmsg probe")); + CHECK(sscanf(line, "%u,%llu,%llu,", &priority, &sequence, ×tamp) == 3); + CHECK(priority == 15 && sequence > first_sequence); + CHECK(strstr(line, ";reliefnt kmsg probe\\x5cbyte\n") != NULL); + CHECK(read(reader, line, sizeof(line)) < 0 && errno == EAGAIN); + CHECK(read(other, line, 1) < 0 && errno == EINVAL); + CHECK(close(shared) == 0 && close(epoll) == 0 && close(writer) == 0); + CHECK(close(other) == 0 && close(reader) == 0); + return 0; +} + +struct acl_value { + uint32_t version; + struct { uint16_t tag, perm; uint32_t id; } entries[5]; +}; + +static const char access_acl[] = "system.posix_acl_access"; +static const char default_acl[] = "system.posix_acl_default"; +static const struct acl_value reader_acl = {2, { + {1, 7, UINT32_MAX}, {2, 7, 61111}, {4, 0, UINT32_MAX}, + {16, 5, UINT32_MAX}, {32, 0, UINT32_MAX}, +}}; + +static int check_access(const char *path, uid_t uid, int mode, int expected) +{ + pid_t child = fork(); + CHECK(child >= 0); + if (!child) { + if (setresgid(uid, uid, uid) || setresuid(uid, uid, uid)) _exit(2); + int fd = open(path, mode); + _exit(expected ? fd < 0 && errno == expected ? 0 : 1 : fd >= 0 ? 0 : 1); + } + int status; + CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); + return 0; +} + +static int acl(void) +{ + char dir[] = "/var/tmp/reliefnt-acl-XXXXXX", path[128], inherited[128], subdir[128]; + CHECK(mkdtemp(dir) && chmod(dir, 0755) == 0); + snprintf(path, sizeof(path), "%s/journal", dir); + snprintf(inherited, sizeof(inherited), "%s/inherited", dir); + snprintf(subdir, sizeof(subdir), "%s/subdir", dir); + int fd = open(path, O_CREAT | O_EXCL | O_RDWR, 0600); + CHECK(fd >= 0 && write(fd, "j", 1) == 1); + CHECK(fsetxattr(fd, access_acl, &reader_acl, sizeof(reader_acl), 0) == 0); + struct acl_value readback, invalid = reader_acl; + invalid.entries[2].tag = 32; + CHECK(fsetxattr(fd, access_acl, &invalid, sizeof(invalid), 0) < 0 && errno == EINVAL); + CHECK(fgetxattr(fd, access_acl, &readback, sizeof(readback)) == sizeof(readback)); + CHECK(readback.entries[1].id == 61111 && readback.entries[3].perm == 5); + char names[256]; + CHECK(flistxattr(fd, names, sizeof(names)) == sizeof(access_acl) && !strcmp(names, access_acl)); + struct stat metadata; + CHECK(fstat(fd, &metadata) == 0 && (metadata.st_mode & 0777) == 0750); + CHECK(check_access(path, 61111, O_RDONLY, 0) == 0); + CHECK(check_access(path, 61111, O_WRONLY, EACCES) == 0); + CHECK(check_access(path, 61112, O_RDONLY, EACCES) == 0); + CHECK(fchmod(fd, 0710) == 0); + CHECK(check_access(path, 61111, O_RDONLY, EACCES) == 0); + CHECK(fgetxattr(fd, access_acl, &readback, sizeof(readback)) == sizeof(readback)); + CHECK(readback.entries[1].perm == 7 && readback.entries[3].perm == 1); + CHECK(fremovexattr(fd, access_acl) == 0); + CHECK(fgetxattr(fd, access_acl, NULL, 0) < 0 && errno == ENODATA); + CHECK(close(fd) == 0 && unlink(path) == 0); + CHECK(setxattr(dir, default_acl, &reader_acl, sizeof(reader_acl), 0) == 0); + mode_t old_umask = umask(077); + fd = open(inherited, O_CREAT | O_EXCL | O_RDWR, 0666); + CHECK(fd >= 0 && close(fd) == 0 && mkdir(subdir, 0777) == 0); + umask(old_umask); + CHECK(getxattr(subdir, default_acl, &readback, sizeof(readback)) == sizeof(readback)); + CHECK(stat(inherited, &metadata) == 0 && (metadata.st_mode & 0777) == 0640); + CHECK(check_access(inherited, 61111, O_RDONLY, 0) == 0); + CHECK(unlink(inherited) == 0 && rmdir(subdir) == 0 && rmdir(dir) == 0); + return 0; +} + +/* Run only in a disposable guest or private PID namespace. The sender drops + * all privileges and starts a separate session before the broadcast. */ +static int broadcast(void) +{ + CHECK(setsid() >= 0); + CHECK(setresgid(61111, 61111, 61111) == 0 && setresuid(61111, 61111, 61111) == 0); + sigset_t blocked; + sigemptyset(&blocked); + sigaddset(&blocked, SIGUSR1); + CHECK(sigprocmask(SIG_BLOCK, &blocked, NULL) == 0); + pid_t child = fork(); + CHECK(child >= 0); + if (!child) { + siginfo_t info; + alarm(10); + CHECK(sigwaitinfo(&blocked, &info) == SIGUSR1); + CHECK(info.si_pid == getppid() && info.si_uid == 61111 && info.si_code == SI_USER); + return 0; + } + int status; + CHECK(kill(-1, SIGSTOP) == 0); + CHECK(waitpid(child, &status, WUNTRACED) == child && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP); + CHECK(kill(-1, SIGCONT) == 0); + CHECK(kill(-1, SIGUSR1) == 0); + CHECK(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); + CHECK(sigpending(&blocked) == 0 && !sigismember(&blocked, SIGUSR1)); + return 0; +} + +int main(void) +{ + int failures = 0; + struct { const char *name; int (*run)(void); } probes[] = { + {"kmsg", kmsg}, {"ext ACL", acl}, {"kill broadcast", broadcast}, + }; + for (size_t i = 0; i < sizeof(probes) / sizeof(probes[0]); ++i) { + pid_t child = fork(); + if (!child) { alarm(15); _exit(probes[i].run()); } + int status; + int failed = child < 0 || waitpid(child, &status, 0) != child || + !WIFEXITED(status) || WEXITSTATUS(status) != 0; + printf("[systemd-compat] %s %s\n", probes[i].name, failed ? "FAIL" : "PASS"); + failures += failed; + } + printf("[systemd-compat] failures=%d\n", failures); + return failures != 0; +} diff --git a/tools/tests/task8_epoll_user_test.c b/tools/tests/task8_epoll_user_test.c index 37463d6d..a7be5dd1 100644 --- a/tools/tests/task8_epoll_user_test.c +++ b/tools/tests/task8_epoll_user_test.c @@ -7,6 +7,7 @@ #include #include #include "../../kernel/syscall/event/epoll.c" +#include "modules/kmsg.h" #include static struct task current; static struct epoll_event output[2]; diff --git a/tools/tests/task8_host_stubs/descriptor_unreached.c b/tools/tests/task8_host_stubs/descriptor_unreached.c index e7d6482c..feb42d6f 100644 --- a/tools/tests/task8_host_stubs/descriptor_unreached.c +++ b/tools/tests/task8_host_stubs/descriptor_unreached.c @@ -39,5 +39,6 @@ UNREACHED(devpts_slave_pty) UNREACHED(devpts_resolve_ptmx) UNREACHED(devpts_new_pty) UNREACHED(task_pidfd_poll) +UNREACHED(task_pidfd_install) UNREACHED(address_space_user_page_copyable) UNREACHED(task_pipe_try_io) diff --git a/tools/tests/vt_console_test.c b/tools/tests/vt_console_test.c index 103599ee..5c789800 100644 --- a/tools/tests/vt_console_test.c +++ b/tools/tests/vt_console_test.c @@ -67,6 +67,10 @@ void vga_putc(char c) { (void)c; } uint64_t time_uptime_us(void) { return 0; } uint64_t kernel_irq_save(void) { return 0; } void kernel_irq_restore(uint64_t flags) { (void)flags; } +void kernel_spin_lock_irqsave(struct kernel_spinlock *lock, uint64_t *flags) +{ assert(!lock->state); lock->state=1; *flags=0; } +void kernel_spin_unlock_irqrestore(struct kernel_spinlock *lock, uint64_t flags) +{ (void)flags; assert(lock->state); lock->state=0; } uint32_t smp_current_cpu(void) { return 0; } uint32_t smp_cpu_count(void) { return 1; } void smp_membarrier_poll(void) {} From 12a162041b868bc39fa7bdc12102916b6ea36deb Mon Sep 17 00:00:00 2001 From: VasilyZa <450270247@qq.com> Date: Thu, 3 Dec 2026 16:19:40 +0800 Subject: [PATCH 2/2] fix(ci): update IRQ and cgroup host test fixtures --- tools/tests/cgroup_scheduler_test.c | 5 +---- tools/tests/keyboard_irq_ready_test.c | 6 +++++- tools/tests/ps2_interleaved_irq_test.c | 2 ++ 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/tools/tests/cgroup_scheduler_test.c b/tools/tests/cgroup_scheduler_test.c index de115c09..fe621fbc 100644 --- a/tools/tests/cgroup_scheduler_test.c +++ b/tools/tests/cgroup_scheduler_test.c @@ -76,12 +76,9 @@ void fsnotify_delete(const struct fsnotify_key *key) { (void)key; abort(); } /** @brief Create and pin a child through the mounted cgroup backend. */ static struct vfs_path make_group(const struct vfs_path *parent, const char *name) { - struct storage_node node = {0}; const struct reliefos_permissions mode = {.mode = 0755}; struct vfs_path path; - assert(!parent->mount->ops->create_node(parent->mount->context, vfs_path_node(parent), - name, LINUX_S_IFDIR, &mode, NULL, &node, NULL)); - assert(!vfs_path_lookup_child(parent, name, &path)); + assert(!vfs_path_create_node(parent, name, LINUX_S_IFDIR, &mode, NULL, &path)); return path; } diff --git a/tools/tests/keyboard_irq_ready_test.c b/tools/tests/keyboard_irq_ready_test.c index 4e5a971c..cf944d2a 100644 --- a/tools/tests/keyboard_irq_ready_test.c +++ b/tools/tests/keyboard_irq_ready_test.c @@ -8,6 +8,7 @@ static uint8_t controller_status, controller_byte; static unsigned data_reads, input_events, eois; static unsigned apic_eois, timer_entries, timer_pic_eois, timer_apic_eois; static unsigned frame_entries, local_ticks, global_ticks; +static unsigned kmsg_notifications; static uint32_t fixture_cpu; static uint8_t last_key, last_pressed; @@ -33,6 +34,8 @@ void time_on_tick(void) { ++global_ticks; } /* No COM1 is present in this fixture. */ void serial_tx_tick(void) {} void serial_tx_irq(void) { assert(0 && "unexpected COM1 interrupt"); } +/** @brief Count kernel log notifications from the global timer. */ +void kmsg_notify_readers(void) { ++kmsg_notifications; } uint64_t time_uptime_us(void) { return 0; } uint8_t input_caps_lock_active(void) { return 0; } struct task *userland_schedule_from_frame(struct trap_frame *frame) @@ -93,9 +96,10 @@ int main(void) assert(irq_dispatch(&frame) == NULL && local_ticks == 2); fixture_cpu = 1; assert(irq_dispatch(&frame) == NULL && local_ticks == 3); - assert(!global_ticks && timer_entries == saved_timers + 2); + assert(!global_ticks && !kmsg_notifications && timer_entries == saved_timers + 2); fixture_cpu = 0; frame.vector = 0x20; keyboard_led.applied = 0; assert(irq_dispatch(&frame) == NULL && global_ticks == 1); + assert(kmsg_notifications == 1); puts("PASS local preemption on BSP/AP: no extra public clock ticks"); puts("PASS IRQ1: no empty/AUX read, real key make/break and ACK handling preserved"); puts("PASS reschedule IRQ: LAPIC EOI, deferred kernel return, user scheduling without timer accounting"); diff --git a/tools/tests/ps2_interleaved_irq_test.c b/tools/tests/ps2_interleaved_irq_test.c index 62a02dcc..210a080f 100644 --- a/tools/tests/ps2_interleaved_irq_test.c +++ b/tools/tests/ps2_interleaved_irq_test.c @@ -73,6 +73,8 @@ void time_on_tick(void) {} /* No COM1 is present in this fixture. */ void serial_tx_tick(void) {} void serial_tx_irq(void) { assert(0 && "unexpected COM1 interrupt"); } +/** @brief Reject timer-only notifications during keyboard and mouse interrupts. */ +void kmsg_notify_readers(void) { assert(0 && "unexpected kernel log notification"); } uint64_t time_uptime_us(void) { return 0; } uint8_t input_caps_lock_active(void) { return 0; } struct task *userland_schedule_from_frame(struct trap_frame *frame)