ethernet.rs 52 KB

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