forge
Explore
Log in

Don't you dare go Hollow

`niri_ipc::Socket`; `niri msg version`; version checking on IPC (#278)

Browse files at this commit

b5f7e4bd83dbfc77e0c8b973bc217c9a4cb3f364Unverifiedsodiboo and Ivan MolodetskikhParent: b98b958
* Implement version checking in IPC

implement version checking; streamed IPC

streamed IPC will allow multiple requests per connection

add nonsense request

change inline struct to json macro

only check version if request actually fails

fix usage of inspect_err (MSRV 1.72.0; stabilized 1.76.0)

"nonsense request" -> "return error"

oneshot connections

* Change some things around

* Unqualify niri_ipc::Transform

---------
Cargo.lockmodified+1 -0
@@ -2202,6 +2202,7 @@ version = "0.1.4"
2202 dependencies = [2202 dependencies = [
2203 "clap",2203 "clap",
2204 "serde",2204 "serde",
2205+ "serde_json",
2205 ]2206 ]
2206 2207
2207 [[package]]2208 [[package]]
Cargo.tomlmodified+2 -1
@@ -14,6 +14,7 @@ anyhow = "1.0.81"
14 bitflags = "2.5.0"14 bitflags = "2.5.0"
15 clap = { version = "~4.4.18", features = ["derive"] }15 clap = { version = "~4.4.18", features = ["derive"] }
16 serde = { version = "1.0.197", features = ["derive"] }16 serde = { version = "1.0.197", features = ["derive"] }
17+serde_json = "1.0.115"
17 tracing = { version = "0.1.40", features = ["max_level_trace", "release_max_level_debug"] }18 tracing = { version = "0.1.40", features = ["max_level_trace", "release_max_level_debug"] }
18 tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }19 tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
19 tracy-client = { version = "0.17.0", default-features = false }20 tracy-client = { version = "0.17.0", default-features = false }
@@ -67,7 +68,7 @@ portable-atomic = { version = "1.6.0", default-features = false, features = ["fl
67 profiling = "1.0.15"68 profiling = "1.0.15"
68 sd-notify = "0.4.1"69 sd-notify = "0.4.1"
69 serde.workspace = true70 serde.workspace = true
70-serde_json = "1.0.115"71+serde_json.workspace = true
71 smithay-drm-extras.workspace = true72 smithay-drm-extras.workspace = true
72 tracing-subscriber.workspace = true73 tracing-subscriber.workspace = true
73 tracing.workspace = true74 tracing.workspace = true
niri-ipc/Cargo.tomlmodified+1 -0
@@ -10,6 +10,7 @@ repository.workspace = true
10 [dependencies]10 [dependencies]
11 clap = { workspace = true, optional = true }11 clap = { workspace = true, optional = true }
12 serde.workspace = true12 serde.workspace = true
13+serde_json.workspace = true
13 14
14 [features]15 [features]
15 clap = ["dep:clap"]16 clap = ["dep:clap"]
niri-ipc/src/lib.rsmodified+8 -2
@@ -6,18 +6,22 @@ use std::str::FromStr;
6 6
7 use serde::{Deserialize, Serialize};7 use serde::{Deserialize, Serialize};
8 8
9-/// Name of the environment variable containing the niri IPC socket path.9+mod socket;
10-pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET";10+pub use socket::{Socket, SOCKET_PATH_ENV};
11 11
12 /// Request from client to niri.12 /// Request from client to niri.
13 #[derive(Debug, Serialize, Deserialize, Clone)]13 #[derive(Debug, Serialize, Deserialize, Clone)]
14 pub enum Request {14 pub enum Request {
15+ /// Request the version string for the running niri instance.
16+ Version,
15 /// Request information about connected outputs.17 /// Request information about connected outputs.
16 Outputs,18 Outputs,
17 /// Request information about the focused window.19 /// Request information about the focused window.
18 FocusedWindow,20 FocusedWindow,
19 /// Perform an action.21 /// Perform an action.
20 Action(Action),22 Action(Action),
23+ /// Respond with an error (for testing error handling).
24+ ReturnError,
21 }25 }
22 26
23 /// Reply from niri to client.27 /// Reply from niri to client.
@@ -35,6 +39,8 @@ pub type Reply = Result<Response, String>;
35 pub enum Response {39 pub enum Response {
36 /// A request that does not need a response was handled successfully.40 /// A request that does not need a response was handled successfully.
37 Handled,41 Handled,
42+ /// The version string for the running niri instance.
43+ Version(String),
38 /// Information about connected outputs.44 /// Information about connected outputs.
39 ///45 ///
40 /// Map from connector name to output info.46 /// Map from connector name to output info.
niri-ipc/src/socket.rsadded+63 -0
@@ -0,0 +1,63 @@
1+//! Helper for blocking communication over the niri socket.
2+
3+use std::env;
4+use std::io::{self, Read, Write};
5+use std::net::Shutdown;
6+use std::os::unix::net::UnixStream;
7+use std::path::Path;
8+
9+use crate::{Reply, Request};
10+
11+/// Name of the environment variable containing the niri IPC socket path.
12+pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET";
13+
14+/// Helper for blocking communication over the niri socket.
15+///
16+/// This struct is used to communicate with the niri IPC server. It handles the socket connection
17+/// and serialization/deserialization of messages.
18+pub struct Socket {
19+ stream: UnixStream,
20+}
21+
22+impl Socket {
23+ /// Connects to the default niri IPC socket.
24+ ///
25+ /// This is equivalent to calling [`Self::connect_to`] with the path taken from the
26+ /// [`SOCKET_PATH_ENV`] environment variable.
27+ pub fn connect() -> io::Result<Self> {
28+ let socket_path = env::var_os(SOCKET_PATH_ENV).ok_or_else(|| {
29+ io::Error::new(
30+ io::ErrorKind::NotFound,
31+ format!("{SOCKET_PATH_ENV} is not set, are you running this within niri?"),
32+ )
33+ })?;
34+ Self::connect_to(socket_path)
35+ }
36+
37+ /// Connects to the niri IPC socket at the given path.
38+ pub fn connect_to(path: impl AsRef<Path>) -> io::Result<Self> {
39+ let stream = UnixStream::connect(path.as_ref())?;
40+ Ok(Self { stream })
41+ }
42+
43+ /// Sends a request to niri and returns the response.
44+ ///
45+ /// Return values:
46+ ///
47+ /// * `Ok(Ok(response))`: successful [`Response`](crate::Response) from niri
48+ /// * `Ok(Err(message))`: error message from niri
49+ /// * `Err(error)`: error communicating with niri
50+ pub fn send(self, request: Request) -> io::Result<Reply> {
51+ let Self { mut stream } = self;
52+
53+ let mut buf = serde_json::to_vec(&request).unwrap();
54+ stream.write_all(&buf)?;
55+ stream.shutdown(Shutdown::Write)?;
56+
57+ buf.clear();
58+ stream.read_to_end(&mut buf)?;
59+
60+ let reply = serde_json::from_slice(&buf)?;
61+ Ok(reply)
62+ }
63+}
src/cli.rsmodified+4 -0
@@ -52,6 +52,8 @@ pub enum Sub {
52 52
53 #[derive(Subcommand)]53 #[derive(Subcommand)]
54 pub enum Msg {54 pub enum Msg {
55+ /// Print the version of the running niri instance.
56+ Version,
55 /// List connected outputs.57 /// List connected outputs.
56 Outputs,58 Outputs,
57 /// Print information about the focused window.59 /// Print information about the focused window.
@@ -61,4 +63,6 @@ pub enum Msg {
61 #[command(subcommand)]63 #[command(subcommand)]
62 action: Action,64 action: Action,
63 },65 },
66+ /// Request an error from the running niri instance.
67+ RequestError,
64 }68 }
src/ipc/client.rsmodified+84 -43
@@ -1,54 +1,99 @@
1-use std::env;
2-use std::io::{Read, Write};
3-use std::net::Shutdown;
4-use std::os::unix::net::UnixStream;
5-
6 use anyhow::{anyhow, bail, Context};1 use anyhow::{anyhow, bail, Context};
7-use niri_ipc::{LogicalOutput, Mode, Output, Reply, Request, Response};2+use niri_ipc::{LogicalOutput, Mode, Output, Request, Response, Socket, Transform};
3+use serde_json::json;
8 4
9 use crate::cli::Msg;5 use crate::cli::Msg;
6+use crate::utils::version;
10 7
11 pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {8 pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
12- let socket_path = env::var_os(niri_ipc::SOCKET_PATH_ENV).with_context(|| {
13- format!(
14- "{} is not set, are you running this within niri?",
15- niri_ipc::SOCKET_PATH_ENV
16- )
17- })?;
18-
19- let mut stream =
20- UnixStream::connect(socket_path).context("error connecting to {socket_path}")?;
21-
22 let request = match &msg {9 let request = match &msg {
10+ Msg::Version => Request::Version,
23 Msg::Outputs => Request::Outputs,11 Msg::Outputs => Request::Outputs,
24 Msg::FocusedWindow => Request::FocusedWindow,12 Msg::FocusedWindow => Request::FocusedWindow,
25 Msg::Action { action } => Request::Action(action.clone()),13 Msg::Action { action } => Request::Action(action.clone()),
14+ Msg::RequestError => Request::ReturnError,
26 };15 };
27- let mut buf = serde_json::to_vec(&request).unwrap();
28- stream
29- .write_all(&buf)
30- .context("error writing IPC request")?;
31- stream
32- .shutdown(Shutdown::Write)
33- .context("error closing IPC stream for writing")?;
34 16
35- buf.clear();17+ let socket = Socket::connect().context("error connecting to the niri socket")?;
36- stream
37- .read_to_end(&mut buf)
38- .context("error reading IPC response")?;
39 18
40- let reply: Reply = serde_json::from_slice(&buf).context("error parsing IPC reply")?;19+ let reply = socket
20+ .send(request)
21+ .context("error communicating with niri")?;
41 22
42- let response = reply23+ let compositor_version = match reply {
43- .map_err(|msg| anyhow!(msg))24+ Err(_) if !matches!(msg, Msg::Version) => {
44- .context("niri could not handle the request")?;25+ // If we got an error, it might be that the CLI is a different version from the running
26+ // niri instance. Request the running instance version to compare and print a message.
27+ Socket::connect()
28+ .and_then(|socket| socket.send(Request::Version))
29+ .ok()
30+ }
31+ _ => None,
32+ };
45 33
46 // Default SIGPIPE so that our prints don't panic on stdout closing.34 // Default SIGPIPE so that our prints don't panic on stdout closing.
47 unsafe {35 unsafe {
48 libc::signal(libc::SIGPIPE, libc::SIG_DFL);36 libc::signal(libc::SIGPIPE, libc::SIG_DFL);
49 }37 }
50 38
39+ let response = reply.map_err(|err_msg| {
40+ // Check for CLI-server version mismatch to add helpful context.
41+ match compositor_version {
42+ Some(Ok(Response::Version(compositor_version))) => {
43+ let cli_version = version();
44+ if cli_version != compositor_version {
45+ eprintln!("Running niri compositor has a different version from the niri CLI:");
46+ eprintln!("Compositor version: {compositor_version}");
47+ eprintln!("CLI version: {cli_version}");
48+ eprintln!("Did you forget to restart niri after an update?");
49+ eprintln!();
50+ }
51+ }
52+ Some(_) => {
53+ eprintln!("Unable to get the running niri compositor version.");
54+ eprintln!("Did you forget to restart niri after an update?");
55+ eprintln!();
56+ }
57+ None => {
58+ // Communication error, or the original request was already a version request.
59+ // Don't add irrelevant context.
60+ }
61+ }
62+
63+ anyhow!(err_msg).context("niri returned an error")
64+ })?;
65+
51 match msg {66 match msg {
67+ Msg::RequestError => {
68+ bail!("unexpected response: expected an error, got {response:?}");
69+ }
70+ Msg::Version => {
71+ let Response::Version(compositor_version) = response else {
72+ bail!("unexpected response: expected Version, got {response:?}");
73+ };
74+
75+ let cli_version = version();
76+
77+ if json {
78+ println!(
79+ "{}",
80+ json!({
81+ "compositor": compositor_version,
82+ "cli": cli_version,
83+ })
84+ );
85+ return Ok(());
86+ }
87+
88+ if cli_version != compositor_version {
89+ eprintln!("Running niri compositor has a different version from the niri CLI.");
90+ eprintln!("Did you forget to restart niri after an update?");
91+ eprintln!();
92+ }
93+
94+ println!("Compositor version: {compositor_version}");
95+ println!("CLI version: {cli_version}");
96+ }
52 Msg::Outputs => {97 Msg::Outputs => {
53 let Response::Outputs(outputs) = response else {98 let Response::Outputs(outputs) = response else {
54 bail!("unexpected response: expected Outputs, got {response:?}");99 bail!("unexpected response: expected Outputs, got {response:?}");
@@ -123,18 +168,14 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
123 println!(" Scale: {scale}");168 println!(" Scale: {scale}");
124 169
125 let transform = match transform {170 let transform = match transform {
126- niri_ipc::Transform::Normal => "normal",171+ Transform::Normal => "normal",
127- niri_ipc::Transform::_90 => "90° counter-clockwise",172+ Transform::_90 => "90° counter-clockwise",
128- niri_ipc::Transform::_180 => "180°",173+ Transform::_180 => "180°",
129- niri_ipc::Transform::_270 => "270° counter-clockwise",174+ Transform::_270 => "270° counter-clockwise",
130- niri_ipc::Transform::Flipped => "flipped horizontally",175+ Transform::Flipped => "flipped horizontally",
131- niri_ipc::Transform::Flipped90 => {176+ Transform::Flipped90 => "90° counter-clockwise, flipped horizontally",
132- "90° counter-clockwise, flipped horizontally"177+ Transform::Flipped180 => "flipped vertically",
133- }178+ Transform::Flipped270 => "270° counter-clockwise, flipped horizontally",
134- niri_ipc::Transform::Flipped180 => "flipped vertically",
135- niri_ipc::Transform::Flipped270 => {
136- "270° counter-clockwise, flipped horizontally"
137- }
138 };179 };
139 println!(" Transform: {transform}");180 println!(" Transform: {transform}");
140 }181 }
src/ipc/server.rsmodified+17 -8
@@ -8,7 +8,7 @@ use calloop::io::Async;
8 use directories::BaseDirs;8 use directories::BaseDirs;
9 use futures_util::io::{AsyncReadExt, BufReader};9 use futures_util::io::{AsyncReadExt, BufReader};
10 use futures_util::{AsyncBufReadExt, AsyncWriteExt};10 use futures_util::{AsyncBufReadExt, AsyncWriteExt};
11-use niri_ipc::{Request, Response};11+use niri_ipc::{Reply, Request, Response};
12 use smithay::desktop::Window;12 use smithay::desktop::Window;
13 use smithay::reexports::calloop::generic::Generic;13 use smithay::reexports::calloop::generic::Generic;
14 use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};14 use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
@@ -18,6 +18,7 @@ use smithay::wayland::shell::xdg::XdgToplevelSurfaceData;
18 18
19 use crate::backend::IpcOutputMap;19 use crate::backend::IpcOutputMap;
20 use crate::niri::State;20 use crate::niri::State;
21+use crate::utils::version;
21 22
22 pub struct IpcServer {23 pub struct IpcServer {
23 pub socket_path: PathBuf,24 pub socket_path: PathBuf,
@@ -114,10 +115,18 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow:
114 .await115 .await
115 .context("error reading request")?;116 .context("error reading request")?;
116 117
117- let reply = process(&ctx, &buf).map_err(|err| {118+ let request = serde_json::from_str(&buf)
118- warn!("error processing IPC request: {err:?}");119+ .context("error parsing request")
119- err.to_string()120+ .map_err(|err| err.to_string());
120- });121+ let requested_error = matches!(request, Ok(Request::ReturnError));
122+
123+ let reply = request.and_then(|request| process(&ctx, request));
124+
125+ if let Err(err) = &reply {
126+ if !requested_error {
127+ warn!("error processing IPC request: {err:?}");
128+ }
129+ }
121 130
122 let buf = serde_json::to_vec(&reply).context("error formatting reply")?;131 let buf = serde_json::to_vec(&reply).context("error formatting reply")?;
123 write.write_all(&buf).await.context("error writing reply")?;132 write.write_all(&buf).await.context("error writing reply")?;
@@ -125,10 +134,10 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow:
125 Ok(())134 Ok(())
126 }135 }
127 136
128-fn process(ctx: &ClientCtx, buf: &str) -> anyhow::Result<Response> {137+fn process(ctx: &ClientCtx, request: Request) -> Reply {
129- let request: Request = serde_json::from_str(buf).context("error parsing request")?;
130-
131 let response = match request {138 let response = match request {
139+ Request::ReturnError => return Err(String::from("example compositor error")),
140+ Request::Version => Response::Version(version()),
132 Request::Outputs => {141 Request::Outputs => {
133 let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone();142 let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone();
134 Response::Outputs(ipc_outputs)143 Response::Outputs(ipc_outputs)