1use std::{
8 env,
9 ffi::OsString,
10 io::Write,
11 path::{Path, PathBuf},
12 process::{Command, Stdio},
13};
14
15use razers_ipc::{
16 DeviceList, JSON_RPC_VERSION, METHOD_DEVICES_LIST, PROTOCOL_VERSION, Request, Response,
17 ResponseResult,
18};
19use serde_json::json;
20
21#[derive(Clone, Debug)]
24pub struct DiscoveryError {
25 pub message: &'static str,
26 pub detail: String,
27}
28impl DiscoveryError {
29 fn new(message: &'static str, detail: impl std::fmt::Display) -> Self {
30 Self {
31 message,
32 detail: detail.to_string(),
33 }
34 }
35}
36impl std::fmt::Display for DiscoveryError {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 write!(f, "{} {}", self.message, self.detail)
39 }
40}
41impl std::error::Error for DiscoveryError {}
42
43pub fn discover_via_agent() -> Result<DeviceList, DiscoveryError> {
47 let current_executable = env::current_exe()
48 .map_err(|error| DiscoveryError::new("Unable to locate the RazeRS executable.", error))?;
49 let (program, arguments) = agent_command(¤t_executable);
50 request_devices(program, &arguments)
51}
52
53fn agent_command(current_executable: &Path) -> (PathBuf, Vec<OsString>) {
54 let executable_name = if cfg!(windows) {
55 "razers-agent.exe"
56 } else {
57 "razers-agent"
58 };
59 let sibling = current_executable.with_file_name(executable_name);
60 if sibling.is_file() {
61 (sibling, vec!["--stdio".into()])
62 } else {
63 (
64 current_executable.to_path_buf(),
65 vec!["--agent-stdio".into()],
66 )
67 }
68}
69
70fn request_devices(program: PathBuf, arguments: &[OsString]) -> Result<DeviceList, DiscoveryError> {
71 let mut child = Command::new(&program)
72 .args(arguments)
73 .stdin(Stdio::piped())
74 .stdout(Stdio::piped())
75 .stderr(Stdio::piped())
76 .spawn()
77 .map_err(|error| DiscoveryError::new("Unable to start the local RazeRS Agent.", error))?;
78 let request = Request::new(METHOD_DEVICES_LIST, json!(1));
79 let mut input = child
80 .stdin
81 .take()
82 .ok_or_else(|| DiscoveryError::new("Unable to open the local RazeRS Agent input.", ""))?;
83 serde_json::to_writer(&mut input, &request)
84 .map_err(|error| DiscoveryError::new("Unable to encode the Agent request.", error))?;
85 input
86 .write_all(b"\n")
87 .map_err(|error| DiscoveryError::new("Unable to send the Agent request.", error))?;
88 drop(input);
89
90 let output = child.wait_with_output().map_err(|error| {
91 DiscoveryError::new("Unable to wait for the local RazeRS Agent.", error)
92 })?;
93 if !output.status.success() {
94 let detail = String::from_utf8_lossy(&output.stderr).trim().to_owned();
95 return Err(DiscoveryError::new(
96 "The local RazeRS Agent stopped unexpectedly.",
97 detail,
98 ));
99 }
100 decode_device_response(&output.stdout)
101}
102
103fn decode_device_response(encoded: &[u8]) -> Result<DeviceList, DiscoveryError> {
104 let response: Response = serde_json::from_slice(encoded).map_err(|error| {
105 DiscoveryError::new("The local RazeRS Agent returned invalid data.", error)
106 })?;
107 if response.jsonrpc != JSON_RPC_VERSION || response.id != json!(1) {
108 return Err(DiscoveryError::new(
109 "The local RazeRS Agent returned a mismatched response.",
110 "",
111 ));
112 }
113 if let Some(error) = response.error {
114 let message = match error.code {
115 razers_ipc::ERROR_PROTOCOL_VERSION => {
116 "The local RazeRS Agent uses an incompatible protocol version."
117 }
118 razers_ipc::ERROR_INTERNAL => "Device discovery failed.",
119 _ => "Agent request failed.",
120 };
121 return Err(DiscoveryError::new(
122 message,
123 format!(
124 "{} ({}) {}",
125 error.message,
126 error.code,
127 error.data.unwrap_or_default()
128 ),
129 ));
130 }
131 match response.result {
132 Some(ResponseResult::DeviceList(devices))
133 if devices.protocol_version == PROTOCOL_VERSION =>
134 {
135 Ok(devices)
136 }
137 Some(ResponseResult::DeviceList(_)) => Err(DiscoveryError::new(
138 "The local RazeRS Agent uses an incompatible protocol version.",
139 "",
140 )),
141 Some(ResponseResult::AgentInfo(_)) | None => Err(DiscoveryError::new(
142 "The local RazeRS Agent returned an unexpected result.",
143 "",
144 )),
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use razers_ipc::{DeviceSummary, Response};
151
152 use super::*;
153
154 #[test]
155 fn decodes_a_versioned_device_response() {
156 let response = Response::success(
157 json!(1),
158 ResponseResult::DeviceList(DeviceList {
159 protocol_version: PROTOCOL_VERSION,
160 devices: vec![DeviceSummary {
161 display_name: "Razer Test Mouse".into(),
162 vid: 0x1532,
163 pid: 1,
164 interface_count: 2,
165 vendor_interface_count: 1,
166 support_label: "Detected".into(),
167 support_detail: "Read-only".into(),
168 capabilities: vec!["DPI".into()],
169 evidence_label: "Recorded".into(),
170 evidence_source_count: None,
171 control_available: false,
172 }],
173 interface_count: 2,
174 }),
175 );
176
177 let decoded = decode_device_response(&serde_json::to_vec(&response).unwrap()).unwrap();
178
179 assert_eq!(decoded.devices[0].display_name, "Razer Test Mouse");
180 assert_eq!(decoded.protocol_version, PROTOCOL_VERSION);
181 }
182
183 #[test]
184 fn rejects_error_and_wrong_method_responses() {
185 let error = Response::failure(json!(1), -32603, "Device discovery failed");
186 let wrong_result = Response::success(
187 json!(1),
188 ResponseResult::AgentInfo(razers_ipc::AgentInfo {
189 protocol_version: PROTOCOL_VERSION,
190 agent_version: "0.1.0".into(),
191 access_mode: "descriptor-only".into(),
192 transport: "stdio-child".into(),
193 }),
194 );
195
196 assert!(decode_device_response(&serde_json::to_vec(&error).unwrap()).is_err());
197 assert!(decode_device_response(&serde_json::to_vec(&wrong_result).unwrap()).is_err());
198 }
199
200 #[test]
201 fn rejects_an_incompatible_result_protocol_version() {
202 let response = Response::success(
203 json!(1),
204 ResponseResult::DeviceList(DeviceList {
205 protocol_version: PROTOCOL_VERSION + 1,
206 devices: Vec::new(),
207 interface_count: 0,
208 }),
209 );
210
211 let error = decode_device_response(&serde_json::to_vec(&response).unwrap()).unwrap_err();
212
213 assert!(error.message.contains("incompatible protocol version"));
214 }
215
216 #[test]
217 fn falls_back_to_the_app_when_a_sibling_agent_is_missing() {
218 let temporary =
219 std::env::temp_dir().join(format!("razers-agent-path-test-{}", std::process::id()));
220 let app = temporary.join(if cfg!(windows) {
221 "razers.exe"
222 } else {
223 "razers"
224 });
225
226 let (fallback, fallback_arguments) = agent_command(&app);
227
228 assert_eq!(fallback, app);
229 assert_eq!(fallback_arguments, [OsString::from("--agent-stdio")]);
230 }
231}