From 99e447898bc02dedabd7a27f8b7de66cce0b1553 Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Mon, 29 Jul 2024 16:50:59 -0500 Subject: [PATCH] tighten up systemd launch check --- src/os/systemd.zig | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/src/os/systemd.zig b/src/os/systemd.zig index 5aeffdc24..ca5ebc06b 100644 --- a/src/os/systemd.zig +++ b/src/os/systemd.zig @@ -39,20 +39,43 @@ pub fn launchedBySystemd() bool { // a user systemd daemon. Do that by checking the `/proc//exe` symlink // to see if it ends with `/systemd`. - var path_buf: [std.fs.max_path_bytes]u8 = undefined; - const path = std.fmt.bufPrint(&path_buf, "/proc/{d}/exe", .{ppid}) catch { - log.err("unable to format path to exe {d}", .{ppid}); + var exe_path_buf: [std.fs.max_path_bytes]u8 = undefined; + const exe_path = std.fmt.bufPrint(&exe_path_buf, "/proc/{d}/exe", .{ppid}) catch { + log.err("unable to format path to exe for pid {d}", .{ppid}); break :linux false; }; - var link_buf: [std.fs.max_path_bytes]u8 = undefined; - const link = std.fs.readLinkAbsolute(path, &link_buf) catch { - log.err("unable to read link '{s}'", .{path}); + var exe_link_buf: [std.fs.max_path_bytes]u8 = undefined; + const exe_link = std.fs.readLinkAbsolute(exe_path, &exe_link_buf) catch { + log.err("unable to read link '{s}'", .{exe_path}); + // Some systems prohibit access to /proc//exe for some - // reason so don't fail if we can't read the link. - break :linux true; + // reason so fall back to reading /proc//comm and see if it + // is equal to "systemd". + + var comm_path_buf: [std.fs.max_path_bytes]u8 = undefined; + const comm_path = std.fmt.bufPrint(&comm_path_buf, "/proc/{d}/comm", .{ppid}) catch { + log.err("unable to format comm path for pid {d}", .{ppid}); + break :linux false; + }; + const comm_file = std.fs.openFileAbsolute(comm_path, .{ .mode = .read_only }) catch { + log.err("unable to open '{s}' for reading", .{comm_path}); + break :linux false; + }; + defer comm_file.close(); + + var comm_data_buf: [std.fs.MAX_NAME_BYTES]u8 = undefined; + const comm_size = comm_file.readAll(&comm_data_buf) catch { + log.err("problems reading from '{s}'", .{comm_path}); + break :linux false; + }; + const comm_data = comm_data_buf[0..comm_size]; + + if (std.mem.eql(u8, comm_data, "systemd")) break :linux true; + + break :linux false; }; - if (std.mem.endsWith(u8, link, "/systemd")) break :linux true; + if (std.mem.endsWith(u8, exe_link, "/systemd")) break :linux true; break :linux false; },