Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:

- name: Format check
continue-on-error: true
run: zig fmt --check src/
run: zig fmt --check src/ zephwm-bar/

- name: Build
run: zig build
Expand Down
135 changes: 128 additions & 7 deletions src/event.zig
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@
fn getWorkspaceOutputName(ws: *tree.Container) []const u8 {
if (ws.parent) |parent| {
if (parent.type == .output) {
if (parent.workspace) |wsd| {
if (wsd.output_name.len > 0) return wsd.output_name;
if (parent.output_data) |od| {
if (od.name.len > 0) return od.name;
}
}
}
Expand Down Expand Up @@ -124,17 +124,17 @@
const response_type = event.response_type & 0x7f; // mask out sent-event bit

switch (response_type) {
xcb.MAP_REQUEST => handleMapRequest(ctx, @ptrCast(event)),

Check warning on line 127 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.MAP_REQUEST => handleMapRequest(ctx, @ptrCast(event)),
xcb.UNMAP_NOTIFY => handleUnmapNotify(ctx, @ptrCast(event)),

Check warning on line 128 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.UNMAP_NOTIFY => handleUnmapNotify(ctx, @ptrCast(event)),
xcb.DESTROY_NOTIFY => handleDestroyNotify(ctx, @ptrCast(event)),

Check warning on line 129 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.DESTROY_NOTIFY => handleDestroyNotify(ctx, @ptrCast(event)),
xcb.KEY_PRESS => handleKeyPress(ctx, @ptrCast(event)),

Check warning on line 130 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.KEY_PRESS => handleKeyPress(ctx, @ptrCast(event)),
xcb.ENTER_NOTIFY => handleEnterNotify(ctx, @ptrCast(event)),

Check warning on line 131 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.ENTER_NOTIFY => handleEnterNotify(ctx, @ptrCast(event)),
xcb.CONFIGURE_REQUEST => handleConfigureRequest(ctx, @ptrCast(event)),

Check warning on line 132 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.CONFIGURE_REQUEST => handleConfigureRequest(ctx, @ptrCast(event)),
xcb.PROPERTY_NOTIFY => handlePropertyNotify(ctx, @ptrCast(event)),

Check warning on line 133 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.PROPERTY_NOTIFY => handlePropertyNotify(ctx, @ptrCast(event)),
xcb.CLIENT_MESSAGE => handleClientMessage(ctx, @ptrCast(event)),

Check warning on line 134 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.CLIENT_MESSAGE => handleClientMessage(ctx, @ptrCast(event)),
xcb.BUTTON_PRESS => handleButtonPress(ctx, @ptrCast(event)),

Check warning on line 135 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.BUTTON_PRESS => handleButtonPress(ctx, @ptrCast(event)),
xcb.c.XCB_BUTTON_RELEASE => handleButtonRelease(ctx),
xcb.c.XCB_MOTION_NOTIFY => handleMotionNotify(ctx, @ptrCast(event)),

Check warning on line 137 in src/event.zig

View workflow job for this annotation

GitHub Actions / security-audit

[Tracked] @ptrCast: xcb.c.XCB_MOTION_NOTIFY => handleMotionNotify(ctx, @ptrCast(event)),
xcb.c.XCB_EXPOSE => handleExpose(ctx, @ptrCast(@alignCast(event))),
xcb.FOCUS_IN => handleFocusIn(ctx, @ptrCast(event)),
xcb.MAPPING_NOTIFY => handleMappingNotify(ctx, event),
Expand Down Expand Up @@ -285,13 +285,49 @@
// Set X11 input focus
if (con.window) |wd| {
_ = xcb.setInputFocus(ctx.conn, xcb.INPUT_FOCUS_POINTER_ROOT, wd.id, xcb.CURRENT_TIME);
// Send WM_TAKE_FOCUS if the window supports it (ICCCM focus protocol)
sendTakeFocus(ctx, wd.id);
updateActiveWindow(ctx, wd.id);
} else {
// No window (e.g. focusing a workspace) — clear active window
updateActiveWindow(ctx, xcb.WINDOW_NONE);
}
}

/// Send WM_TAKE_FOCUS ClientMessage if the window supports it (ICCCM).
fn sendTakeFocus(ctx: *EventContext, window: xcb.Window) void {
// Check if window supports WM_TAKE_FOCUS in WM_PROTOCOLS
const cookie = xcb.getProperty(ctx.conn, 0, window, ctx.atoms.wm_protocols, xcb.ATOM_ATOM, 0, 32);
const reply = xcb.getPropertyReply(ctx.conn, cookie, null) orelse return;
defer std.c.free(reply);

const len = xcb.getPropertyValueLength(reply);
if (len <= 0) return;
const ptr = xcb.getPropertyValue(reply) orelse return;
const atoms_list: [*]const xcb.Atom = @ptrCast(@alignCast(ptr));
const count: usize = @intCast(@divTrunc(len, 4));

var supports_take_focus = false;
for (atoms_list[0..count]) |atom| {
if (atom == ctx.atoms.wm_take_focus) {
supports_take_focus = true;
break;
}
}
if (!supports_take_focus) return;

// Send WM_TAKE_FOCUS client message
var event_data: xcb.c.xcb_client_message_event_t = std.mem.zeroes(xcb.c.xcb_client_message_event_t);
event_data.response_type = xcb.CLIENT_MESSAGE;
event_data.format = 32;
event_data.window = window;
event_data.type = ctx.atoms.wm_protocols;
event_data.data.data32[0] = ctx.atoms.wm_take_focus;
event_data.data.data32[1] = xcb.CURRENT_TIME;

_ = xcb.sendEvent(ctx.conn, 0, window, xcb.EVENT_MASK_NO_EVENT, @ptrCast(&event_data));
}

/// Clear is_focused along the currently focused path only. O(depth).
fn clearFocusedPath(root: *tree.Container) void {
var con = root;
Expand Down Expand Up @@ -446,11 +482,11 @@
/// Collect all managed window IDs and set _NET_CLIENT_LIST on the root window.
pub fn updateClientList(ctx: *EventContext) void {
// Build client list from window_map (O(n) where n = managed windows, no tree walk)
var ids: [1024]u32 = undefined;
var ids: [4096]u32 = undefined;
var count: usize = 0;
var iter = ctx.window_map.iterator();
while (iter.next()) |entry| {
if (count >= 1024) break;
if (count >= ids.len) break;
const con = entry.value_ptr.*;
const wd = con.window orelse continue;
if (entry.key_ptr.* != wd.id) continue; // skip frame_id entries
Expand Down Expand Up @@ -666,6 +702,8 @@
window_type: []const u8 = "",
window_role: []const u8 = "",
should_float: bool = false,
min_w: u32 = 0,
min_h: u32 = 0,
};

/// Read all window properties in a single batched roundtrip.
Expand All @@ -680,6 +718,7 @@
const transient_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_TRANSIENT_FOR, xcb.ATOM_WINDOW, 0, 1);
const type_cookie = xcb.getProperty(conn, 0, window, atoms.net_wm_window_type, xcb.ATOM_ATOM, 0, 32);
const role_cookie = xcb.getProperty(conn, 0, window, atoms.wm_window_role, xcb.ATOM_STRING, 0, 256);
const hints_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_NORMAL_HINTS, xcb.ATOM_WM_SIZE_HINTS, 0, 18);

var props = BatchedWindowProps{};

Expand Down Expand Up @@ -799,6 +838,24 @@
}
}

// 6. WM_NORMAL_HINTS — extract minimum size constraints
if (xcb.getPropertyReply(conn, hints_cookie, null)) |reply| {
defer std.c.free(reply);
const len = xcb.getPropertyValueLength(reply);
// WM_SIZE_HINTS: flags at offset 0, min_width at offset 5, min_height at offset 6 (u32 units)
if (len >= 7 * 4) {
if (xcb.getPropertyValue(reply)) |ptr| {
const vals: [*]const u32 = @ptrCast(@alignCast(ptr));
const flags = vals[0];
const PMinSize: u32 = (1 << 4); // ICCCM PMinSize flag
if (flags & PMinSize != 0) {
props.min_w = vals[5];
props.min_h = vals[6];
}
}
}
}

return props;
}

Expand Down Expand Up @@ -892,6 +949,8 @@
.window_role = props.window_role,
.transient_for = props.transient_for,
.pending_unmap = 0, // Window is unmapped at MapRequest time; reparent of unmapped window does not generate UnmapNotify
.min_w = props.min_w,
.min_h = props.min_h,
};
con.is_floating = props.should_float;
// Apply default border style from config
Expand Down Expand Up @@ -1668,7 +1727,62 @@

// --- Command execution ---

/// Collect window IDs of containers matching criteria (max 64). Walks tree depth-first.
/// Uses window IDs instead of raw pointers so commands that destroy/move containers
/// don't cause dangling pointer access.
fn collectMatchingWindowIds(root: *tree.Container, crit: *const criteria.Criteria, out: *[64]xcb.Window) usize {
var count: usize = 0;
collectMatchingWindowIdsRecursive(root, crit, out, &count);
return count;
}

fn collectMatchingWindowIdsRecursive(con: *tree.Container, crit: *const criteria.Criteria, out: *[64]xcb.Window, count: *usize) void {
if (count.* >= 64) return;
if (criteria.matches(crit, con)) {
if (con.window) |wd| {
out[count.*] = wd.id;
count.* += 1;
}
}
var cur = con.children.first;
while (cur) |child| : (cur = child.next) {
collectMatchingWindowIdsRecursive(child, crit, out, count);
}
}

pub fn executeCommand(ctx: *EventContext, cmd: command_mod.Command) void {
// If command has criteria, execute on all matching containers instead of focused
if (cmd.criteria) |crit| {
var window_ids: [64]xcb.Window = undefined;
const match_count = collectMatchingWindowIds(ctx.tree_root, &crit, &window_ids);
if (match_count == 0) return;

// Save original focused window ID for restoration
const original_focused_wid: ?xcb.Window = if (getFocusedContainer(ctx.tree_root)) |fc|
(if (fc.window) |wd| wd.id else null)
else
null;

for (window_ids[0..match_count]) |wid| {
// Re-resolve container from window ID — it may have been destroyed by a prior command
const target = findContainerByWindow(ctx, wid) orelse continue;
setFocus(ctx, target);
var cmd_no_crit = cmd;
cmd_no_crit.criteria = null;
executeCommand(ctx, cmd_no_crit);
}
// Restore original focus only if the original window still exists and
// the command was not a focus command (i3 behavior: [criteria] focus keeps new focus)
if (cmd.type != .focus) {
if (original_focused_wid) |wid| {
if (findContainerByWindow(ctx, wid)) |orig| {
setFocus(ctx, orig);
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return;
}

switch (cmd.type) {
.split => executeSplit(ctx, cmd),
.focus => executeFocus(ctx, cmd),
Expand Down Expand Up @@ -2203,6 +2317,8 @@

fn executeFloating(ctx: *EventContext) void {
const focused = getFocusedContainer(ctx.tree_root) orelse return;
// Only windows and split_cons can float — workspaces/outputs/root cannot
if (focused.type != .window and focused.type != .split_con) return;
focused.is_floating = !focused.is_floating;
focused.markDirtyToWorkspace();
relayoutAndRender(ctx);
Expand Down Expand Up @@ -2283,6 +2399,8 @@

fn executeFullscreen(ctx: *EventContext) void {
const focused = getFocusedContainer(ctx.tree_root) orelse return;
// Only windows can be fullscreened
if (focused.type != .window) return;
focused.is_fullscreen = if (focused.is_fullscreen != .none) .none else .window;
focused.markDirtyToWorkspace();

Expand Down Expand Up @@ -2539,10 +2657,13 @@
target_out.appendChild(current_ws);
current_ws.rect = target_out.rect;

// Update workspace output_name to match target output
// Update workspace output_name to match target output (must dupe to avoid aliased ownership)
if (current_ws.workspace) |*wsd| {
if (target_out.workspace) |tout_wsd| {
wsd.output_name = tout_wsd.output_name;
if (target_out.output_data) |od| {
if (ctx.allocator.dupe(u8, od.name)) |new_name| {
if (wsd.output_name.len > 0) ctx.allocator.free(wsd.output_name);
wsd.output_name = new_name;
} else |_| {} // OOM: keep old output_name rather than aliasing
}
}

Expand Down
17 changes: 11 additions & 6 deletions src/ipc.zig
Original file line number Diff line number Diff line change
Expand Up @@ -133,15 +133,20 @@ pub fn acceptClient(listen_fd: std.posix.fd_t) !std.posix.fd_t {

/// Read a complete message from client fd into buf.
/// Returns msg_type + payload slice, or null if EOF/disconnect.
/// Returns error.WouldBlock if no data available yet (EAGAIN).
/// Returns error.WouldBlock if no data available yet (EAGAIN) AND no bytes have been read.
/// If partial data was consumed and WouldBlock occurs, returns null (disconnect) to avoid
/// busy-looping on the single-threaded event loop.
pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { msg_type: u32, payload: []const u8 } {
if (buf.len < HEADER_SIZE) return null;

// Read header
var total_read: usize = 0;
while (total_read < HEADER_SIZE) {
const n = std.posix.read(fd, buf[total_read..]) catch |err| {
if (err == error.WouldBlock) return error.WouldBlock;
if (err == error.WouldBlock) {
if (total_read == 0) return error.WouldBlock;
return null; // Partial header + WouldBlock: drop client to avoid busy-loop
}
Comment on lines +146 to +149

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using continue when error.WouldBlock is encountered after partial data has been read creates a busy loop. Since the window manager is single-threaded, this will consume 100% CPU and hang the entire WM if a client sends a partial message (e.g., just the header) and then stalls. This is a potential Denial of Service (DoS) vector.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return null;
};
if (n == 0) return null; // EOF
Expand All @@ -155,10 +160,10 @@ pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { ms
const total_needed = HEADER_SIZE + payload_len;
if (buf.len < total_needed) return null;

// Read payload
// Read payload — once header is read, we must complete the message
while (total_read < total_needed) {
const n = std.posix.read(fd, buf[total_read..total_needed]) catch |err| {
if (err == error.WouldBlock) return error.WouldBlock;
if (err == error.WouldBlock) return null; // Partial payload: drop client to avoid busy-loop

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve partial IPC reads instead of closing the client

This branch treats error.WouldBlock after a partial payload read as a disconnect, but IPC sockets are stream-based and non-blocking reads can legitimately return partial frames. If a client’s header/payload arrives across multiple writes (or a short read happens), the server will close a healthy connection mid-message and drop the request, causing intermittent IPC failures for valid clients.

Useful? React with 👍 / 👎.

return null;
};
if (n == 0) return null;
Expand Down Expand Up @@ -203,10 +208,10 @@ pub fn sendRequest(allocator: std.mem.Allocator, sock_path: []const u8, msg_type
const fd = connectToServer(sock_path) catch return null;
defer std.posix.close(fd);

// Send
// Send (use writeAll to handle partial writes correctly)
var send_buf: [4096 + HEADER_SIZE]u8 = undefined;
const msg = encode(msg_type, payload, &send_buf);
_ = std.posix.write(fd, msg) catch return null;
writeAll(fd, msg) catch return null;

// Read response
var recv_buf: [65536]u8 = undefined;
Expand Down
2 changes: 1 addition & 1 deletion src/layout.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const log = std.log.scoped(.layout);
const tree = @import("tree.zig");
const render = @import("render.zig");

const MAX_TILING_CHILDREN: usize = 64;
const MAX_TILING_CHILDREN: usize = 256;

/// Apply layout to a container's children. Recursively descends into split_con children.
/// gap: pixel gap between windows
Expand Down
Loading
Loading