csp_login.rs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. //! Example for usage of the Chat Server Protocol state machine, doing a real handshake with the
  2. //! chat server, exiting immediately after successful login.
  3. #![expect(unused_crate_dependencies, reason = "Example triggered false positive")]
  4. use std::io;
  5. use anyhow::bail;
  6. use clap::{ArgAction, Parser};
  7. use libthreema::{
  8. cli::config::{FullIdentityConfig, FullIdentityConfigOptions},
  9. csp::{CspProtocol, CspProtocolContext, CspStateUpdate, payload::OutgoingFrame},
  10. https::cli::https_client_builder,
  11. utils::logging::init_stderr_logging,
  12. };
  13. use tokio::{
  14. io::{AsyncReadExt as _, AsyncWriteExt as _},
  15. net::TcpStream,
  16. };
  17. use tracing::{Level, debug, error, info, trace, warn};
  18. #[derive(Parser)]
  19. #[command()]
  20. struct CspLoginCommand {
  21. #[command(flatten)]
  22. config: FullIdentityConfigOptions,
  23. /// Turn on debugging information.
  24. /// Use -v -vv to control log level.
  25. #[arg(short, action = ArgAction::Count)]
  26. verbose: u8,
  27. }
  28. struct CspProtocolRunner {
  29. /// The TCP stream.
  30. stream: TcpStream,
  31. /// An instance of the [`CspProtocol`] state machine.
  32. protocol: CspProtocol,
  33. }
  34. impl CspProtocolRunner {
  35. /// Initiate a CSP protocol connection and hand out the initial `client_hello` message
  36. #[tracing::instrument(skip_all)]
  37. async fn new(
  38. server_address: Vec<(String, u16)>,
  39. context: CspProtocolContext,
  40. ) -> anyhow::Result<(Self, OutgoingFrame)> {
  41. // Connect via TCP
  42. debug!(?server_address, "Establishing TCP connection to chat server",);
  43. let tcp_stream = TcpStream::connect(
  44. server_address
  45. .first()
  46. .expect("CSP config should have at least one address"),
  47. )
  48. .await?;
  49. // Create the protocol
  50. let (csp_protocol, client_hello) = CspProtocol::new(context);
  51. Ok((
  52. Self {
  53. stream: tcp_stream,
  54. protocol: csp_protocol,
  55. },
  56. client_hello,
  57. ))
  58. }
  59. /// Do the handshake with the chat server by exchanging the following messages:
  60. ///
  61. /// ```txt
  62. /// C -- client-hello -> S
  63. /// C <- server-hello -- S
  64. /// C ---- login ---- -> S
  65. /// C <-- login-ack ---- S
  66. /// ```
  67. #[tracing::instrument(skip_all)]
  68. async fn run_handshake_flow(&mut self, client_hello: OutgoingFrame) -> anyhow::Result<()> {
  69. // Send the client hello
  70. debug!(length = client_hello.0.len(), "Sending client hello");
  71. self.send(&client_hello.0).await?;
  72. // Handshake by polling the CSP state
  73. for iteration in 1_usize.. {
  74. trace!("Iteration #{iteration}");
  75. // Receive required bytes and add them
  76. let bytes = self.receive_required().await?;
  77. self.protocol.add_chunks(&[&bytes])?;
  78. // Handle instruction
  79. let Some(instruction) = self.protocol.poll()? else {
  80. continue;
  81. };
  82. // We do not expect an incoming payload at this stage
  83. if let Some(incoming_payload) = instruction.incoming_payload {
  84. let message = "Unexpected incoming payload during handshake";
  85. error!(?incoming_payload, message);
  86. bail!(message)
  87. }
  88. // Send any outgoing frame
  89. if let Some(frame) = instruction.outgoing_frame {
  90. self.send(&frame.0).await?;
  91. }
  92. // Check if we've completed the handshake
  93. if let Some(CspStateUpdate::PostHandshake(login_ack_data)) = instruction.state_update {
  94. info!(?login_ack_data, "Handshake complete");
  95. break;
  96. }
  97. }
  98. Ok(())
  99. }
  100. /// Shut down the TCP connection
  101. #[tracing::instrument(skip_all)]
  102. async fn shutdown(&mut self) -> anyhow::Result<()> {
  103. info!("Shutting down TCP connection");
  104. Ok(self.stream.shutdown().await?)
  105. }
  106. /// Send bytes to the server over the TCP connection
  107. #[tracing::instrument(skip_all, fields(bytes_length = bytes.len()))]
  108. async fn send(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
  109. trace!(length = bytes.len(), "Sending bytes");
  110. self.stream.write_all(bytes).await?;
  111. Ok(())
  112. }
  113. #[tracing::instrument(skip_all)]
  114. async fn receive_required(&mut self) -> anyhow::Result<Vec<u8>> {
  115. // Get the minimum amount of bytes we'll need to receive
  116. let length = self.protocol.next_required_length()?;
  117. let mut buffer = vec![0; length];
  118. trace!(?length, "Reading bytes");
  119. // If there is nothing to read, return immediately
  120. if length == 0 {
  121. return Ok(buffer);
  122. }
  123. // Read the exact number of bytes required
  124. let _ = self.stream.read_exact(&mut buffer).await?;
  125. // Read more if available
  126. match self.stream.try_read_buf(&mut buffer) {
  127. Ok(0) => {
  128. // Remote shut down our reading end. But we still need to process the previously
  129. // read bytes.
  130. warn!("TCP reading end closed");
  131. },
  132. Ok(length) => {
  133. trace!(length, "Got additional bytes");
  134. },
  135. Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
  136. trace!("No additional bytes available");
  137. },
  138. Err(error) => {
  139. return Err(error.into());
  140. },
  141. }
  142. debug!(length = buffer.len(), "Received bytes");
  143. Ok(buffer)
  144. }
  145. }
  146. #[tokio::main]
  147. async fn main() -> anyhow::Result<()> {
  148. // Parse arguments for command
  149. let arguments = CspLoginCommand::parse();
  150. // Configure logging
  151. let log_level = match arguments.verbose {
  152. 1 => Level::DEBUG,
  153. 2 => Level::TRACE,
  154. _ => Level::INFO,
  155. };
  156. init_stderr_logging(log_level);
  157. // Create HTTP client
  158. let http_client = https_client_builder().build()?;
  159. let config = FullIdentityConfig::from_options(&http_client, arguments.config).await?;
  160. // Create CSP protocol and establish a connection
  161. let (mut csp_runner, client_hello) = CspProtocolRunner::new(
  162. config
  163. .minimal
  164. .common
  165. .config
  166. .chat_server_address
  167. .addresses(&config.csp_server_group),
  168. config
  169. .csp_context_init()
  170. .try_into()
  171. .expect("Configuration should be valid"),
  172. )
  173. .await?;
  174. // Run the handshake flow
  175. csp_runner.run_handshake_flow(client_hello).await?;
  176. // Shut down
  177. csp_runner.shutdown().await?;
  178. Ok(())
  179. }
  180. #[test]
  181. fn verify_cli() {
  182. use clap::CommandFactory;
  183. CspLoginCommand::command().debug_assert();
  184. }