1use std::io::prelude::*;
3use std::io::BufReader;
4use std::io::LineWriter;
5use std::os::unix::net::UnixListener;
6use std::os::unix::net::UnixStream;
7use std::path::PathBuf;
8use std::{io, net, time};
9
10use radicle::node::Handle;
11use serde_json as json;
12
13use crate::identity::RepoId;
14use crate::node::NodeId;
15use crate::node::{Command, CommandResult};
16use crate::runtime;
17use crate::runtime::thread;
18
19const MAX_TIMEOUT: time::Duration = time::Duration::MAX;
21
22#[derive(thiserror::Error, Debug)]
23pub enum Error {
24 #[error("failed to bind control socket listener: {0}")]
25 Bind(io::Error),
26 #[error("invalid socket path specified: {0}")]
27 InvalidPath(PathBuf),
28 #[error("node: {0}")]
29 Node(#[from] runtime::HandleError),
30}
31
32pub fn listen<E, H>(listener: UnixListener, handle: H) -> Result<(), Error>
34where
35 H: Handle<Error = runtime::HandleError> + 'static,
36 H::Sessions: serde::Serialize,
37 CommandResult<E>: From<H::Event>,
38 E: serde::Serialize,
39{
40 log::debug!(target: "control", "Control thread listening on socket..");
41 let nid = handle.nid()?;
42
43 for incoming in listener.incoming() {
44 match incoming {
45 Ok(mut stream) => {
46 let handle = handle.clone();
47
48 thread::spawn(&nid, "control", move || {
49 if let Err(e) = command(&stream, handle) {
50 log::error!(target: "control", "Command returned error: {e}");
51
52 CommandResult::error(e).to_writer(&mut stream).ok();
53
54 stream.flush().ok();
55 stream.shutdown(net::Shutdown::Both).ok();
56 }
57 });
58 }
59 Err(e) => log::error!(target: "control", "Failed to accept incoming connection: {}", e),
60 }
61 }
62 log::debug!(target: "control", "Exiting control loop..");
63
64 Ok(())
65}
66
67#[derive(thiserror::Error, Debug)]
68enum CommandError {
69 #[error("(de)serialization failed: {0}")]
70 Serialization(#[from] json::Error),
71 #[error("runtime error: {0}")]
72 Runtime(#[from] runtime::HandleError),
73 #[error("i/o error: {0}")]
74 Io(#[from] io::Error),
75}
76
77fn command<E, H>(stream: &UnixStream, mut handle: H) -> Result<(), CommandError>
78where
79 H: Handle<Error = runtime::HandleError> + 'static,
80 H::Sessions: serde::Serialize,
81 CommandResult<E>: From<H::Event>,
82 E: serde::Serialize,
83{
84 let mut reader = BufReader::new(stream);
85 let mut writer = LineWriter::new(stream);
86 let mut line = String::new();
87
88 reader.read_line(&mut line)?;
89 let input = line.trim_end();
90
91 log::debug!(target: "control", "Received `{input}` on control socket");
92 let cmd: Command = json::from_str(input)?;
93
94 match cmd {
95 Command::Connect { addr, opts } => {
96 let (nid, addr) = addr.into();
97 match handle.connect(nid, addr, opts) {
98 Err(e) => return Err(CommandError::Runtime(e)),
99 Ok(result) => {
100 json::to_writer(&mut writer, &result)?;
101 writer.write_all(b"\n")?;
102 }
103 }
104 }
105 Command::Disconnect { nid } => match handle.disconnect(nid) {
106 Err(e) => return Err(CommandError::Runtime(e)),
107 Ok(()) => {
108 CommandResult::ok().to_writer(writer).ok();
109 }
110 },
111 Command::Fetch { rid, nid, timeout } => {
112 fetch(rid, nid, timeout, writer, &mut handle)?;
113 }
114 Command::Config => {
115 let config = handle.config()?;
116
117 CommandResult::Okay(config).to_writer(writer)?;
118 }
119 Command::ListenAddrs => {
120 let addrs = handle.listen_addrs()?;
121
122 CommandResult::Okay(addrs).to_writer(writer)?;
123 }
124 Command::Seeds { rid } => {
125 let seeds = handle.seeds(rid)?;
126
127 CommandResult::Okay(seeds).to_writer(writer)?;
128 }
129 Command::Sessions => {
130 let sessions = handle.sessions()?;
131
132 CommandResult::Okay(sessions).to_writer(writer)?;
133 }
134 Command::Seed { rid, scope } => match handle.seed(rid, scope) {
135 Ok(result) => {
136 CommandResult::updated(result).to_writer(writer)?;
137 }
138 Err(e) => {
139 return Err(CommandError::Runtime(e));
140 }
141 },
142 Command::Unseed { rid } => match handle.unseed(rid) {
143 Ok(result) => {
144 CommandResult::updated(result).to_writer(writer)?;
145 }
146 Err(e) => {
147 return Err(CommandError::Runtime(e));
148 }
149 },
150 Command::Follow { nid, alias } => match handle.follow(nid, alias) {
151 Ok(result) => {
152 CommandResult::updated(result).to_writer(writer)?;
153 }
154 Err(e) => {
155 return Err(CommandError::Runtime(e));
156 }
157 },
158 Command::Unfollow { nid } => match handle.unfollow(nid) {
159 Ok(result) => {
160 CommandResult::updated(result).to_writer(writer)?;
161 }
162 Err(e) => {
163 return Err(CommandError::Runtime(e));
164 }
165 },
166 Command::AnnounceRefs { rid } => {
167 let refs = handle.announce_refs(rid)?;
168
169 CommandResult::Okay(refs).to_writer(writer)?;
170 }
171 Command::AnnounceInventory => {
172 if let Err(e) = handle.announce_inventory() {
173 return Err(CommandError::Runtime(e));
174 }
175 CommandResult::ok().to_writer(writer).ok();
176 }
177 Command::AddInventory { rid } => match handle.add_inventory(rid) {
178 Ok(result) => {
179 CommandResult::updated(result).to_writer(writer)?;
180 }
181 Err(e) => {
182 return Err(CommandError::Runtime(e));
183 }
184 },
185 Command::Subscribe => match handle.subscribe(MAX_TIMEOUT) {
186 Ok(events) => {
187 for e in events {
188 CommandResult::from(e).to_writer(&mut writer)?;
189 }
190 }
191 Err(e) => return Err(CommandError::Runtime(e)),
192 },
193 Command::Status => {
194 CommandResult::ok().to_writer(writer).ok();
195 }
196 Command::NodeId => match handle.nid() {
197 Ok(nid) => {
198 CommandResult::Okay(nid).to_writer(writer)?;
199 }
200 Err(e) => return Err(CommandError::Runtime(e)),
201 },
202 Command::Debug => {
203 let debug = handle.debug()?;
204
205 CommandResult::Okay(debug).to_writer(writer)?;
206 }
207 Command::Shutdown => {
208 log::debug!(target: "control", "Shutdown requested..");
209 handle.shutdown().ok();
212 CommandResult::ok().to_writer(writer).ok();
213 }
214 }
215 Ok(())
216}
217
218fn fetch<W: Write, H: Handle<Error = runtime::HandleError>>(
219 id: RepoId,
220 node: NodeId,
221 timeout: time::Duration,
222 mut writer: W,
223 handle: &mut H,
224) -> Result<(), CommandError> {
225 match handle.fetch(id, node, timeout) {
226 Ok(result) => {
227 json::to_writer(&mut writer, &result)?;
228 }
229 Err(e) => {
230 return Err(CommandError::Runtime(e));
231 }
232 }
233 Ok(())
234}
235
236#[cfg(test)]
237mod tests {
238 use std::io::prelude::*;
239 use std::os::unix::net::UnixStream;
240 use std::thread;
241
242 use super::*;
243 use crate::identity::RepoId;
244 use crate::node::Handle;
245 use crate::node::{Alias, Node, NodeId};
246 use crate::service::policy::Scope;
247 use crate::test;
248
249 #[test]
250 fn test_control_socket() {
251 let tmp = tempfile::tempdir().unwrap();
252 let handle = test::handle::Handle::default();
253 let socket = tmp.path().join("alice.sock");
254 let rids = test::arbitrary::set::<RepoId>(1..3);
255 let listener = UnixListener::bind(&socket).unwrap();
256
257 thread::spawn({
258 let handle = handle.clone();
259
260 move || listen(listener, handle)
261 });
262
263 for rid in &rids {
264 let stream = loop {
265 if let Ok(stream) = UnixStream::connect(&socket) {
266 break stream;
267 }
268 };
269 writeln!(
270 &stream,
271 "{}",
272 json::to_string(&Command::AnnounceRefs {
273 rid: rid.to_owned()
274 })
275 .unwrap()
276 )
277 .unwrap();
278
279 let stream = BufReader::new(stream);
280 let line = stream.lines().next().unwrap().unwrap();
281
282 assert_eq!(
283 line,
284 json::json!({
285 "remote": handle.nid().unwrap(),
286 "at": "0000000000000000000000000000000000000000"
287 })
288 .to_string()
289 );
290 }
291
292 for rid in &rids {
293 assert!(handle.updates.lock().unwrap().contains(rid));
294 }
295 }
296
297 #[test]
298 fn test_seed_unseed() {
299 let tmp = tempfile::tempdir().unwrap();
300 let socket = tmp.path().join("node.sock");
301 let proj = test::arbitrary::gen::<RepoId>(1);
302 let peer = test::arbitrary::gen::<NodeId>(1);
303 let listener = UnixListener::bind(&socket).unwrap();
304 let mut handle = Node::new(&socket);
305
306 thread::spawn({
307 let handle = crate::test::handle::Handle::default();
308
309 move || crate::control::listen(listener, handle)
310 });
311
312 while !handle.is_running() {}
314
315 assert!(handle.seed(proj, Scope::default()).unwrap());
316 assert!(!handle.seed(proj, Scope::default()).unwrap());
317 assert!(handle.unseed(proj).unwrap());
318 assert!(!handle.unseed(proj).unwrap());
319
320 assert!(handle.follow(peer, Some(Alias::new("alice"))).unwrap());
321 assert!(!handle.follow(peer, Some(Alias::new("alice"))).unwrap());
322 assert!(handle.unfollow(peer).unwrap());
323 assert!(!handle.unfollow(peer).unwrap());
324 }
325}