csp_ping_pong.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. //! Example for usage of the Chat Server Protocol state machine, doing a real handshake with the
  2. //! chat server and an exemplary payload flow loop.
  3. #![expect(unused_crate_dependencies, reason = "Example triggered false positive")]
  4. #![expect(
  5. clippy::integer_division_remainder_used,
  6. reason = "Some internal of tokio::select triggers this"
  7. )]
  8. use core::time::Duration;
  9. use std::io;
  10. use anyhow::bail;
  11. use clap::{ArgAction, Parser};
  12. use libthreema::{
  13. cli::config::{FullIdentityConfig, FullIdentityConfigOptions},
  14. csp::{
  15. CspProtocol, CspProtocolContext, CspStateUpdate,
  16. payload::{EchoPayload, IncomingPayload, OutgoingFrame, OutgoingPayload},
  17. },
  18. https::cli::https_client_builder,
  19. utils::logging::init_stderr_logging,
  20. };
  21. use tokio::{
  22. io::{AsyncReadExt as _, AsyncWriteExt as _},
  23. net::TcpStream,
  24. signal,
  25. sync::mpsc,
  26. time::{self, Instant},
  27. };
  28. use tracing::{Level, debug, error, info, trace, warn};
  29. #[derive(Parser)]
  30. #[command()]
  31. struct CspPingPongCommand {
  32. #[command(flatten)]
  33. config: FullIdentityConfigOptions,
  34. /// Turn on debugging information.
  35. /// Use -v -vv to control log level.
  36. #[arg(short, action = ArgAction::Count)]
  37. verbose: u8,
  38. }
  39. /// Payload queues for the main process.
  40. struct PayloadQueuesForCspPingPong {
  41. incoming: mpsc::Receiver<IncomingPayload>,
  42. outgoing: mpsc::Sender<OutgoingPayload>,
  43. }
  44. /// Payload queues for the protocol flow runner.
  45. struct PayloadQueuesForCsp {
  46. incoming: mpsc::Sender<IncomingPayload>,
  47. outgoing: mpsc::Receiver<OutgoingPayload>,
  48. }
  49. struct CspProtocolRunner {
  50. /// The TCP stream.
  51. stream: TcpStream,
  52. /// An instance of the [`CspProtocol`] state machine.
  53. protocol: CspProtocol,
  54. }
  55. impl CspProtocolRunner {
  56. /// Initiate a CSP protocol connection and hand out the initial `client_hello` message
  57. #[tracing::instrument(skip_all)]
  58. async fn new(
  59. server_address: Vec<(String, u16)>,
  60. context: CspProtocolContext,
  61. ) -> anyhow::Result<(Self, OutgoingFrame)> {
  62. // Connect via TCP
  63. debug!(?server_address, "Establishing TCP connection to chat server",);
  64. let tcp_stream = TcpStream::connect(
  65. server_address
  66. .first()
  67. .expect("CSP config should have at least one address"),
  68. )
  69. .await?;
  70. // Create the protocol
  71. let (csp_protocol, client_hello) = CspProtocol::new(context);
  72. Ok((
  73. Self {
  74. stream: tcp_stream,
  75. protocol: csp_protocol,
  76. },
  77. client_hello,
  78. ))
  79. }
  80. /// Do the handshake with the chat server by exchanging the following messages:
  81. ///
  82. /// ```txt
  83. /// C -- client-hello -> S
  84. /// C <- server-hello -- S
  85. /// C ---- login ---- -> S
  86. /// C <-- login-ack ---- S
  87. /// ```
  88. #[tracing::instrument(skip_all)]
  89. async fn run_handshake_flow(&mut self, client_hello: OutgoingFrame) -> anyhow::Result<()> {
  90. // Send the client hello
  91. debug!(length = client_hello.0.len(), "Sending client hello");
  92. self.send(&client_hello.0).await?;
  93. // Handshake by polling the CSP state
  94. for iteration in 1_usize.. {
  95. trace!("Iteration #{iteration}");
  96. // Receive required bytes and add them
  97. let bytes = self.receive_required().await?;
  98. self.protocol.add_chunks(&[&bytes])?;
  99. // Handle instruction
  100. let Some(instruction) = self.protocol.poll()? else {
  101. continue;
  102. };
  103. // We do not expect an incoming payload at this stage
  104. if let Some(incoming_payload) = instruction.incoming_payload {
  105. let message = "Unexpected incoming payload during handshake";
  106. error!(?incoming_payload, message);
  107. bail!(message)
  108. }
  109. // Send any outgoing frame
  110. if let Some(frame) = instruction.outgoing_frame {
  111. self.send(&frame.0).await?;
  112. }
  113. // Check if we've completed the handshake
  114. if let Some(CspStateUpdate::PostHandshake(login_ack_data)) = instruction.state_update {
  115. info!(?login_ack_data, "Handshake complete");
  116. break;
  117. }
  118. }
  119. Ok(())
  120. }
  121. /// Run the payload exchange flow until stopped.
  122. #[tracing::instrument(skip_all)]
  123. async fn run_payload_flow(&mut self, mut queues: PayloadQueuesForCsp) -> anyhow::Result<()> {
  124. let mut read_buffer = [0_u8; 8192];
  125. for iteration in 1_usize.. {
  126. trace!("Payload flow iteration #{iteration}");
  127. // Poll for any pending instruction
  128. let mut instruction = self.protocol.poll()?;
  129. if instruction.is_none() {
  130. // No pending instruction left, wait for more input
  131. instruction = tokio::select! {
  132. // Forward any incoming chunks from the TCP stream
  133. _ = self.stream.readable() => {
  134. let length = self.try_receive(&mut read_buffer)?;
  135. // Add chunks (poll in the next iteration)
  136. self.protocol
  137. .add_chunks(&[read_buffer.get(..length)
  138. .expect("Amount of read bytes should be available")])?;
  139. None
  140. },
  141. // Forward any outgoing payloads
  142. Some(outgoing_payload) = queues.outgoing.recv() => {
  143. debug!(?outgoing_payload, "Sending payload");
  144. Some(self.protocol.create_payload(&outgoing_payload)?)
  145. }
  146. }
  147. }
  148. let Some(instruction) = instruction else {
  149. continue;
  150. };
  151. // We do not expect any state updates at this stage
  152. if let Some(state_update) = instruction.state_update {
  153. let message = "Unexpected state update after handshake";
  154. error!(?state_update, message);
  155. bail!(message)
  156. }
  157. // Forward any incoming payload
  158. if let Some(incoming_payload) = instruction.incoming_payload {
  159. debug!(?incoming_payload, "Received payload");
  160. queues.incoming.send(incoming_payload).await?;
  161. }
  162. // Send any outgoing frame
  163. if let Some(frame) = instruction.outgoing_frame {
  164. self.send(&frame.0).await?;
  165. }
  166. }
  167. Ok(())
  168. }
  169. /// Shut down the TCP connection
  170. #[tracing::instrument(skip_all)]
  171. async fn shutdown(&mut self) -> anyhow::Result<()> {
  172. info!("Shutting down TCP connection");
  173. Ok(self.stream.shutdown().await?)
  174. }
  175. /// Send bytes to the server over the TCP connection
  176. #[tracing::instrument(skip_all, fields(bytes_length = bytes.len()))]
  177. async fn send(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
  178. trace!(length = bytes.len(), "Sending bytes");
  179. self.stream.write_all(bytes).await?;
  180. Ok(())
  181. }
  182. #[tracing::instrument(skip_all)]
  183. async fn receive_required(&mut self) -> anyhow::Result<Vec<u8>> {
  184. // Get the minimum amount of bytes we'll need to receive
  185. let length = self.protocol.next_required_length()?;
  186. let mut buffer = vec![0; length];
  187. trace!(?length, "Reading bytes");
  188. // If there is nothing to read, return immediately
  189. if length == 0 {
  190. return Ok(buffer);
  191. }
  192. // Read the exact number of bytes required
  193. let _ = self.stream.read_exact(&mut buffer).await?;
  194. // Read more if available
  195. match self.stream.try_read_buf(&mut buffer) {
  196. Ok(0) => {
  197. // Remote shut down our reading end. But we still need to process the previously
  198. // read bytes.
  199. warn!("TCP reading end closed");
  200. },
  201. Ok(length) => {
  202. trace!(length, "Got additional bytes");
  203. },
  204. Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
  205. trace!("No additional bytes available");
  206. },
  207. Err(error) => {
  208. return Err(error.into());
  209. },
  210. }
  211. debug!(length = buffer.len(), "Received bytes");
  212. Ok(buffer)
  213. }
  214. #[tracing::instrument(skip_all)]
  215. fn try_receive(&mut self, buffer: &mut [u8]) -> anyhow::Result<usize> {
  216. match self.stream.try_read(buffer) {
  217. Ok(0) => {
  218. // Remote shut down our reading end gracefully.
  219. //
  220. // IMPORTANT: An implementation needs to ensure that it stops gracefully by processing any
  221. // remaining payloads prior to stopping the protocol. This example implementation ensures this
  222. // by handling all pending instructions prior to polling for more data. The only case we bail
  223. // is therefore when our instruction queue is already dry.
  224. bail!("TCP reading end closed")
  225. },
  226. Ok(length) => {
  227. debug!(length, "Received bytes");
  228. Ok(length)
  229. },
  230. Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
  231. trace!("No bytes to receive");
  232. Ok(0)
  233. },
  234. Err(error) => Err(error.into()),
  235. }
  236. }
  237. }
  238. #[tracing::instrument(skip_all)]
  239. async fn run_ping_pong_flow(mut queues: PayloadQueuesForCspPingPong) -> anyhow::Result<()> {
  240. // Create the echo timer that will trigger an outgoing payload every 10s
  241. let mut echo_timer = time::interval_at(
  242. Instant::now()
  243. .checked_add(Duration::from_secs(10))
  244. .expect("Oops, apocalypse in 10s"),
  245. Duration::from_secs(10),
  246. );
  247. // Enter ping-pong flow loop
  248. loop {
  249. tokio::select! {
  250. // Send echo-request when the timer fires
  251. _ = echo_timer.tick() => {
  252. let echo_request = OutgoingPayload::EchoRequest(
  253. EchoPayload("ping".as_bytes().to_owned()));
  254. info!(?echo_request, "Sending echo request");
  255. queues.outgoing.send(echo_request).await?;
  256. },
  257. // Process incoming payload
  258. incoming_payload = queues.incoming.recv() => {
  259. if let Some(incoming_payload) = incoming_payload {
  260. info!(?incoming_payload, "Received payload");
  261. } else {
  262. break
  263. }
  264. }
  265. };
  266. }
  267. Ok(())
  268. }
  269. #[tokio::main]
  270. async fn main() -> anyhow::Result<()> {
  271. // Parse command
  272. let arguments = CspPingPongCommand::parse();
  273. // Configure logging
  274. let log_level = match arguments.verbose {
  275. 1 => Level::DEBUG,
  276. 2 => Level::TRACE,
  277. _ => Level::INFO,
  278. };
  279. init_stderr_logging(log_level);
  280. // Create HTTP client
  281. let http_client = https_client_builder().build()?;
  282. let config = FullIdentityConfig::from_options(&http_client, arguments.config).await?;
  283. // Create payload queues
  284. let (csp_ping_pong_queues, csp_queues) = {
  285. let incoming_payload = mpsc::channel(4);
  286. let outgoing_payload = mpsc::channel(4);
  287. (
  288. PayloadQueuesForCspPingPong {
  289. incoming: incoming_payload.1,
  290. outgoing: outgoing_payload.0,
  291. },
  292. PayloadQueuesForCsp {
  293. incoming: incoming_payload.0,
  294. outgoing: outgoing_payload.1,
  295. },
  296. )
  297. };
  298. // Create CSP protocol and establish a connection
  299. let (mut csp_runner, client_hello) = CspProtocolRunner::new(
  300. config
  301. .minimal
  302. .common
  303. .config
  304. .chat_server_address
  305. .addresses(&config.csp_server_group),
  306. config
  307. .csp_context_init()
  308. .try_into()
  309. .expect("Configuration should be valid"),
  310. )
  311. .await?;
  312. // Run the handshake flow
  313. csp_runner.run_handshake_flow(client_hello).await?;
  314. // Run the protocols
  315. tokio::select! {
  316. _ = csp_runner.run_payload_flow(csp_queues) => {},
  317. _ = run_ping_pong_flow(csp_ping_pong_queues) => {},
  318. _ = signal::ctrl_c() => {},
  319. };
  320. // Shut down
  321. csp_runner.shutdown().await?;
  322. Ok(())
  323. }
  324. #[test]
  325. fn verify_cli() {
  326. use clap::CommandFactory;
  327. CspPingPongCommand::command().debug_assert();
  328. }