server.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{collections::HashSet, io::ErrorKind, sync::Arc};
  19. use async_trait::async_trait;
  20. use log::{debug, error, info};
  21. use smol::{
  22. io::{ReadHalf, WriteHalf},
  23. lock::{Mutex, MutexGuard},
  24. };
  25. use tinyjson::JsonValue;
  26. use url::Url;
  27. use super::{
  28. common::{read_from_stream, write_to_stream, INIT_BUF_SIZE},
  29. jsonrpc::*,
  30. };
  31. use crate::{
  32. net::transport::{Listener, PtListener, PtStream},
  33. system::{StoppableTask, StoppableTaskPtr},
  34. Error, Result,
  35. };
  36. /// Asynchronous trait implementing a handler for incoming JSON-RPC requests.
  37. #[async_trait]
  38. pub trait RequestHandler: Sync + Send {
  39. async fn handle_request(&self, req: JsonRequest) -> JsonResult;
  40. async fn pong(&self, id: u16, _params: JsonValue) -> JsonResult {
  41. JsonResponse::new(JsonValue::String("pong".to_string()), id).into()
  42. }
  43. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>>;
  44. async fn connections(&self) -> Vec<StoppableTaskPtr> {
  45. self.connections_mut().await.iter().cloned().collect()
  46. }
  47. async fn mark_connection(&self, task: StoppableTaskPtr) {
  48. self.connections_mut().await.insert(task);
  49. }
  50. async fn unmark_connection(&self, task: StoppableTaskPtr) {
  51. self.connections_mut().await.remove(&task);
  52. }
  53. async fn active_connections(&self) -> usize {
  54. self.connections_mut().await.len()
  55. }
  56. async fn stop_connections(&self) {
  57. info!(target: "rpc::server", "[RPC] Server stopped, closing connections");
  58. for (i, task) in self.connections().await.iter().enumerate() {
  59. debug!(target: "rpc::server", "Stopping connection #{}", i);
  60. task.stop().await;
  61. }
  62. }
  63. }
  64. /// Accept function that should run inside a loop for accepting incoming
  65. /// JSON-RPC requests and passing them to the [`RequestHandler`].
  66. pub async fn accept(
  67. reader: Arc<Mutex<ReadHalf<Box<dyn PtStream>>>>,
  68. writer: Arc<Mutex<WriteHalf<Box<dyn PtStream>>>>,
  69. addr: Url,
  70. rh: Arc<impl RequestHandler + 'static>,
  71. conn_limit: Option<usize>,
  72. ex: Arc<smol::Executor<'_>>,
  73. ) -> Result<()> {
  74. // If there's a connection limit set, we will refuse connections
  75. // after this point.
  76. if let Some(conn_limit) = conn_limit {
  77. if rh.clone().active_connections().await >= conn_limit {
  78. debug!(
  79. target: "rpc::server::accept()",
  80. "Connection limit reached, refusing new conn"
  81. );
  82. return Err(Error::RpcConnectionsExhausted)
  83. }
  84. }
  85. // We'll hold our background tasks here
  86. let tasks = Arc::new(Mutex::new(HashSet::new()));
  87. loop {
  88. let mut buf = Vec::with_capacity(INIT_BUF_SIZE);
  89. let mut reader_lock = reader.lock().await;
  90. let _ = read_from_stream(&mut reader_lock, &mut buf, false).await?;
  91. drop(reader_lock);
  92. let read_string = match String::from_utf8(buf) {
  93. Ok(v) => v,
  94. Err(e) => {
  95. error!(
  96. target: "rpc::server::accept()",
  97. "[RPC SERVER] Failed parsing string from read buffer: {}", e,
  98. );
  99. return Err(e.into())
  100. }
  101. };
  102. // Implementation note:
  103. // When using this JSON-RPC server with XMRig, an issue arises.
  104. // XMRig tends to send something we do not parse as a line in
  105. // read_from_stream(), so as a stop-gap hack we do this:
  106. let line = read_string.trim().lines().take(1).next().unwrap();
  107. // Parse the line as JSON
  108. let val: JsonValue = match line.parse() {
  109. Ok(v) => v,
  110. Err(e) => {
  111. error!(
  112. target: "rpc::server::accept()",
  113. "[RPC SERVER] Failed parsing JSON string: {}", e,
  114. );
  115. return Err(e.into())
  116. }
  117. };
  118. // Cast to JsonRequest
  119. let req = match JsonRequest::try_from(&val) {
  120. Ok(v) => v,
  121. Err(e) => {
  122. error!(
  123. target: "rpc::server::accept()",
  124. "[RPC SERVER] Failed casting JSON to a JsonRequest: {}", e,
  125. );
  126. return Err(e.into())
  127. }
  128. };
  129. debug!(target: "rpc::server", "{} --> {}", addr, val.stringify()?);
  130. let rep = rh.handle_request(req).await;
  131. match rep {
  132. JsonResult::Subscriber(subscriber) => {
  133. let task = StoppableTask::new();
  134. // Clone what needs to go in the background
  135. let task_ = task.clone();
  136. let addr_ = addr.clone();
  137. let tasks_ = tasks.clone();
  138. let writer_ = writer.clone();
  139. // Detach the subscriber so we can multiplex further requests
  140. task.clone().start(
  141. async move {
  142. // Subscribe to the inner method subscriber
  143. let subscription = subscriber.sub.subscribe().await;
  144. loop {
  145. // Listen for notifications
  146. let notification = subscription.receive().await;
  147. // Push notification
  148. debug!(target: "rpc::server", "{} <-- {}", addr_, notification.stringify()?);
  149. let notification = JsonResult::Notification(notification);
  150. let mut writer_lock = writer_.lock().await;
  151. if let Err(e) = write_to_stream(&mut writer_lock, &notification).await {
  152. subscription.unsubscribe().await;
  153. return Err(e)
  154. }
  155. drop(writer_lock);
  156. }
  157. },
  158. move |_| async move {
  159. debug!(
  160. target: "rpc::server",
  161. "Removing background task {} from map", task_.task_id,
  162. );
  163. tasks_.lock().await.remove(&task_);
  164. },
  165. Error::DetachedTaskStopped,
  166. ex.clone(),
  167. );
  168. debug!(target: "rpc::server", "Adding background task {} to map", task.task_id);
  169. tasks.lock().await.insert(task.clone());
  170. }
  171. JsonResult::SubscriberWithReply(subscriber, reply) => {
  172. // Write the response
  173. debug!(target: "rpc::server", "{} <-- {}", addr, reply.stringify()?);
  174. let mut writer_lock = writer.lock().await;
  175. write_to_stream(&mut writer_lock, &reply.into()).await?;
  176. drop(writer_lock);
  177. let task = StoppableTask::new();
  178. // Clone what needs to go in the background
  179. let task_ = task.clone();
  180. let addr_ = addr.clone();
  181. let tasks_ = tasks.clone();
  182. let writer_ = writer.clone();
  183. // Detach the subscriber so we can multiplex further requests
  184. task.clone().start(
  185. async move {
  186. // Start the subscriber loop
  187. let subscription = subscriber.sub.subscribe().await;
  188. loop {
  189. // Listen for notifications
  190. let notification = subscription.receive().await;
  191. // Push notification
  192. debug!(target: "rpc::server", "{} <-- {}", addr_, notification.stringify()?);
  193. let notification = JsonResult::Notification(notification);
  194. let mut writer_lock = writer_.lock().await;
  195. if let Err(e) = write_to_stream(&mut writer_lock, &notification).await {
  196. subscription.unsubscribe().await;
  197. drop(writer_lock);
  198. return Err(e)
  199. }
  200. drop(writer_lock);
  201. }
  202. },
  203. move |_| async move {
  204. debug!(
  205. target: "rpc::server",
  206. "Removing background task {} from map", task_.task_id,
  207. );
  208. tasks_.lock().await.remove(&task_);
  209. },
  210. Error::DetachedTaskStopped,
  211. ex.clone(),
  212. );
  213. debug!(target: "rpc::server", "Adding background task {} to map", task.task_id);
  214. tasks.lock().await.insert(task.clone());
  215. }
  216. JsonResult::Request(_) | JsonResult::Notification(_) => {
  217. unreachable!("Should never happen")
  218. }
  219. JsonResult::Response(ref v) => {
  220. debug!(target: "rpc::server", "{} <-- {}", addr, v.stringify()?);
  221. let mut writer_lock = writer.lock().await;
  222. write_to_stream(&mut writer_lock, &rep).await?;
  223. drop(writer_lock);
  224. }
  225. JsonResult::Error(ref v) => {
  226. debug!(target: "rpc::server", "{} <-- {}", addr, v.stringify()?);
  227. let mut writer_lock = writer.lock().await;
  228. write_to_stream(&mut writer_lock, &rep).await?;
  229. drop(writer_lock);
  230. }
  231. }
  232. }
  233. }
  234. /// Wrapper function around [`accept()`] to take the incoming connection and
  235. /// pass it forward.
  236. async fn run_accept_loop(
  237. listener: Box<dyn PtListener>,
  238. rh: Arc<impl RequestHandler + 'static>,
  239. conn_limit: Option<usize>,
  240. ex: Arc<smol::Executor<'_>>,
  241. ) -> Result<()> {
  242. loop {
  243. match listener.next().await {
  244. Ok((stream, url)) => {
  245. let rh_ = rh.clone();
  246. info!(target: "rpc::server", "[RPC] Server accepted conn from {}", url);
  247. let (reader, writer) = smol::io::split(stream);
  248. let reader = Arc::new(Mutex::new(reader));
  249. let writer = Arc::new(Mutex::new(writer));
  250. let task = StoppableTask::new();
  251. let task_ = task.clone();
  252. let ex_ = ex.clone();
  253. task.clone().start(
  254. accept(reader, writer, url.clone(), rh.clone(), conn_limit, ex_),
  255. |_| async move {
  256. rh_.clone().unmark_connection(task_.clone()).await;
  257. },
  258. Error::ChannelStopped,
  259. ex.clone(),
  260. );
  261. rh.clone().mark_connection(task.clone()).await;
  262. }
  263. // As per accept(2) recommendation:
  264. Err(e) if e.raw_os_error().is_some() => match e.raw_os_error().unwrap() {
  265. libc::EAGAIN | libc::ECONNABORTED | libc::EPROTO | libc::EINTR => continue,
  266. _ => {
  267. error!(
  268. target: "rpc::server::run_accept_loop()",
  269. "[RPC] Server failed listening: {}", e,
  270. );
  271. error!(
  272. target: "rpc::server::run_accept_loop()",
  273. "[RPC] Closing accept loop"
  274. );
  275. return Err(e.into())
  276. }
  277. },
  278. // In case a TLS handshake fails, we'll get this:
  279. Err(e) if e.kind() == ErrorKind::UnexpectedEof => continue,
  280. // Errors we didn't handle above:
  281. Err(e) => {
  282. error!(
  283. target: "rpc::server::run_accept_loop()",
  284. "[RPC] Unhandled listener.next() error: {}", e,
  285. );
  286. error!(
  287. target: "rpc::server::run_accept_loop()",
  288. "[RPC] Closing acceptloop"
  289. );
  290. return Err(e.into())
  291. }
  292. }
  293. }
  294. }
  295. /// Start a JSON-RPC server bound to the given accept URL and use the
  296. /// given [`RequestHandler`] to handle incoming requests.
  297. pub async fn listen_and_serve(
  298. accept_url: Url,
  299. rh: Arc<impl RequestHandler + 'static>,
  300. conn_limit: Option<usize>,
  301. ex: Arc<smol::Executor<'_>>,
  302. ) -> Result<()> {
  303. let listener = Listener::new(accept_url).await?.listen().await?;
  304. run_accept_loop(listener, rh, conn_limit, ex.clone()).await
  305. }
  306. #[cfg(test)]
  307. mod tests {
  308. use super::*;
  309. use crate::{rpc::client::RpcClient, system::msleep};
  310. use smol::{lock::Mutex, net::TcpListener, Executor};
  311. struct RpcServer {
  312. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  313. }
  314. #[async_trait]
  315. impl RequestHandler for RpcServer {
  316. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  317. match req.method.as_str() {
  318. "ping" => return self.pong(req.id, req.params).await,
  319. _ => panic!(),
  320. }
  321. }
  322. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  323. self.rpc_connections.lock().await
  324. }
  325. }
  326. #[test]
  327. fn conn_manager() -> Result<()> {
  328. let executor = Arc::new(Executor::new());
  329. // This simulates a server and a client. Through the function, there
  330. // are some calls to sleep(), which are used for the tests, because
  331. // otherwise they execute too fast. In practice, The RPC server is
  332. // a long-running task so when polled, it should handle things in a
  333. // correct manner.
  334. smol::block_on(executor.run(async {
  335. // Find an available port
  336. let listener = TcpListener::bind("127.0.0.1:0").await?;
  337. let sockaddr = listener.local_addr()?;
  338. let endpoint = Url::parse(&format!("tcp://127.0.0.1:{}", sockaddr.port()))?;
  339. drop(listener);
  340. let rpc_server = Arc::new(RpcServer { rpc_connections: Mutex::new(HashSet::new()) });
  341. let rpc_server_ = rpc_server.clone();
  342. let server_task = StoppableTask::new();
  343. server_task.clone().start(
  344. listen_and_serve(endpoint.clone(), rpc_server.clone(), None, executor.clone()),
  345. |res| async move {
  346. match res {
  347. Ok(()) | Err(Error::RpcServerStopped) => {
  348. rpc_server_.stop_connections().await
  349. }
  350. Err(e) => panic!("{}", e),
  351. }
  352. },
  353. Error::RpcServerStopped,
  354. executor.clone(),
  355. );
  356. // Let the server spawn
  357. msleep(500).await;
  358. // Connect a client
  359. let rpc_client0 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  360. msleep(500).await;
  361. assert!(rpc_server.active_connections().await == 1);
  362. // Connect another client
  363. let rpc_client1 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  364. msleep(500).await;
  365. assert!(rpc_server.active_connections().await == 2);
  366. // And another one
  367. let _rpc_client2 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  368. msleep(500).await;
  369. assert!(rpc_server.active_connections().await == 3);
  370. // Close the first client
  371. rpc_client0.stop().await;
  372. msleep(500).await;
  373. assert!(rpc_server.active_connections().await == 2);
  374. // Close the second client
  375. rpc_client1.stop().await;
  376. msleep(500).await;
  377. assert!(rpc_server.active_connections().await == 1);
  378. // The Listener should be stopped when we stop the server task.
  379. server_task.stop().await;
  380. assert!(RpcClient::new(endpoint, executor.clone()).await.is_err());
  381. // After the server is stopped, the connections tasks should also be stopped
  382. assert!(rpc_server.active_connections().await == 0);
  383. Ok(())
  384. }))
  385. }
  386. }