From 74f7be728715e164d5b7f174491797ce31206c8d Mon Sep 17 00:00:00 2001 From: Ilia Bozhinov Date: Sun, 19 Jul 2020 14:57:10 +0200 Subject: [PATCH] xwayland: do not allow apps to change focus after wlroots request --- include/xwayland/xwm.h | 1 + xwayland/xwm.c | 22 ++++++++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/include/xwayland/xwm.h b/include/xwayland/xwm.h index a3e7132d..362b4cef 100644 --- a/include/xwayland/xwm.h +++ b/include/xwayland/xwm.h @@ -128,6 +128,7 @@ struct wlr_xwm { #if WLR_HAS_XCB_ERRORS xcb_errors_context_t *errors_context; #endif + unsigned int last_focus_seq; struct wl_listener compositor_new_surface; struct wl_listener compositor_destroy; diff --git a/xwayland/xwm.c b/xwayland/xwm.c index 88f4c3c5..87b9edc1 100644 --- a/xwayland/xwm.c +++ b/xwayland/xwm.c @@ -275,8 +275,9 @@ static void xwm_set_focus_window(struct wlr_xwm *xwm, } else { xwm_send_wm_message(xsurface, &message_data, XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT); - xcb_set_input_focus(xwm->xcb_conn, XCB_INPUT_FOCUS_POINTER_ROOT, - xsurface->window_id, XCB_CURRENT_TIME); + xcb_void_cookie_t cookie = xcb_set_input_focus(xwm->xcb_conn, + XCB_INPUT_FOCUS_POINTER_ROOT, xsurface->window_id, XCB_CURRENT_TIME); + xwm->last_focus_seq = cookie.sequence; } uint32_t values[1]; @@ -1293,6 +1294,16 @@ static void xwm_handle_client_message(struct wlr_xwm *xwm, } } +static bool validate_focus_serial(uint16_t last_focus_seq, uint16_t event_seq) { + uint16_t rev_dist = event_seq - last_focus_seq; + if (rev_dist >= UINT16_MAX / 2) { + // Probably overflow or too old + return false; + } + + return true; +} + static void xwm_handle_focus_in(struct wlr_xwm *xwm, xcb_focus_in_event_t *ev) { // Do not interfere with grabs @@ -1311,10 +1322,13 @@ static void xwm_handle_focus_in(struct wlr_xwm *xwm, // Note: Some applications rely on being able to change focus, for ex. Steam: // https://github.com/swaywm/sway/issues/1865 // Because of that, we allow changing focus between surfaces belonging to the - // same application. + // same application. We must be careful to ignore requests that are too old + // though, because otherwise it may lead to race conditions: + // https://github.com/swaywm/wlroots/issues/2324 struct wlr_xwayland_surface *requested_focus = lookup_surface(xwm, ev->event); if (xwm->focus_surface && requested_focus && - requested_focus->pid == xwm->focus_surface->pid) { + requested_focus->pid == xwm->focus_surface->pid && + validate_focus_serial(xwm->last_focus_seq, ev->sequence)) { xwm_set_focus_window(xwm, requested_focus); } else { xwm_set_focus_window(xwm, xwm->focus_surface);