1use std::collections::BTreeMap;
2use std::process::{Command, Stdio};
3
4use crate::error::Result;
5use crate::models::{
6 MSFHostCheckResult, MSFHostInfo, MSFHostsResult, MSFLoginResult, MSFWorkspaceInfo,
7 MSFWorkspacesResult,
8};
9use crate::msgpack::{decode, encode, MsgValue};
10
11#[derive(Debug, Clone)]
12pub struct MsfRpcClient {
13 host: String,
14 port: u16,
15 ssl: bool,
16 username: String,
17 password: String,
18 token: Option<String>,
19}
20
21impl MsfRpcClient {
22 pub fn new(host: &str, port: u16, username: &str, password: &str, ssl: bool) -> Self {
23 Self {
24 host: host.to_string(),
25 port,
26 ssl,
27 username: username.to_string(),
28 password: password.to_string(),
29 token: None,
30 }
31 }
32
33 pub fn login(&mut self) -> Result<MSFLoginResult> {
34 let url = build_url(&self.host, self.port, self.ssl);
35 let payload = encode(&msg_array(vec![
37 msg_str("auth.login"),
38 msg_str(&self.username),
39 msg_str(&self.password),
40 ]));
41
42 match send_request(&url, &payload, 10) {
43 Ok(val) => {
44 let success = val.get("result").and_then(MsgValue::as_str) == Some("success");
45 let token = val
46 .get("token")
47 .and_then(MsgValue::as_str)
48 .unwrap_or("")
49 .to_string();
50
51 if success && !token.is_empty() {
52 self.token = Some(token.clone());
53 Ok(MSFLoginResult {
54 success: true,
55 token,
56 error: String::new(),
57 })
58 } else {
59 let error_msg = val
60 .get("error_message")
61 .or_else(|| val.get("error_string"))
62 .and_then(MsgValue::as_str)
63 .unwrap_or("Authentication failed");
64 Ok(MSFLoginResult {
65 success: false,
66 token: String::new(),
67 error: error_msg.to_string(),
68 })
69 }
70 }
71 Err(error) => Ok(MSFLoginResult {
72 success: false,
73 token: String::new(),
74 error,
75 }),
76 }
77 }
78
79 pub fn logout(&mut self) {
80 if let Some(token) = self.token.clone() {
81 let url = build_url(&self.host, self.port, self.ssl);
82 let payload = encode(&msg_array(vec![msg_str("auth.logout"), msg_str(&token)]));
84 let _ = send_request(&url, &payload, 5);
85 }
86 self.token = None;
87 }
88
89 pub fn is_authenticated(&self) -> bool {
90 self.token.is_some()
91 }
92
93 pub fn get_workspaces(&self) -> Result<MSFWorkspacesResult> {
94 let token = match self.token.as_ref() {
95 Some(token) => token.clone(),
96 None => {
97 return Ok(MSFWorkspacesResult {
98 workspaces: vec![],
99 error: "Not authenticated".to_string(),
100 });
101 }
102 };
103
104 let url = build_url(&self.host, self.port, self.ssl);
105 let payload = encode(&msg_array(vec![msg_str("db.workspaces"), msg_str(&token)]));
107
108 match send_request(&url, &payload, 15) {
109 Ok(val) => Ok(MSFWorkspacesResult {
110 workspaces: extract_workspaces(&val),
111 error: String::new(),
112 }),
113 Err(error) => Ok(MSFWorkspacesResult {
114 workspaces: vec![],
115 error,
116 }),
117 }
118 }
119
120 pub fn get_hosts(&self, workspace: Option<&str>) -> Result<MSFHostsResult> {
121 let token = match self.token.as_ref() {
122 Some(token) => token.clone(),
123 None => {
124 return Ok(MSFHostsResult {
125 hosts: vec![],
126 error: "Not authenticated".to_string(),
127 });
128 }
129 };
130
131 let url = build_url(&self.host, self.port, self.ssl);
132 let mut params = vec![msg_str("db.hosts"), msg_str(&token)];
136 if let Some(workspace) = workspace {
137 params.push(MsgValue::Map(BTreeMap::from([(
138 "workspace".to_string(),
139 msg_str(workspace),
140 )])));
141 } else {
142 params.push(MsgValue::Map(BTreeMap::new()));
143 }
144 let payload = encode(&msg_array(params));
145
146 match send_request(&url, &payload, 15) {
147 Ok(val) => Ok(MSFHostsResult {
148 hosts: extract_hosts(&val),
149 error: String::new(),
150 }),
151 Err(error) => Ok(MSFHostsResult {
152 hosts: vec![],
153 error,
154 }),
155 }
156 }
157
158 pub fn check_host_exists(
159 &self,
160 address: &str,
161 workspace: Option<&str>,
162 ) -> Result<MSFHostCheckResult> {
163 let hosts = self.get_hosts(workspace)?;
164 Ok(MSFHostCheckResult {
165 exists: hosts.hosts.iter().any(|host| host.address == address),
166 error: hosts.error,
167 })
168 }
169}
170
171fn build_url(host: &str, port: u16, ssl: bool) -> String {
172 let scheme = if ssl { "https" } else { "http" };
173 format!("{}://{}:{}/api/", scheme, host, port)
174}
175
176fn send_request(
177 url: &str,
178 payload: &[u8],
179 timeout_secs: u64,
180) -> std::result::Result<MsgValue, String> {
181 let mut child = Command::new("curl")
182 .arg("-sS")
183 .arg("--max-time")
184 .arg(timeout_secs.to_string())
185 .arg("-H")
186 .arg("Content-Type: binary/message-pack")
187 .arg("-H")
188 .arg("Accept: binary/message-pack")
189 .arg("-i")
190 .arg("--data-binary")
191 .arg("@-")
192 .arg(url)
193 .stdin(Stdio::piped())
194 .stdout(Stdio::piped())
195 .stderr(Stdio::piped())
196 .spawn()
197 .map_err(|e| format!("failed to spawn curl: {e}"))?;
198
199 if let Some(stdin) = child.stdin.as_mut() {
200 use std::io::Write;
201 stdin
202 .write_all(payload)
203 .map_err(|e| format!("failed to write request body: {e}"))?;
204 }
205
206 let output = child
207 .wait_with_output()
208 .map_err(|e| format!("curl wait failed: {e}"))?;
209
210 let stdout = &output.stdout;
211 if stdout.is_empty() {
212 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
213 if !stderr.is_empty() {
214 return Err(stderr);
215 }
216 return Err("empty response from server".to_string());
217 }
218
219 let body = if let Some(pos) = find_header_body_boundary(stdout) {
221 let header_part = String::from_utf8_lossy(&stdout[..pos]);
222 let status_line = header_part.lines().next().unwrap_or("unknown");
223 eprintln!("[MSF-RPC] HTTP {status_line}");
224 &stdout[pos..]
225 } else {
226 &stdout[..]
227 };
228
229 if body.is_empty() {
230 return Err("empty response body from server".to_string());
231 }
232
233 decode(body).map_err(|e| {
234 let dump_len = body.len().min(512);
235 let hex_dump: Vec<String> = body[..dump_len]
236 .iter()
237 .map(|b| format!("{:02x}", b))
238 .collect();
239 let utf8_dump = String::from_utf8_lossy(&body[..dump_len]);
240 format!(
241 "{}\n response body hex ({} bytes): {}\n response body utf8: {}",
242 e,
243 dump_len,
244 hex_dump.join(" "),
245 utf8_dump
246 )
247 })
248}
249
250fn find_header_body_boundary(data: &[u8]) -> Option<usize> {
251 data.windows(4)
252 .position(|w| w == b"\r\n\r\n")
253 .map(|p| p + 4)
254}
255
256fn msg_str(value: &str) -> MsgValue {
257 MsgValue::String(value.to_string())
258}
259
260fn msg_array(values: Vec<MsgValue>) -> MsgValue {
261 MsgValue::Array(values)
262}
263
264fn extract_workspaces(val: &MsgValue) -> Vec<MSFWorkspaceInfo> {
265 let mut workspaces = Vec::new();
266 if let Some(map) = val.as_map() {
267 if let Some(MsgValue::Array(ws_arr)) = map.get("workspaces") {
268 for ws in ws_arr {
269 if let Some(ws_map) = ws.as_map() {
270 let name = ws_map
271 .get("name")
272 .and_then(MsgValue::as_str)
273 .unwrap_or("")
274 .to_string();
275 let scope = ws_map
276 .get("scope")
277 .and_then(MsgValue::as_str)
278 .unwrap_or("")
279 .to_string();
280 let host_count = ws_map
281 .get("hosts_count")
282 .or_else(|| ws_map.get("host_count"))
283 .and_then(MsgValue::as_u64)
284 .unwrap_or(0);
285
286 workspaces.push(MSFWorkspaceInfo {
287 name,
288 scope,
289 host_count,
290 });
291 }
292 }
293 }
294 }
295 workspaces
296}
297
298fn extract_hosts(val: &MsgValue) -> Vec<MSFHostInfo> {
299 let mut hosts = Vec::new();
300 if let Some(map) = val.as_map() {
301 if let Some(MsgValue::Array(host_arr)) = map.get("hosts") {
302 for host in host_arr {
303 if let Some(host_map) = host.as_map() {
304 let address = host_map
305 .get("address")
306 .and_then(MsgValue::as_str)
307 .unwrap_or("")
308 .to_string();
309 let os_name = host_map
310 .get("os_name")
311 .and_then(MsgValue::as_str)
312 .unwrap_or("")
313 .to_string();
314 let os_flavor = host_map
315 .get("os_flavor")
316 .and_then(MsgValue::as_str)
317 .unwrap_or("")
318 .to_string();
319 let state = host_map
320 .get("state")
321 .and_then(MsgValue::as_str)
322 .unwrap_or("")
323 .to_string();
324 let notes_count = host_map
325 .get("notes_count")
326 .and_then(MsgValue::as_u64)
327 .unwrap_or(0);
328
329 hosts.push(MSFHostInfo {
330 address,
331 os_name,
332 os_flavor,
333 state,
334 notes_count,
335 });
336 }
337 }
338 }
339 }
340 hosts
341}