1 //! 6lowpan exmaple
2 //!
3 //! This example is designed to run using the Linux ieee802154/6lowpan support,
4 //! using mac802154_hwsim.
5 //!
6 //! mac802154_hwsim allows you to create multiple "virtual" radios and specify
7 //! which is in range with which. This is very useful for testing without
8 //! needing real hardware. By default it creates two interfaces `wpan0` and
9 //! `wpan1` that are in range with each other. You can customize this with
10 //! the `wpan-hwsim` tool.
11 //!
12 //! We'll configure Linux to speak 6lowpan on `wpan0`, and leave `wpan1`
13 //! unconfigured so smoltcp can use it with a raw socket.
14 //!
15 //! # Setup
16 //!
17 //!     modprobe mac802154_hwsim
18 //!
19 //!     ip link set wpan0 down
20 //!     ip link set wpan1 down
21 //!     iwpan dev wpan0 set pan_id 0xbeef
22 //!     iwpan dev wpan1 set pan_id 0xbeef
23 //!     ip link add link wpan0 name lowpan0 type lowpan
24 //!     ip link set wpan0 up
25 //!     ip link set wpan1 up
26 //!     ip link set lowpan0 up
27 //!
28 //! # Running
29 //!
30 //! Run it with `sudo ./target/debug/examples/sixlowpan`.
31 //!
32 //! You can set wireshark to sniff on interface `wpan0` to see the packets.
33 //!
34 //! Ping it with `ping fe80::180b:4242:4242:4242%lowpan0`.
35 //!
36 //! Speak UDP with `nc -uv fe80::180b:4242:4242:4242%lowpan0 6969`.
37 //!
38 //! # Teardown
39 //!
40 //!     rmmod mac802154_hwsim
41 //!
42 
43 mod utils;
44 
45 use log::debug;
46 use std::os::unix::io::AsRawFd;
47 use std::str;
48 
49 use smoltcp::iface::{Config, Interface, SocketSet};
50 use smoltcp::phy::{wait as phy_wait, Medium, RawSocket};
51 use smoltcp::socket::tcp;
52 use smoltcp::socket::udp;
53 use smoltcp::time::Instant;
54 use smoltcp::wire::{Ieee802154Address, Ieee802154Pan, IpAddress, IpCidr};
55 
main()56 fn main() {
57     utils::setup_logging("");
58 
59     let (mut opts, mut free) = utils::create_options();
60     utils::add_middleware_options(&mut opts, &mut free);
61 
62     let mut matches = utils::parse_options(&opts, free);
63 
64     let device = RawSocket::new("wpan1", Medium::Ieee802154).unwrap();
65     let fd = device.as_raw_fd();
66     let mut device =
67         utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
68 
69     // Create interface
70     let mut config = Config::new();
71     config.random_seed = rand::random();
72     config.hardware_addr =
73         Some(Ieee802154Address::Extended([0x1a, 0x0b, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42]).into());
74     config.pan_id = Some(Ieee802154Pan(0xbeef));
75 
76     let mut iface = Interface::new(config, &mut device);
77     iface.update_ip_addrs(|ip_addrs| {
78         ip_addrs
79             .push(IpCidr::new(
80                 IpAddress::v6(0xfe80, 0, 0, 0, 0x180b, 0x4242, 0x4242, 0x4242),
81                 64,
82             ))
83             .unwrap();
84     });
85 
86     // Create sockets
87     let udp_rx_buffer = udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY], vec![0; 1280]);
88     let udp_tx_buffer = udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY], vec![0; 1280]);
89     let udp_socket = udp::Socket::new(udp_rx_buffer, udp_tx_buffer);
90 
91     let tcp_rx_buffer = tcp::SocketBuffer::new(vec![0; 4096]);
92     let tcp_tx_buffer = tcp::SocketBuffer::new(vec![0; 4096]);
93     let tcp_socket = tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer);
94 
95     let mut sockets = SocketSet::new(vec![]);
96     let udp_handle = sockets.add(udp_socket);
97     let tcp_handle = sockets.add(tcp_socket);
98 
99     let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
100     socket.listen(50000).unwrap();
101 
102     let mut tcp_active = false;
103 
104     loop {
105         let timestamp = Instant::now();
106         iface.poll(timestamp, &mut device, &mut sockets);
107 
108         // udp:6969: respond "hello"
109         let socket = sockets.get_mut::<udp::Socket>(udp_handle);
110         if !socket.is_open() {
111             socket.bind(6969).unwrap()
112         }
113 
114         let mut buffer = vec![0; 1500];
115         let client = match socket.recv() {
116             Ok((data, endpoint)) => {
117                 debug!(
118                     "udp:6969 recv data: {:?} from {}",
119                     str::from_utf8(data).unwrap(),
120                     endpoint
121                 );
122                 buffer[..data.len()].copy_from_slice(data);
123                 Some((data.len(), endpoint))
124             }
125             Err(_) => None,
126         };
127         if let Some((len, endpoint)) = client {
128             debug!(
129                 "udp:6969 send data: {:?}",
130                 str::from_utf8(&buffer[..len]).unwrap()
131             );
132             socket.send_slice(&buffer[..len], endpoint).unwrap();
133         }
134 
135         let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
136         if socket.is_active() && !tcp_active {
137             debug!("connected");
138         } else if !socket.is_active() && tcp_active {
139             debug!("disconnected");
140         }
141         tcp_active = socket.is_active();
142 
143         if socket.may_recv() {
144             let data = socket
145                 .recv(|data| {
146                     let data = data.to_owned();
147                     if !data.is_empty() {
148                         debug!(
149                             "recv data: {:?}",
150                             str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
151                         );
152                     }
153                     (data.len(), data)
154                 })
155                 .unwrap();
156 
157             if socket.can_send() && !data.is_empty() {
158                 debug!(
159                     "send data: {:?}",
160                     str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
161                 );
162                 socket.send_slice(&data[..]).unwrap();
163             }
164         } else if socket.may_send() {
165             debug!("close");
166             socket.close();
167         }
168 
169         phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
170     }
171 }
172