loopback.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #![cfg_attr(not(feature = "std"), no_std)]
  2. #![allow(unused_mut)]
  3. #[macro_use]
  4. extern crate log;
  5. extern crate smoltcp;
  6. #[cfg(feature = "std")]
  7. extern crate env_logger;
  8. #[cfg(feature = "std")]
  9. extern crate getopts;
  10. #[cfg(feature = "std")]
  11. #[allow(dead_code)]
  12. mod utils;
  13. use smoltcp::Error;
  14. use smoltcp::phy::Loopback;
  15. use smoltcp::phy::EthernetTracer;
  16. use smoltcp::wire::{EthernetAddress, IpAddress};
  17. use smoltcp::iface::{ArpCache, SliceArpCache, EthernetInterface};
  18. use smoltcp::socket::{AsSocket, SocketSet};
  19. use smoltcp::socket::{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. #[cfg(feature = "std")]
  59. {
  60. let clock = clock.clone();
  61. utils::setup_logging_with_clock("", move || clock.elapsed());
  62. }
  63. let mut device = Loopback::new();
  64. let mut device = EthernetTracer::new(device, |_timestamp, printer| trace!("{}", printer));
  65. #[cfg(feature = "std")]
  66. let mut device = {
  67. let (mut opts, mut free) = utils::create_options();
  68. utils::add_middleware_options(&mut opts, &mut free);
  69. let mut matches = utils::parse_options(&opts, free);
  70. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/true);
  71. device
  72. };
  73. let mut arp_cache_entries: [_; 8] = Default::default();
  74. let mut arp_cache = SliceArpCache::new(&mut arp_cache_entries[..]);
  75. let hardware_addr = EthernetAddress::default();
  76. let mut protocol_addrs = [IpAddress::v4(127, 0, 0, 1)];
  77. let mut iface = EthernetInterface::new(
  78. &mut device, &mut arp_cache as &mut ArpCache,
  79. hardware_addr, &mut protocol_addrs[..]);
  80. let server_socket = {
  81. // It is not strictly necessary to use a `static mut` and unsafe code here, but
  82. // on embedded systems that smoltcp targets it is far better to allocate the data
  83. // statically to verify that it fits into RAM rather than get undefined behavior
  84. // when stack overflows.
  85. static mut TCP_SERVER_RX_DATA: [u8; 1024] = [0; 1024];
  86. static mut TCP_SERVER_TX_DATA: [u8; 1024] = [0; 1024];
  87. let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
  88. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
  89. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  90. };
  91. let client_socket = {
  92. static mut TCP_CLIENT_RX_DATA: [u8; 1024] = [0; 1024];
  93. static mut TCP_CLIENT_TX_DATA: [u8; 1024] = [0; 1024];
  94. let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
  95. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
  96. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  97. };
  98. let mut socket_set_entries: [_; 2] = Default::default();
  99. let mut socket_set = SocketSet::new(&mut socket_set_entries[..]);
  100. let server_handle = socket_set.add(server_socket);
  101. let client_handle = socket_set.add(client_socket);
  102. let mut did_listen = false;
  103. let mut did_connect = false;
  104. let mut done = false;
  105. while !done && clock.elapsed() < 10_000 {
  106. {
  107. let socket: &mut TcpSocket = socket_set.get_mut(server_handle).as_socket();
  108. if !socket.is_active() && !socket.is_listening() {
  109. if !did_listen {
  110. socket.listen(1234).unwrap();
  111. did_listen = true;
  112. }
  113. }
  114. if socket.can_recv() {
  115. debug!("got {:?}", socket.recv(32).unwrap());
  116. socket.close();
  117. done = true;
  118. }
  119. }
  120. {
  121. let socket: &mut TcpSocket = socket_set.get_mut(client_handle).as_socket();
  122. if !socket.is_open() {
  123. if !did_connect {
  124. socket.connect((IpAddress::v4(127, 0, 0, 1), 1234),
  125. (IpAddress::Unspecified, 65000)).unwrap();
  126. did_connect = true;
  127. }
  128. }
  129. if socket.can_send() {
  130. socket.send_slice(b"0123456789abcdef").unwrap();
  131. socket.close();
  132. }
  133. }
  134. match iface.poll(&mut socket_set, clock.elapsed()) {
  135. Ok(()) | Err(Error::Exhausted) => (),
  136. Err(e) => debug!("poll error: {}", e)
  137. }
  138. clock.advance(1);
  139. }
  140. if !done {
  141. error!("this is taking too long, bailing out");
  142. }
  143. }