loopback.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. #![cfg_attr(not(feature = "std"), no_std)]
  2. #![allow(unused_mut)]
  3. #[macro_use]
  4. extern crate log;
  5. #[cfg(feature = "std")]
  6. extern crate env_logger;
  7. #[cfg(feature = "std")]
  8. extern crate getopts;
  9. extern crate smoltcp;
  10. #[cfg(feature = "std")]
  11. mod utils;
  12. use smoltcp::Error;
  13. use smoltcp::phy::Loopback;
  14. #[cfg(feature = "std")]
  15. use smoltcp::phy::Tracer;
  16. use smoltcp::wire::{EthernetAddress, IpAddress};
  17. #[cfg(feature = "std")]
  18. use smoltcp::wire::EthernetFrame;
  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(&mut 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. #[cfg(feature = "std")]
  61. {
  62. let clock = clock.clone();
  63. utils::setup_logging_with_clock(move || clock.elapsed());
  64. }
  65. let mut device = Loopback::new();
  66. #[cfg(feature = "std")]
  67. let mut device = Tracer::<_, EthernetFrame<&'static [u8]>>::new(device, utils::trace_writer);
  68. let mut arp_cache_entries: [_; 8] = Default::default();
  69. let mut arp_cache = SliceArpCache::new(&mut arp_cache_entries[..]);
  70. let hardware_addr = EthernetAddress::default();
  71. let mut protocol_addrs = [IpAddress::v4(127, 0, 0, 1)];
  72. let mut iface = EthernetInterface::new(
  73. &mut device, &mut arp_cache as &mut ArpCache,
  74. hardware_addr, &mut protocol_addrs[..]);
  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 socket: &mut TcpSocket = socket_set.get_mut(server_handle).as_socket();
  103. if !socket.is_active() && !socket.is_listening() {
  104. if !did_listen {
  105. socket.listen(1234).unwrap();
  106. did_listen = true;
  107. }
  108. }
  109. if socket.can_recv() {
  110. debug!("got {:?}", socket.recv(32).unwrap());
  111. socket.close();
  112. done = true;
  113. }
  114. }
  115. {
  116. let socket: &mut TcpSocket = socket_set.get_mut(client_handle).as_socket();
  117. if !socket.is_open() {
  118. if !did_connect {
  119. socket.connect((IpAddress::v4(127, 0, 0, 1), 1234),
  120. (IpAddress::v4(127, 0, 0, 1), 65000)).unwrap();
  121. did_connect = true;
  122. }
  123. }
  124. if socket.can_send() {
  125. socket.send_slice(b"0123456789abcdef").unwrap();
  126. socket.close();
  127. }
  128. }
  129. match iface.poll(&mut socket_set, clock.elapsed()) {
  130. Ok(()) | Err(Error::Exhausted) => (),
  131. Err(e) => debug!("poll error: {}", e)
  132. }
  133. clock.advance(1);
  134. }
  135. if !done {
  136. error!("this is taking too long, bailing out");
  137. }
  138. }