loopback.rs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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, |printer| trace!("{}", printer));
  65. let mut arp_cache_entries: [_; 8] = Default::default();
  66. let mut arp_cache = SliceArpCache::new(&mut arp_cache_entries[..]);
  67. let hardware_addr = EthernetAddress::default();
  68. let mut protocol_addrs = [IpAddress::v4(127, 0, 0, 1)];
  69. let mut iface = EthernetInterface::new(
  70. &mut device, &mut arp_cache as &mut ArpCache,
  71. hardware_addr, &mut protocol_addrs[..]);
  72. let server_socket = {
  73. // It is not strictly necessary to use a `static mut` and unsafe code here, but
  74. // on embedded systems that smoltcp targets it is far better to allocate the data
  75. // statically to verify that it fits into RAM rather than get undefined behavior
  76. // when stack overflows.
  77. static mut TCP_SERVER_RX_DATA: [u8; 1024] = [0; 1024];
  78. static mut TCP_SERVER_TX_DATA: [u8; 1024] = [0; 1024];
  79. let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
  80. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
  81. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  82. };
  83. let client_socket = {
  84. static mut TCP_CLIENT_RX_DATA: [u8; 1024] = [0; 1024];
  85. static mut TCP_CLIENT_TX_DATA: [u8; 1024] = [0; 1024];
  86. let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
  87. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
  88. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  89. };
  90. let mut socket_set_entries: [_; 2] = Default::default();
  91. let mut socket_set = SocketSet::new(&mut socket_set_entries[..]);
  92. let server_handle = socket_set.add(server_socket);
  93. let client_handle = socket_set.add(client_socket);
  94. let mut did_listen = false;
  95. let mut did_connect = false;
  96. let mut done = false;
  97. while !done && clock.elapsed() < 10_000 {
  98. {
  99. let socket: &mut TcpSocket = socket_set.get_mut(server_handle).as_socket();
  100. if !socket.is_active() && !socket.is_listening() {
  101. if !did_listen {
  102. socket.listen(1234).unwrap();
  103. did_listen = true;
  104. }
  105. }
  106. if socket.can_recv() {
  107. debug!("got {:?}", socket.recv(32).unwrap());
  108. socket.close();
  109. done = true;
  110. }
  111. }
  112. {
  113. let socket: &mut TcpSocket = socket_set.get_mut(client_handle).as_socket();
  114. if !socket.is_open() {
  115. if !did_connect {
  116. socket.connect((IpAddress::v4(127, 0, 0, 1), 1234),
  117. (IpAddress::v4(127, 0, 0, 1), 65000)).unwrap();
  118. did_connect = true;
  119. }
  120. }
  121. if socket.can_send() {
  122. socket.send_slice(b"0123456789abcdef").unwrap();
  123. socket.close();
  124. }
  125. }
  126. match iface.poll(&mut socket_set, clock.elapsed()) {
  127. Ok(()) | Err(Error::Exhausted) => (),
  128. Err(e) => debug!("poll error: {}", e)
  129. }
  130. clock.advance(1);
  131. }
  132. if !done {
  133. error!("this is taking too long, bailing out");
  134. }
  135. }