d2d_rendezvous.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. //! Example for usage of the Connection Rendezvous Protocol state machine, using MPSC channels to
  2. //! simulate paths.
  3. #![expect(unused_crate_dependencies, reason = "Example triggered false positive")]
  4. use core::time::Duration;
  5. use std::{
  6. sync::mpsc::{self, RecvTimeoutError},
  7. thread,
  8. time::Instant,
  9. };
  10. use anyhow::Context as _;
  11. use clap::{ArgAction, Parser};
  12. use libthreema::{
  13. d2d_rendezvous::{
  14. RendezvousAuthenticationKey, RendezvousOutgoingFrame, RendezvousPathProcessResult,
  15. RendezvousPathStateUpdate, RendezvousProtocol,
  16. },
  17. utils::logging::init_stderr_logging,
  18. };
  19. use libthreema_dependencies::data_encoding::HEXLOWER_PERMISSIVE;
  20. use tracing::{Level, info, trace, warn};
  21. #[derive(Parser)]
  22. #[command()]
  23. struct D2dRendezvousCommand {
  24. /// Turn on debugging information.
  25. /// Use -v -vv to control log level.
  26. #[arg(short, action = ArgAction::Count)]
  27. verbose: u8,
  28. }
  29. struct Keys;
  30. impl Keys {
  31. const AK: [u8; 32] = [
  32. 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1,
  33. 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1,
  34. ];
  35. }
  36. fn process_incoming_frame(
  37. protocol: &mut RendezvousProtocol,
  38. pid: u32,
  39. incoming_frame: &RendezvousOutgoingFrame,
  40. ) -> anyhow::Result<Option<RendezvousPathProcessResult>> {
  41. let (header, payload) = incoming_frame.encode();
  42. if let Some(nominated_pid) = protocol.nominated_path()
  43. && pid != nominated_pid
  44. {
  45. warn!(
  46. pid,
  47. ?incoming_frame,
  48. "Discarding chunk for unknown or dropped path"
  49. );
  50. return Ok(None);
  51. }
  52. // Process incoming frame
  53. protocol
  54. .add_chunks(pid, &[header.as_slice(), payload])
  55. .context("Failed to add chunk")?;
  56. let result = protocol.process_frame(pid).context("Failed to process frame")?;
  57. Ok(result)
  58. }
  59. #[expect(clippy::needless_pass_by_value, reason = "Prevent re-use")]
  60. fn run_protocol(
  61. mut protocol: RendezvousProtocol,
  62. initial_outgoing_frames: Vec<(u32, RendezvousOutgoingFrame)>,
  63. tx: mpsc::Sender<(u32, RendezvousOutgoingFrame)>,
  64. rx: mpsc::Receiver<(u32, RendezvousOutgoingFrame)>,
  65. ) -> anyhow::Result<()> {
  66. // Send initial frames
  67. for outgoing_frame in initial_outgoing_frames {
  68. tx.send(outgoing_frame)?;
  69. }
  70. // Nomination loop where we run the handshakes simultaneously over all available paths until we
  71. // have nominated one path.
  72. info!("Entering nomination loop");
  73. let (nominated_pid, rph) = 'nomination: loop {
  74. // Receive and process incoming frame
  75. let (pid, incoming_frame) = rx.recv().context("Failed to receive incoming frame")?;
  76. let mut maybe_result = process_incoming_frame(&mut protocol, pid, &incoming_frame)?;
  77. // Handle results
  78. while let Some(result) = maybe_result {
  79. // We're not expecting to receive any incoming ULP data.
  80. assert!(result.incoming_ulp_data.is_none(), "Unexpected incoming ULP data");
  81. // Send any outgoing frame
  82. if let Some(outgoing_frame) = result.outgoing_frame {
  83. tx.send((pid, outgoing_frame))
  84. .context("Failed to send outgoing frame")?;
  85. }
  86. // Handle any state update
  87. maybe_result = match result.state_update {
  88. Some(RendezvousPathStateUpdate::AwaitingNominate { measured_rtt }) => {
  89. // Check if we should nominate the path
  90. //
  91. // Note: A real implementation should wait a bit and then choose the _best_ path
  92. // based on the measured RTT.
  93. trace!(?measured_rtt, "Path ready to nominate");
  94. if protocol.is_nominator() {
  95. Some(protocol.nominate_path(pid).context("Failed to nominate")?)
  96. } else {
  97. None
  98. }
  99. },
  100. Some(RendezvousPathStateUpdate::Nominated { rph }) => {
  101. // The path was nominated
  102. break 'nomination (pid, rph);
  103. },
  104. None => None,
  105. }
  106. }
  107. };
  108. // ULP loop where we can use the nominated path to exchange arbitrary data. For this example, we
  109. // will send a string every 3s and print out whatever remote sent us.
  110. info!(
  111. rph = HEXLOWER_PERMISSIVE.encode(&rph.0),
  112. "Path nominated, entering ULP loop"
  113. );
  114. let (initial_timeout, outgoing_ulp_data) = if protocol.is_nominator() {
  115. (1000, "Tick")
  116. } else {
  117. (2000, "Tock")
  118. };
  119. let mut timeout = Duration::from_millis(initial_timeout);
  120. loop {
  121. let started_at = Instant::now();
  122. match rx.recv_timeout(timeout) {
  123. Ok((pid, incoming_frame)) => {
  124. // Calculate remaining time for the next iteration
  125. timeout = timeout.saturating_sub(Instant::elapsed(&started_at));
  126. // Receive and process incoming frame
  127. let maybe_result = process_incoming_frame(&mut protocol, pid, &incoming_frame)?;
  128. // Handle result
  129. if let Some(result) = maybe_result {
  130. // We're not expecting any state updates.
  131. assert!(result.state_update.is_none(), "Unexpected state update");
  132. // We're not expecting to send any outgoing frames since the handshake state
  133. // machine has completed.
  134. assert!(
  135. result.outgoing_frame.is_none(),
  136. "Unexpected outgoing frame in nominated state"
  137. );
  138. // We do expect incoming ULP data.
  139. let incoming_ulp_data =
  140. String::from_utf8(result.incoming_ulp_data.expect("Expecting incoming ULP data"))
  141. .context("Failed to decode ULP data string")?;
  142. info!(data = incoming_ulp_data, ?incoming_frame, "Received ULP data");
  143. }
  144. },
  145. Err(RecvTimeoutError::Timeout) => {
  146. // Create outgoing frame
  147. let result = protocol
  148. .create_ulp_frame(outgoing_ulp_data.as_bytes().to_vec())
  149. .context("Failed to create ULP frame")?;
  150. info!(
  151. data = outgoing_ulp_data,
  152. outgoing_frame = ?result.outgoing_frame,
  153. "Sending ULP data"
  154. );
  155. // We're not expecting any state updates.
  156. assert!(result.state_update.is_none(), "Unexpected state update");
  157. // Send any outgoing frame
  158. if let Some(outgoing_frame) = result.outgoing_frame {
  159. tx.send((nominated_pid, outgoing_frame))
  160. .context("Failed to send outgoing frame")?;
  161. }
  162. // We're not expecting to receive any incoming ULP data.
  163. assert!(result.incoming_ulp_data.is_none(), "Unexpected incoming ULP data");
  164. // Reset timeout
  165. timeout = Duration::from_secs(2);
  166. },
  167. Err(RecvTimeoutError::Disconnected) => {
  168. return Err(RecvTimeoutError::Disconnected).context("Failed to receive incoming frame")?;
  169. },
  170. }
  171. }
  172. }
  173. fn main() {
  174. // Parse arguments
  175. let arguments = D2dRendezvousCommand::parse();
  176. // Configure logging
  177. let log_level = match arguments.verbose {
  178. 1 => Level::DEBUG,
  179. 2 => Level::TRACE,
  180. _ => Level::INFO,
  181. };
  182. init_stderr_logging(log_level);
  183. // Communication channels for RID and RRD
  184. let (to_rrd, from_rid) = mpsc::channel::<(u32, RendezvousOutgoingFrame)>();
  185. let (to_rid, from_rrd) = mpsc::channel::<(u32, RendezvousOutgoingFrame)>();
  186. // Start RID
  187. let rid_thread = thread::spawn(move || {
  188. tracing::trace_span!("initiator").in_scope(|| {
  189. // Create and run protocol for RID
  190. let protocol =
  191. RendezvousProtocol::new_as_rid(true, RendezvousAuthenticationKey(Keys::AK), &[0x1, 0x2]);
  192. let result = run_protocol(protocol, vec![], to_rrd, from_rrd);
  193. info!("Initiator stopped: {result:?}");
  194. });
  195. });
  196. // Start RRD
  197. let rrd_thread = thread::spawn(move || {
  198. tracing::trace_span!("responder").in_scope(|| {
  199. // Create and run protocol for RRD
  200. let (protocol, initial_outgoing_frames) =
  201. RendezvousProtocol::new_as_rrd(false, RendezvousAuthenticationKey(Keys::AK), &[0x1, 0x2]);
  202. let result = run_protocol(protocol, initial_outgoing_frames, to_rid, from_rid);
  203. info!("Responder stopped: {result:?}");
  204. });
  205. });
  206. // Join threads
  207. let _ = [rid_thread, rrd_thread].map(|handle| handle.join().expect("Joining threads failed"));
  208. }