loopback.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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::wire::{EthernetAddress, IpAddress};
  16. use smoltcp::iface::{ArpCache, SliceArpCache, EthernetInterface};
  17. use smoltcp::socket::{AsSocket, SocketSet};
  18. use smoltcp::socket::{TcpSocket, TcpSocketBuffer};
  19. #[cfg(not(feature = "std"))]
  20. mod mock {
  21. use core::cell::Cell;
  22. #[derive(Debug)]
  23. pub struct Clock(Cell<u64>);
  24. impl Clock {
  25. pub fn new() -> Clock {
  26. Clock(Cell::new(0))
  27. }
  28. pub fn advance(&self, millis: u64) {
  29. self.0.set(self.0.get() + millis)
  30. }
  31. pub fn elapsed(&self) -> u64 {
  32. self.0.get()
  33. }
  34. }
  35. }
  36. #[cfg(feature = "std")]
  37. mod mock {
  38. use std::sync::Arc;
  39. use std::sync::atomic::{Ordering, AtomicUsize};
  40. // should be AtomicU64 but that's unstable
  41. #[derive(Debug, Clone)]
  42. pub struct Clock(Arc<AtomicUsize>);
  43. impl Clock {
  44. pub fn new() -> Clock {
  45. Clock(Arc::new(AtomicUsize::new(0)))
  46. }
  47. pub fn advance(&self, millis: u64) {
  48. self.0.fetch_add(millis as usize, Ordering::SeqCst);
  49. }
  50. pub fn elapsed(&self) -> u64 {
  51. self.0.load(Ordering::SeqCst) as u64
  52. }
  53. }
  54. }
  55. fn main() {
  56. let clock = mock::Clock::new();
  57. let mut device = Loopback::new();
  58. #[cfg(feature = "std")]
  59. let mut device = {
  60. let clock = clock.clone();
  61. utils::setup_logging_with_clock("", move || clock.elapsed());
  62. let (mut opts, mut free) = utils::create_options();
  63. utils::add_middleware_options(&mut opts, &mut free);
  64. let mut matches = utils::parse_options(&opts, free);
  65. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/true);
  66. device
  67. };
  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::Unspecified, 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. }