loopback.rs 5.3 KB

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