loopback.rs 5.4 KB

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