loopback.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. #![cfg_attr(not(feature = "std"), no_std)]
  2. #![allow(unused_mut)]
  3. #[cfg(feature = "std")]
  4. use std as core;
  5. #[macro_use]
  6. extern crate log;
  7. extern crate smoltcp;
  8. #[cfg(feature = "std")]
  9. extern crate env_logger;
  10. #[cfg(feature = "std")]
  11. extern crate getopts;
  12. #[cfg(feature = "std")]
  13. #[allow(dead_code)]
  14. mod utils;
  15. use core::str;
  16. use smoltcp::phy::Loopback;
  17. use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr};
  18. use smoltcp::iface::{ArpCache, SliceArpCache, EthernetInterface};
  19. use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer};
  20. #[cfg(not(feature = "std"))]
  21. mod mock {
  22. use core::cell::Cell;
  23. #[derive(Debug)]
  24. pub struct Clock(Cell<u64>);
  25. impl Clock {
  26. pub fn new() -> Clock {
  27. Clock(Cell::new(0))
  28. }
  29. pub fn advance(&self, millis: u64) {
  30. self.0.set(self.0.get() + millis)
  31. }
  32. pub fn elapsed(&self) -> u64 {
  33. self.0.get()
  34. }
  35. }
  36. }
  37. #[cfg(feature = "std")]
  38. mod mock {
  39. use std::sync::Arc;
  40. use std::sync::atomic::{Ordering, AtomicUsize};
  41. // should be AtomicU64 but that's unstable
  42. #[derive(Debug, Clone)]
  43. pub struct Clock(Arc<AtomicUsize>);
  44. impl Clock {
  45. pub fn new() -> Clock {
  46. Clock(Arc::new(AtomicUsize::new(0)))
  47. }
  48. pub fn advance(&self, millis: u64) {
  49. self.0.fetch_add(millis as usize, Ordering::SeqCst);
  50. }
  51. pub fn elapsed(&self) -> u64 {
  52. self.0.load(Ordering::SeqCst) as u64
  53. }
  54. }
  55. }
  56. fn main() {
  57. let clock = mock::Clock::new();
  58. let mut device = Loopback::new();
  59. #[cfg(feature = "std")]
  60. let mut device = {
  61. let clock = clock.clone();
  62. utils::setup_logging_with_clock("", move || clock.elapsed());
  63. let (mut opts, mut free) = utils::create_options();
  64. utils::add_middleware_options(&mut opts, &mut free);
  65. let mut matches = utils::parse_options(&opts, free);
  66. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/true);
  67. device
  68. };
  69. let mut arp_cache_entries: [_; 8] = Default::default();
  70. let mut arp_cache = SliceArpCache::new(&mut arp_cache_entries[..]);
  71. let mut ip_addrs = [IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8)];
  72. let mut iface = EthernetInterface::new(
  73. &mut device, &mut arp_cache as &mut ArpCache,
  74. EthernetAddress::default(), &mut ip_addrs[..], None);
  75. let server_socket = {
  76. // It is not strictly necessary to use a `static mut` and unsafe code here, but
  77. // on embedded systems that smoltcp targets it is far better to allocate the data
  78. // statically to verify that it fits into RAM rather than get undefined behavior
  79. // when stack overflows.
  80. static mut TCP_SERVER_RX_DATA: [u8; 1024] = [0; 1024];
  81. static mut TCP_SERVER_TX_DATA: [u8; 1024] = [0; 1024];
  82. let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
  83. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
  84. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  85. };
  86. let client_socket = {
  87. static mut TCP_CLIENT_RX_DATA: [u8; 1024] = [0; 1024];
  88. static mut TCP_CLIENT_TX_DATA: [u8; 1024] = [0; 1024];
  89. let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
  90. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
  91. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  92. };
  93. let mut socket_set_entries: [_; 2] = Default::default();
  94. let mut socket_set = SocketSet::new(&mut socket_set_entries[..]);
  95. let server_handle = socket_set.add(server_socket);
  96. let client_handle = socket_set.add(client_socket);
  97. let mut did_listen = false;
  98. let mut did_connect = false;
  99. let mut done = false;
  100. while !done && clock.elapsed() < 10_000 {
  101. {
  102. let mut socket = socket_set.get::<TcpSocket>(server_handle);
  103. if !socket.is_active() && !socket.is_listening() {
  104. if !did_listen {
  105. debug!("listening");
  106. socket.listen(1234).unwrap();
  107. did_listen = true;
  108. }
  109. }
  110. if socket.can_recv() {
  111. debug!("got {:?}", socket.recv(|buffer| {
  112. (buffer.len(), str::from_utf8(buffer).unwrap())
  113. }));
  114. socket.close();
  115. done = true;
  116. }
  117. }
  118. {
  119. let mut socket = socket_set.get::<TcpSocket>(client_handle);
  120. if !socket.is_open() {
  121. if !did_connect {
  122. debug!("connecting");
  123. socket.connect((IpAddress::v4(127, 0, 0, 1), 1234),
  124. (IpAddress::Unspecified, 65000)).unwrap();
  125. did_connect = true;
  126. }
  127. }
  128. if socket.can_send() {
  129. debug!("sending");
  130. socket.send_slice(b"0123456789abcdef").unwrap();
  131. socket.close();
  132. }
  133. }
  134. match iface.poll(&mut socket_set, clock.elapsed()) {
  135. Ok(Some(poll_at)) => {
  136. let delay = poll_at - clock.elapsed();
  137. debug!("sleeping for {} ms", delay);
  138. clock.advance(delay)
  139. }
  140. Ok(None) => clock.advance(1),
  141. Err(e) => debug!("poll error: {}", e)
  142. }
  143. }
  144. if done {
  145. info!("done")
  146. } else {
  147. error!("this is taking too long, bailing out")
  148. }
  149. }