ethernet.rs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  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 time::{Duration, Instant};
  8. use wire::pretty_print::PrettyPrinter;
  9. use wire::{EthernetAddress, EthernetProtocol, EthernetFrame};
  10. use wire::{IpAddress, IpProtocol, IpRepr, IpCidr};
  11. #[cfg(feature = "proto-ipv6")]
  12. use wire::{Ipv6Address, Ipv6Packet, Ipv6Repr, IPV6_MIN_MTU};
  13. #[cfg(feature = "proto-ipv4")]
  14. use wire::{Ipv4Address, Ipv4Packet, Ipv4Repr, IPV4_MIN_MTU};
  15. #[cfg(feature = "proto-ipv4")]
  16. use wire::{ArpPacket, ArpRepr, ArpOperation};
  17. #[cfg(feature = "proto-ipv4")]
  18. use wire::{Icmpv4Packet, Icmpv4Repr, Icmpv4DstUnreachable};
  19. #[cfg(feature = "proto-ipv6")]
  20. use wire::{Icmpv6Packet, Icmpv6Repr, Icmpv6ParamProblem};
  21. #[cfg(all(feature = "proto-ipv6", feature = "socket-udp"))]
  22. use wire::Icmpv6DstUnreachable;
  23. #[cfg(feature = "socket-udp")]
  24. use wire::{UdpPacket, UdpRepr};
  25. #[cfg(feature = "socket-tcp")]
  26. use wire::{TcpPacket, TcpRepr, TcpControl};
  27. use socket::{Socket, SocketSet, AnySocket};
  28. #[cfg(feature = "socket-raw")]
  29. use socket::RawSocket;
  30. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  31. use socket::IcmpSocket;
  32. #[cfg(feature = "socket-udp")]
  33. use socket::UdpSocket;
  34. #[cfg(feature = "socket-tcp")]
  35. use socket::TcpSocket;
  36. use super::{NeighborCache, NeighborAnswer};
  37. /// An Ethernet network interface.
  38. ///
  39. /// The network interface logically owns a number of other data structures; to avoid
  40. /// a dependency on heap allocation, it instead owns a `BorrowMut<[T]>`, which can be
  41. /// a `&mut [T]`, or `Vec<T>` if a heap is available.
  42. pub struct Interface<'b, 'c, DeviceT: for<'d> Device<'d>> {
  43. device: DeviceT,
  44. inner: InterfaceInner<'b, 'c>,
  45. }
  46. /// The device independent part of an Ethernet network interface.
  47. ///
  48. /// Separating the device from the data required for prorcessing and dispatching makes
  49. /// it possible to borrow them independently. For example, the tx and rx tokens borrow
  50. /// the `device` mutably until they're used, which makes it impossible to call other
  51. /// methods on the `Interface` in this time (since its `device` field is borrowed
  52. /// exclusively). However, it is still possible to call methods on its `inner` field.
  53. struct InterfaceInner<'b, 'c> {
  54. neighbor_cache: NeighborCache<'b>,
  55. ethernet_addr: EthernetAddress,
  56. ip_addrs: ManagedSlice<'c, IpCidr>,
  57. #[cfg(feature = "proto-ipv4")]
  58. ipv4_gateway: Option<Ipv4Address>,
  59. device_capabilities: DeviceCapabilities,
  60. }
  61. /// A builder structure used for creating a Ethernet network
  62. /// interface.
  63. pub struct InterfaceBuilder <'b, 'c, DeviceT: for<'d> Device<'d>> {
  64. device: DeviceT,
  65. ethernet_addr: Option<EthernetAddress>,
  66. neighbor_cache: Option<NeighborCache<'b>>,
  67. ip_addrs: ManagedSlice<'c, IpCidr>,
  68. #[cfg(feature = "proto-ipv4")]
  69. ipv4_gateway: Option<Ipv4Address>,
  70. }
  71. impl<'b, 'c, DeviceT> InterfaceBuilder<'b, 'c, DeviceT>
  72. where DeviceT: for<'d> Device<'d> {
  73. /// Create a builder used for creating a network interface using the
  74. /// given device and address.
  75. ///
  76. /// # Examples
  77. ///
  78. /// ```
  79. /// # use std::collections::BTreeMap;
  80. /// use smoltcp::iface::{EthernetInterfaceBuilder, NeighborCache};
  81. /// # use smoltcp::phy::Loopback;
  82. /// use smoltcp::wire::{EthernetAddress, IpCidr, IpAddress};
  83. ///
  84. /// let device = // ...
  85. /// # Loopback::new();
  86. /// let hw_addr = // ...
  87. /// # EthernetAddress::default();
  88. /// let neighbor_cache = // ...
  89. /// # NeighborCache::new(BTreeMap::new());
  90. /// let ip_addrs = // ...
  91. /// # [];
  92. /// let iface = EthernetInterfaceBuilder::new(device)
  93. /// .ethernet_addr(hw_addr)
  94. /// .neighbor_cache(neighbor_cache)
  95. /// .ip_addrs(ip_addrs)
  96. /// .finalize();
  97. /// ```
  98. pub fn new(device: DeviceT) -> InterfaceBuilder<'b, 'c, DeviceT> {
  99. InterfaceBuilder {
  100. device: device,
  101. ethernet_addr: None,
  102. neighbor_cache: None,
  103. ip_addrs: ManagedSlice::Borrowed(&mut []),
  104. #[cfg(feature = "proto-ipv4")]
  105. ipv4_gateway: None
  106. }
  107. }
  108. /// Set the Ethernet address the interface will use. See also
  109. /// [ethernet_addr].
  110. ///
  111. /// # Panics
  112. /// This function panics if the address is not unicast.
  113. ///
  114. /// [ethernet_addr]: struct.EthernetInterface.html#method.ethernet_addr
  115. pub fn ethernet_addr(mut self, addr: EthernetAddress) -> InterfaceBuilder<'b, 'c, DeviceT> {
  116. InterfaceInner::check_ethernet_addr(&addr);
  117. self.ethernet_addr = Some(addr);
  118. self
  119. }
  120. /// Set the IP addresses the interface will use. See also
  121. /// [ip_addrs].
  122. ///
  123. /// # Panics
  124. /// This function panics if any of the addresses are not unicast.
  125. ///
  126. /// [ip_addrs]: struct.EthernetInterface.html#method.ip_addrs
  127. pub fn ip_addrs<T>(mut self, ip_addrs: T) -> InterfaceBuilder<'b, 'c, DeviceT>
  128. where T: Into<ManagedSlice<'c, IpCidr>>
  129. {
  130. let ip_addrs = ip_addrs.into();
  131. InterfaceInner::check_ip_addrs(&ip_addrs);
  132. self.ip_addrs = ip_addrs;
  133. self
  134. }
  135. /// Set the IPv4 gateway the interface will use. See also
  136. /// [ipv4_gateway].
  137. ///
  138. /// # Panics
  139. /// This function panics if the given address is not unicast.
  140. ///
  141. /// [ipv4_gateway]: struct.EthernetInterface.html#method.ipv4_gateway
  142. #[cfg(feature = "proto-ipv4")]
  143. pub fn ipv4_gateway<T>(mut self, gateway: T) -> InterfaceBuilder<'b, 'c, DeviceT>
  144. where T: Into<Ipv4Address>
  145. {
  146. let addr = gateway.into();
  147. InterfaceInner::check_gateway_addr(&addr);
  148. self.ipv4_gateway = Some(addr);
  149. self
  150. }
  151. /// Set the Neighbor Cache the interface will use.
  152. pub fn neighbor_cache(mut self, neighbor_cache: NeighborCache<'b>) ->
  153. InterfaceBuilder<'b, 'c, DeviceT> {
  154. self.neighbor_cache = Some(neighbor_cache);
  155. self
  156. }
  157. /// Create a network interface using the previously provided configuration.
  158. ///
  159. /// # Panics
  160. /// If a required option is not provided, this function will panic. Required
  161. /// options are:
  162. ///
  163. /// - [ethernet_addr]
  164. /// - [neighbor_cache]
  165. ///
  166. /// [ethernet_addr]: #method.ethernet_addr
  167. /// [neighbor_cache]: #method.neighbor_cache
  168. pub fn finalize(self) -> Interface<'b, 'c, DeviceT> {
  169. match (self.ethernet_addr, self.neighbor_cache) {
  170. (Some(ethernet_addr), Some(neighbor_cache)) => {
  171. let device_capabilities = self.device.capabilities();
  172. Interface {
  173. device: self.device,
  174. inner: InterfaceInner {
  175. ethernet_addr, device_capabilities, neighbor_cache,
  176. ip_addrs: self.ip_addrs,
  177. #[cfg(feature = "proto-ipv4")]
  178. ipv4_gateway: self.ipv4_gateway,
  179. }
  180. }
  181. },
  182. _ => panic!("a required option was not set"),
  183. }
  184. }
  185. }
  186. #[derive(Debug, PartialEq)]
  187. enum Packet<'a> {
  188. None,
  189. #[cfg(feature = "proto-ipv4")]
  190. Arp(ArpRepr),
  191. #[cfg(feature = "proto-ipv4")]
  192. Icmpv4((Ipv4Repr, Icmpv4Repr<'a>)),
  193. #[cfg(feature = "proto-ipv6")]
  194. Icmpv6((Ipv6Repr, Icmpv6Repr<'a>)),
  195. #[cfg(feature = "socket-raw")]
  196. Raw((IpRepr, &'a [u8])),
  197. #[cfg(feature = "socket-udp")]
  198. Udp((IpRepr, UdpRepr<'a>)),
  199. #[cfg(feature = "socket-tcp")]
  200. Tcp((IpRepr, TcpRepr<'a>))
  201. }
  202. impl<'a> Packet<'a> {
  203. fn neighbor_addr(&self) -> Option<IpAddress> {
  204. match self {
  205. &Packet::None => None,
  206. #[cfg(feature = "proto-ipv4")]
  207. &Packet::Arp(_) => None,
  208. #[cfg(feature = "proto-ipv4")]
  209. &Packet::Icmpv4((ref ipv4_repr, _)) => Some(ipv4_repr.dst_addr.into()),
  210. #[cfg(feature = "proto-ipv6")]
  211. &Packet::Icmpv6((ref ipv6_repr, _)) => Some(ipv6_repr.dst_addr.into()),
  212. #[cfg(feature = "socket-raw")]
  213. &Packet::Raw((ref ip_repr, _)) => Some(ip_repr.dst_addr()),
  214. #[cfg(feature = "socket-udp")]
  215. &Packet::Udp((ref ip_repr, _)) => Some(ip_repr.dst_addr()),
  216. #[cfg(feature = "socket-tcp")]
  217. &Packet::Tcp((ref ip_repr, _)) => Some(ip_repr.dst_addr())
  218. }
  219. }
  220. }
  221. #[cfg(any(feature = "proto-ipv4", feature = "proto-ipv6"))]
  222. fn icmp_reply_payload_len(len: usize, mtu: usize, header_len: usize) -> usize {
  223. // Send back as much of the original payload as will fit within
  224. // the minimum MTU required by IPv4. See RFC 1812 § 4.3.2.3 for
  225. // more details.
  226. //
  227. // Since the entire network layer packet must fit within the minumum
  228. // MTU supported, the payload must not exceed the following:
  229. //
  230. // <min mtu> - IP Header Size * 2 - ICMPv4 DstUnreachable hdr size
  231. cmp::min(len, mtu - header_len * 2 - 8)
  232. }
  233. impl<'b, 'c, DeviceT> Interface<'b, 'c, DeviceT>
  234. where DeviceT: for<'d> Device<'d> {
  235. /// Get the Ethernet address of the interface.
  236. pub fn ethernet_addr(&self) -> EthernetAddress {
  237. self.inner.ethernet_addr
  238. }
  239. /// Set the Ethernet address of the interface.
  240. ///
  241. /// # Panics
  242. /// This function panics if the address is not unicast.
  243. pub fn set_ethernet_addr(&mut self, addr: EthernetAddress) {
  244. self.inner.ethernet_addr = addr;
  245. InterfaceInner::check_ethernet_addr(&self.inner.ethernet_addr);
  246. }
  247. /// Get the IP addresses of the interface.
  248. pub fn ip_addrs(&self) -> &[IpCidr] {
  249. self.inner.ip_addrs.as_ref()
  250. }
  251. /// Determine if the given `Ipv6Address` is the solicited node
  252. /// multicast address for a IPv6 addresses assigned to the interface.
  253. /// See [RFC 4291 § 2.7.1] for more details.
  254. ///
  255. /// [RFC 4291 § 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1
  256. #[cfg(feature = "proto-ipv6")]
  257. pub fn has_solicited_node(&self, addr: Ipv6Address) -> bool {
  258. self.inner.ip_addrs.iter().find(|cidr| {
  259. match *cidr {
  260. &IpCidr::Ipv6(cidr) if cidr.address() != Ipv6Address::LOOPBACK=> {
  261. // Take the lower order 24 bits of the IPv6 address and
  262. // append those bits to FF02:0:0:0:0:1:FF00::/104.
  263. addr.as_bytes()[14..] == cidr.address().as_bytes()[14..]
  264. }
  265. _ => false,
  266. }
  267. }).is_some()
  268. }
  269. /// Update the IP addresses of the interface.
  270. ///
  271. /// # Panics
  272. /// This function panics if any of the addresses are not unicast.
  273. pub fn update_ip_addrs<F: FnOnce(&mut ManagedSlice<'c, IpCidr>)>(&mut self, f: F) {
  274. f(&mut self.inner.ip_addrs);
  275. InterfaceInner::check_ip_addrs(&self.inner.ip_addrs)
  276. }
  277. /// Check whether the interface has the given IP address assigned.
  278. pub fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  279. self.inner.has_ip_addr(addr)
  280. }
  281. /// Get the IPv4 gateway of the interface.
  282. #[cfg(feature = "proto-ipv4")]
  283. pub fn ipv4_gateway(&self) -> Option<Ipv4Address> {
  284. self.inner.ipv4_gateway
  285. }
  286. /// Set the IPv4 gateway of the interface.
  287. ///
  288. /// # Panics
  289. /// This function panics if the given address is not unicast.
  290. #[cfg(feature = "proto-ipv4")]
  291. pub fn set_ipv4_gateway<GatewayAddrT>(&mut self, gateway: GatewayAddrT)
  292. where GatewayAddrT: Into<Option<Ipv4Address>> {
  293. self.inner.ipv4_gateway = gateway.into();
  294. self.inner.ipv4_gateway.map(|addr| InterfaceInner::check_gateway_addr(&addr));
  295. }
  296. /// Transmit packets queued in the given sockets, and receive packets queued
  297. /// in the device.
  298. ///
  299. /// This function returns a boolean value indicating whether any packets were
  300. /// processed or emitted, and thus, whether the readiness of any socket might
  301. /// have changed.
  302. ///
  303. /// # Errors
  304. /// This method will routinely return errors in response to normal network
  305. /// activity as well as certain boundary conditions such as buffer exhaustion.
  306. /// These errors are provided as an aid for troubleshooting, and are meant
  307. /// to be logged and ignored.
  308. ///
  309. /// As a special case, `Err(Error::Unrecognized)` is returned in response to
  310. /// packets containing any unsupported protocol, option, or form, which is
  311. /// a very common occurrence and on a production system it should not even
  312. /// be logged.
  313. pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  314. let mut readiness_may_have_changed = false;
  315. loop {
  316. let processed_any = self.socket_ingress(sockets, timestamp)?;
  317. let emitted_any = self.socket_egress(sockets, timestamp)?;
  318. if processed_any || emitted_any {
  319. readiness_may_have_changed = true;
  320. } else {
  321. break
  322. }
  323. }
  324. Ok(readiness_may_have_changed)
  325. }
  326. /// Return a _soft deadline_ for calling [poll] the next time.
  327. /// The [Instant] returned is the time at which you should call [poll] next.
  328. /// It is harmless (but wastes energy) to call it before the [Instant], and
  329. /// potentially harmful (impacting quality of service) to call it after the
  330. /// [Instant]
  331. ///
  332. /// [poll]: #method.poll
  333. /// [Instant]: struct.Instant.html
  334. pub fn poll_at(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Instant> {
  335. sockets.iter().filter_map(|socket| {
  336. let socket_poll_at = socket.poll_at();
  337. socket.meta().poll_at(socket_poll_at, |ip_addr|
  338. self.inner.has_neighbor(&ip_addr, timestamp))
  339. }).min()
  340. }
  341. /// Return an _advisory wait time_ for calling [poll] the next time.
  342. /// The [Duration] returned is the time left to wait before calling [poll] next.
  343. /// It is harmless (but wastes energy) to call it before the [Duration] has passed,
  344. /// and potentially harmful (impacting quality of service) to call it after the
  345. /// [Duration] has passed.
  346. ///
  347. /// [poll]: #method.poll
  348. /// [Duration]: struct.Duration.html
  349. pub fn poll_delay(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Duration> {
  350. match self.poll_at(sockets, timestamp) {
  351. Some(poll_at) if timestamp < poll_at => {
  352. Some(poll_at - timestamp)
  353. }
  354. Some(_) => {
  355. Some(Duration::from_millis(0))
  356. }
  357. _ => None
  358. }
  359. }
  360. fn socket_ingress(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  361. let mut processed_any = false;
  362. loop {
  363. let &mut Self { ref mut device, ref mut inner } = self;
  364. let (rx_token, tx_token) = match device.receive() {
  365. None => break,
  366. Some(tokens) => tokens,
  367. };
  368. rx_token.consume(timestamp, |frame| {
  369. inner.process_ethernet(sockets, timestamp, &frame).map_err(|err| {
  370. net_debug!("cannot process ingress packet: {}", err);
  371. net_debug!("packet dump follows:\n{}",
  372. PrettyPrinter::<EthernetFrame<&[u8]>>::new("", &frame));
  373. err
  374. }).and_then(|response| {
  375. processed_any = true;
  376. inner.dispatch(tx_token, timestamp, response).map_err(|err| {
  377. net_debug!("cannot dispatch response packet: {}", err);
  378. err
  379. })
  380. })
  381. })?;
  382. }
  383. Ok(processed_any)
  384. }
  385. fn socket_egress(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  386. let mut caps = self.device.capabilities();
  387. caps.max_transmission_unit -= EthernetFrame::<&[u8]>::header_len();
  388. let mut emitted_any = false;
  389. for mut socket in sockets.iter_mut() {
  390. if !socket.meta_mut().egress_permitted(|ip_addr|
  391. self.inner.has_neighbor(&ip_addr, timestamp)) {
  392. continue
  393. }
  394. let mut neighbor_addr = None;
  395. let mut device_result = Ok(());
  396. let &mut Self { ref mut device, ref mut inner } = self;
  397. macro_rules! respond {
  398. ($response:expr) => ({
  399. let response = $response;
  400. neighbor_addr = response.neighbor_addr();
  401. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  402. device_result = inner.dispatch(tx_token, timestamp, response);
  403. device_result
  404. })
  405. }
  406. let socket_result =
  407. match *socket {
  408. #[cfg(feature = "socket-raw")]
  409. Socket::Raw(ref mut socket) =>
  410. socket.dispatch(&caps.checksum, |response|
  411. respond!(Packet::Raw(response))),
  412. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  413. Socket::Icmp(ref mut socket) =>
  414. socket.dispatch(&caps, |response| {
  415. match response {
  416. #[cfg(feature = "proto-ipv4")]
  417. (IpRepr::Ipv4(ipv4_repr), icmpv4_repr) =>
  418. respond!(Packet::Icmpv4((ipv4_repr, icmpv4_repr))),
  419. _ => Err(Error::Unaddressable)
  420. }
  421. }),
  422. #[cfg(feature = "socket-udp")]
  423. Socket::Udp(ref mut socket) =>
  424. socket.dispatch(|response|
  425. respond!(Packet::Udp(response))),
  426. #[cfg(feature = "socket-tcp")]
  427. Socket::Tcp(ref mut socket) =>
  428. socket.dispatch(timestamp, &caps, |response|
  429. respond!(Packet::Tcp(response))),
  430. Socket::__Nonexhaustive(_) => unreachable!()
  431. };
  432. match (device_result, socket_result) {
  433. (Err(Error::Exhausted), _) => break, // nowhere to transmit
  434. (Ok(()), Err(Error::Exhausted)) => (), // nothing to transmit
  435. (Err(Error::Unaddressable), _) => {
  436. // `NeighborCache` already takes care of rate limiting the neighbor discovery
  437. // requests from the socket. However, without an additional rate limiting
  438. // mechanism, we would spin on every socket that has yet to discover its
  439. // neighboor.
  440. socket.meta_mut().neighbor_missing(timestamp,
  441. neighbor_addr.expect("non-IP response packet"));
  442. break
  443. }
  444. (Err(err), _) | (_, Err(err)) => {
  445. net_debug!("{}: cannot dispatch egress packet: {}",
  446. socket.meta().handle, err);
  447. return Err(err)
  448. }
  449. (Ok(()), Ok(())) => emitted_any = true
  450. }
  451. }
  452. Ok(emitted_any)
  453. }
  454. }
  455. impl<'b, 'c> InterfaceInner<'b, 'c> {
  456. fn check_ethernet_addr(addr: &EthernetAddress) {
  457. if addr.is_multicast() {
  458. panic!("Ethernet address {} is not unicast", addr)
  459. }
  460. }
  461. fn check_ip_addrs(addrs: &[IpCidr]) {
  462. for cidr in addrs {
  463. if !cidr.address().is_unicast() {
  464. panic!("IP address {} is not unicast", cidr.address())
  465. }
  466. }
  467. }
  468. #[cfg(feature = "proto-ipv4")]
  469. fn check_gateway_addr(addr: &Ipv4Address) {
  470. if !addr.is_unicast() {
  471. panic!("gateway IP address {} is not unicast", addr);
  472. }
  473. }
  474. /// Check whether the interface has the given IP address assigned.
  475. fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  476. let addr = addr.into();
  477. self.ip_addrs.iter().any(|probe| probe.address() == addr)
  478. }
  479. fn process_ethernet<'frame, T: AsRef<[u8]>>
  480. (&mut self, sockets: &mut SocketSet, timestamp: Instant, frame: &'frame T) ->
  481. Result<Packet<'frame>>
  482. {
  483. let eth_frame = EthernetFrame::new_checked(frame)?;
  484. // Ignore any packets not directed to our hardware address.
  485. if !eth_frame.dst_addr().is_broadcast() &&
  486. !eth_frame.dst_addr().is_multicast() &&
  487. eth_frame.dst_addr() != self.ethernet_addr {
  488. return Ok(Packet::None)
  489. }
  490. match eth_frame.ethertype() {
  491. #[cfg(feature = "proto-ipv4")]
  492. EthernetProtocol::Arp =>
  493. self.process_arp(timestamp, &eth_frame),
  494. #[cfg(feature = "proto-ipv4")]
  495. EthernetProtocol::Ipv4 =>
  496. self.process_ipv4(sockets, timestamp, &eth_frame),
  497. #[cfg(feature = "proto-ipv6")]
  498. EthernetProtocol::Ipv6 =>
  499. self.process_ipv6(sockets, timestamp, &eth_frame),
  500. // Drop all other traffic.
  501. _ => Err(Error::Unrecognized),
  502. }
  503. }
  504. #[cfg(feature = "proto-ipv4")]
  505. fn process_arp<'frame, T: AsRef<[u8]>>
  506. (&mut self, timestamp: Instant, eth_frame: &EthernetFrame<&'frame T>) ->
  507. Result<Packet<'frame>>
  508. {
  509. let arp_packet = ArpPacket::new_checked(eth_frame.payload())?;
  510. let arp_repr = ArpRepr::parse(&arp_packet)?;
  511. match arp_repr {
  512. // Respond to ARP requests aimed at us, and fill the ARP cache from all ARP
  513. // requests and replies, to minimize the chance that we have to perform
  514. // an explicit ARP request.
  515. ArpRepr::EthernetIpv4 {
  516. operation, source_hardware_addr, source_protocol_addr, target_protocol_addr, ..
  517. } => {
  518. if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() {
  519. self.neighbor_cache.fill(source_protocol_addr.into(),
  520. source_hardware_addr,
  521. timestamp);
  522. } else {
  523. // Discard packets with non-unicast source addresses.
  524. net_debug!("non-unicast source address");
  525. return Err(Error::Malformed)
  526. }
  527. if operation == ArpOperation::Request && self.has_ip_addr(target_protocol_addr) {
  528. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  529. operation: ArpOperation::Reply,
  530. source_hardware_addr: self.ethernet_addr,
  531. source_protocol_addr: target_protocol_addr,
  532. target_hardware_addr: source_hardware_addr,
  533. target_protocol_addr: source_protocol_addr
  534. }))
  535. } else {
  536. Ok(Packet::None)
  537. }
  538. }
  539. _ => Err(Error::Unrecognized)
  540. }
  541. }
  542. #[cfg(all(any(feature = "proto-ipv4", feature = "proto-ipv6"), feature = "socket-raw"))]
  543. fn raw_socket_filter<'frame>(&mut self, sockets: &mut SocketSet, ip_repr: &IpRepr,
  544. ip_payload: &'frame [u8]) -> bool {
  545. let checksum_caps = self.device_capabilities.checksum.clone();
  546. let mut handled_by_raw_socket = false;
  547. // Pass every IP packet to all raw sockets we have registered.
  548. for mut raw_socket in sockets.iter_mut().filter_map(RawSocket::downcast) {
  549. if !raw_socket.accepts(&ip_repr) { continue }
  550. match raw_socket.process(&ip_repr, ip_payload, &checksum_caps) {
  551. // The packet is valid and handled by socket.
  552. Ok(()) => handled_by_raw_socket = true,
  553. // The socket buffer is full.
  554. Err(Error::Exhausted) => (),
  555. // Raw sockets don't validate the packets in any way.
  556. Err(_) => unreachable!(),
  557. }
  558. }
  559. handled_by_raw_socket
  560. }
  561. #[cfg(feature = "proto-ipv6")]
  562. fn process_ipv6<'frame, T: AsRef<[u8]>>
  563. (&mut self, sockets: &mut SocketSet, timestamp: Instant,
  564. eth_frame: &EthernetFrame<&'frame T>) ->
  565. Result<Packet<'frame>>
  566. {
  567. let ipv6_packet = Ipv6Packet::new_checked(eth_frame.payload())?;
  568. let ipv6_repr = Ipv6Repr::parse(&ipv6_packet)?;
  569. if !ipv6_repr.src_addr.is_unicast() {
  570. // Discard packets with non-unicast source addresses.
  571. net_debug!("non-unicast source address");
  572. return Err(Error::Malformed)
  573. }
  574. if eth_frame.src_addr().is_unicast() {
  575. // Fill the neighbor cache from IP header of unicast frames.
  576. let ip_addr = IpAddress::Ipv6(ipv6_repr.src_addr);
  577. if self.in_same_network(&ip_addr) {
  578. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  579. }
  580. }
  581. let ip_repr = IpRepr::Ipv6(ipv6_repr);
  582. let ip_payload = ipv6_packet.payload();
  583. #[cfg(feature = "socket-raw")]
  584. let handled_by_raw_socket = self.raw_socket_filter(sockets, &ip_repr, ip_payload);
  585. match ipv6_repr.next_header {
  586. IpProtocol::Icmpv6 =>
  587. self.process_icmpv6(sockets, ip_repr, ip_payload),
  588. #[cfg(feature = "socket-udp")]
  589. IpProtocol::Udp =>
  590. self.process_udp(sockets, ip_repr, ip_payload),
  591. #[cfg(feature = "socket-tcp")]
  592. IpProtocol::Tcp =>
  593. self.process_tcp(sockets, timestamp, ip_repr, ip_payload),
  594. #[cfg(feature = "socket-raw")]
  595. _ if handled_by_raw_socket =>
  596. Ok(Packet::None),
  597. _ => {
  598. // Send back as much of the original payload as we can.
  599. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU,
  600. ipv6_repr.buffer_len());
  601. let icmp_reply_repr = Icmpv6Repr::ParamProblem {
  602. reason: Icmpv6ParamProblem::UnrecognizedNxtHdr,
  603. // The offending packet is after the IPv6 header.
  604. pointer: ipv6_repr.buffer_len() as u32,
  605. header: ipv6_repr,
  606. data: &ip_payload[0..payload_len]
  607. };
  608. Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
  609. },
  610. }
  611. }
  612. #[cfg(feature = "proto-ipv4")]
  613. fn process_ipv4<'frame, T: AsRef<[u8]>>
  614. (&mut self, sockets: &mut SocketSet, timestamp: Instant,
  615. eth_frame: &EthernetFrame<&'frame T>) ->
  616. Result<Packet<'frame>>
  617. {
  618. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
  619. let checksum_caps = self.device_capabilities.checksum.clone();
  620. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &checksum_caps)?;
  621. if !ipv4_repr.src_addr.is_unicast() {
  622. // Discard packets with non-unicast source addresses.
  623. net_debug!("non-unicast source address");
  624. return Err(Error::Malformed)
  625. }
  626. if eth_frame.src_addr().is_unicast() {
  627. // Fill the neighbor cache from IP header of unicast frames.
  628. let ip_addr = IpAddress::Ipv4(ipv4_repr.src_addr);
  629. if self.in_same_network(&ip_addr) {
  630. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  631. }
  632. }
  633. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  634. let ip_payload = ipv4_packet.payload();
  635. #[cfg(feature = "socket-raw")]
  636. let handled_by_raw_socket = self.raw_socket_filter(sockets, &ip_repr, ip_payload);
  637. if !ipv4_repr.dst_addr.is_broadcast() &&
  638. !ipv4_repr.dst_addr.is_multicast() &&
  639. !self.has_ip_addr(ipv4_repr.dst_addr) {
  640. // Ignore IP packets not directed at us.
  641. return Ok(Packet::None)
  642. }
  643. match ipv4_repr.protocol {
  644. IpProtocol::Icmp =>
  645. self.process_icmpv4(sockets, ip_repr, ip_payload),
  646. #[cfg(feature = "socket-udp")]
  647. IpProtocol::Udp =>
  648. self.process_udp(sockets, ip_repr, ip_payload),
  649. #[cfg(feature = "socket-tcp")]
  650. IpProtocol::Tcp =>
  651. self.process_tcp(sockets, timestamp, ip_repr, ip_payload),
  652. #[cfg(feature = "socket-raw")]
  653. _ if handled_by_raw_socket =>
  654. Ok(Packet::None),
  655. _ => {
  656. // Send back as much of the original payload as we can.
  657. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU,
  658. ipv4_repr.buffer_len());
  659. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  660. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  661. header: ipv4_repr,
  662. data: &ip_payload[0..payload_len]
  663. };
  664. Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr))
  665. }
  666. }
  667. }
  668. #[cfg(feature = "proto-ipv6")]
  669. fn process_icmpv6<'frame>(&self, _sockets: &mut SocketSet, ip_repr: IpRepr,
  670. ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  671. {
  672. let icmp_packet = Icmpv6Packet::new_checked(ip_payload)?;
  673. let checksum_caps = self.device_capabilities.checksum.clone();
  674. let icmp_repr = Icmpv6Repr::parse(&icmp_packet, &checksum_caps)?;
  675. match icmp_repr {
  676. // Respond to echo requests.
  677. Icmpv6Repr::EchoRequest { ident, seq_no, data } => {
  678. match ip_repr {
  679. IpRepr::Ipv6(ipv6_repr) => {
  680. let icmp_reply_repr = Icmpv6Repr::EchoReply {
  681. ident: ident,
  682. seq_no: seq_no,
  683. data: data
  684. };
  685. Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
  686. },
  687. _ => Err(Error::Unrecognized),
  688. }
  689. }
  690. // Ignore any echo replies.
  691. Icmpv6Repr::EchoReply { .. } => Ok(Packet::None),
  692. // FIXME: do something correct here?
  693. _ => Err(Error::Unrecognized),
  694. }
  695. }
  696. #[cfg(feature = "proto-ipv4")]
  697. fn process_icmpv4<'frame>(&self, _sockets: &mut SocketSet, ip_repr: IpRepr,
  698. ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  699. {
  700. let icmp_packet = Icmpv4Packet::new_checked(ip_payload)?;
  701. let checksum_caps = self.device_capabilities.checksum.clone();
  702. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &checksum_caps)?;
  703. #[cfg(feature = "socket-icmp")]
  704. let mut handled_by_icmp_socket = false;
  705. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  706. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  707. if !icmp_socket.accepts(&ip_repr, &icmp_repr, &checksum_caps) { continue }
  708. match icmp_socket.process(&ip_repr, &icmp_repr, &checksum_caps) {
  709. // The packet is valid and handled by socket.
  710. Ok(()) => handled_by_icmp_socket = true,
  711. // The socket buffer is full.
  712. Err(Error::Exhausted) => (),
  713. // ICMP sockets don't validate the packets in any way.
  714. Err(_) => unreachable!(),
  715. }
  716. }
  717. match icmp_repr {
  718. // Respond to echo requests.
  719. Icmpv4Repr::EchoRequest { ident, seq_no, data } => {
  720. let icmp_reply_repr = Icmpv4Repr::EchoReply {
  721. ident: ident,
  722. seq_no: seq_no,
  723. data: data
  724. };
  725. match ip_repr {
  726. IpRepr::Ipv4(ipv4_repr) => Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr)),
  727. _ => Err(Error::Unrecognized),
  728. }
  729. }
  730. // Ignore any echo replies.
  731. Icmpv4Repr::EchoReply { .. } => Ok(Packet::None),
  732. // Don't report an error if a packet with unknown type
  733. // has been handled by an ICMP socket
  734. #[cfg(feature = "socket-icmp")]
  735. _ if handled_by_icmp_socket => Ok(Packet::None),
  736. // FIXME: do something correct here?
  737. _ => Err(Error::Unrecognized),
  738. }
  739. }
  740. #[cfg(feature = "proto-ipv4")]
  741. fn icmpv4_reply<'frame, 'icmp: 'frame>
  742. (&self, ipv4_repr: Ipv4Repr, icmp_repr: Icmpv4Repr<'icmp>) ->
  743. Packet<'frame>
  744. {
  745. if ipv4_repr.dst_addr.is_unicast() {
  746. let ipv4_reply_repr = Ipv4Repr {
  747. src_addr: ipv4_repr.dst_addr,
  748. dst_addr: ipv4_repr.src_addr,
  749. protocol: IpProtocol::Icmp,
  750. payload_len: icmp_repr.buffer_len(),
  751. hop_limit: 64
  752. };
  753. Packet::Icmpv4((ipv4_reply_repr, icmp_repr))
  754. } else {
  755. // Do not send any ICMP replies to a broadcast destination address.
  756. Packet::None
  757. }
  758. }
  759. #[cfg(feature = "proto-ipv6")]
  760. fn icmpv6_reply<'frame, 'icmp: 'frame>
  761. (&self, ipv6_repr: Ipv6Repr, icmp_repr: Icmpv6Repr<'icmp>) ->
  762. Packet<'frame>
  763. {
  764. if ipv6_repr.dst_addr.is_unicast() {
  765. let ipv6_reply_repr = Ipv6Repr {
  766. src_addr: ipv6_repr.dst_addr,
  767. dst_addr: ipv6_repr.src_addr,
  768. next_header: IpProtocol::Icmpv6,
  769. payload_len: icmp_repr.buffer_len(),
  770. hop_limit: 64
  771. };
  772. Packet::Icmpv6((ipv6_reply_repr, icmp_repr))
  773. } else {
  774. // Do not send any ICMP replies to a broadcast destination address.
  775. Packet::None
  776. }
  777. }
  778. #[cfg(feature = "socket-udp")]
  779. fn process_udp<'frame>(&self, sockets: &mut SocketSet,
  780. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  781. Result<Packet<'frame>>
  782. {
  783. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  784. let udp_packet = UdpPacket::new_checked(ip_payload)?;
  785. let checksum_caps = self.device_capabilities.checksum.clone();
  786. let udp_repr = UdpRepr::parse(&udp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  787. for mut udp_socket in sockets.iter_mut().filter_map(UdpSocket::downcast) {
  788. if !udp_socket.accepts(&ip_repr, &udp_repr) { continue }
  789. match udp_socket.process(&ip_repr, &udp_repr) {
  790. // The packet is valid and handled by socket.
  791. Ok(()) => return Ok(Packet::None),
  792. // The packet is malformed, or the socket buffer is full.
  793. Err(e) => return Err(e)
  794. }
  795. }
  796. // The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  797. match ip_repr {
  798. #[cfg(feature = "proto-ipv4")]
  799. IpRepr::Ipv4(ipv4_repr) => {
  800. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU,
  801. ipv4_repr.buffer_len());
  802. let icmpv4_reply_repr = Icmpv4Repr::DstUnreachable {
  803. reason: Icmpv4DstUnreachable::PortUnreachable,
  804. header: ipv4_repr,
  805. data: &ip_payload[0..payload_len]
  806. };
  807. Ok(self.icmpv4_reply(ipv4_repr, icmpv4_reply_repr))
  808. },
  809. #[cfg(feature = "proto-ipv6")]
  810. IpRepr::Ipv6(ipv6_repr) => {
  811. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU,
  812. ipv6_repr.buffer_len());
  813. let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable {
  814. reason: Icmpv6DstUnreachable::PortUnreachable,
  815. header: ipv6_repr,
  816. data: &ip_payload[0..payload_len]
  817. };
  818. Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr))
  819. },
  820. IpRepr::Unspecified { .. } |
  821. IpRepr::__Nonexhaustive => Err(Error::Unaddressable),
  822. }
  823. }
  824. #[cfg(feature = "socket-tcp")]
  825. fn process_tcp<'frame>(&self, sockets: &mut SocketSet, timestamp: Instant,
  826. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  827. Result<Packet<'frame>>
  828. {
  829. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  830. let tcp_packet = TcpPacket::new_checked(ip_payload)?;
  831. let checksum_caps = self.device_capabilities.checksum.clone();
  832. let tcp_repr = TcpRepr::parse(&tcp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  833. for mut tcp_socket in sockets.iter_mut().filter_map(TcpSocket::downcast) {
  834. if !tcp_socket.accepts(&ip_repr, &tcp_repr) { continue }
  835. match tcp_socket.process(timestamp, &ip_repr, &tcp_repr) {
  836. // The packet is valid and handled by socket.
  837. Ok(reply) => return Ok(reply.map_or(Packet::None, Packet::Tcp)),
  838. // The packet is malformed, or doesn't match the socket state,
  839. // or the socket buffer is full.
  840. Err(e) => return Err(e)
  841. }
  842. }
  843. if tcp_repr.control == TcpControl::Rst {
  844. // Never reply to a TCP RST packet with another TCP RST packet.
  845. Ok(Packet::None)
  846. } else {
  847. // The packet wasn't handled by a socket, send a TCP RST packet.
  848. Ok(Packet::Tcp(TcpSocket::rst_reply(&ip_repr, &tcp_repr)))
  849. }
  850. }
  851. fn dispatch<Tx>(&mut self, tx_token: Tx, timestamp: Instant,
  852. packet: Packet) -> Result<()>
  853. where Tx: TxToken
  854. {
  855. let checksum_caps = self.device_capabilities.checksum.clone();
  856. match packet {
  857. #[cfg(feature = "proto-ipv4")]
  858. Packet::Arp(arp_repr) => {
  859. let dst_hardware_addr =
  860. match arp_repr {
  861. ArpRepr::EthernetIpv4 { target_hardware_addr, .. } => target_hardware_addr,
  862. _ => unreachable!()
  863. };
  864. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  865. frame.set_dst_addr(dst_hardware_addr);
  866. frame.set_ethertype(EthernetProtocol::Arp);
  867. let mut packet = ArpPacket::new(frame.payload_mut());
  868. arp_repr.emit(&mut packet);
  869. })
  870. },
  871. #[cfg(feature = "proto-ipv4")]
  872. Packet::Icmpv4((ipv4_repr, icmpv4_repr)) => {
  873. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv4(ipv4_repr),
  874. |_ip_repr, payload| {
  875. icmpv4_repr.emit(&mut Icmpv4Packet::new(payload), &checksum_caps);
  876. })
  877. }
  878. #[cfg(feature = "proto-ipv6")]
  879. Packet::Icmpv6((ipv6_repr, icmpv6_repr)) => {
  880. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv6(ipv6_repr),
  881. |_ip_repr, payload| {
  882. icmpv6_repr.emit(&mut Icmpv6Packet::new(payload), &checksum_caps);
  883. })
  884. }
  885. #[cfg(feature = "socket-raw")]
  886. Packet::Raw((ip_repr, raw_packet)) => {
  887. self.dispatch_ip(tx_token, timestamp, ip_repr, |_ip_repr, payload| {
  888. payload.copy_from_slice(raw_packet);
  889. })
  890. }
  891. #[cfg(feature = "socket-udp")]
  892. Packet::Udp((ip_repr, udp_repr)) => {
  893. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  894. udp_repr.emit(&mut UdpPacket::new(payload),
  895. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  896. &checksum_caps);
  897. })
  898. }
  899. #[cfg(feature = "socket-tcp")]
  900. Packet::Tcp((ip_repr, mut tcp_repr)) => {
  901. let caps = self.device_capabilities.clone();
  902. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  903. // This is a terrible hack to make TCP performance more acceptable on systems
  904. // where the TCP buffers are significantly larger than network buffers,
  905. // e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
  906. // together with four 1500 B Ethernet receive buffers. If left untreated,
  907. // this would result in our peer pushing our window and sever packet loss.
  908. //
  909. // I'm really not happy about this "solution" but I don't know what else to do.
  910. if let Some(max_burst_size) = caps.max_burst_size {
  911. let mut max_segment_size = caps.max_transmission_unit;
  912. max_segment_size -= EthernetFrame::<&[u8]>::header_len();
  913. max_segment_size -= ip_repr.buffer_len();
  914. max_segment_size -= tcp_repr.header_len();
  915. let max_window_size = max_burst_size * max_segment_size;
  916. if tcp_repr.window_len as usize > max_window_size {
  917. tcp_repr.window_len = max_window_size as u16;
  918. }
  919. }
  920. tcp_repr.emit(&mut TcpPacket::new(payload),
  921. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  922. &checksum_caps);
  923. })
  924. }
  925. Packet::None => Ok(())
  926. }
  927. }
  928. fn dispatch_ethernet<Tx, F>(&mut self, tx_token: Tx, timestamp: Instant,
  929. buffer_len: usize, f: F) -> Result<()>
  930. where Tx: TxToken, F: FnOnce(EthernetFrame<&mut [u8]>)
  931. {
  932. let tx_len = EthernetFrame::<&[u8]>::buffer_len(buffer_len);
  933. tx_token.consume(timestamp, tx_len, |tx_buffer| {
  934. debug_assert!(tx_buffer.as_ref().len() == tx_len);
  935. let mut frame = EthernetFrame::new(tx_buffer.as_mut());
  936. frame.set_src_addr(self.ethernet_addr);
  937. f(frame);
  938. Ok(())
  939. })
  940. }
  941. fn in_same_network(&self, addr: &IpAddress) -> bool {
  942. self.ip_addrs
  943. .iter()
  944. .find(|cidr| cidr.contains_addr(addr))
  945. .is_some()
  946. }
  947. fn route(&self, addr: &IpAddress) -> Result<IpAddress> {
  948. // Send directly.
  949. if self.in_same_network(addr) || addr.is_broadcast() {
  950. return Ok(addr.clone())
  951. }
  952. // Route via a gateway.
  953. match addr {
  954. #[cfg(feature = "proto-ipv4")]
  955. &IpAddress::Ipv4(_) => match self.ipv4_gateway {
  956. Some(gateway) => Ok(gateway.into()),
  957. None => Err(Error::Unaddressable),
  958. }
  959. _ => Err(Error::Unaddressable)
  960. }
  961. }
  962. fn has_neighbor<'a>(&self, addr: &'a IpAddress, timestamp: Instant) -> bool {
  963. match self.route(addr) {
  964. Ok(routed_addr) => {
  965. self.neighbor_cache
  966. .lookup_pure(&routed_addr, timestamp)
  967. .is_some()
  968. }
  969. Err(_) => false
  970. }
  971. }
  972. fn lookup_hardware_addr<Tx>(&mut self, tx_token: Tx, timestamp: Instant,
  973. src_addr: &IpAddress, dst_addr: &IpAddress) ->
  974. Result<(EthernetAddress, Tx)>
  975. where Tx: TxToken
  976. {
  977. if dst_addr.is_multicast() {
  978. let b = dst_addr.as_bytes();
  979. let hardware_addr =
  980. match dst_addr {
  981. &IpAddress::Unspecified =>
  982. None,
  983. #[cfg(feature = "proto-ipv4")]
  984. &IpAddress::Ipv4(_addr) =>
  985. Some(EthernetAddress::from_bytes(&[
  986. 0x01, 0x00,
  987. 0x5e, b[1] & 0x7F,
  988. b[2], b[3],
  989. ])),
  990. #[cfg(feature = "proto-ipv6")]
  991. &IpAddress::Ipv6(_addr) =>
  992. Some(EthernetAddress::from_bytes(&[
  993. 0x33, 0x33,
  994. b[12], b[13],
  995. b[14], b[15],
  996. ])),
  997. &IpAddress::__Nonexhaustive =>
  998. unreachable!()
  999. };
  1000. match hardware_addr {
  1001. Some(hardware_addr) =>
  1002. // Destination is multicast
  1003. return Ok((hardware_addr, tx_token)),
  1004. None =>
  1005. // Continue
  1006. (),
  1007. }
  1008. }
  1009. let dst_addr = self.route(dst_addr)?;
  1010. match self.neighbor_cache.lookup(&dst_addr, timestamp) {
  1011. NeighborAnswer::Found(hardware_addr) =>
  1012. return Ok((hardware_addr, tx_token)),
  1013. NeighborAnswer::RateLimited =>
  1014. return Err(Error::Unaddressable),
  1015. NeighborAnswer::NotFound => (),
  1016. }
  1017. match (src_addr, dst_addr) {
  1018. #[cfg(feature = "proto-ipv4")]
  1019. (&IpAddress::Ipv4(src_addr), IpAddress::Ipv4(dst_addr)) => {
  1020. net_debug!("address {} not in neighbor cache, sending ARP request",
  1021. dst_addr);
  1022. let arp_repr = ArpRepr::EthernetIpv4 {
  1023. operation: ArpOperation::Request,
  1024. source_hardware_addr: self.ethernet_addr,
  1025. source_protocol_addr: src_addr,
  1026. target_hardware_addr: EthernetAddress::BROADCAST,
  1027. target_protocol_addr: dst_addr,
  1028. };
  1029. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  1030. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1031. frame.set_ethertype(EthernetProtocol::Arp);
  1032. arp_repr.emit(&mut ArpPacket::new(frame.payload_mut()))
  1033. })?;
  1034. Err(Error::Unaddressable)
  1035. }
  1036. _ => Err(Error::Unaddressable)
  1037. }
  1038. }
  1039. fn dispatch_ip<Tx, F>(&mut self, tx_token: Tx, timestamp: Instant,
  1040. ip_repr: IpRepr, f: F) -> Result<()>
  1041. where Tx: TxToken, F: FnOnce(IpRepr, &mut [u8])
  1042. {
  1043. let ip_repr = ip_repr.lower(&self.ip_addrs)?;
  1044. let checksum_caps = self.device_capabilities.checksum.clone();
  1045. let (dst_hardware_addr, tx_token) =
  1046. self.lookup_hardware_addr(tx_token, timestamp,
  1047. &ip_repr.src_addr(), &ip_repr.dst_addr())?;
  1048. self.dispatch_ethernet(tx_token, timestamp, ip_repr.total_len(), |mut frame| {
  1049. frame.set_dst_addr(dst_hardware_addr);
  1050. match ip_repr {
  1051. #[cfg(feature = "proto-ipv4")]
  1052. IpRepr::Ipv4(_) => frame.set_ethertype(EthernetProtocol::Ipv4),
  1053. #[cfg(feature = "proto-ipv6")]
  1054. IpRepr::Ipv6(_) => frame.set_ethertype(EthernetProtocol::Ipv6),
  1055. _ => return
  1056. }
  1057. ip_repr.emit(frame.payload_mut(), &checksum_caps);
  1058. let payload = &mut frame.payload_mut()[ip_repr.buffer_len()..];
  1059. f(ip_repr, payload)
  1060. })
  1061. }
  1062. }
  1063. #[cfg(test)]
  1064. mod test {
  1065. use std::collections::BTreeMap;
  1066. use {Result, Error};
  1067. use super::InterfaceBuilder;
  1068. use iface::{NeighborCache, EthernetInterface};
  1069. use phy::{self, Loopback, ChecksumCapabilities};
  1070. use time::Instant;
  1071. use socket::SocketSet;
  1072. #[cfg(feature = "proto-ipv4")]
  1073. use wire::{ArpOperation, ArpPacket, ArpRepr};
  1074. use wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
  1075. use wire::{IpAddress, IpCidr, IpProtocol, IpRepr};
  1076. #[cfg(feature = "proto-ipv4")]
  1077. use wire::{Ipv4Address, Ipv4Repr};
  1078. #[cfg(feature = "proto-ipv4")]
  1079. use wire::{Icmpv4Repr, Icmpv4DstUnreachable};
  1080. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1081. use wire::{UdpPacket, UdpRepr};
  1082. #[cfg(feature = "proto-ipv6")]
  1083. use wire::{Ipv6Address, Ipv6Repr};
  1084. #[cfg(feature = "proto-ipv6")]
  1085. use wire::{Icmpv6Repr, Icmpv6ParamProblem};
  1086. use super::Packet;
  1087. fn create_loopback<'a, 'b>() -> (EthernetInterface<'static, 'b, Loopback>,
  1088. SocketSet<'static, 'a, 'b>) {
  1089. // Create a basic device
  1090. let device = Loopback::new();
  1091. let ip_addrs = [
  1092. #[cfg(feature = "proto-ipv4")]
  1093. IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8),
  1094. #[cfg(feature = "proto-ipv6")]
  1095. IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 128)
  1096. ];
  1097. let iface = InterfaceBuilder::new(device)
  1098. .ethernet_addr(EthernetAddress::default())
  1099. .neighbor_cache(NeighborCache::new(BTreeMap::new()))
  1100. .ip_addrs(ip_addrs)
  1101. .finalize();
  1102. (iface, SocketSet::new(vec![]))
  1103. }
  1104. #[derive(Debug, PartialEq)]
  1105. struct MockTxToken;
  1106. impl phy::TxToken for MockTxToken {
  1107. fn consume<R, F>(self, _: Instant, _: usize, _: F) -> Result<R>
  1108. where F: FnOnce(&mut [u8]) -> Result<R> {
  1109. Err(Error::__Nonexhaustive)
  1110. }
  1111. }
  1112. #[test]
  1113. #[should_panic(expected = "a required option was not set")]
  1114. fn test_builder_initialization_panic() {
  1115. InterfaceBuilder::new(Loopback::new()).finalize();
  1116. }
  1117. #[test]
  1118. #[cfg(feature = "proto-ipv4")]
  1119. fn test_no_icmp_to_broadcast() {
  1120. let (mut iface, mut socket_set) = create_loopback();
  1121. let mut eth_bytes = vec![0u8; 34];
  1122. // Unknown Ipv4 Protocol
  1123. //
  1124. // Because the destination is the broadcast address
  1125. // this should not trigger and Destination Unreachable
  1126. // response. See RFC 1122 § 3.2.2.
  1127. let repr = IpRepr::Ipv4(Ipv4Repr {
  1128. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1129. dst_addr: Ipv4Address::BROADCAST,
  1130. protocol: IpProtocol::Unknown(0x0c),
  1131. payload_len: 0,
  1132. hop_limit: 0x40
  1133. });
  1134. let frame = {
  1135. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1136. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1137. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1138. frame.set_ethertype(EthernetProtocol::Ipv4);
  1139. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1140. EthernetFrame::new(&*frame.into_inner())
  1141. };
  1142. // Ensure that the unknown protocol frame does not trigger an
  1143. // ICMP error response when the destination address is a
  1144. // broadcast address
  1145. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  1146. Ok(Packet::None));
  1147. }
  1148. #[test]
  1149. #[cfg(feature = "proto-ipv4")]
  1150. fn test_icmp_error_no_payload() {
  1151. static NO_BYTES: [u8; 0] = [];
  1152. let (mut iface, mut socket_set) = create_loopback();
  1153. let mut eth_bytes = vec![0u8; 34];
  1154. // Unknown Ipv4 Protocol with no payload
  1155. let repr = IpRepr::Ipv4(Ipv4Repr {
  1156. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1157. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1158. protocol: IpProtocol::Unknown(0x0c),
  1159. payload_len: 0,
  1160. hop_limit: 0x40
  1161. });
  1162. // emit the above repr to a frame
  1163. let frame = {
  1164. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1165. frame.set_dst_addr(EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  1166. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1167. frame.set_ethertype(EthernetProtocol::Ipv4);
  1168. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1169. EthernetFrame::new(&*frame.into_inner())
  1170. };
  1171. // The expected Destination Unreachable response due to the
  1172. // unknown protocol
  1173. let icmp_repr = Icmpv4Repr::DstUnreachable {
  1174. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  1175. header: Ipv4Repr {
  1176. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1177. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1178. protocol: IpProtocol::Unknown(12),
  1179. payload_len: 0,
  1180. hop_limit: 64
  1181. },
  1182. data: &NO_BYTES
  1183. };
  1184. let expected_repr = Packet::Icmpv4((
  1185. Ipv4Repr {
  1186. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1187. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1188. protocol: IpProtocol::Icmp,
  1189. payload_len: icmp_repr.buffer_len(),
  1190. hop_limit: 64
  1191. },
  1192. icmp_repr
  1193. ));
  1194. // Ensure that the unknown protocol triggers an error response.
  1195. // And we correctly handle no payload.
  1196. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  1197. Ok(expected_repr));
  1198. }
  1199. #[test]
  1200. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1201. fn test_icmp_error_port_unreachable() {
  1202. static UDP_PAYLOAD: [u8; 12] = [
  1203. 0x48, 0x65, 0x6c, 0x6c,
  1204. 0x6f, 0x2c, 0x20, 0x57,
  1205. 0x6f, 0x6c, 0x64, 0x21
  1206. ];
  1207. let (iface, mut socket_set) = create_loopback();
  1208. let mut udp_bytes_unicast = vec![0u8; 20];
  1209. let mut udp_bytes_broadcast = vec![0u8; 20];
  1210. let mut packet_unicast = UdpPacket::new(&mut udp_bytes_unicast);
  1211. let mut packet_broadcast = UdpPacket::new(&mut udp_bytes_broadcast);
  1212. let udp_repr = UdpRepr {
  1213. src_port: 67,
  1214. dst_port: 68,
  1215. payload: &UDP_PAYLOAD
  1216. };
  1217. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1218. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1219. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1220. protocol: IpProtocol::Udp,
  1221. payload_len: udp_repr.buffer_len(),
  1222. hop_limit: 64
  1223. });
  1224. // Emit the representations to a packet
  1225. udp_repr.emit(&mut packet_unicast, &ip_repr.src_addr(),
  1226. &ip_repr.dst_addr(), &ChecksumCapabilities::default());
  1227. let data = packet_unicast.into_inner();
  1228. // The expected Destination Unreachable ICMPv4 error response due
  1229. // to no sockets listening on the destination port.
  1230. let icmp_repr = Icmpv4Repr::DstUnreachable {
  1231. reason: Icmpv4DstUnreachable::PortUnreachable,
  1232. header: Ipv4Repr {
  1233. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1234. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1235. protocol: IpProtocol::Udp,
  1236. payload_len: udp_repr.buffer_len(),
  1237. hop_limit: 64
  1238. },
  1239. data: &data
  1240. };
  1241. let expected_repr = Packet::Icmpv4((
  1242. Ipv4Repr {
  1243. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1244. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1245. protocol: IpProtocol::Icmp,
  1246. payload_len: icmp_repr.buffer_len(),
  1247. hop_limit: 64
  1248. },
  1249. icmp_repr
  1250. ));
  1251. // Ensure that the unknown protocol triggers an error response.
  1252. // And we correctly handle no payload.
  1253. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, data),
  1254. Ok(expected_repr));
  1255. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1256. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1257. dst_addr: Ipv4Address::BROADCAST,
  1258. protocol: IpProtocol::Udp,
  1259. payload_len: udp_repr.buffer_len(),
  1260. hop_limit: 64
  1261. });
  1262. // Emit the representations to a packet
  1263. udp_repr.emit(&mut packet_broadcast, &ip_repr.src_addr(),
  1264. &IpAddress::Ipv4(Ipv4Address::BROADCAST),
  1265. &ChecksumCapabilities::default());
  1266. // Ensure that the port unreachable error does not trigger an
  1267. // ICMP error response when the destination address is a
  1268. // broadcast address and no socket is bound to the port.
  1269. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr,
  1270. packet_broadcast.into_inner()), Ok(Packet::None));
  1271. }
  1272. #[test]
  1273. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1274. fn test_handle_udp_broadcast() {
  1275. use socket::{UdpSocket, UdpSocketBuffer, UdpPacketMetadata};
  1276. use wire::IpEndpoint;
  1277. static UDP_PAYLOAD: [u8; 5] = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
  1278. let (iface, mut socket_set) = create_loopback();
  1279. let rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  1280. let tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  1281. let udp_socket = UdpSocket::new(rx_buffer, tx_buffer);
  1282. let mut udp_bytes = vec![0u8; 13];
  1283. let mut packet = UdpPacket::new(&mut udp_bytes);
  1284. let socket_handle = socket_set.add(udp_socket);
  1285. let src_ip = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1286. let udp_repr = UdpRepr {
  1287. src_port: 67,
  1288. dst_port: 68,
  1289. payload: &UDP_PAYLOAD
  1290. };
  1291. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1292. src_addr: src_ip,
  1293. dst_addr: Ipv4Address::BROADCAST,
  1294. protocol: IpProtocol::Udp,
  1295. payload_len: udp_repr.buffer_len(),
  1296. hop_limit: 0x40
  1297. });
  1298. {
  1299. // Bind the socket to port 68
  1300. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1301. assert_eq!(socket.bind(68), Ok(()));
  1302. assert!(!socket.can_recv());
  1303. assert!(socket.can_send());
  1304. }
  1305. udp_repr.emit(&mut packet, &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1306. &ChecksumCapabilities::default());
  1307. // Packet should be handled by bound UDP socket
  1308. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, packet.into_inner()),
  1309. Ok(Packet::None));
  1310. {
  1311. // Make sure the payload to the UDP packet processed by process_udp is
  1312. // appended to the bound sockets rx_buffer
  1313. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1314. assert!(socket.can_recv());
  1315. assert_eq!(socket.recv(), Ok((&UDP_PAYLOAD[..], IpEndpoint::new(src_ip.into(), 67))));
  1316. }
  1317. }
  1318. #[test]
  1319. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1320. fn test_icmpv4_reply_size() {
  1321. use wire::IPV4_MIN_MTU;
  1322. let (iface, mut socket_set) = create_loopback();
  1323. let src_addr = Ipv4Address([192, 168, 1, 1]);
  1324. let dst_addr = Ipv4Address([192, 168, 1, 2]);
  1325. // UDP packet that if not tructated will cause a icmp port unreachable reply
  1326. // to exeed 576 bytes in length.
  1327. let udp_repr = UdpRepr {
  1328. src_port: 67,
  1329. dst_port: 68,
  1330. payload: &[0x2a; 524]
  1331. };
  1332. let mut bytes = vec![0xff; udp_repr.buffer_len()];
  1333. let mut packet = UdpPacket::new(&mut bytes[..]);
  1334. udp_repr.emit(&mut packet, &src_addr.into(), &dst_addr.into(), &ChecksumCapabilities::default());
  1335. let ipv4_repr = Ipv4Repr {
  1336. src_addr: src_addr,
  1337. dst_addr: dst_addr,
  1338. protocol: IpProtocol::Udp,
  1339. hop_limit: 64,
  1340. payload_len: udp_repr.buffer_len()
  1341. };
  1342. let payload = packet.into_inner();
  1343. // Expected packets
  1344. let expected_icmpv4_repr = Icmpv4Repr::DstUnreachable {
  1345. reason: Icmpv4DstUnreachable::PortUnreachable,
  1346. header: ipv4_repr,
  1347. // We only include 520 bytes of the original payload
  1348. // in the expected packets payload. We must only send
  1349. // ICMPv4 replies that do not exceed 576 bytes in length.
  1350. //
  1351. // 528 + 2 * sizeof(IPv4 Header) + sizeof(DstUnreachable Header) = 576
  1352. data: &payload[..528]
  1353. };
  1354. let expected_ipv4_repr = Ipv4Repr {
  1355. src_addr: dst_addr,
  1356. dst_addr: src_addr,
  1357. protocol: IpProtocol::Icmp,
  1358. hop_limit: 64,
  1359. payload_len: expected_icmpv4_repr.buffer_len()
  1360. };
  1361. // The expected packet does not exceed the IPV4_MIN_MTU
  1362. assert_eq!(expected_ipv4_repr.buffer_len() + expected_icmpv4_repr.buffer_len(),
  1363. IPV4_MIN_MTU);
  1364. // The expected packet and the generated packet are equal
  1365. assert_eq!(iface.inner.process_udp(&mut socket_set, ipv4_repr.into(), payload),
  1366. Ok(Packet::Icmpv4((expected_ipv4_repr, expected_icmpv4_repr))));
  1367. }
  1368. #[test]
  1369. #[cfg(feature = "proto-ipv4")]
  1370. fn test_handle_valid_arp_request() {
  1371. let (mut iface, mut socket_set) = create_loopback();
  1372. let mut eth_bytes = vec![0u8; 42];
  1373. let local_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x01]);
  1374. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1375. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  1376. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  1377. let repr = ArpRepr::EthernetIpv4 {
  1378. operation: ArpOperation::Request,
  1379. source_hardware_addr: remote_hw_addr,
  1380. source_protocol_addr: remote_ip_addr,
  1381. target_hardware_addr: EthernetAddress::default(),
  1382. target_protocol_addr: local_ip_addr,
  1383. };
  1384. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1385. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1386. frame.set_src_addr(remote_hw_addr);
  1387. frame.set_ethertype(EthernetProtocol::Arp);
  1388. {
  1389. let mut packet = ArpPacket::new(frame.payload_mut());
  1390. repr.emit(&mut packet);
  1391. }
  1392. // Ensure an ARP Request for us triggers an ARP Reply
  1393. assert_eq!(iface.inner.process_ethernet(&mut socket_set, Instant::from_millis(0), frame.into_inner()),
  1394. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  1395. operation: ArpOperation::Reply,
  1396. source_hardware_addr: local_hw_addr,
  1397. source_protocol_addr: local_ip_addr,
  1398. target_hardware_addr: remote_hw_addr,
  1399. target_protocol_addr: remote_ip_addr
  1400. })));
  1401. // Ensure the address of the requestor was entered in the cache
  1402. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  1403. &IpAddress::Ipv4(local_ip_addr), &IpAddress::Ipv4(remote_ip_addr)),
  1404. Ok((remote_hw_addr, MockTxToken)));
  1405. }
  1406. #[test]
  1407. #[cfg(feature = "proto-ipv4")]
  1408. fn test_handle_other_arp_request() {
  1409. let (mut iface, mut socket_set) = create_loopback();
  1410. let mut eth_bytes = vec![0u8; 42];
  1411. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1412. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  1413. let repr = ArpRepr::EthernetIpv4 {
  1414. operation: ArpOperation::Request,
  1415. source_hardware_addr: remote_hw_addr,
  1416. source_protocol_addr: remote_ip_addr,
  1417. target_hardware_addr: EthernetAddress::default(),
  1418. target_protocol_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x03]),
  1419. };
  1420. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1421. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1422. frame.set_src_addr(remote_hw_addr);
  1423. frame.set_ethertype(EthernetProtocol::Arp);
  1424. {
  1425. let mut packet = ArpPacket::new(frame.payload_mut());
  1426. repr.emit(&mut packet);
  1427. }
  1428. // Ensure an ARP Request for someone else does not trigger an ARP Reply
  1429. assert_eq!(iface.inner.process_ethernet(&mut socket_set, Instant::from_millis(0), frame.into_inner()),
  1430. Ok(Packet::None));
  1431. // Ensure the address of the requestor was entered in the cache
  1432. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  1433. &IpAddress::Ipv4(Ipv4Address([0x7f, 0x00, 0x00, 0x01])),
  1434. &IpAddress::Ipv4(remote_ip_addr)),
  1435. Ok((remote_hw_addr, MockTxToken)));
  1436. }
  1437. #[test]
  1438. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  1439. fn test_icmpv4_socket() {
  1440. use socket::{IcmpSocket, IcmpEndpoint, IcmpSocketBuffer, IcmpPacketMetadata};
  1441. use wire::Icmpv4Packet;
  1442. let (iface, mut socket_set) = create_loopback();
  1443. let rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 24]);
  1444. let tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 24]);
  1445. let icmpv4_socket = IcmpSocket::new(rx_buffer, tx_buffer);
  1446. let socket_handle = socket_set.add(icmpv4_socket);
  1447. let ident = 0x1234;
  1448. let seq_no = 0x5432;
  1449. let echo_data = &[0xff; 16];
  1450. {
  1451. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  1452. // Bind to the ID 0x1234
  1453. assert_eq!(socket.bind(IcmpEndpoint::Ident(ident)), Ok(()));
  1454. }
  1455. // Ensure the ident we bound to and the ident of the packet are the same.
  1456. let mut bytes = [0xff; 24];
  1457. let mut packet = Icmpv4Packet::new(&mut bytes);
  1458. let echo_repr = Icmpv4Repr::EchoRequest{ ident, seq_no, data: echo_data };
  1459. echo_repr.emit(&mut packet, &ChecksumCapabilities::default());
  1460. let icmp_data = &packet.into_inner()[..];
  1461. let ipv4_repr = Ipv4Repr {
  1462. src_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x02),
  1463. dst_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x01),
  1464. protocol: IpProtocol::Icmp,
  1465. payload_len: 24,
  1466. hop_limit: 64
  1467. };
  1468. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  1469. // Open a socket and ensure the packet is handled due to the listening
  1470. // socket.
  1471. {
  1472. assert!(!socket_set.get::<IcmpSocket>(socket_handle).can_recv());
  1473. }
  1474. // Confirm we still get EchoReply from `smoltcp` even with the ICMP socket listening
  1475. let echo_reply = Icmpv4Repr::EchoReply{ ident, seq_no, data: echo_data };
  1476. let ipv4_reply = Ipv4Repr {
  1477. src_addr: ipv4_repr.dst_addr,
  1478. dst_addr: ipv4_repr.src_addr,
  1479. ..ipv4_repr
  1480. };
  1481. assert_eq!(iface.inner.process_icmpv4(&mut socket_set, ip_repr, icmp_data),
  1482. Ok(Packet::Icmpv4((ipv4_reply, echo_reply))));
  1483. {
  1484. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  1485. assert!(socket.can_recv());
  1486. assert_eq!(socket.recv(),
  1487. Ok((&icmp_data[..],
  1488. IpAddress::Ipv4(Ipv4Address::new(0x7f, 0x00, 0x00, 0x02)))));
  1489. }
  1490. }
  1491. #[test]
  1492. #[cfg(feature = "proto-ipv6")]
  1493. fn test_solicited_node_addrs() {
  1494. let (mut iface, _) = create_loopback();
  1495. let mut new_addrs = vec![IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 1, 2, 0, 2), 64),
  1496. IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 3, 4, 0, 0xffff), 64)];
  1497. iface.update_ip_addrs(|addrs| {
  1498. new_addrs.extend(addrs.to_vec());
  1499. *addrs = From::from(new_addrs);
  1500. });
  1501. assert!(iface.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0x0002)));
  1502. assert!(iface.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0xffff)));
  1503. assert!(!iface.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0x0001)));
  1504. }
  1505. #[test]
  1506. #[cfg(feature = "proto-ipv6")]
  1507. fn test_icmpv6_nxthdr_unknown() {
  1508. let (mut iface, mut socket_set) = create_loopback();
  1509. let remote_ip_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  1510. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x01]);
  1511. let mut eth_bytes = vec![0; 58];
  1512. let payload = [0x12, 0x34, 0x56, 0x78];
  1513. let ipv6_repr = Ipv6Repr {
  1514. src_addr: remote_ip_addr,
  1515. dst_addr: Ipv6Address::LOOPBACK,
  1516. next_header: IpProtocol::Unknown(0x0c),
  1517. payload_len: 4,
  1518. hop_limit: 0x40,
  1519. };
  1520. let ip_repr = IpRepr::Ipv6(ipv6_repr);
  1521. let frame = {
  1522. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1523. frame.set_dst_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1524. frame.set_src_addr(remote_hw_addr);
  1525. frame.set_ethertype(EthernetProtocol::Ipv6);
  1526. ip_repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1527. frame.payload_mut()[ip_repr.buffer_len()..].copy_from_slice(&payload);
  1528. EthernetFrame::new(&*frame.into_inner())
  1529. };
  1530. let reply_icmp_repr = Icmpv6Repr::ParamProblem {
  1531. reason: Icmpv6ParamProblem::UnrecognizedNxtHdr,
  1532. pointer: 40,
  1533. header: ipv6_repr,
  1534. data: &payload[..]
  1535. };
  1536. let reply_ipv6_repr = Ipv6Repr {
  1537. src_addr: Ipv6Address::LOOPBACK,
  1538. dst_addr: remote_ip_addr,
  1539. next_header: IpProtocol::Icmpv6,
  1540. payload_len: reply_icmp_repr.buffer_len(),
  1541. hop_limit: 0x40,
  1542. };
  1543. // Ensure the unknown next header causes a ICMPv6 Parameter Problem
  1544. // error message to be sent to the sender.
  1545. assert_eq!(iface.inner.process_ipv6(&mut socket_set, Instant::from_millis(0), &frame),
  1546. Ok(Packet::Icmpv6((reply_ipv6_repr, reply_icmp_repr))));
  1547. // Ensure the address of the requestor was entered in the cache
  1548. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  1549. &IpAddress::Ipv6(Ipv6Address::LOOPBACK),
  1550. &IpAddress::Ipv6(remote_ip_addr)),
  1551. Ok((remote_hw_addr, MockTxToken)));
  1552. }
  1553. }