forked from smoltcp-rs/smoltcp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loopback.rs
189 lines (159 loc) · 5.87 KB
/
loopback.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(unused_mut)]
#[cfg(feature = "std")]
use std as core;
#[macro_use]
extern crate log;
extern crate smoltcp;
#[cfg(feature = "std")]
extern crate env_logger;
#[cfg(feature = "std")]
extern crate getopts;
#[cfg(feature = "std")]
#[allow(dead_code)]
mod utils;
use core::str;
use smoltcp::phy::Loopback;
use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr};
use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder};
use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer};
use smoltcp::time::{Duration, Instant};
#[cfg(not(feature = "std"))]
mod mock {
use smoltcp::time::{Duration, Instant};
use core::cell::Cell;
#[derive(Debug)]
pub struct Clock(Cell<Instant>);
impl Clock {
pub fn new() -> Clock {
Clock(Cell::new(Instant::from_millis(0)))
}
pub fn advance(&self, duration: Duration) {
self.0.set(self.0.get() + duration)
}
pub fn elapsed(&self) -> Instant {
self.0.get()
}
}
}
#[cfg(feature = "std")]
mod mock {
use std::sync::Arc;
use std::sync::atomic::{Ordering, AtomicUsize};
use smoltcp::time::{Duration, Instant};
// should be AtomicU64 but that's unstable
#[derive(Debug, Clone)]
pub struct Clock(Arc<AtomicUsize>);
impl Clock {
pub fn new() -> Clock {
Clock(Arc::new(AtomicUsize::new(0)))
}
pub fn advance(&self, duration: Duration) {
self.0.fetch_add(duration.total_millis() as usize, Ordering::SeqCst);
}
pub fn elapsed(&self) -> Instant {
Instant::from_millis(self.0.load(Ordering::SeqCst) as i64)
}
}
}
fn main() {
let clock = mock::Clock::new();
let device = Loopback::new();
#[cfg(feature = "std")]
let device = {
let clock = clock.clone();
utils::setup_logging_with_clock("", move || clock.elapsed());
let (mut opts, mut free) = utils::create_options();
utils::add_middleware_options(&mut opts, &mut free);
let mut matches = utils::parse_options(&opts, free);
let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/true);
device
};
let mut neighbor_cache_entries = [None; 8];
let mut neighbor_cache = NeighborCache::new(&mut neighbor_cache_entries[..]);
let mut ip_addrs = [IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8)];
let mut iface = EthernetInterfaceBuilder::new(device)
.ethernet_addr(EthernetAddress::default())
.neighbor_cache(neighbor_cache)
.ip_addrs(ip_addrs)
.finalize();
let server_socket = {
// It is not strictly necessary to use a `static mut` and unsafe code here, but
// on embedded systems that smoltcp targets it is far better to allocate the data
// statically to verify that it fits into RAM rather than get undefined behavior
// when stack overflows.
static mut TCP_SERVER_RX_DATA: [u8; 1024] = [0; 1024];
static mut TCP_SERVER_TX_DATA: [u8; 1024] = [0; 1024];
let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
};
let client_socket = {
static mut TCP_CLIENT_RX_DATA: [u8; 1024] = [0; 1024];
static mut TCP_CLIENT_TX_DATA: [u8; 1024] = [0; 1024];
let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
};
let mut socket_set_entries: [_; 2] = Default::default();
let mut socket_set = SocketSet::new(&mut socket_set_entries[..]);
let server_handle = socket_set.add(server_socket);
let client_handle = socket_set.add(client_socket);
let mut did_listen = false;
let mut did_connect = false;
let mut done = false;
while !done && clock.elapsed() < Instant::from_millis(10_000) {
match iface.poll(&mut socket_set, clock.elapsed()) {
Ok(_) => {},
Err(e) => {
debug!("poll error: {}", e);
}
}
{
let mut socket = socket_set.get::<TcpSocket>(server_handle);
if !socket.is_active() && !socket.is_listening() {
if !did_listen {
debug!("listening");
socket.listen(1234).unwrap();
did_listen = true;
}
}
if socket.can_recv() {
debug!("got {:?}", socket.recv(|buffer| {
(buffer.len(), str::from_utf8(buffer).unwrap())
}));
socket.close();
done = true;
}
}
{
let mut socket = socket_set.get::<TcpSocket>(client_handle);
if !socket.is_open() {
if !did_connect {
debug!("connecting");
socket.connect((IpAddress::v4(127, 0, 0, 1), 1234),
(IpAddress::Unspecified, 65000)).unwrap();
did_connect = true;
}
}
if socket.can_send() {
debug!("sending");
socket.send_slice(b"0123456789abcdef").unwrap();
socket.close();
}
}
match iface.poll_delay(&socket_set, clock.elapsed()) {
Some(Duration { millis: 0 }) => debug!("resuming"),
Some(delay) => {
debug!("sleeping for {} ms", delay);
clock.advance(delay)
},
None => clock.advance(Duration::from_millis(1))
}
}
if done {
info!("done")
} else {
error!("this is taking too long, bailing out")
}
}