ethernet.rs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  1. // Heads up! Before working on this file you should read the parts
  2. // of RFC 1122 that discuss Ethernet, ARP and IP.
  3. use core::cmp;
  4. use managed::ManagedSlice;
  5. use {Error, Result};
  6. use phy::{Device, DeviceCapabilities, RxToken, TxToken};
  7. use wire::pretty_print::PrettyPrinter;
  8. use wire::{EthernetAddress, EthernetProtocol, EthernetFrame};
  9. use wire::{Ipv4Address};
  10. use wire::{IpAddress, IpProtocol, IpRepr, IpCidr};
  11. use wire::{ArpPacket, ArpRepr, ArpOperation};
  12. use wire::{Ipv4Packet, Ipv4Repr};
  13. use wire::{Icmpv4Packet, Icmpv4Repr, Icmpv4DstUnreachable};
  14. #[cfg(feature = "socket-udp")]
  15. use wire::{UdpPacket, UdpRepr};
  16. #[cfg(feature = "socket-tcp")]
  17. use wire::{TcpPacket, TcpRepr, TcpControl};
  18. use socket::{Socket, SocketSet, AnySocket};
  19. #[cfg(feature = "socket-raw")]
  20. use socket::RawSocket;
  21. #[cfg(feature = "socket-icmp")]
  22. use socket::IcmpSocket;
  23. #[cfg(feature = "socket-udp")]
  24. use socket::UdpSocket;
  25. #[cfg(feature = "socket-tcp")]
  26. use socket::TcpSocket;
  27. use super::{NeighborCache, NeighborAnswer};
  28. /// An Ethernet network interface.
  29. ///
  30. /// The network interface logically owns a number of other data structures; to avoid
  31. /// a dependency on heap allocation, it instead owns a `BorrowMut<[T]>`, which can be
  32. /// a `&mut [T]`, or `Vec<T>` if a heap is available.
  33. pub struct Interface<'b, 'c, DeviceT: for<'d> Device<'d>> {
  34. device: DeviceT,
  35. inner: InterfaceInner<'b, 'c>,
  36. }
  37. /// The device independent part of an Ethernet network interface.
  38. ///
  39. /// Separating the device from the data required for prorcessing and dispatching makes
  40. /// it possible to borrow them independently. For example, the tx and rx tokens borrow
  41. /// the `device` mutably until they're used, which makes it impossible to call other
  42. /// methods on the `Interface` in this time (since its `device` field is borrowed
  43. /// exclusively). However, it is still possible to call methods on its `inner` field.
  44. struct InterfaceInner<'b, 'c> {
  45. neighbor_cache: NeighborCache<'b>,
  46. ethernet_addr: EthernetAddress,
  47. ip_addrs: ManagedSlice<'c, IpCidr>,
  48. ipv4_gateway: Option<Ipv4Address>,
  49. device_capabilities: DeviceCapabilities,
  50. }
  51. /// A builder structure used for creating a Ethernet network
  52. /// interface.
  53. pub struct InterfaceBuilder <'b, 'c, DeviceT: for<'d> Device<'d>> {
  54. device: DeviceT,
  55. ethernet_addr: Option<EthernetAddress>,
  56. neighbor_cache: Option<NeighborCache<'b>>,
  57. ip_addrs: Option<ManagedSlice<'c, IpCidr>>,
  58. ipv4_gateway: Option<Ipv4Address>,
  59. }
  60. impl<'b, 'c, DeviceT> InterfaceBuilder<'b, 'c, DeviceT>
  61. where DeviceT: for<'d> Device<'d> {
  62. /// Create a builder used for creating a network interface using the
  63. /// given device and address.
  64. ///
  65. /// # Examples
  66. ///
  67. /// ```
  68. /// # use std::collections::BTreeMap;
  69. /// use smoltcp::iface::{EthernetInterfaceBuilder, NeighborCache};
  70. /// # use smoltcp::phy::Loopback;
  71. /// use smoltcp::wire::{EthernetAddress, IpCidr, IpAddress};
  72. ///
  73. /// let device = // ...
  74. /// # Loopback::new();
  75. /// let hw_addr = // ...
  76. /// # EthernetAddress::default();
  77. /// let neighbor_cache = // ...
  78. /// # NeighborCache::new(BTreeMap::new());
  79. /// let ip_addrs = // ...
  80. /// # [];
  81. /// let iface = EthernetInterfaceBuilder::new(device)
  82. /// .ethernet_addr(hw_addr)
  83. /// .neighbor_cache(neighbor_cache)
  84. /// .ip_addrs(ip_addrs)
  85. /// .finalize();
  86. /// ```
  87. pub fn new(device: DeviceT) -> InterfaceBuilder<'b, 'c, DeviceT> {
  88. InterfaceBuilder {
  89. device: device,
  90. ethernet_addr: None,
  91. neighbor_cache: None,
  92. ip_addrs: None,
  93. ipv4_gateway: None
  94. }
  95. }
  96. /// Set the Ethernet address the interface will use. See also
  97. /// [ethernet_addr].
  98. ///
  99. /// # Panics
  100. /// This function panics if the address is not unicast.
  101. ///
  102. /// [ethernet_addr]: struct.EthernetInterface.html#method.ethernet_addr
  103. pub fn ethernet_addr(mut self, addr: EthernetAddress) -> InterfaceBuilder<'b, 'c, DeviceT> {
  104. InterfaceInner::check_ethernet_addr(&addr);
  105. self.ethernet_addr = Some(addr);
  106. self
  107. }
  108. /// Set the IP addresses the interface will use. See also
  109. /// [ip_addrs].
  110. ///
  111. /// # Panics
  112. /// This function panics if any of the addresses is not unicast.
  113. ///
  114. /// [ip_addrs]: struct.EthernetInterface.html#method.ip_addrs
  115. pub fn ip_addrs<T: Into<ManagedSlice<'c, IpCidr>>>(mut self, ips: T) -> InterfaceBuilder<'b, 'c, DeviceT> {
  116. let ips = ips.into();
  117. InterfaceInner::check_ip_addrs(&ips);
  118. self.ip_addrs = Some(ips);
  119. self
  120. }
  121. /// Set the IPv4 gateway the interface will use. See also
  122. /// [ipv4_gateway].
  123. ///
  124. /// # Panics
  125. /// This function panics if the given address is not unicast.
  126. ///
  127. /// [ipv4_gateway]: struct.EthernetInterface.html#method.ipv4_gateway
  128. pub fn ipv4_gateway<T>(mut self, gateway: T) -> InterfaceBuilder<'b, 'c, DeviceT>
  129. where T: Into<Ipv4Address> {
  130. let addr = gateway.into();
  131. InterfaceInner::check_gateway_addr(&addr);
  132. self.ipv4_gateway = Some(addr);
  133. self
  134. }
  135. /// Set the Neighbor Cache the interface will use.
  136. pub fn neighbor_cache(mut self, neighbor_cache: NeighborCache<'b>) -> InterfaceBuilder<'b, 'c, DeviceT> {
  137. self.neighbor_cache = Some(neighbor_cache);
  138. self
  139. }
  140. /// Create a network interface using the previously provided configuration.
  141. ///
  142. /// # Panics
  143. /// If a required option is not provided, this function will panic. Required
  144. /// options are:
  145. ///
  146. /// - [ethernet_addr]
  147. /// - [neighbor_cache]
  148. /// - [ip_addrs]
  149. ///
  150. /// [ethernet_addr]: #method.ethernet_addr
  151. /// [neighbor_cache]: #method.neighbor_cache
  152. /// [ip_addrs]: #method.ip_addrs
  153. pub fn finalize(self) -> Interface<'b, 'c, DeviceT> {
  154. // TODO: Limit the number of required options.
  155. match (self.ethernet_addr, self.neighbor_cache, self.ip_addrs) {
  156. (Some(ethernet_addr), Some(neighbor_cache), Some(ip_addrs)) => {
  157. let device_capabilities = self.device.capabilities();
  158. Interface {
  159. device: self.device,
  160. inner: InterfaceInner {
  161. ethernet_addr, device_capabilities, neighbor_cache,
  162. ip_addrs, ipv4_gateway: self.ipv4_gateway,
  163. }
  164. }
  165. },
  166. _ => panic!("a required option was not set"),
  167. }
  168. }
  169. }
  170. #[derive(Debug, PartialEq)]
  171. enum Packet<'a> {
  172. None,
  173. Arp(ArpRepr),
  174. Icmpv4((Ipv4Repr, Icmpv4Repr<'a>)),
  175. #[cfg(feature = "socket-raw")]
  176. Raw((IpRepr, &'a [u8])),
  177. #[cfg(feature = "socket-udp")]
  178. Udp((IpRepr, UdpRepr<'a>)),
  179. #[cfg(feature = "socket-tcp")]
  180. Tcp((IpRepr, TcpRepr<'a>))
  181. }
  182. impl<'a> Packet<'a> {
  183. fn neighbor_addr(&self) -> Option<IpAddress> {
  184. match self {
  185. &Packet::None | &Packet::Arp(_) => None,
  186. &Packet::Icmpv4((ref ipv4_repr, _)) => Some(ipv4_repr.dst_addr.into()),
  187. #[cfg(feature = "socket-raw")]
  188. &Packet::Raw((ref ip_repr, _)) => Some(ip_repr.dst_addr()),
  189. #[cfg(feature = "socket-udp")]
  190. &Packet::Udp((ref ip_repr, _)) => Some(ip_repr.dst_addr()),
  191. #[cfg(feature = "socket-tcp")]
  192. &Packet::Tcp((ref ip_repr, _)) => Some(ip_repr.dst_addr())
  193. }
  194. }
  195. }
  196. impl<'b, 'c, DeviceT> Interface<'b, 'c, DeviceT>
  197. where DeviceT: for<'d> Device<'d> {
  198. /// Get the Ethernet address of the interface.
  199. pub fn ethernet_addr(&self) -> EthernetAddress {
  200. self.inner.ethernet_addr
  201. }
  202. /// Set the Ethernet address of the interface.
  203. ///
  204. /// # Panics
  205. /// This function panics if the address is not unicast.
  206. pub fn set_ethernet_addr(&mut self, addr: EthernetAddress) {
  207. self.inner.ethernet_addr = addr;
  208. InterfaceInner::check_ethernet_addr(&self.inner.ethernet_addr);
  209. }
  210. /// Get the IP addresses of the interface.
  211. pub fn ip_addrs(&self) -> &[IpCidr] {
  212. self.inner.ip_addrs.as_ref()
  213. }
  214. /// Update the IP addresses of the interface.
  215. ///
  216. /// # Panics
  217. /// This function panics if any of the addresses is not unicast.
  218. pub fn update_ip_addrs<F: FnOnce(&mut ManagedSlice<'c, IpCidr>)>(&mut self, f: F) {
  219. f(&mut self.inner.ip_addrs);
  220. InterfaceInner::check_ip_addrs(&self.inner.ip_addrs)
  221. }
  222. /// Check whether the interface has the given IP address assigned.
  223. pub fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  224. self.inner.has_ip_addr(addr)
  225. }
  226. /// Get the IPv4 gateway of the interface.
  227. pub fn ipv4_gateway(&self) -> Option<Ipv4Address> {
  228. self.inner.ipv4_gateway
  229. }
  230. /// Set the IPv4 gateway of the interface.
  231. pub fn set_ipv4_gateway<GatewayAddrT>(&mut self, gateway: GatewayAddrT)
  232. where GatewayAddrT: Into<Option<Ipv4Address>> {
  233. self.inner.ipv4_gateway = gateway.into();
  234. }
  235. /// Transmit packets queued in the given sockets, and receive packets queued
  236. /// in the device.
  237. ///
  238. /// The timestamp must be a number of milliseconds, monotonically increasing
  239. /// since an arbitrary moment in time, such as system startup.
  240. ///
  241. /// This function returns a _soft deadline_ for calling it the next time.
  242. /// That is, if `iface.poll(&mut sockets, 1000)` returns `Ok(Some(2000))`,
  243. /// it harmless (but wastes energy) to call it 500 ms later, and potentially
  244. /// harmful (impacting quality of service) to call it 1500 ms later.
  245. ///
  246. /// # Errors
  247. /// This method will routinely return errors in response to normal network
  248. /// activity as well as certain boundary conditions such as buffer exhaustion.
  249. /// These errors are provided as an aid for troubleshooting, and are meant
  250. /// to be logged and ignored.
  251. ///
  252. /// As a special case, `Err(Error::Unrecognized)` is returned in response to
  253. /// packets containing any unsupported protocol, option, or form, which is
  254. /// a very common occurrence and on a production system it should not even
  255. /// be logged.
  256. pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<Option<u64>> {
  257. self.socket_egress(sockets, timestamp)?;
  258. if self.socket_ingress(sockets, timestamp)? {
  259. Ok(Some(0))
  260. } else {
  261. Ok(sockets.iter().filter_map(|socket| {
  262. let socket_poll_at = socket.poll_at();
  263. socket.meta().poll_at(socket_poll_at, |ip_addr|
  264. self.inner.has_neighbor(&ip_addr, timestamp))
  265. }).min())
  266. }
  267. }
  268. fn socket_ingress(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<bool> {
  269. let mut processed_any = false;
  270. loop {
  271. let &mut Self { ref mut device, ref mut inner } = self;
  272. let (rx_token, tx_token) = match device.receive() {
  273. None => break,
  274. Some(tokens) => tokens,
  275. };
  276. let dispatch_result = rx_token.consume(timestamp, |frame| {
  277. let response = inner.process_ethernet(sockets, timestamp, &frame).map_err(|err| {
  278. net_debug!("cannot process ingress packet: {}", err);
  279. net_debug!("packet dump follows:\n{}",
  280. PrettyPrinter::<EthernetFrame<&[u8]>>::new("", &frame));
  281. err
  282. })?;
  283. processed_any = true;
  284. inner.dispatch(tx_token, timestamp, response)
  285. });
  286. dispatch_result.map_err(|err| {
  287. net_debug!("cannot dispatch response packet: {}", err);
  288. err
  289. })?;
  290. }
  291. Ok(processed_any)
  292. }
  293. fn socket_egress(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<()> {
  294. let mut caps = self.device.capabilities();
  295. caps.max_transmission_unit -= EthernetFrame::<&[u8]>::header_len();
  296. for mut socket in sockets.iter_mut() {
  297. if !socket.meta_mut().egress_permitted(|ip_addr|
  298. self.inner.has_neighbor(&ip_addr, timestamp)) {
  299. continue
  300. }
  301. let mut neighbor_addr = None;
  302. let mut device_result = Ok(());
  303. let &mut Self { ref mut device, ref mut inner } = self;
  304. let socket_result =
  305. match *socket {
  306. #[cfg(feature = "socket-raw")]
  307. Socket::Raw(ref mut socket) =>
  308. socket.dispatch(|response| {
  309. let response = Packet::Raw(response);
  310. neighbor_addr = response.neighbor_addr();
  311. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  312. device_result = inner.dispatch(tx_token, timestamp, response);
  313. device_result
  314. }, &caps.checksum),
  315. #[cfg(feature = "socket-icmp")]
  316. Socket::Icmp(ref mut socket) =>
  317. socket.dispatch(&caps, |response| {
  318. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  319. device_result = match response {
  320. (IpRepr::Ipv4(ipv4_repr), icmpv4_repr) => {
  321. let response = Packet::Icmpv4((ipv4_repr, icmpv4_repr));
  322. neighbor_addr = response.neighbor_addr();
  323. inner.dispatch(tx_token, timestamp, response)
  324. }
  325. _ => Err(Error::Unaddressable),
  326. };
  327. device_result
  328. }),
  329. #[cfg(feature = "socket-udp")]
  330. Socket::Udp(ref mut socket) =>
  331. socket.dispatch(|response| {
  332. let response = Packet::Udp(response);
  333. neighbor_addr = response.neighbor_addr();
  334. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  335. device_result = inner.dispatch(tx_token, timestamp, response);
  336. device_result
  337. }),
  338. #[cfg(feature = "socket-tcp")]
  339. Socket::Tcp(ref mut socket) =>
  340. socket.dispatch(timestamp, &caps, |response| {
  341. let response = Packet::Tcp(response);
  342. neighbor_addr = response.neighbor_addr();
  343. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  344. device_result = inner.dispatch(tx_token, timestamp, response);
  345. device_result
  346. }),
  347. Socket::__Nonexhaustive(_) => unreachable!()
  348. };
  349. match (device_result, socket_result) {
  350. (Err(Error::Exhausted), _) => break, // nowhere to transmit
  351. (Ok(()), Err(Error::Exhausted)) => (), // nothing to transmit
  352. (Err(Error::Unaddressable), _) => {
  353. // `NeighborCache` already takes care of rate limiting the neighbor discovery
  354. // requests from the socket. However, without an additional rate limiting
  355. // mechanism, we would spin on every socket that has yet to discover its
  356. // neighboor.
  357. socket.meta_mut().neighbor_missing(timestamp,
  358. neighbor_addr.expect("non-IP response packet"));
  359. break
  360. }
  361. (Err(err), _) | (_, Err(err)) => {
  362. net_debug!("{}: cannot dispatch egress packet: {}",
  363. socket.meta().handle, err);
  364. return Err(err)
  365. }
  366. (Ok(()), Ok(())) => ()
  367. }
  368. }
  369. Ok(())
  370. }
  371. }
  372. impl<'b, 'c> InterfaceInner<'b, 'c> {
  373. fn check_ethernet_addr(addr: &EthernetAddress) {
  374. if addr.is_multicast() {
  375. panic!("Ethernet address {} is not unicast", addr)
  376. }
  377. }
  378. fn check_ip_addrs(addrs: &[IpCidr]) {
  379. for cidr in addrs {
  380. if !cidr.address().is_unicast() {
  381. panic!("IP address {} is not unicast", cidr.address())
  382. }
  383. }
  384. }
  385. fn check_gateway_addr(addr: &Ipv4Address) {
  386. if !addr.is_unicast() {
  387. panic!("gateway IP address {} is not unicast", addr);
  388. }
  389. }
  390. /// Check whether the interface has the given IP address assigned.
  391. fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  392. let addr = addr.into();
  393. self.ip_addrs.iter().any(|probe| probe.address() == addr)
  394. }
  395. fn process_ethernet<'frame, T: AsRef<[u8]>>
  396. (&mut self, sockets: &mut SocketSet, timestamp: u64, frame: &'frame T) ->
  397. Result<Packet<'frame>>
  398. {
  399. let eth_frame = EthernetFrame::new_checked(frame)?;
  400. // Ignore any packets not directed to our hardware address.
  401. if !eth_frame.dst_addr().is_broadcast() &&
  402. eth_frame.dst_addr() != self.ethernet_addr {
  403. return Ok(Packet::None)
  404. }
  405. match eth_frame.ethertype() {
  406. EthernetProtocol::Arp =>
  407. self.process_arp(timestamp, &eth_frame),
  408. EthernetProtocol::Ipv4 =>
  409. self.process_ipv4(sockets, timestamp, &eth_frame),
  410. // Drop all other traffic.
  411. _ => Err(Error::Unrecognized),
  412. }
  413. }
  414. fn process_arp<'frame, T: AsRef<[u8]>>
  415. (&mut self, timestamp: u64, eth_frame: &EthernetFrame<&'frame T>) ->
  416. Result<Packet<'frame>>
  417. {
  418. let arp_packet = ArpPacket::new_checked(eth_frame.payload())?;
  419. let arp_repr = ArpRepr::parse(&arp_packet)?;
  420. match arp_repr {
  421. // Respond to ARP requests aimed at us, and fill the ARP cache from all ARP
  422. // requests and replies, to minimize the chance that we have to perform
  423. // an explicit ARP request.
  424. ArpRepr::EthernetIpv4 {
  425. operation, source_hardware_addr, source_protocol_addr, target_protocol_addr, ..
  426. } => {
  427. if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() {
  428. self.neighbor_cache.fill(source_protocol_addr.into(),
  429. source_hardware_addr,
  430. timestamp);
  431. } else {
  432. // Discard packets with non-unicast source addresses.
  433. net_debug!("non-unicast source address");
  434. return Err(Error::Malformed)
  435. }
  436. if operation == ArpOperation::Request && self.has_ip_addr(target_protocol_addr) {
  437. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  438. operation: ArpOperation::Reply,
  439. source_hardware_addr: self.ethernet_addr,
  440. source_protocol_addr: target_protocol_addr,
  441. target_hardware_addr: source_hardware_addr,
  442. target_protocol_addr: source_protocol_addr
  443. }))
  444. } else {
  445. Ok(Packet::None)
  446. }
  447. }
  448. _ => Err(Error::Unrecognized)
  449. }
  450. }
  451. fn process_ipv4<'frame, T: AsRef<[u8]>>
  452. (&mut self, sockets: &mut SocketSet, timestamp: u64,
  453. eth_frame: &EthernetFrame<&'frame T>) ->
  454. Result<Packet<'frame>>
  455. {
  456. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
  457. let checksum_caps = self.device_capabilities.checksum.clone();
  458. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &checksum_caps)?;
  459. if !ipv4_repr.src_addr.is_unicast() {
  460. // Discard packets with non-unicast source addresses.
  461. net_debug!("non-unicast source address");
  462. return Err(Error::Malformed)
  463. }
  464. if eth_frame.src_addr().is_unicast() {
  465. // Fill the neighbor cache from IP header of unicast frames.
  466. let ip_addr = IpAddress::Ipv4(ipv4_repr.src_addr);
  467. if self.in_same_network(&ip_addr) {
  468. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  469. }
  470. }
  471. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  472. let ip_payload = ipv4_packet.payload();
  473. #[cfg(feature = "socket-raw")]
  474. let mut handled_by_raw_socket = false;
  475. // Pass every IP packet to all raw sockets we have registered.
  476. #[cfg(feature = "socket-raw")]
  477. for mut raw_socket in sockets.iter_mut().filter_map(RawSocket::downcast) {
  478. if !raw_socket.accepts(&ip_repr) { continue }
  479. match raw_socket.process(&ip_repr, ip_payload, &checksum_caps) {
  480. // The packet is valid and handled by socket.
  481. Ok(()) => handled_by_raw_socket = true,
  482. // The socket buffer is full.
  483. Err(Error::Exhausted) => (),
  484. // Raw sockets don't validate the packets in any way.
  485. Err(_) => unreachable!(),
  486. }
  487. }
  488. if !ipv4_repr.dst_addr.is_broadcast() && !self.has_ip_addr(ipv4_repr.dst_addr) {
  489. // Ignore IP packets not directed at us.
  490. return Ok(Packet::None)
  491. }
  492. match ipv4_repr.protocol {
  493. IpProtocol::Icmp =>
  494. self.process_icmpv4(sockets, ip_repr, ip_payload),
  495. #[cfg(feature = "socket-udp")]
  496. IpProtocol::Udp =>
  497. self.process_udp(sockets, ip_repr, ip_payload),
  498. #[cfg(feature = "socket-tcp")]
  499. IpProtocol::Tcp =>
  500. self.process_tcp(sockets, timestamp, ip_repr, ip_payload),
  501. #[cfg(feature = "socket-raw")]
  502. _ if handled_by_raw_socket =>
  503. Ok(Packet::None),
  504. _ => {
  505. // Send back as much of the original payload as we can
  506. let payload_len = cmp::min(
  507. ip_payload.len(), self.device_capabilities.max_transmission_unit);
  508. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  509. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  510. header: ipv4_repr,
  511. data: &ip_payload[0..payload_len]
  512. };
  513. Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr))
  514. }
  515. }
  516. }
  517. fn process_icmpv4<'frame>(&self, _sockets: &mut SocketSet, ip_repr: IpRepr,
  518. ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  519. {
  520. let icmp_packet = Icmpv4Packet::new_checked(ip_payload)?;
  521. let checksum_caps = self.device_capabilities.checksum.clone();
  522. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &checksum_caps)?;
  523. #[cfg(feature = "socket-icmp")]
  524. let mut handled_by_icmp_socket = false;
  525. #[cfg(feature = "socket-icmp")]
  526. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  527. if !icmp_socket.accepts(&ip_repr, &icmp_repr, &checksum_caps) { continue }
  528. match icmp_socket.process(&ip_repr, &icmp_repr, &checksum_caps) {
  529. // The packet is valid and handled by socket.
  530. Ok(()) => handled_by_icmp_socket = true,
  531. // The socket buffer is full.
  532. Err(Error::Exhausted) => (),
  533. // ICMP sockets don't validate the packets in any way.
  534. Err(_) => unreachable!(),
  535. }
  536. }
  537. match icmp_repr {
  538. // Respond to echo requests.
  539. Icmpv4Repr::EchoRequest { ident, seq_no, data } => {
  540. let icmp_reply_repr = Icmpv4Repr::EchoReply {
  541. ident: ident,
  542. seq_no: seq_no,
  543. data: data
  544. };
  545. match ip_repr {
  546. IpRepr::Ipv4(ipv4_repr) => Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr)),
  547. _ => Err(Error::Unrecognized),
  548. }
  549. }
  550. // Ignore any echo replies.
  551. Icmpv4Repr::EchoReply { .. } => Ok(Packet::None),
  552. // Don't report an error if a packet with unknown type
  553. // has been handled by an ICMP socket
  554. #[cfg(feature = "socket-icmp")]
  555. _ if handled_by_icmp_socket => Ok(Packet::None),
  556. // FIXME: do something correct here?
  557. _ => Err(Error::Unrecognized),
  558. }
  559. }
  560. fn icmpv4_reply<'frame, 'icmp: 'frame>
  561. (&self, ipv4_repr: Ipv4Repr, icmp_repr: Icmpv4Repr<'icmp>) ->
  562. Packet<'frame>
  563. {
  564. if ipv4_repr.dst_addr.is_unicast() {
  565. let ipv4_reply_repr = Ipv4Repr {
  566. src_addr: ipv4_repr.dst_addr,
  567. dst_addr: ipv4_repr.src_addr,
  568. protocol: IpProtocol::Icmp,
  569. payload_len: icmp_repr.buffer_len(),
  570. ttl: 64
  571. };
  572. Packet::Icmpv4((ipv4_reply_repr, icmp_repr))
  573. } else {
  574. // Do not send any ICMP replies to a broadcast destination address.
  575. Packet::None
  576. }
  577. }
  578. #[cfg(feature = "socket-udp")]
  579. fn process_udp<'frame>(&self, sockets: &mut SocketSet,
  580. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  581. Result<Packet<'frame>>
  582. {
  583. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  584. let udp_packet = UdpPacket::new_checked(ip_payload)?;
  585. let checksum_caps = self.device_capabilities.checksum.clone();
  586. let udp_repr = UdpRepr::parse(&udp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  587. for mut udp_socket in sockets.iter_mut().filter_map(UdpSocket::downcast) {
  588. if !udp_socket.accepts(&ip_repr, &udp_repr) { continue }
  589. match udp_socket.process(&ip_repr, &udp_repr) {
  590. // The packet is valid and handled by socket.
  591. Ok(()) => return Ok(Packet::None),
  592. // The packet is malformed, or the socket buffer is full.
  593. Err(e) => return Err(e)
  594. }
  595. }
  596. // The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  597. match ip_repr {
  598. IpRepr::Ipv4(ipv4_repr) => {
  599. // Send back as much of the original payload as we can
  600. let payload_len = cmp::min(
  601. ip_payload.len(), self.device_capabilities.max_transmission_unit);
  602. let icmpv4_reply_repr = Icmpv4Repr::DstUnreachable {
  603. reason: Icmpv4DstUnreachable::PortUnreachable,
  604. header: ipv4_repr,
  605. data: &ip_payload[0..payload_len]
  606. };
  607. Ok(self.icmpv4_reply(ipv4_repr, icmpv4_reply_repr))
  608. },
  609. IpRepr::Unspecified { .. } |
  610. IpRepr::__Nonexhaustive =>
  611. unreachable!()
  612. }
  613. }
  614. #[cfg(feature = "socket-tcp")]
  615. fn process_tcp<'frame>(&self, sockets: &mut SocketSet, timestamp: u64,
  616. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  617. Result<Packet<'frame>>
  618. {
  619. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  620. let tcp_packet = TcpPacket::new_checked(ip_payload)?;
  621. let checksum_caps = self.device_capabilities.checksum.clone();
  622. let tcp_repr = TcpRepr::parse(&tcp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  623. for mut tcp_socket in sockets.iter_mut().filter_map(TcpSocket::downcast) {
  624. if !tcp_socket.accepts(&ip_repr, &tcp_repr) { continue }
  625. match tcp_socket.process(timestamp, &ip_repr, &tcp_repr) {
  626. // The packet is valid and handled by socket.
  627. Ok(reply) => return Ok(reply.map_or(Packet::None, Packet::Tcp)),
  628. // The packet is malformed, or doesn't match the socket state,
  629. // or the socket buffer is full.
  630. Err(e) => return Err(e)
  631. }
  632. }
  633. if tcp_repr.control == TcpControl::Rst {
  634. // Never reply to a TCP RST packet with another TCP RST packet.
  635. Ok(Packet::None)
  636. } else {
  637. // The packet wasn't handled by a socket, send a TCP RST packet.
  638. Ok(Packet::Tcp(TcpSocket::rst_reply(&ip_repr, &tcp_repr)))
  639. }
  640. }
  641. fn dispatch<Tx>(&mut self, tx_token: Tx, timestamp: u64,
  642. packet: Packet) -> Result<()>
  643. where Tx: TxToken
  644. {
  645. let checksum_caps = self.device_capabilities.checksum.clone();
  646. match packet {
  647. Packet::Arp(arp_repr) => {
  648. let dst_hardware_addr =
  649. match arp_repr {
  650. ArpRepr::EthernetIpv4 { target_hardware_addr, .. } => target_hardware_addr,
  651. _ => unreachable!()
  652. };
  653. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  654. frame.set_dst_addr(dst_hardware_addr);
  655. frame.set_ethertype(EthernetProtocol::Arp);
  656. let mut packet = ArpPacket::new(frame.payload_mut());
  657. arp_repr.emit(&mut packet);
  658. })
  659. },
  660. Packet::Icmpv4((ipv4_repr, icmpv4_repr)) => {
  661. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv4(ipv4_repr),
  662. |_ip_repr, payload| {
  663. icmpv4_repr.emit(&mut Icmpv4Packet::new(payload), &checksum_caps);
  664. })
  665. }
  666. #[cfg(feature = "socket-raw")]
  667. Packet::Raw((ip_repr, raw_packet)) => {
  668. self.dispatch_ip(tx_token, timestamp, ip_repr, |_ip_repr, payload| {
  669. payload.copy_from_slice(raw_packet);
  670. })
  671. }
  672. #[cfg(feature = "socket-udp")]
  673. Packet::Udp((ip_repr, udp_repr)) => {
  674. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  675. udp_repr.emit(&mut UdpPacket::new(payload),
  676. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  677. &checksum_caps);
  678. })
  679. }
  680. #[cfg(feature = "socket-tcp")]
  681. Packet::Tcp((ip_repr, mut tcp_repr)) => {
  682. let caps = self.device_capabilities.clone();
  683. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  684. // This is a terrible hack to make TCP performance more acceptable on systems
  685. // where the TCP buffers are significantly larger than network buffers,
  686. // e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
  687. // together with four 1500 B Ethernet receive buffers. If left untreated,
  688. // this would result in our peer pushing our window and sever packet loss.
  689. //
  690. // I'm really not happy about this "solution" but I don't know what else to do.
  691. if let Some(max_burst_size) = caps.max_burst_size {
  692. let mut max_segment_size = caps.max_transmission_unit;
  693. max_segment_size -= EthernetFrame::<&[u8]>::header_len();
  694. max_segment_size -= ip_repr.buffer_len();
  695. max_segment_size -= tcp_repr.header_len();
  696. let max_window_size = max_burst_size * max_segment_size;
  697. if tcp_repr.window_len as usize > max_window_size {
  698. tcp_repr.window_len = max_window_size as u16;
  699. }
  700. }
  701. tcp_repr.emit(&mut TcpPacket::new(payload),
  702. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  703. &checksum_caps);
  704. })
  705. }
  706. Packet::None => Ok(())
  707. }
  708. }
  709. fn dispatch_ethernet<Tx, F>(&mut self, tx_token: Tx, timestamp: u64,
  710. buffer_len: usize, f: F) -> Result<()>
  711. where Tx: TxToken, F: FnOnce(EthernetFrame<&mut [u8]>)
  712. {
  713. let tx_len = EthernetFrame::<&[u8]>::buffer_len(buffer_len);
  714. tx_token.consume(timestamp, tx_len, |tx_buffer| {
  715. debug_assert!(tx_buffer.as_ref().len() == tx_len);
  716. let mut frame = EthernetFrame::new(tx_buffer.as_mut());
  717. frame.set_src_addr(self.ethernet_addr);
  718. f(frame);
  719. Ok(())
  720. })
  721. }
  722. fn in_same_network(&self, addr: &IpAddress) -> bool {
  723. self.ip_addrs
  724. .iter()
  725. .find(|cidr| cidr.contains_addr(addr))
  726. .is_some()
  727. }
  728. fn route(&self, addr: &IpAddress) -> Result<IpAddress> {
  729. // Send directly.
  730. if self.in_same_network(addr) {
  731. return Ok(addr.clone())
  732. }
  733. // Route via a gateway.
  734. match (addr, self.ipv4_gateway) {
  735. (&IpAddress::Ipv4(_), Some(gateway)) => Ok(gateway.into()),
  736. _ => Err(Error::Unaddressable)
  737. }
  738. }
  739. fn has_neighbor<'a>(&self, addr: &'a IpAddress, timestamp: u64) -> bool {
  740. match self.route(addr) {
  741. Ok(routed_addr) => {
  742. self.neighbor_cache
  743. .lookup_pure(&routed_addr, timestamp)
  744. .is_some()
  745. }
  746. Err(_) => false
  747. }
  748. }
  749. fn lookup_hardware_addr<Tx>(&mut self, tx_token: Tx, timestamp: u64,
  750. src_addr: &IpAddress, dst_addr: &IpAddress) ->
  751. Result<(EthernetAddress, Tx)>
  752. where Tx: TxToken
  753. {
  754. let dst_addr = self.route(dst_addr)?;
  755. match self.neighbor_cache.lookup(&dst_addr, timestamp) {
  756. NeighborAnswer::Found(hardware_addr) =>
  757. return Ok((hardware_addr, tx_token)),
  758. NeighborAnswer::RateLimited =>
  759. return Err(Error::Unaddressable),
  760. NeighborAnswer::NotFound => (),
  761. }
  762. match (src_addr, dst_addr) {
  763. (&IpAddress::Ipv4(src_addr), IpAddress::Ipv4(dst_addr)) => {
  764. net_debug!("address {} not in neighbor cache, sending ARP request",
  765. dst_addr);
  766. let arp_repr = ArpRepr::EthernetIpv4 {
  767. operation: ArpOperation::Request,
  768. source_hardware_addr: self.ethernet_addr,
  769. source_protocol_addr: src_addr,
  770. target_hardware_addr: EthernetAddress::BROADCAST,
  771. target_protocol_addr: dst_addr,
  772. };
  773. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  774. frame.set_dst_addr(EthernetAddress::BROADCAST);
  775. frame.set_ethertype(EthernetProtocol::Arp);
  776. arp_repr.emit(&mut ArpPacket::new(frame.payload_mut()))
  777. })?;
  778. Err(Error::Unaddressable)
  779. }
  780. _ => unreachable!()
  781. }
  782. }
  783. fn dispatch_ip<Tx, F>(&mut self, tx_token: Tx, timestamp: u64,
  784. ip_repr: IpRepr, f: F) -> Result<()>
  785. where Tx: TxToken, F: FnOnce(IpRepr, &mut [u8])
  786. {
  787. let ip_repr = ip_repr.lower(&self.ip_addrs)?;
  788. let checksum_caps = self.device_capabilities.checksum.clone();
  789. let (dst_hardware_addr, tx_token) =
  790. self.lookup_hardware_addr(tx_token, timestamp,
  791. &ip_repr.src_addr(), &ip_repr.dst_addr())?;
  792. self.dispatch_ethernet(tx_token, timestamp, ip_repr.total_len(), |mut frame| {
  793. frame.set_dst_addr(dst_hardware_addr);
  794. match ip_repr {
  795. IpRepr::Ipv4(_) => frame.set_ethertype(EthernetProtocol::Ipv4),
  796. _ => unreachable!()
  797. }
  798. ip_repr.emit(frame.payload_mut(), &checksum_caps);
  799. let payload = &mut frame.payload_mut()[ip_repr.buffer_len()..];
  800. f(ip_repr, payload)
  801. })
  802. }
  803. }
  804. #[cfg(test)]
  805. mod test {
  806. use std::collections::BTreeMap;
  807. use {Result, Error};
  808. use super::InterfaceBuilder;
  809. use iface::{NeighborCache, EthernetInterface};
  810. use phy::{self, Loopback, ChecksumCapabilities};
  811. use socket::SocketSet;
  812. use wire::{ArpOperation, ArpPacket, ArpRepr};
  813. use wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
  814. use wire::{IpAddress, IpCidr, IpProtocol, IpRepr};
  815. use wire::{Ipv4Address, Ipv4Repr};
  816. use wire::{Icmpv4Repr, Icmpv4DstUnreachable};
  817. use wire::{UdpPacket, UdpRepr};
  818. use super::Packet;
  819. fn create_loopback<'a, 'b>() -> (EthernetInterface<'static, 'b, Loopback>,
  820. SocketSet<'static, 'a, 'b>) {
  821. // Create a basic device
  822. let device = Loopback::new();
  823. let iface = InterfaceBuilder::new(device)
  824. .ethernet_addr(EthernetAddress::default())
  825. .neighbor_cache(NeighborCache::new(BTreeMap::new()))
  826. .ip_addrs([IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8)])
  827. .finalize();
  828. (iface, SocketSet::new(vec![]))
  829. }
  830. #[derive(Debug, PartialEq)]
  831. struct MockTxToken;
  832. impl phy::TxToken for MockTxToken {
  833. fn consume<R, F>(self, _: u64, _: usize, _: F) -> Result<R>
  834. where F: FnOnce(&mut [u8]) -> Result<R> {
  835. Err(Error::__Nonexhaustive)
  836. }
  837. }
  838. #[test]
  839. #[should_panic(expected = "a required option was not set")]
  840. fn test_builder_initialization_panic() {
  841. InterfaceBuilder::new(Loopback::new()).finalize();
  842. }
  843. #[test]
  844. fn test_no_icmp_to_broadcast() {
  845. let (mut iface, mut socket_set) = create_loopback();
  846. let mut eth_bytes = vec![0u8; 34];
  847. // Unknown Ipv4 Protocol
  848. //
  849. // Because the destination is the broadcast address
  850. // this should not trigger and Destination Unreachable
  851. // response. See RFC 1122 § 3.2.2.
  852. let repr = IpRepr::Ipv4(Ipv4Repr {
  853. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  854. dst_addr: Ipv4Address::BROADCAST,
  855. protocol: IpProtocol::Unknown(0x0c),
  856. payload_len: 0,
  857. ttl: 0x40
  858. });
  859. let frame = {
  860. let mut frame = EthernetFrame::new(&mut eth_bytes);
  861. frame.set_dst_addr(EthernetAddress::BROADCAST);
  862. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  863. frame.set_ethertype(EthernetProtocol::Ipv4);
  864. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  865. EthernetFrame::new(&*frame.into_inner())
  866. };
  867. // Ensure that the unknown protocol frame does not trigger an
  868. // ICMP error response when the destination address is a
  869. // broadcast address
  870. assert_eq!(iface.inner.process_ipv4(&mut socket_set, 0, &frame),
  871. Ok(Packet::None));
  872. }
  873. #[test]
  874. fn test_icmp_error_no_payload() {
  875. static NO_BYTES: [u8; 0] = [];
  876. let (mut iface, mut socket_set) = create_loopback();
  877. let mut eth_bytes = vec![0u8; 34];
  878. // Unknown Ipv4 Protocol with no payload
  879. let repr = IpRepr::Ipv4(Ipv4Repr {
  880. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  881. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  882. protocol: IpProtocol::Unknown(0x0c),
  883. payload_len: 0,
  884. ttl: 0x40
  885. });
  886. // emit the above repr to a frame
  887. let frame = {
  888. let mut frame = EthernetFrame::new(&mut eth_bytes);
  889. frame.set_dst_addr(EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  890. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  891. frame.set_ethertype(EthernetProtocol::Ipv4);
  892. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  893. EthernetFrame::new(&*frame.into_inner())
  894. };
  895. // The expected Destination Unreachable response due to the
  896. // unknown protocol
  897. let icmp_repr = Icmpv4Repr::DstUnreachable {
  898. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  899. header: Ipv4Repr {
  900. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  901. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  902. protocol: IpProtocol::Unknown(12),
  903. payload_len: 0,
  904. ttl: 64
  905. },
  906. data: &NO_BYTES
  907. };
  908. let expected_repr = Packet::Icmpv4((
  909. Ipv4Repr {
  910. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  911. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  912. protocol: IpProtocol::Icmp,
  913. payload_len: icmp_repr.buffer_len(),
  914. ttl: 64
  915. },
  916. icmp_repr
  917. ));
  918. // Ensure that the unknown protocol triggers an error response.
  919. // And we correctly handle no payload.
  920. assert_eq!(iface.inner.process_ipv4(&mut socket_set, 0, &frame),
  921. Ok(expected_repr));
  922. }
  923. #[test]
  924. fn test_icmp_error_port_unreachable() {
  925. static UDP_PAYLOAD: [u8; 12] = [
  926. 0x48, 0x65, 0x6c, 0x6c,
  927. 0x6f, 0x2c, 0x20, 0x57,
  928. 0x6f, 0x6c, 0x64, 0x21
  929. ];
  930. let (iface, mut socket_set) = create_loopback();
  931. let mut udp_bytes_unicast = vec![0u8; 20];
  932. let mut udp_bytes_broadcast = vec![0u8; 20];
  933. let mut packet_unicast = UdpPacket::new(&mut udp_bytes_unicast);
  934. let mut packet_broadcast = UdpPacket::new(&mut udp_bytes_broadcast);
  935. let udp_repr = UdpRepr {
  936. src_port: 67,
  937. dst_port: 68,
  938. payload: &UDP_PAYLOAD
  939. };
  940. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  941. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  942. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  943. protocol: IpProtocol::Udp,
  944. payload_len: udp_repr.buffer_len(),
  945. ttl: 64
  946. });
  947. // Emit the representations to a packet
  948. udp_repr.emit(&mut packet_unicast, &ip_repr.src_addr(),
  949. &ip_repr.dst_addr(), &ChecksumCapabilities::default());
  950. let data = packet_unicast.into_inner();
  951. // The expected Destination Unreachable ICMPv4 error response due
  952. // to no sockets listening on the destination port.
  953. let icmp_repr = Icmpv4Repr::DstUnreachable {
  954. reason: Icmpv4DstUnreachable::PortUnreachable,
  955. header: Ipv4Repr {
  956. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  957. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  958. protocol: IpProtocol::Udp,
  959. payload_len: udp_repr.buffer_len(),
  960. ttl: 64
  961. },
  962. data: &data
  963. };
  964. let expected_repr = Packet::Icmpv4((
  965. Ipv4Repr {
  966. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  967. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  968. protocol: IpProtocol::Icmp,
  969. payload_len: icmp_repr.buffer_len(),
  970. ttl: 64
  971. },
  972. icmp_repr
  973. ));
  974. // Ensure that the unknown protocol triggers an error response.
  975. // And we correctly handle no payload.
  976. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, data),
  977. Ok(expected_repr));
  978. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  979. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  980. dst_addr: Ipv4Address::BROADCAST,
  981. protocol: IpProtocol::Udp,
  982. payload_len: udp_repr.buffer_len(),
  983. ttl: 64
  984. });
  985. // Emit the representations to a packet
  986. udp_repr.emit(&mut packet_broadcast, &ip_repr.src_addr(),
  987. &IpAddress::Ipv4(Ipv4Address::BROADCAST),
  988. &ChecksumCapabilities::default());
  989. // Ensure that the port unreachable error does not trigger an
  990. // ICMP error response when the destination address is a
  991. // broadcast address and no socket is bound to the port.
  992. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr,
  993. packet_broadcast.into_inner()), Ok(Packet::None));
  994. }
  995. #[test]
  996. #[cfg(feature = "socket-udp")]
  997. fn test_handle_udp_broadcast() {
  998. use socket::{UdpPacketBuffer, UdpSocket, UdpSocketBuffer};
  999. use wire::IpEndpoint;
  1000. static UDP_PAYLOAD: [u8; 5] = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
  1001. let (iface, mut socket_set) = create_loopback();
  1002. let rx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 15])]);
  1003. let tx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 15])]);
  1004. let udp_socket = UdpSocket::new(rx_buffer, tx_buffer);
  1005. let mut udp_bytes = vec![0u8; 13];
  1006. let mut packet = UdpPacket::new(&mut udp_bytes);
  1007. let socket_handle = socket_set.add(udp_socket);
  1008. let src_ip = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1009. let udp_repr = UdpRepr {
  1010. src_port: 67,
  1011. dst_port: 68,
  1012. payload: &UDP_PAYLOAD
  1013. };
  1014. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1015. src_addr: src_ip,
  1016. dst_addr: Ipv4Address::BROADCAST,
  1017. protocol: IpProtocol::Udp,
  1018. payload_len: udp_repr.buffer_len(),
  1019. ttl: 0x40
  1020. });
  1021. {
  1022. // Bind the socket to port 68
  1023. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1024. assert_eq!(socket.bind(68), Ok(()));
  1025. assert!(!socket.can_recv());
  1026. assert!(socket.can_send());
  1027. }
  1028. udp_repr.emit(&mut packet, &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1029. &ChecksumCapabilities::default());
  1030. // Packet should be handled by bound UDP socket
  1031. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, packet.into_inner()),
  1032. Ok(Packet::None));
  1033. {
  1034. // Make sure the payload to the UDP packet processed by process_udp is
  1035. // appended to the bound sockets rx_buffer
  1036. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1037. assert!(socket.can_recv());
  1038. assert_eq!(socket.recv(), Ok((&UDP_PAYLOAD[..], IpEndpoint::new(src_ip.into(), 67))));
  1039. }
  1040. }
  1041. #[test]
  1042. fn test_handle_valid_arp_request() {
  1043. let (mut iface, mut socket_set) = create_loopback();
  1044. let mut eth_bytes = vec![0u8; 42];
  1045. let local_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x01]);
  1046. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1047. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  1048. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  1049. let repr = ArpRepr::EthernetIpv4 {
  1050. operation: ArpOperation::Request,
  1051. source_hardware_addr: remote_hw_addr,
  1052. source_protocol_addr: remote_ip_addr,
  1053. target_hardware_addr: EthernetAddress::default(),
  1054. target_protocol_addr: local_ip_addr,
  1055. };
  1056. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1057. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1058. frame.set_src_addr(remote_hw_addr);
  1059. frame.set_ethertype(EthernetProtocol::Arp);
  1060. {
  1061. let mut packet = ArpPacket::new(frame.payload_mut());
  1062. repr.emit(&mut packet);
  1063. }
  1064. // Ensure an ARP Request for us triggers an ARP Reply
  1065. assert_eq!(iface.inner.process_ethernet(&mut socket_set, 0, frame.into_inner()),
  1066. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  1067. operation: ArpOperation::Reply,
  1068. source_hardware_addr: local_hw_addr,
  1069. source_protocol_addr: local_ip_addr,
  1070. target_hardware_addr: remote_hw_addr,
  1071. target_protocol_addr: remote_ip_addr
  1072. })));
  1073. // Ensure the address of the requestor was entered in the cache
  1074. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, 0,
  1075. &IpAddress::Ipv4(local_ip_addr), &IpAddress::Ipv4(remote_ip_addr)),
  1076. Ok((remote_hw_addr, MockTxToken)));
  1077. }
  1078. #[test]
  1079. fn test_handle_other_arp_request() {
  1080. let (mut iface, mut socket_set) = create_loopback();
  1081. let mut eth_bytes = vec![0u8; 42];
  1082. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1083. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  1084. let repr = ArpRepr::EthernetIpv4 {
  1085. operation: ArpOperation::Request,
  1086. source_hardware_addr: remote_hw_addr,
  1087. source_protocol_addr: remote_ip_addr,
  1088. target_hardware_addr: EthernetAddress::default(),
  1089. target_protocol_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x03]),
  1090. };
  1091. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1092. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1093. frame.set_src_addr(remote_hw_addr);
  1094. frame.set_ethertype(EthernetProtocol::Arp);
  1095. {
  1096. let mut packet = ArpPacket::new(frame.payload_mut());
  1097. repr.emit(&mut packet);
  1098. }
  1099. // Ensure an ARP Request for someone else does not trigger an ARP Reply
  1100. assert_eq!(iface.inner.process_ethernet(&mut socket_set, 0, frame.into_inner()),
  1101. Ok(Packet::None));
  1102. // Ensure the address of the requestor was entered in the cache
  1103. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, 0,
  1104. &IpAddress::Ipv4(Ipv4Address([0x7f, 0x00, 0x00, 0x01])),
  1105. &IpAddress::Ipv4(remote_ip_addr)),
  1106. Ok((remote_hw_addr, MockTxToken)));
  1107. }
  1108. #[test]
  1109. #[cfg(feature = "socket-icmp")]
  1110. fn test_icmpv4_socket() {
  1111. use socket::{IcmpPacketBuffer, IcmpSocket, IcmpSocketBuffer, IcmpEndpoint};
  1112. use wire::Icmpv4Packet;
  1113. let (iface, mut socket_set) = create_loopback();
  1114. let rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketBuffer::new(vec![0; 24])]);
  1115. let tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketBuffer::new(vec![0; 24])]);
  1116. let icmpv4_socket = IcmpSocket::new(rx_buffer, tx_buffer);
  1117. let socket_handle = socket_set.add(icmpv4_socket);
  1118. let ident = 0x1234;
  1119. let seq_no = 0x5432;
  1120. let echo_data = &[0xff; 16];
  1121. {
  1122. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  1123. // Bind to the ID 0x1234
  1124. assert_eq!(socket.bind(IcmpEndpoint::Ident(ident)), Ok(()));
  1125. }
  1126. // Ensure the ident we bound to and the ident of the packet are the same.
  1127. let mut bytes = [0xff; 24];
  1128. let mut packet = Icmpv4Packet::new(&mut bytes);
  1129. let echo_repr = Icmpv4Repr::EchoRequest{ ident, seq_no, data: echo_data };
  1130. echo_repr.emit(&mut packet, &ChecksumCapabilities::default());
  1131. let icmp_data = &packet.into_inner()[..];
  1132. let ipv4_repr = Ipv4Repr {
  1133. src_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x02),
  1134. dst_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x01),
  1135. protocol: IpProtocol::Icmp,
  1136. payload_len: 24,
  1137. ttl: 64
  1138. };
  1139. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  1140. // Open a socket and ensure the packet is handled due to the listening
  1141. // socket.
  1142. {
  1143. assert!(!socket_set.get::<IcmpSocket>(socket_handle).can_recv());
  1144. }
  1145. // Confirm we still get EchoReply from `smoltcp` even with the ICMP socket listening
  1146. let echo_reply = Icmpv4Repr::EchoReply{ ident, seq_no, data: echo_data };
  1147. let ipv4_reply = Ipv4Repr {
  1148. src_addr: ipv4_repr.dst_addr,
  1149. dst_addr: ipv4_repr.src_addr,
  1150. ..ipv4_repr
  1151. };
  1152. assert_eq!(iface.inner.process_icmpv4(&mut socket_set, ip_repr, icmp_data),
  1153. Ok(Packet::Icmpv4((ipv4_reply, echo_reply))));
  1154. {
  1155. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  1156. assert!(socket.can_recv());
  1157. assert_eq!(socket.recv(),
  1158. Ok((&icmp_data[..],
  1159. IpAddress::Ipv4(Ipv4Address::new(0x7f, 0x00, 0x00, 0x02)))));
  1160. }
  1161. }
  1162. }