ethernet.rs 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596
  1. // Heads up! Before working on this file you should read the parts
  2. // of RFC 1122 that discuss Ethernet, ARP and IP for any IPv4 work
  3. // and RFCs 8200 and 4861 for any IPv6 and NDISC work.
  4. use core::cmp;
  5. use managed::{ManagedSlice, ManagedMap};
  6. #[cfg(not(feature = "proto-igmp"))]
  7. use core::marker::PhantomData;
  8. use {Error, Result};
  9. use phy::{Device, DeviceCapabilities, RxToken, TxToken};
  10. use time::{Duration, Instant};
  11. use wire::pretty_print::PrettyPrinter;
  12. use wire::{EthernetAddress, EthernetProtocol, EthernetFrame};
  13. use wire::{IpAddress, IpProtocol, IpRepr, IpCidr};
  14. #[cfg(feature = "proto-ipv6")]
  15. use wire::{Ipv6Address, Ipv6Packet, Ipv6Repr, IPV6_MIN_MTU};
  16. #[cfg(feature = "proto-ipv4")]
  17. use wire::{Ipv4Address, Ipv4Packet, Ipv4Repr, IPV4_MIN_MTU};
  18. #[cfg(feature = "proto-ipv4")]
  19. use wire::{ArpPacket, ArpRepr, ArpOperation};
  20. #[cfg(feature = "proto-ipv4")]
  21. use wire::{Icmpv4Packet, Icmpv4Repr, Icmpv4DstUnreachable};
  22. #[cfg(feature = "proto-igmp")]
  23. use wire::{IgmpPacket, IgmpRepr, IgmpVersion};
  24. #[cfg(feature = "proto-ipv6")]
  25. use wire::{Icmpv6Packet, Icmpv6Repr, Icmpv6ParamProblem};
  26. #[cfg(all(feature = "socket-icmp", any(feature = "proto-ipv4", feature = "proto-ipv6")))]
  27. use wire::IcmpRepr;
  28. #[cfg(feature = "proto-ipv6")]
  29. use wire::{Ipv6HopByHopHeader, Ipv6HopByHopRepr};
  30. #[cfg(feature = "proto-ipv6")]
  31. use wire::{Ipv6OptionRepr, Ipv6OptionFailureType};
  32. #[cfg(feature = "proto-ipv6")]
  33. use wire::{NdiscNeighborFlags, NdiscRepr};
  34. #[cfg(all(feature = "proto-ipv6", feature = "socket-udp"))]
  35. use wire::Icmpv6DstUnreachable;
  36. #[cfg(feature = "socket-udp")]
  37. use wire::{UdpPacket, UdpRepr};
  38. #[cfg(feature = "socket-tcp")]
  39. use wire::{TcpPacket, TcpRepr, TcpControl};
  40. use socket::{Socket, SocketSet, AnySocket, PollAt};
  41. #[cfg(feature = "socket-raw")]
  42. use socket::RawSocket;
  43. #[cfg(all(feature = "socket-icmp", any(feature = "proto-ipv4", feature = "proto-ipv6")))]
  44. use socket::IcmpSocket;
  45. #[cfg(feature = "socket-udp")]
  46. use socket::UdpSocket;
  47. #[cfg(feature = "socket-tcp")]
  48. use socket::TcpSocket;
  49. use super::{NeighborCache, NeighborAnswer};
  50. use super::Routes;
  51. /// An Ethernet network interface.
  52. ///
  53. /// The network interface logically owns a number of other data structures; to avoid
  54. /// a dependency on heap allocation, it instead owns a `BorrowMut<[T]>`, which can be
  55. /// a `&mut [T]`, or `Vec<T>` if a heap is available.
  56. pub struct Interface<'b, 'c, 'e, DeviceT: for<'d> Device<'d>> {
  57. device: DeviceT,
  58. inner: InterfaceInner<'b, 'c, 'e>,
  59. }
  60. /// The device independent part of an Ethernet network interface.
  61. ///
  62. /// Separating the device from the data required for prorcessing and dispatching makes
  63. /// it possible to borrow them independently. For example, the tx and rx tokens borrow
  64. /// the `device` mutably until they're used, which makes it impossible to call other
  65. /// methods on the `Interface` in this time (since its `device` field is borrowed
  66. /// exclusively). However, it is still possible to call methods on its `inner` field.
  67. struct InterfaceInner<'b, 'c, 'e> {
  68. neighbor_cache: NeighborCache<'b>,
  69. ethernet_addr: EthernetAddress,
  70. ip_addrs: ManagedSlice<'c, IpCidr>,
  71. #[cfg(feature = "proto-ipv4")]
  72. any_ip: bool,
  73. routes: Routes<'e>,
  74. #[cfg(feature = "proto-igmp")]
  75. ipv4_multicast_groups: ManagedMap<'e, Ipv4Address, ()>,
  76. #[cfg(not(feature = "proto-igmp"))]
  77. _ipv4_multicast_groups: PhantomData<&'e ()>,
  78. /// When to report for (all or) the next multicast group membership via IGMP
  79. #[cfg(feature = "proto-igmp")]
  80. igmp_report_state: IgmpReportState,
  81. device_capabilities: DeviceCapabilities,
  82. }
  83. /// A builder structure used for creating a Ethernet network
  84. /// interface.
  85. pub struct InterfaceBuilder <'b, 'c, 'e, DeviceT: for<'d> Device<'d>> {
  86. device: DeviceT,
  87. ethernet_addr: Option<EthernetAddress>,
  88. neighbor_cache: Option<NeighborCache<'b>>,
  89. ip_addrs: ManagedSlice<'c, IpCidr>,
  90. #[cfg(feature = "proto-ipv4")]
  91. any_ip: bool,
  92. routes: Routes<'e>,
  93. /// Does not share storage with `ipv6_multicast_groups` to avoid IPv6 size overhead.
  94. #[cfg(feature = "proto-igmp")]
  95. ipv4_multicast_groups: ManagedMap<'e, Ipv4Address, ()>,
  96. #[cfg(not(feature = "proto-igmp"))]
  97. _ipv4_multicast_groups: PhantomData<&'e ()>,
  98. }
  99. impl<'b, 'c, 'e, DeviceT> InterfaceBuilder<'b, 'c, 'e, DeviceT>
  100. where DeviceT: for<'d> Device<'d> {
  101. /// Create a builder used for creating a network interface using the
  102. /// given device and address.
  103. ///
  104. /// # Examples
  105. ///
  106. /// ```
  107. /// # use std::collections::BTreeMap;
  108. /// use smoltcp::iface::{EthernetInterfaceBuilder, NeighborCache};
  109. /// # use smoltcp::phy::Loopback;
  110. /// use smoltcp::wire::{EthernetAddress, IpCidr, IpAddress};
  111. ///
  112. /// let device = // ...
  113. /// # Loopback::new();
  114. /// let hw_addr = // ...
  115. /// # EthernetAddress::default();
  116. /// let neighbor_cache = // ...
  117. /// # NeighborCache::new(BTreeMap::new());
  118. /// let ip_addrs = // ...
  119. /// # [];
  120. /// let iface = EthernetInterfaceBuilder::new(device)
  121. /// .ethernet_addr(hw_addr)
  122. /// .neighbor_cache(neighbor_cache)
  123. /// .ip_addrs(ip_addrs)
  124. /// .finalize();
  125. /// ```
  126. pub fn new(device: DeviceT) -> Self {
  127. InterfaceBuilder {
  128. device: device,
  129. ethernet_addr: None,
  130. neighbor_cache: None,
  131. ip_addrs: ManagedSlice::Borrowed(&mut []),
  132. #[cfg(feature = "proto-ipv4")]
  133. any_ip: false,
  134. routes: Routes::new(ManagedMap::Borrowed(&mut [])),
  135. #[cfg(feature = "proto-igmp")]
  136. ipv4_multicast_groups: ManagedMap::Borrowed(&mut []),
  137. #[cfg(not(feature = "proto-igmp"))]
  138. _ipv4_multicast_groups: PhantomData,
  139. }
  140. }
  141. /// Set the Ethernet address the interface will use. See also
  142. /// [ethernet_addr].
  143. ///
  144. /// # Panics
  145. /// This function panics if the address is not unicast.
  146. ///
  147. /// [ethernet_addr]: struct.EthernetInterface.html#method.ethernet_addr
  148. pub fn ethernet_addr(mut self, addr: EthernetAddress) -> Self {
  149. InterfaceInner::check_ethernet_addr(&addr);
  150. self.ethernet_addr = Some(addr);
  151. self
  152. }
  153. /// Set the IP addresses the interface will use. See also
  154. /// [ip_addrs].
  155. ///
  156. /// # Panics
  157. /// This function panics if any of the addresses are not unicast.
  158. ///
  159. /// [ip_addrs]: struct.EthernetInterface.html#method.ip_addrs
  160. pub fn ip_addrs<T>(mut self, ip_addrs: T) -> Self
  161. where T: Into<ManagedSlice<'c, IpCidr>>
  162. {
  163. let ip_addrs = ip_addrs.into();
  164. InterfaceInner::check_ip_addrs(&ip_addrs);
  165. self.ip_addrs = ip_addrs;
  166. self
  167. }
  168. /// Enable or disable the AnyIP capability, allowing packets to be received
  169. /// locally on IPv4 addresses other than the interface's configured [ip_addrs].
  170. /// When AnyIP is enabled and a route prefix in [routes] specifies one of
  171. /// the interface's [ip_addrs] as its gateway, the interface will accept
  172. /// packets addressed to that prefix.
  173. ///
  174. /// # IPv6
  175. ///
  176. /// This option is not available or required for IPv6 as packets sent to
  177. /// the interface are not filtered by IPv6 address.
  178. ///
  179. /// [routes]: struct.EthernetInterface.html#method.routes
  180. /// [ip_addrs]: struct.EthernetInterface.html#method.ip_addrs
  181. #[cfg(feature = "proto-ipv4")]
  182. pub fn any_ip(mut self, enabled: bool) -> Self {
  183. self.any_ip = enabled;
  184. self
  185. }
  186. /// Set the IP routes the interface will use. See also
  187. /// [routes].
  188. ///
  189. /// [routes]: struct.EthernetInterface.html#method.routes
  190. pub fn routes<T>(mut self, routes: T) -> InterfaceBuilder<'b, 'c, 'e, DeviceT>
  191. where T: Into<Routes<'e>>
  192. {
  193. self.routes = routes.into();
  194. self
  195. }
  196. /// Provide storage for multicast groups.
  197. ///
  198. /// Join multicast groups by calling [`join_multicast_group()`] on an `Interface`.
  199. /// Using [`join_multicast_group()`] will send initial membership reports.
  200. ///
  201. /// A previously destroyed interface can be recreated by reusing the multicast group
  202. /// storage, i.e. providing a non-empty storage to `ipv4_multicast_groups()`.
  203. /// Note that this way initial membership reports are **not** sent.
  204. ///
  205. /// [`join_multicast_group()`]: struct.EthernetInterface.html#method.join_multicast_group
  206. #[cfg(feature = "proto-igmp")]
  207. pub fn ipv4_multicast_groups<T>(mut self, ipv4_multicast_groups: T) -> Self
  208. where T: Into<ManagedMap<'e, Ipv4Address, ()>>
  209. {
  210. self.ipv4_multicast_groups = ipv4_multicast_groups.into();
  211. self
  212. }
  213. /// Set the Neighbor Cache the interface will use.
  214. pub fn neighbor_cache(mut self, neighbor_cache: NeighborCache<'b>) -> Self {
  215. self.neighbor_cache = Some(neighbor_cache);
  216. self
  217. }
  218. /// Create a network interface using the previously provided configuration.
  219. ///
  220. /// # Panics
  221. /// If a required option is not provided, this function will panic. Required
  222. /// options are:
  223. ///
  224. /// - [ethernet_addr]
  225. /// - [neighbor_cache]
  226. ///
  227. /// [ethernet_addr]: #method.ethernet_addr
  228. /// [neighbor_cache]: #method.neighbor_cache
  229. pub fn finalize(self) -> Interface<'b, 'c, 'e, DeviceT> {
  230. match (self.ethernet_addr, self.neighbor_cache) {
  231. (Some(ethernet_addr), Some(neighbor_cache)) => {
  232. let device_capabilities = self.device.capabilities();
  233. Interface {
  234. device: self.device,
  235. inner: InterfaceInner {
  236. ethernet_addr, device_capabilities, neighbor_cache,
  237. ip_addrs: self.ip_addrs,
  238. #[cfg(feature = "proto-ipv4")]
  239. any_ip: self.any_ip,
  240. routes: self.routes,
  241. #[cfg(feature = "proto-igmp")]
  242. ipv4_multicast_groups: self.ipv4_multicast_groups,
  243. #[cfg(not(feature = "proto-igmp"))]
  244. _ipv4_multicast_groups: PhantomData,
  245. #[cfg(feature = "proto-igmp")]
  246. igmp_report_state: IgmpReportState::Inactive,
  247. }
  248. }
  249. },
  250. _ => panic!("a required option was not set"),
  251. }
  252. }
  253. }
  254. #[derive(Debug, PartialEq)]
  255. enum Packet<'a> {
  256. None,
  257. #[cfg(feature = "proto-ipv4")]
  258. Arp(ArpRepr),
  259. #[cfg(feature = "proto-ipv4")]
  260. Icmpv4((Ipv4Repr, Icmpv4Repr<'a>)),
  261. #[cfg(feature = "proto-igmp")]
  262. Igmp((Ipv4Repr, IgmpRepr)),
  263. #[cfg(feature = "proto-ipv6")]
  264. Icmpv6((Ipv6Repr, Icmpv6Repr<'a>)),
  265. #[cfg(feature = "socket-raw")]
  266. Raw((IpRepr, &'a [u8])),
  267. #[cfg(feature = "socket-udp")]
  268. Udp((IpRepr, UdpRepr<'a>)),
  269. #[cfg(feature = "socket-tcp")]
  270. Tcp((IpRepr, TcpRepr<'a>))
  271. }
  272. impl<'a> Packet<'a> {
  273. fn neighbor_addr(&self) -> Option<IpAddress> {
  274. match self {
  275. &Packet::None => None,
  276. #[cfg(feature = "proto-ipv4")]
  277. &Packet::Arp(_) => None,
  278. #[cfg(feature = "proto-ipv4")]
  279. &Packet::Icmpv4((ref ipv4_repr, _)) => Some(ipv4_repr.dst_addr.into()),
  280. #[cfg(feature = "proto-igmp")]
  281. &Packet::Igmp((ref ipv4_repr, _)) => Some(ipv4_repr.dst_addr.into()),
  282. #[cfg(feature = "proto-ipv6")]
  283. &Packet::Icmpv6((ref ipv6_repr, _)) => Some(ipv6_repr.dst_addr.into()),
  284. #[cfg(feature = "socket-raw")]
  285. &Packet::Raw((ref ip_repr, _)) => Some(ip_repr.dst_addr()),
  286. #[cfg(feature = "socket-udp")]
  287. &Packet::Udp((ref ip_repr, _)) => Some(ip_repr.dst_addr()),
  288. #[cfg(feature = "socket-tcp")]
  289. &Packet::Tcp((ref ip_repr, _)) => Some(ip_repr.dst_addr())
  290. }
  291. }
  292. }
  293. #[cfg(any(feature = "proto-ipv4", feature = "proto-ipv6"))]
  294. fn icmp_reply_payload_len(len: usize, mtu: usize, header_len: usize) -> usize {
  295. // Send back as much of the original payload as will fit within
  296. // the minimum MTU required by IPv4. See RFC 1812 § 4.3.2.3 for
  297. // more details.
  298. //
  299. // Since the entire network layer packet must fit within the minumum
  300. // MTU supported, the payload must not exceed the following:
  301. //
  302. // <min mtu> - IP Header Size * 2 - ICMPv4 DstUnreachable hdr size
  303. cmp::min(len, mtu - header_len * 2 - 8)
  304. }
  305. #[cfg(feature = "proto-igmp")]
  306. enum IgmpReportState {
  307. Inactive,
  308. ToGeneralQuery {
  309. version: IgmpVersion,
  310. timeout: Instant,
  311. interval: Duration,
  312. next_index: usize
  313. },
  314. ToSpecificQuery {
  315. version: IgmpVersion,
  316. timeout: Instant,
  317. group: Ipv4Address
  318. },
  319. }
  320. impl<'b, 'c, 'e, DeviceT> Interface<'b, 'c, 'e, DeviceT>
  321. where DeviceT: for<'d> Device<'d> {
  322. /// Get the Ethernet address of the interface.
  323. pub fn ethernet_addr(&self) -> EthernetAddress {
  324. self.inner.ethernet_addr
  325. }
  326. /// Set the Ethernet address of the interface.
  327. ///
  328. /// # Panics
  329. /// This function panics if the address is not unicast.
  330. pub fn set_ethernet_addr(&mut self, addr: EthernetAddress) {
  331. self.inner.ethernet_addr = addr;
  332. InterfaceInner::check_ethernet_addr(&self.inner.ethernet_addr);
  333. }
  334. /// Get a reference to the inner device.
  335. pub fn device(&self) -> &DeviceT {
  336. &self.device
  337. }
  338. /// Get a mutable reference to the inner device.
  339. ///
  340. /// There are no invariants imposed on the device by the interface itself. Furthermore the
  341. /// trait implementations, required for references of all lifetimes, guarantees that the
  342. /// mutable reference can not invalidate the device as such. For some devices, such access may
  343. /// still allow modifications with adverse effects on the usability as a `phy` device. You
  344. /// should not use them this way.
  345. pub fn device_mut(&mut self) -> &mut DeviceT {
  346. &mut self.device
  347. }
  348. /// Add an address to a list of subscribed multicast IP addresses.
  349. ///
  350. /// Returns `Ok(announce_sent)` if the address was added successfully, where `annouce_sent`
  351. /// indicates whether an initial immediate announcement has been sent.
  352. pub fn join_multicast_group<T: Into<IpAddress>>(&mut self, addr: T, _timestamp: Instant) -> Result<bool> {
  353. match addr.into() {
  354. #[cfg(feature = "proto-igmp")]
  355. IpAddress::Ipv4(addr) => {
  356. let is_not_new = self.inner.ipv4_multicast_groups.insert(addr, ())
  357. .map_err(|_| Error::Exhausted)?
  358. .is_some();
  359. if is_not_new {
  360. Ok(false)
  361. } else if let Some(pkt) =
  362. self.inner.igmp_report_packet(IgmpVersion::Version2, addr) {
  363. // Send initial membership report
  364. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  365. self.inner.dispatch(tx_token, _timestamp, pkt)?;
  366. Ok(true)
  367. } else {
  368. Ok(false)
  369. }
  370. }
  371. // Multicast is not yet implemented for other address families
  372. _ => Err(Error::Unaddressable)
  373. }
  374. }
  375. /// Remove an address from the subscribed multicast IP addresses.
  376. ///
  377. /// Returns `Ok(leave_sent)` if the address was removed successfully, where `leave_sent`
  378. /// indicates whether an immediate leave packet has been sent.
  379. pub fn leave_multicast_group<T: Into<IpAddress>>(&mut self, addr: T, _timestamp: Instant) -> Result<bool> {
  380. match addr.into() {
  381. #[cfg(feature = "proto-igmp")]
  382. IpAddress::Ipv4(addr) => {
  383. let was_not_present = self.inner.ipv4_multicast_groups.remove(&addr)
  384. .is_none();
  385. if was_not_present {
  386. Ok(false)
  387. } else if let Some(pkt) = self.inner.igmp_leave_packet(addr) {
  388. // Send group leave packet
  389. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  390. self.inner.dispatch(tx_token, _timestamp, pkt)?;
  391. Ok(true)
  392. } else {
  393. Ok(false)
  394. }
  395. }
  396. // Multicast is not yet implemented for other address families
  397. _ => Err(Error::Unaddressable)
  398. }
  399. }
  400. /// Check whether the interface listens to given destination multicast IP address.
  401. pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
  402. self.inner.has_multicast_group(addr)
  403. }
  404. /// Get the IP addresses of the interface.
  405. pub fn ip_addrs(&self) -> &[IpCidr] {
  406. self.inner.ip_addrs.as_ref()
  407. }
  408. /// Update the IP addresses of the interface.
  409. ///
  410. /// # Panics
  411. /// This function panics if any of the addresses are not unicast.
  412. pub fn update_ip_addrs<F: FnOnce(&mut ManagedSlice<'c, IpCidr>)>(&mut self, f: F) {
  413. f(&mut self.inner.ip_addrs);
  414. InterfaceInner::check_ip_addrs(&self.inner.ip_addrs)
  415. }
  416. /// Check whether the interface has the given IP address assigned.
  417. pub fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  418. self.inner.has_ip_addr(addr)
  419. }
  420. /// Get the first IPv4 address of the interface.
  421. #[cfg(feature = "proto-ipv4")]
  422. pub fn ipv4_address(&self) -> Option<Ipv4Address> {
  423. self.inner.ipv4_address()
  424. }
  425. pub fn routes(&self) -> &Routes<'e> {
  426. &self.inner.routes
  427. }
  428. pub fn routes_mut(&mut self) -> &mut Routes<'e> {
  429. &mut self.inner.routes
  430. }
  431. /// Transmit packets queued in the given sockets, and receive packets queued
  432. /// in the device.
  433. ///
  434. /// This function returns a boolean value indicating whether any packets were
  435. /// processed or emitted, and thus, whether the readiness of any socket might
  436. /// have changed.
  437. ///
  438. /// # Errors
  439. /// This method will routinely return errors in response to normal network
  440. /// activity as well as certain boundary conditions such as buffer exhaustion.
  441. /// These errors are provided as an aid for troubleshooting, and are meant
  442. /// to be logged and ignored.
  443. ///
  444. /// As a special case, `Err(Error::Unrecognized)` is returned in response to
  445. /// packets containing any unsupported protocol, option, or form, which is
  446. /// a very common occurrence and on a production system it should not even
  447. /// be logged.
  448. pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  449. let mut readiness_may_have_changed = false;
  450. loop {
  451. let processed_any = self.socket_ingress(sockets, timestamp)?;
  452. let emitted_any = self.socket_egress(sockets, timestamp)?;
  453. #[cfg(feature = "proto-igmp")]
  454. self.igmp_egress(timestamp)?;
  455. if processed_any || emitted_any {
  456. readiness_may_have_changed = true;
  457. } else {
  458. break
  459. }
  460. }
  461. Ok(readiness_may_have_changed)
  462. }
  463. /// Return a _soft deadline_ for calling [poll] the next time.
  464. /// The [Instant] returned is the time at which you should call [poll] next.
  465. /// It is harmless (but wastes energy) to call it before the [Instant], and
  466. /// potentially harmful (impacting quality of service) to call it after the
  467. /// [Instant]
  468. ///
  469. /// [poll]: #method.poll
  470. /// [Instant]: struct.Instant.html
  471. pub fn poll_at(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Instant> {
  472. sockets.iter().filter_map(|socket| {
  473. let socket_poll_at = socket.poll_at();
  474. match socket.meta().poll_at(socket_poll_at, |ip_addr|
  475. self.inner.has_neighbor(&ip_addr, timestamp)) {
  476. PollAt::Ingress => None,
  477. PollAt::Time(instant) => Some(instant),
  478. PollAt::Now => Some(Instant::from_millis(0)),
  479. }
  480. }).min()
  481. }
  482. /// Return an _advisory wait time_ for calling [poll] the next time.
  483. /// The [Duration] returned is the time left to wait before calling [poll] next.
  484. /// It is harmless (but wastes energy) to call it before the [Duration] has passed,
  485. /// and potentially harmful (impacting quality of service) to call it after the
  486. /// [Duration] has passed.
  487. ///
  488. /// [poll]: #method.poll
  489. /// [Duration]: struct.Duration.html
  490. pub fn poll_delay(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Duration> {
  491. match self.poll_at(sockets, timestamp) {
  492. Some(poll_at) if timestamp < poll_at => {
  493. Some(poll_at - timestamp)
  494. }
  495. Some(_) => {
  496. Some(Duration::from_millis(0))
  497. }
  498. _ => None
  499. }
  500. }
  501. fn socket_ingress(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  502. let mut processed_any = false;
  503. loop {
  504. let &mut Self { ref mut device, ref mut inner } = self;
  505. let (rx_token, tx_token) = match device.receive() {
  506. None => break,
  507. Some(tokens) => tokens,
  508. };
  509. rx_token.consume(timestamp, |frame| {
  510. inner.process_ethernet(sockets, timestamp, &frame).map_err(|err| {
  511. net_debug!("cannot process ingress packet: {}", err);
  512. net_debug!("packet dump follows:\n{}",
  513. PrettyPrinter::<EthernetFrame<&[u8]>>::new("", &frame));
  514. err
  515. }).and_then(|response| {
  516. processed_any = true;
  517. inner.dispatch(tx_token, timestamp, response).map_err(|err| {
  518. net_debug!("cannot dispatch response packet: {}", err);
  519. err
  520. })
  521. })
  522. })?;
  523. }
  524. Ok(processed_any)
  525. }
  526. fn socket_egress(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  527. let mut caps = self.device.capabilities();
  528. caps.max_transmission_unit -= EthernetFrame::<&[u8]>::header_len();
  529. let mut emitted_any = false;
  530. for mut socket in sockets.iter_mut() {
  531. if !socket.meta_mut().egress_permitted(|ip_addr|
  532. self.inner.has_neighbor(&ip_addr, timestamp)) {
  533. continue
  534. }
  535. let mut neighbor_addr = None;
  536. let mut device_result = Ok(());
  537. let &mut Self { ref mut device, ref mut inner } = self;
  538. macro_rules! respond {
  539. ($response:expr) => ({
  540. let response = $response;
  541. neighbor_addr = response.neighbor_addr();
  542. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  543. device_result = inner.dispatch(tx_token, timestamp, response);
  544. device_result
  545. })
  546. }
  547. let socket_result =
  548. match *socket {
  549. #[cfg(feature = "socket-raw")]
  550. Socket::Raw(ref mut socket) =>
  551. socket.dispatch(&caps.checksum, |response|
  552. respond!(Packet::Raw(response))),
  553. #[cfg(all(feature = "socket-icmp", any(feature = "proto-ipv4", feature = "proto-ipv6")))]
  554. Socket::Icmp(ref mut socket) =>
  555. socket.dispatch(&caps, |response| {
  556. match response {
  557. #[cfg(feature = "proto-ipv4")]
  558. (IpRepr::Ipv4(ipv4_repr), IcmpRepr::Ipv4(icmpv4_repr)) =>
  559. respond!(Packet::Icmpv4((ipv4_repr, icmpv4_repr))),
  560. #[cfg(feature = "proto-ipv6")]
  561. (IpRepr::Ipv6(ipv6_repr), IcmpRepr::Ipv6(icmpv6_repr)) =>
  562. respond!(Packet::Icmpv6((ipv6_repr, icmpv6_repr))),
  563. _ => Err(Error::Unaddressable)
  564. }
  565. }),
  566. #[cfg(feature = "socket-udp")]
  567. Socket::Udp(ref mut socket) =>
  568. socket.dispatch(|response|
  569. respond!(Packet::Udp(response))),
  570. #[cfg(feature = "socket-tcp")]
  571. Socket::Tcp(ref mut socket) =>
  572. socket.dispatch(timestamp, &caps, |response|
  573. respond!(Packet::Tcp(response))),
  574. Socket::__Nonexhaustive(_) => unreachable!()
  575. };
  576. match (device_result, socket_result) {
  577. (Err(Error::Exhausted), _) => break, // nowhere to transmit
  578. (Ok(()), Err(Error::Exhausted)) => (), // nothing to transmit
  579. (Err(Error::Unaddressable), _) => {
  580. // `NeighborCache` already takes care of rate limiting the neighbor discovery
  581. // requests from the socket. However, without an additional rate limiting
  582. // mechanism, we would spin on every socket that has yet to discover its
  583. // neighboor.
  584. socket.meta_mut().neighbor_missing(timestamp,
  585. neighbor_addr.expect("non-IP response packet"));
  586. break
  587. }
  588. (Err(err), _) | (_, Err(err)) => {
  589. net_debug!("{}: cannot dispatch egress packet: {}",
  590. socket.meta().handle, err);
  591. return Err(err)
  592. }
  593. (Ok(()), Ok(())) => emitted_any = true
  594. }
  595. }
  596. Ok(emitted_any)
  597. }
  598. /// Depending on `igmp_report_state` and the therein contained
  599. /// timeouts, send IGMP membership reports.
  600. #[cfg(feature = "proto-igmp")]
  601. fn igmp_egress(&mut self, timestamp: Instant) -> Result<bool> {
  602. match self.inner.igmp_report_state {
  603. IgmpReportState::ToSpecificQuery { version, timeout, group }
  604. if timestamp >= timeout => {
  605. if let Some(pkt) = self.inner.igmp_report_packet(version, group) {
  606. // Send initial membership report
  607. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  608. self.inner.dispatch(tx_token, timestamp, pkt)?;
  609. }
  610. self.inner.igmp_report_state = IgmpReportState::Inactive;
  611. Ok(true)
  612. }
  613. IgmpReportState::ToGeneralQuery { version, timeout, interval, next_index }
  614. if timestamp >= timeout => {
  615. let addr = self.inner.ipv4_multicast_groups
  616. .iter()
  617. .nth(next_index)
  618. .map(|(addr, ())| *addr);
  619. match addr {
  620. Some(addr) => {
  621. if let Some(pkt) = self.inner.igmp_report_packet(version, addr) {
  622. // Send initial membership report
  623. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  624. self.inner.dispatch(tx_token, timestamp, pkt)?;
  625. }
  626. let next_timeout = (timeout + interval).max(timestamp);
  627. self.inner.igmp_report_state = IgmpReportState::ToGeneralQuery {
  628. version, timeout: next_timeout, interval, next_index: next_index + 1
  629. };
  630. Ok(true)
  631. }
  632. None => {
  633. self.inner.igmp_report_state = IgmpReportState::Inactive;
  634. Ok(false)
  635. }
  636. }
  637. }
  638. _ => Ok(false)
  639. }
  640. }
  641. }
  642. impl<'b, 'c, 'e> InterfaceInner<'b, 'c, 'e> {
  643. fn check_ethernet_addr(addr: &EthernetAddress) {
  644. if addr.is_multicast() {
  645. panic!("Ethernet address {} is not unicast", addr)
  646. }
  647. }
  648. fn check_ip_addrs(addrs: &[IpCidr]) {
  649. for cidr in addrs {
  650. if !cidr.address().is_unicast() {
  651. panic!("IP address {} is not unicast", cidr.address())
  652. }
  653. }
  654. }
  655. /// Determine if the given `Ipv6Address` is the solicited node
  656. /// multicast address for a IPv6 addresses assigned to the interface.
  657. /// See [RFC 4291 § 2.7.1] for more details.
  658. ///
  659. /// [RFC 4291 § 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1
  660. #[cfg(feature = "proto-ipv6")]
  661. pub fn has_solicited_node(&self, addr: Ipv6Address) -> bool {
  662. self.ip_addrs.iter().find(|cidr| {
  663. match *cidr {
  664. &IpCidr::Ipv6(cidr) if cidr.address() != Ipv6Address::LOOPBACK=> {
  665. // Take the lower order 24 bits of the IPv6 address and
  666. // append those bits to FF02:0:0:0:0:1:FF00::/104.
  667. addr.as_bytes()[14..] == cidr.address().as_bytes()[14..]
  668. }
  669. _ => false,
  670. }
  671. }).is_some()
  672. }
  673. /// Check whether the interface has the given IP address assigned.
  674. fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  675. let addr = addr.into();
  676. self.ip_addrs.iter().any(|probe| probe.address() == addr)
  677. }
  678. /// Get the first IPv4 address of the interface.
  679. #[cfg(feature = "proto-ipv4")]
  680. pub fn ipv4_address(&self) -> Option<Ipv4Address> {
  681. self.ip_addrs.iter()
  682. .filter_map(
  683. |addr| match addr {
  684. &IpCidr::Ipv4(cidr) => Some(cidr.address()),
  685. _ => None,
  686. })
  687. .next()
  688. }
  689. /// Check whether the interface listens to given destination multicast IP address.
  690. ///
  691. /// If built without feature `proto-igmp` this function will
  692. /// always return `false`.
  693. pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
  694. match addr.into() {
  695. #[cfg(feature = "proto-igmp")]
  696. IpAddress::Ipv4(key) =>
  697. key == Ipv4Address::MULTICAST_ALL_SYSTEMS ||
  698. self.ipv4_multicast_groups.get(&key).is_some(),
  699. _ =>
  700. false,
  701. }
  702. }
  703. fn process_ethernet<'frame, T: AsRef<[u8]>>
  704. (&mut self, sockets: &mut SocketSet, timestamp: Instant, frame: &'frame T) ->
  705. Result<Packet<'frame>>
  706. {
  707. let eth_frame = EthernetFrame::new_checked(frame)?;
  708. // Ignore any packets not directed to our hardware address or any of the multicast groups.
  709. if !eth_frame.dst_addr().is_broadcast() &&
  710. !eth_frame.dst_addr().is_multicast() &&
  711. eth_frame.dst_addr() != self.ethernet_addr
  712. {
  713. return Ok(Packet::None)
  714. }
  715. match eth_frame.ethertype() {
  716. #[cfg(feature = "proto-ipv4")]
  717. EthernetProtocol::Arp =>
  718. self.process_arp(timestamp, &eth_frame),
  719. #[cfg(feature = "proto-ipv4")]
  720. EthernetProtocol::Ipv4 =>
  721. self.process_ipv4(sockets, timestamp, &eth_frame),
  722. #[cfg(feature = "proto-ipv6")]
  723. EthernetProtocol::Ipv6 =>
  724. self.process_ipv6(sockets, timestamp, &eth_frame),
  725. // Drop all other traffic.
  726. _ => Err(Error::Unrecognized),
  727. }
  728. }
  729. #[cfg(feature = "proto-ipv4")]
  730. fn process_arp<'frame, T: AsRef<[u8]>>
  731. (&mut self, timestamp: Instant, eth_frame: &EthernetFrame<&'frame T>) ->
  732. Result<Packet<'frame>>
  733. {
  734. let arp_packet = ArpPacket::new_checked(eth_frame.payload())?;
  735. let arp_repr = ArpRepr::parse(&arp_packet)?;
  736. match arp_repr {
  737. // Respond to ARP requests aimed at us, and fill the ARP cache from all ARP
  738. // requests and replies, to minimize the chance that we have to perform
  739. // an explicit ARP request.
  740. ArpRepr::EthernetIpv4 {
  741. operation, source_hardware_addr, source_protocol_addr, target_protocol_addr, ..
  742. } => {
  743. if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() {
  744. self.neighbor_cache.fill(source_protocol_addr.into(),
  745. source_hardware_addr,
  746. timestamp);
  747. } else {
  748. // Discard packets with non-unicast source addresses.
  749. net_debug!("non-unicast source address");
  750. return Err(Error::Malformed)
  751. }
  752. if operation == ArpOperation::Request && self.has_ip_addr(target_protocol_addr) {
  753. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  754. operation: ArpOperation::Reply,
  755. source_hardware_addr: self.ethernet_addr,
  756. source_protocol_addr: target_protocol_addr,
  757. target_hardware_addr: source_hardware_addr,
  758. target_protocol_addr: source_protocol_addr
  759. }))
  760. } else {
  761. Ok(Packet::None)
  762. }
  763. }
  764. _ => Err(Error::Unrecognized)
  765. }
  766. }
  767. #[cfg(all(any(feature = "proto-ipv4", feature = "proto-ipv6"), feature = "socket-raw"))]
  768. fn raw_socket_filter<'frame>(&mut self, sockets: &mut SocketSet, ip_repr: &IpRepr,
  769. ip_payload: &'frame [u8]) -> bool {
  770. let checksum_caps = self.device_capabilities.checksum.clone();
  771. let mut handled_by_raw_socket = false;
  772. // Pass every IP packet to all raw sockets we have registered.
  773. for mut raw_socket in sockets.iter_mut().filter_map(RawSocket::downcast) {
  774. if !raw_socket.accepts(&ip_repr) { continue }
  775. match raw_socket.process(&ip_repr, ip_payload, &checksum_caps) {
  776. // The packet is valid and handled by socket.
  777. Ok(()) => handled_by_raw_socket = true,
  778. // The socket buffer is full.
  779. Err(Error::Exhausted) => (),
  780. // Raw sockets don't validate the packets in any way.
  781. Err(_) => unreachable!(),
  782. }
  783. }
  784. handled_by_raw_socket
  785. }
  786. #[cfg(feature = "proto-ipv6")]
  787. fn process_ipv6<'frame, T: AsRef<[u8]>>
  788. (&mut self, sockets: &mut SocketSet, timestamp: Instant,
  789. eth_frame: &EthernetFrame<&'frame T>) ->
  790. Result<Packet<'frame>>
  791. {
  792. let ipv6_packet = Ipv6Packet::new_checked(eth_frame.payload())?;
  793. let ipv6_repr = Ipv6Repr::parse(&ipv6_packet)?;
  794. if !ipv6_repr.src_addr.is_unicast() {
  795. // Discard packets with non-unicast source addresses.
  796. net_debug!("non-unicast source address");
  797. return Err(Error::Malformed)
  798. }
  799. if eth_frame.src_addr().is_unicast() {
  800. // Fill the neighbor cache from IP header of unicast frames.
  801. let ip_addr = IpAddress::Ipv6(ipv6_repr.src_addr);
  802. if self.in_same_network(&ip_addr) &&
  803. self.neighbor_cache.lookup_pure(&ip_addr, timestamp).is_none() {
  804. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  805. }
  806. }
  807. let ip_payload = ipv6_packet.payload();
  808. #[cfg(feature = "socket-raw")]
  809. let handled_by_raw_socket = self.raw_socket_filter(sockets, &ipv6_repr.into(), ip_payload);
  810. #[cfg(not(feature = "socket-raw"))]
  811. let handled_by_raw_socket = false;
  812. self.process_nxt_hdr(sockets, timestamp, ipv6_repr, ipv6_repr.next_header,
  813. handled_by_raw_socket, ip_payload)
  814. }
  815. /// Given the next header value forward the payload onto the correct process
  816. /// function.
  817. #[cfg(feature = "proto-ipv6")]
  818. fn process_nxt_hdr<'frame>
  819. (&mut self, sockets: &mut SocketSet, timestamp: Instant, ipv6_repr: Ipv6Repr,
  820. nxt_hdr: IpProtocol, handled_by_raw_socket: bool, ip_payload: &'frame [u8])
  821. -> Result<Packet<'frame>>
  822. {
  823. match nxt_hdr {
  824. IpProtocol::Icmpv6 =>
  825. self.process_icmpv6(sockets, timestamp, ipv6_repr.into(), ip_payload),
  826. #[cfg(feature = "socket-udp")]
  827. IpProtocol::Udp =>
  828. self.process_udp(sockets, ipv6_repr.into(), ip_payload),
  829. #[cfg(feature = "socket-tcp")]
  830. IpProtocol::Tcp =>
  831. self.process_tcp(sockets, timestamp, ipv6_repr.into(), ip_payload),
  832. IpProtocol::HopByHop =>
  833. self.process_hopbyhop(sockets, timestamp, ipv6_repr, handled_by_raw_socket, ip_payload),
  834. #[cfg(feature = "socket-raw")]
  835. _ if handled_by_raw_socket =>
  836. Ok(Packet::None),
  837. _ => {
  838. // Send back as much of the original payload as we can.
  839. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU,
  840. ipv6_repr.buffer_len());
  841. let icmp_reply_repr = Icmpv6Repr::ParamProblem {
  842. reason: Icmpv6ParamProblem::UnrecognizedNxtHdr,
  843. // The offending packet is after the IPv6 header.
  844. pointer: ipv6_repr.buffer_len() as u32,
  845. header: ipv6_repr,
  846. data: &ip_payload[0..payload_len]
  847. };
  848. Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
  849. },
  850. }
  851. }
  852. #[cfg(feature = "proto-ipv4")]
  853. fn process_ipv4<'frame, T: AsRef<[u8]>>
  854. (&mut self, sockets: &mut SocketSet, timestamp: Instant,
  855. eth_frame: &EthernetFrame<&'frame T>) ->
  856. Result<Packet<'frame>>
  857. {
  858. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
  859. let checksum_caps = self.device_capabilities.checksum.clone();
  860. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &checksum_caps)?;
  861. if !ipv4_repr.src_addr.is_unicast() {
  862. // Discard packets with non-unicast source addresses.
  863. net_debug!("non-unicast source address");
  864. return Err(Error::Malformed)
  865. }
  866. if eth_frame.src_addr().is_unicast() {
  867. // Fill the neighbor cache from IP header of unicast frames.
  868. let ip_addr = IpAddress::Ipv4(ipv4_repr.src_addr);
  869. if self.in_same_network(&ip_addr) {
  870. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  871. }
  872. }
  873. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  874. let ip_payload = ipv4_packet.payload();
  875. #[cfg(feature = "socket-raw")]
  876. let handled_by_raw_socket = self.raw_socket_filter(sockets, &ip_repr, ip_payload);
  877. if !self.has_ip_addr(ipv4_repr.dst_addr) &&
  878. !ipv4_repr.dst_addr.is_broadcast() &&
  879. !self.has_multicast_group(ipv4_repr.dst_addr) {
  880. // Ignore IP packets not directed at us, or broadcast, or any of the multicast groups.
  881. // If AnyIP is enabled, also check if the packet is routed locally.
  882. if !self.any_ip {
  883. return Ok(Packet::None);
  884. } else if match self.routes.lookup(&IpAddress::Ipv4(ipv4_repr.dst_addr), timestamp) {
  885. Some(router_addr) => !self.has_ip_addr(router_addr),
  886. None => true,
  887. } {
  888. return Ok(Packet::None);
  889. }
  890. }
  891. match ipv4_repr.protocol {
  892. IpProtocol::Icmp =>
  893. self.process_icmpv4(sockets, ip_repr, ip_payload),
  894. #[cfg(feature = "proto-igmp")]
  895. IpProtocol::Igmp =>
  896. self.process_igmp(timestamp, ipv4_repr, ip_payload),
  897. #[cfg(feature = "socket-udp")]
  898. IpProtocol::Udp =>
  899. self.process_udp(sockets, ip_repr, ip_payload),
  900. #[cfg(feature = "socket-tcp")]
  901. IpProtocol::Tcp =>
  902. self.process_tcp(sockets, timestamp, ip_repr, ip_payload),
  903. #[cfg(feature = "socket-raw")]
  904. _ if handled_by_raw_socket =>
  905. Ok(Packet::None),
  906. _ => {
  907. // Send back as much of the original payload as we can.
  908. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU,
  909. ipv4_repr.buffer_len());
  910. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  911. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  912. header: ipv4_repr,
  913. data: &ip_payload[0..payload_len]
  914. };
  915. Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr))
  916. }
  917. }
  918. }
  919. /// Host duties of the **IGMPv2** protocol.
  920. ///
  921. /// Sets up `igmp_report_state` for responding to IGMP general/specific membership queries.
  922. /// Membership must not be reported immediately in order to avoid flooding the network
  923. /// after a query is broadcasted by a router; this is not currently done.
  924. #[cfg(feature = "proto-igmp")]
  925. fn process_igmp<'frame>(&mut self, timestamp: Instant, ipv4_repr: Ipv4Repr,
  926. ip_payload: &'frame [u8]) -> Result<Packet<'frame>> {
  927. let igmp_packet = IgmpPacket::new_checked(ip_payload)?;
  928. let igmp_repr = IgmpRepr::parse(&igmp_packet)?;
  929. // FIXME: report membership after a delay
  930. match igmp_repr {
  931. IgmpRepr::MembershipQuery { group_addr, version, max_resp_time } => {
  932. // General query
  933. if group_addr.is_unspecified() &&
  934. ipv4_repr.dst_addr == Ipv4Address::MULTICAST_ALL_SYSTEMS {
  935. // Are we member in any groups?
  936. if self.ipv4_multicast_groups.iter().next().is_some() {
  937. let interval = match version {
  938. IgmpVersion::Version1 =>
  939. Duration::from_millis(100),
  940. IgmpVersion::Version2 => {
  941. // No dependence on a random generator
  942. // (see [#24](https://github.com/m-labs/smoltcp/issues/24))
  943. // but at least spread reports evenly across max_resp_time.
  944. let intervals = self.ipv4_multicast_groups.len() as u32 + 1;
  945. max_resp_time / intervals
  946. }
  947. };
  948. self.igmp_report_state = IgmpReportState::ToGeneralQuery {
  949. version, timeout: timestamp + interval, interval, next_index: 0
  950. };
  951. }
  952. } else {
  953. // Group-specific query
  954. if self.has_multicast_group(group_addr) && ipv4_repr.dst_addr == group_addr {
  955. // Don't respond immediately
  956. let timeout = max_resp_time / 4;
  957. self.igmp_report_state = IgmpReportState::ToSpecificQuery {
  958. version, timeout: timestamp + timeout, group: group_addr
  959. };
  960. }
  961. }
  962. },
  963. // Ignore membership reports
  964. IgmpRepr::MembershipReport { .. } => (),
  965. // Ignore hosts leaving groups
  966. IgmpRepr::LeaveGroup{ .. } => (),
  967. }
  968. Ok(Packet::None)
  969. }
  970. #[cfg(feature = "proto-ipv6")]
  971. fn process_icmpv6<'frame>(&mut self, _sockets: &mut SocketSet, timestamp: Instant,
  972. ip_repr: IpRepr, ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  973. {
  974. let icmp_packet = Icmpv6Packet::new_checked(ip_payload)?;
  975. let checksum_caps = self.device_capabilities.checksum.clone();
  976. let icmp_repr = Icmpv6Repr::parse(&ip_repr.src_addr(), &ip_repr.dst_addr(),
  977. &icmp_packet, &checksum_caps)?;
  978. #[cfg(feature = "socket-icmp")]
  979. let mut handled_by_icmp_socket = false;
  980. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv6"))]
  981. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  982. if !icmp_socket.accepts(&ip_repr, &icmp_repr.into(), &checksum_caps) { continue }
  983. match icmp_socket.process(&ip_repr, &icmp_repr.into(), &checksum_caps) {
  984. // The packet is valid and handled by socket.
  985. Ok(()) => handled_by_icmp_socket = true,
  986. // The socket buffer is full.
  987. Err(Error::Exhausted) => (),
  988. // ICMP sockets don't validate the packets in any way.
  989. Err(_) => unreachable!(),
  990. }
  991. }
  992. match icmp_repr {
  993. // Respond to echo requests.
  994. Icmpv6Repr::EchoRequest { ident, seq_no, data } => {
  995. match ip_repr {
  996. IpRepr::Ipv6(ipv6_repr) => {
  997. let icmp_reply_repr = Icmpv6Repr::EchoReply {
  998. ident: ident,
  999. seq_no: seq_no,
  1000. data: data
  1001. };
  1002. Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
  1003. },
  1004. _ => Err(Error::Unrecognized),
  1005. }
  1006. }
  1007. // Ignore any echo replies.
  1008. Icmpv6Repr::EchoReply { .. } => Ok(Packet::None),
  1009. // Forward any NDISC packets to the ndisc packet handler
  1010. Icmpv6Repr::Ndisc(repr) if ip_repr.hop_limit() == 0xff => match ip_repr {
  1011. IpRepr::Ipv6(ipv6_repr) => self.process_ndisc(timestamp, ipv6_repr, repr),
  1012. _ => Ok(Packet::None)
  1013. },
  1014. // Don't report an error if a packet with unknown type
  1015. // has been handled by an ICMP socket
  1016. #[cfg(feature = "socket-icmp")]
  1017. _ if handled_by_icmp_socket => Ok(Packet::None),
  1018. // FIXME: do something correct here?
  1019. _ => Err(Error::Unrecognized),
  1020. }
  1021. }
  1022. #[cfg(feature = "proto-ipv6")]
  1023. fn process_ndisc<'frame>(&mut self, timestamp: Instant, ip_repr: Ipv6Repr,
  1024. repr: NdiscRepr<'frame>) -> Result<Packet<'frame>> {
  1025. let packet = match repr {
  1026. NdiscRepr::NeighborAdvert { lladdr, target_addr, flags } => {
  1027. let ip_addr = ip_repr.src_addr.into();
  1028. match lladdr {
  1029. Some(lladdr) if lladdr.is_unicast() && target_addr.is_unicast() => {
  1030. if flags.contains(NdiscNeighborFlags::OVERRIDE) {
  1031. self.neighbor_cache.fill(ip_addr, lladdr, timestamp)
  1032. } else {
  1033. if self.neighbor_cache.lookup_pure(&ip_addr, timestamp).is_none() {
  1034. self.neighbor_cache.fill(ip_addr, lladdr, timestamp)
  1035. }
  1036. }
  1037. },
  1038. _ => (),
  1039. }
  1040. Ok(Packet::None)
  1041. }
  1042. NdiscRepr::NeighborSolicit { target_addr, lladdr, .. } => {
  1043. match lladdr {
  1044. Some(lladdr) if lladdr.is_unicast() && target_addr.is_unicast() => {
  1045. self.neighbor_cache.fill(ip_repr.src_addr.into(), lladdr, timestamp)
  1046. },
  1047. _ => (),
  1048. }
  1049. if self.has_solicited_node(ip_repr.dst_addr) && self.has_ip_addr(target_addr) {
  1050. let advert = Icmpv6Repr::Ndisc(NdiscRepr::NeighborAdvert {
  1051. flags: NdiscNeighborFlags::SOLICITED,
  1052. target_addr: target_addr,
  1053. lladdr: Some(self.ethernet_addr)
  1054. });
  1055. let ip_repr = Ipv6Repr {
  1056. src_addr: target_addr,
  1057. dst_addr: ip_repr.src_addr,
  1058. next_header: IpProtocol::Icmpv6,
  1059. hop_limit: 0xff,
  1060. payload_len: advert.buffer_len()
  1061. };
  1062. Ok(Packet::Icmpv6((ip_repr, advert)))
  1063. } else {
  1064. Ok(Packet::None)
  1065. }
  1066. }
  1067. _ => Ok(Packet::None)
  1068. };
  1069. packet
  1070. }
  1071. #[cfg(feature = "proto-ipv6")]
  1072. fn process_hopbyhop<'frame>(&mut self, sockets: &mut SocketSet, timestamp: Instant,
  1073. ipv6_repr: Ipv6Repr, handled_by_raw_socket: bool,
  1074. ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  1075. {
  1076. let hbh_pkt = Ipv6HopByHopHeader::new_checked(ip_payload)?;
  1077. let hbh_repr = Ipv6HopByHopRepr::parse(&hbh_pkt)?;
  1078. for result in hbh_repr.options() {
  1079. let opt_repr = result?;
  1080. match opt_repr {
  1081. Ipv6OptionRepr::Pad1 | Ipv6OptionRepr::PadN(_) => (),
  1082. Ipv6OptionRepr::Unknown { type_, .. } => {
  1083. match Ipv6OptionFailureType::from(type_) {
  1084. Ipv6OptionFailureType::Skip => (),
  1085. Ipv6OptionFailureType::Discard => {
  1086. return Ok(Packet::None);
  1087. },
  1088. _ => {
  1089. // FIXME(dlrobertson): Send an ICMPv6 parameter problem message
  1090. // here.
  1091. return Err(Error::Unrecognized);
  1092. }
  1093. }
  1094. }
  1095. _ => return Err(Error::Unrecognized),
  1096. }
  1097. }
  1098. self.process_nxt_hdr(sockets, timestamp, ipv6_repr, hbh_repr.next_header,
  1099. handled_by_raw_socket, &ip_payload[hbh_repr.buffer_len()..])
  1100. }
  1101. #[cfg(feature = "proto-ipv4")]
  1102. fn process_icmpv4<'frame>(&self, _sockets: &mut SocketSet, ip_repr: IpRepr,
  1103. ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  1104. {
  1105. let icmp_packet = Icmpv4Packet::new_checked(ip_payload)?;
  1106. let checksum_caps = self.device_capabilities.checksum.clone();
  1107. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &checksum_caps)?;
  1108. #[cfg(feature = "socket-icmp")]
  1109. let mut handled_by_icmp_socket = false;
  1110. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  1111. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  1112. if !icmp_socket.accepts(&ip_repr, &icmp_repr.into(), &checksum_caps) { continue }
  1113. match icmp_socket.process(&ip_repr, &icmp_repr.into(), &checksum_caps) {
  1114. // The packet is valid and handled by socket.
  1115. Ok(()) => handled_by_icmp_socket = true,
  1116. // The socket buffer is full.
  1117. Err(Error::Exhausted) => (),
  1118. // ICMP sockets don't validate the packets in any way.
  1119. Err(_) => unreachable!(),
  1120. }
  1121. }
  1122. match icmp_repr {
  1123. // Respond to echo requests.
  1124. #[cfg(feature = "proto-ipv4")]
  1125. Icmpv4Repr::EchoRequest { ident, seq_no, data } => {
  1126. let icmp_reply_repr = Icmpv4Repr::EchoReply {
  1127. ident: ident,
  1128. seq_no: seq_no,
  1129. data: data
  1130. };
  1131. match ip_repr {
  1132. IpRepr::Ipv4(ipv4_repr) => Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr)),
  1133. _ => Err(Error::Unrecognized),
  1134. }
  1135. },
  1136. // Ignore any echo replies.
  1137. Icmpv4Repr::EchoReply { .. } => Ok(Packet::None),
  1138. // Don't report an error if a packet with unknown type
  1139. // has been handled by an ICMP socket
  1140. #[cfg(feature = "socket-icmp")]
  1141. _ if handled_by_icmp_socket => Ok(Packet::None),
  1142. // FIXME: do something correct here?
  1143. _ => Err(Error::Unrecognized),
  1144. }
  1145. }
  1146. #[cfg(feature = "proto-ipv4")]
  1147. fn icmpv4_reply<'frame, 'icmp: 'frame>
  1148. (&self, ipv4_repr: Ipv4Repr, icmp_repr: Icmpv4Repr<'icmp>) ->
  1149. Packet<'frame>
  1150. {
  1151. if !ipv4_repr.src_addr.is_unicast() {
  1152. // Do not send ICMP replies to non-unicast sources
  1153. Packet::None
  1154. } else if ipv4_repr.dst_addr.is_unicast() {
  1155. // Reply as normal when src_addr and dst_addr are both unicast
  1156. let ipv4_reply_repr = Ipv4Repr {
  1157. src_addr: ipv4_repr.dst_addr,
  1158. dst_addr: ipv4_repr.src_addr,
  1159. protocol: IpProtocol::Icmp,
  1160. payload_len: icmp_repr.buffer_len(),
  1161. hop_limit: 64
  1162. };
  1163. Packet::Icmpv4((ipv4_reply_repr, icmp_repr))
  1164. } else if ipv4_repr.dst_addr.is_broadcast() {
  1165. // Only reply to broadcasts for echo replies and not other ICMP messages
  1166. match icmp_repr {
  1167. Icmpv4Repr::EchoReply {..} => match self.ipv4_address() {
  1168. Some(src_addr) => {
  1169. let ipv4_reply_repr = Ipv4Repr {
  1170. src_addr: src_addr,
  1171. dst_addr: ipv4_repr.src_addr,
  1172. protocol: IpProtocol::Icmp,
  1173. payload_len: icmp_repr.buffer_len(),
  1174. hop_limit: 64
  1175. };
  1176. Packet::Icmpv4((ipv4_reply_repr, icmp_repr))
  1177. },
  1178. None => Packet::None,
  1179. },
  1180. _ => Packet::None,
  1181. }
  1182. } else {
  1183. Packet::None
  1184. }
  1185. }
  1186. #[cfg(feature = "proto-ipv6")]
  1187. fn icmpv6_reply<'frame, 'icmp: 'frame>
  1188. (&self, ipv6_repr: Ipv6Repr, icmp_repr: Icmpv6Repr<'icmp>) ->
  1189. Packet<'frame>
  1190. {
  1191. if ipv6_repr.dst_addr.is_unicast() {
  1192. let ipv6_reply_repr = Ipv6Repr {
  1193. src_addr: ipv6_repr.dst_addr,
  1194. dst_addr: ipv6_repr.src_addr,
  1195. next_header: IpProtocol::Icmpv6,
  1196. payload_len: icmp_repr.buffer_len(),
  1197. hop_limit: 64
  1198. };
  1199. Packet::Icmpv6((ipv6_reply_repr, icmp_repr))
  1200. } else {
  1201. // Do not send any ICMP replies to a broadcast destination address.
  1202. Packet::None
  1203. }
  1204. }
  1205. #[cfg(feature = "socket-udp")]
  1206. fn process_udp<'frame>(&self, sockets: &mut SocketSet,
  1207. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  1208. Result<Packet<'frame>>
  1209. {
  1210. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  1211. let udp_packet = UdpPacket::new_checked(ip_payload)?;
  1212. let checksum_caps = self.device_capabilities.checksum.clone();
  1213. let udp_repr = UdpRepr::parse(&udp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  1214. for mut udp_socket in sockets.iter_mut().filter_map(UdpSocket::downcast) {
  1215. if !udp_socket.accepts(&ip_repr, &udp_repr) { continue }
  1216. match udp_socket.process(&ip_repr, &udp_repr) {
  1217. // The packet is valid and handled by socket.
  1218. Ok(()) => return Ok(Packet::None),
  1219. // The packet is malformed, or the socket buffer is full.
  1220. Err(e) => return Err(e)
  1221. }
  1222. }
  1223. // The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  1224. match ip_repr {
  1225. #[cfg(feature = "proto-ipv4")]
  1226. IpRepr::Ipv4(ipv4_repr) => {
  1227. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU,
  1228. ipv4_repr.buffer_len());
  1229. let icmpv4_reply_repr = Icmpv4Repr::DstUnreachable {
  1230. reason: Icmpv4DstUnreachable::PortUnreachable,
  1231. header: ipv4_repr,
  1232. data: &ip_payload[0..payload_len]
  1233. };
  1234. Ok(self.icmpv4_reply(ipv4_repr, icmpv4_reply_repr))
  1235. },
  1236. #[cfg(feature = "proto-ipv6")]
  1237. IpRepr::Ipv6(ipv6_repr) => {
  1238. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU,
  1239. ipv6_repr.buffer_len());
  1240. let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable {
  1241. reason: Icmpv6DstUnreachable::PortUnreachable,
  1242. header: ipv6_repr,
  1243. data: &ip_payload[0..payload_len]
  1244. };
  1245. Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr))
  1246. },
  1247. IpRepr::Unspecified { .. } |
  1248. IpRepr::__Nonexhaustive => Err(Error::Unaddressable),
  1249. }
  1250. }
  1251. #[cfg(feature = "socket-tcp")]
  1252. fn process_tcp<'frame>(&self, sockets: &mut SocketSet, timestamp: Instant,
  1253. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  1254. Result<Packet<'frame>>
  1255. {
  1256. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  1257. let tcp_packet = TcpPacket::new_checked(ip_payload)?;
  1258. let checksum_caps = self.device_capabilities.checksum.clone();
  1259. let tcp_repr = TcpRepr::parse(&tcp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  1260. for mut tcp_socket in sockets.iter_mut().filter_map(TcpSocket::downcast) {
  1261. if !tcp_socket.accepts(&ip_repr, &tcp_repr) { continue }
  1262. match tcp_socket.process(timestamp, &ip_repr, &tcp_repr) {
  1263. // The packet is valid and handled by socket.
  1264. Ok(reply) => return Ok(reply.map_or(Packet::None, Packet::Tcp)),
  1265. // The packet is malformed, or doesn't match the socket state,
  1266. // or the socket buffer is full.
  1267. Err(e) => return Err(e)
  1268. }
  1269. }
  1270. if tcp_repr.control == TcpControl::Rst {
  1271. // Never reply to a TCP RST packet with another TCP RST packet.
  1272. Ok(Packet::None)
  1273. } else {
  1274. // The packet wasn't handled by a socket, send a TCP RST packet.
  1275. Ok(Packet::Tcp(TcpSocket::rst_reply(&ip_repr, &tcp_repr)))
  1276. }
  1277. }
  1278. fn dispatch<Tx>(&mut self, tx_token: Tx, timestamp: Instant,
  1279. packet: Packet) -> Result<()>
  1280. where Tx: TxToken
  1281. {
  1282. let checksum_caps = self.device_capabilities.checksum.clone();
  1283. match packet {
  1284. #[cfg(feature = "proto-ipv4")]
  1285. Packet::Arp(arp_repr) => {
  1286. let dst_hardware_addr =
  1287. match arp_repr {
  1288. ArpRepr::EthernetIpv4 { target_hardware_addr, .. } => target_hardware_addr,
  1289. _ => unreachable!()
  1290. };
  1291. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  1292. frame.set_dst_addr(dst_hardware_addr);
  1293. frame.set_ethertype(EthernetProtocol::Arp);
  1294. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  1295. arp_repr.emit(&mut packet);
  1296. })
  1297. },
  1298. #[cfg(feature = "proto-ipv4")]
  1299. Packet::Icmpv4((ipv4_repr, icmpv4_repr)) => {
  1300. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv4(ipv4_repr),
  1301. |_ip_repr, payload| {
  1302. icmpv4_repr.emit(&mut Icmpv4Packet::new_unchecked(payload), &checksum_caps);
  1303. })
  1304. }
  1305. #[cfg(feature = "proto-igmp")]
  1306. Packet::Igmp((ipv4_repr, igmp_repr)) => {
  1307. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv4(ipv4_repr), |_ip_repr, payload| {
  1308. igmp_repr.emit(&mut IgmpPacket::new_unchecked(payload));
  1309. })
  1310. }
  1311. #[cfg(feature = "proto-ipv6")]
  1312. Packet::Icmpv6((ipv6_repr, icmpv6_repr)) => {
  1313. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv6(ipv6_repr),
  1314. |ip_repr, payload| {
  1315. icmpv6_repr.emit(&ip_repr.src_addr(), &ip_repr.dst_addr(),
  1316. &mut Icmpv6Packet::new_unchecked(payload), &checksum_caps);
  1317. })
  1318. }
  1319. #[cfg(feature = "socket-raw")]
  1320. Packet::Raw((ip_repr, raw_packet)) => {
  1321. self.dispatch_ip(tx_token, timestamp, ip_repr, |_ip_repr, payload| {
  1322. payload.copy_from_slice(raw_packet);
  1323. })
  1324. }
  1325. #[cfg(feature = "socket-udp")]
  1326. Packet::Udp((ip_repr, udp_repr)) => {
  1327. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  1328. udp_repr.emit(&mut UdpPacket::new_unchecked(payload),
  1329. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1330. &checksum_caps);
  1331. })
  1332. }
  1333. #[cfg(feature = "socket-tcp")]
  1334. Packet::Tcp((ip_repr, mut tcp_repr)) => {
  1335. let caps = self.device_capabilities.clone();
  1336. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  1337. // This is a terrible hack to make TCP performance more acceptable on systems
  1338. // where the TCP buffers are significantly larger than network buffers,
  1339. // e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
  1340. // together with four 1500 B Ethernet receive buffers. If left untreated,
  1341. // this would result in our peer pushing our window and sever packet loss.
  1342. //
  1343. // I'm really not happy about this "solution" but I don't know what else to do.
  1344. if let Some(max_burst_size) = caps.max_burst_size {
  1345. let mut max_segment_size = caps.max_transmission_unit;
  1346. max_segment_size -= EthernetFrame::<&[u8]>::header_len();
  1347. max_segment_size -= ip_repr.buffer_len();
  1348. max_segment_size -= tcp_repr.header_len();
  1349. let max_window_size = max_burst_size * max_segment_size;
  1350. if tcp_repr.window_len as usize > max_window_size {
  1351. tcp_repr.window_len = max_window_size as u16;
  1352. }
  1353. }
  1354. tcp_repr.emit(&mut TcpPacket::new_unchecked(payload),
  1355. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1356. &checksum_caps);
  1357. })
  1358. }
  1359. Packet::None => Ok(())
  1360. }
  1361. }
  1362. fn dispatch_ethernet<Tx, F>(&mut self, tx_token: Tx, timestamp: Instant,
  1363. buffer_len: usize, f: F) -> Result<()>
  1364. where Tx: TxToken, F: FnOnce(EthernetFrame<&mut [u8]>)
  1365. {
  1366. let tx_len = EthernetFrame::<&[u8]>::buffer_len(buffer_len);
  1367. tx_token.consume(timestamp, tx_len, |tx_buffer| {
  1368. debug_assert!(tx_buffer.as_ref().len() == tx_len);
  1369. let mut frame = EthernetFrame::new_unchecked(tx_buffer.as_mut());
  1370. frame.set_src_addr(self.ethernet_addr);
  1371. f(frame);
  1372. Ok(())
  1373. })
  1374. }
  1375. fn in_same_network(&self, addr: &IpAddress) -> bool {
  1376. self.ip_addrs
  1377. .iter()
  1378. .find(|cidr| cidr.contains_addr(addr))
  1379. .is_some()
  1380. }
  1381. fn route(&self, addr: &IpAddress, timestamp: Instant) -> Result<IpAddress> {
  1382. // Send directly.
  1383. if self.in_same_network(addr) || addr.is_broadcast() {
  1384. return Ok(*addr)
  1385. }
  1386. // Route via a router.
  1387. match self.routes.lookup(addr, timestamp) {
  1388. Some(router_addr) => Ok(router_addr),
  1389. None => Err(Error::Unaddressable),
  1390. }
  1391. }
  1392. fn has_neighbor<'a>(&self, addr: &'a IpAddress, timestamp: Instant) -> bool {
  1393. match self.route(addr, timestamp) {
  1394. Ok(routed_addr) => {
  1395. self.neighbor_cache
  1396. .lookup_pure(&routed_addr, timestamp)
  1397. .is_some()
  1398. }
  1399. Err(_) => false
  1400. }
  1401. }
  1402. fn lookup_hardware_addr<Tx>(&mut self, tx_token: Tx, timestamp: Instant,
  1403. src_addr: &IpAddress, dst_addr: &IpAddress) ->
  1404. Result<(EthernetAddress, Tx)>
  1405. where Tx: TxToken
  1406. {
  1407. if dst_addr.is_multicast() {
  1408. let b = dst_addr.as_bytes();
  1409. let hardware_addr =
  1410. match dst_addr {
  1411. &IpAddress::Unspecified =>
  1412. None,
  1413. #[cfg(feature = "proto-ipv4")]
  1414. &IpAddress::Ipv4(_addr) =>
  1415. Some(EthernetAddress::from_bytes(&[
  1416. 0x01, 0x00,
  1417. 0x5e, b[1] & 0x7F,
  1418. b[2], b[3],
  1419. ])),
  1420. #[cfg(feature = "proto-ipv6")]
  1421. &IpAddress::Ipv6(_addr) =>
  1422. Some(EthernetAddress::from_bytes(&[
  1423. 0x33, 0x33,
  1424. b[12], b[13],
  1425. b[14], b[15],
  1426. ])),
  1427. &IpAddress::__Nonexhaustive =>
  1428. unreachable!()
  1429. };
  1430. match hardware_addr {
  1431. Some(hardware_addr) =>
  1432. // Destination is multicast
  1433. return Ok((hardware_addr, tx_token)),
  1434. None =>
  1435. // Continue
  1436. (),
  1437. }
  1438. }
  1439. let dst_addr = self.route(dst_addr, timestamp)?;
  1440. match self.neighbor_cache.lookup(&dst_addr, timestamp) {
  1441. NeighborAnswer::Found(hardware_addr) =>
  1442. return Ok((hardware_addr, tx_token)),
  1443. NeighborAnswer::RateLimited =>
  1444. return Err(Error::Unaddressable),
  1445. NeighborAnswer::NotFound => (),
  1446. }
  1447. match (src_addr, dst_addr) {
  1448. #[cfg(feature = "proto-ipv4")]
  1449. (&IpAddress::Ipv4(src_addr), IpAddress::Ipv4(dst_addr)) => {
  1450. net_debug!("address {} not in neighbor cache, sending ARP request",
  1451. dst_addr);
  1452. let arp_repr = ArpRepr::EthernetIpv4 {
  1453. operation: ArpOperation::Request,
  1454. source_hardware_addr: self.ethernet_addr,
  1455. source_protocol_addr: src_addr,
  1456. target_hardware_addr: EthernetAddress::BROADCAST,
  1457. target_protocol_addr: dst_addr,
  1458. };
  1459. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  1460. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1461. frame.set_ethertype(EthernetProtocol::Arp);
  1462. arp_repr.emit(&mut ArpPacket::new_unchecked(frame.payload_mut()))
  1463. })?;
  1464. Err(Error::Unaddressable)
  1465. }
  1466. #[cfg(feature = "proto-ipv6")]
  1467. (&IpAddress::Ipv6(src_addr), IpAddress::Ipv6(dst_addr)) => {
  1468. net_debug!("address {} not in neighbor cache, sending Neighbor Solicitation",
  1469. dst_addr);
  1470. let checksum_caps = self.device_capabilities.checksum.clone();
  1471. let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit {
  1472. target_addr: src_addr,
  1473. lladdr: Some(self.ethernet_addr),
  1474. });
  1475. let ip_repr = IpRepr::Ipv6(Ipv6Repr {
  1476. src_addr: src_addr,
  1477. dst_addr: dst_addr.solicited_node(),
  1478. next_header: IpProtocol::Icmpv6,
  1479. payload_len: solicit.buffer_len(),
  1480. hop_limit: 0xff
  1481. });
  1482. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  1483. solicit.emit(&ip_repr.src_addr(), &ip_repr.dst_addr(),
  1484. &mut Icmpv6Packet::new_unchecked(payload), &checksum_caps);
  1485. })?;
  1486. Err(Error::Unaddressable)
  1487. }
  1488. _ => Err(Error::Unaddressable)
  1489. }
  1490. }
  1491. fn dispatch_ip<Tx, F>(&mut self, tx_token: Tx, timestamp: Instant,
  1492. ip_repr: IpRepr, f: F) -> Result<()>
  1493. where Tx: TxToken, F: FnOnce(IpRepr, &mut [u8])
  1494. {
  1495. let ip_repr = ip_repr.lower(&self.ip_addrs)?;
  1496. let checksum_caps = self.device_capabilities.checksum.clone();
  1497. let (dst_hardware_addr, tx_token) =
  1498. self.lookup_hardware_addr(tx_token, timestamp,
  1499. &ip_repr.src_addr(), &ip_repr.dst_addr())?;
  1500. self.dispatch_ethernet(tx_token, timestamp, ip_repr.total_len(), |mut frame| {
  1501. frame.set_dst_addr(dst_hardware_addr);
  1502. match ip_repr {
  1503. #[cfg(feature = "proto-ipv4")]
  1504. IpRepr::Ipv4(_) => frame.set_ethertype(EthernetProtocol::Ipv4),
  1505. #[cfg(feature = "proto-ipv6")]
  1506. IpRepr::Ipv6(_) => frame.set_ethertype(EthernetProtocol::Ipv6),
  1507. _ => return
  1508. }
  1509. ip_repr.emit(frame.payload_mut(), &checksum_caps);
  1510. let payload = &mut frame.payload_mut()[ip_repr.buffer_len()..];
  1511. f(ip_repr, payload)
  1512. })
  1513. }
  1514. #[cfg(feature = "proto-igmp")]
  1515. fn igmp_report_packet<'any>(&self, version: IgmpVersion, group_addr: Ipv4Address) -> Option<Packet<'any>> {
  1516. let iface_addr = self.ipv4_address()?;
  1517. let igmp_repr = IgmpRepr::MembershipReport {
  1518. group_addr,
  1519. version,
  1520. };
  1521. let pkt = Packet::Igmp((Ipv4Repr {
  1522. src_addr: iface_addr,
  1523. // Send to the group being reported
  1524. dst_addr: group_addr,
  1525. protocol: IpProtocol::Igmp,
  1526. payload_len: igmp_repr.buffer_len(),
  1527. hop_limit: 1,
  1528. // TODO: add Router Alert IPv4 header option. See
  1529. // [#183](https://github.com/m-labs/smoltcp/issues/183).
  1530. }, igmp_repr));
  1531. Some(pkt)
  1532. }
  1533. #[cfg(feature = "proto-igmp")]
  1534. fn igmp_leave_packet<'any>(&self, group_addr: Ipv4Address) -> Option<Packet<'any>> {
  1535. self.ipv4_address().map(|iface_addr| {
  1536. let igmp_repr = IgmpRepr::LeaveGroup { group_addr };
  1537. let pkt = Packet::Igmp((Ipv4Repr {
  1538. src_addr: iface_addr,
  1539. dst_addr: Ipv4Address::MULTICAST_ALL_ROUTERS,
  1540. protocol: IpProtocol::Igmp,
  1541. payload_len: igmp_repr.buffer_len(),
  1542. hop_limit: 1,
  1543. }, igmp_repr));
  1544. pkt
  1545. })
  1546. }
  1547. }
  1548. #[cfg(test)]
  1549. mod test {
  1550. #[cfg(feature = "proto-igmp")]
  1551. use std::vec::Vec;
  1552. use std::collections::BTreeMap;
  1553. use {Result, Error};
  1554. use super::InterfaceBuilder;
  1555. use iface::{NeighborCache, EthernetInterface};
  1556. use phy::{self, Loopback, ChecksumCapabilities};
  1557. #[cfg(feature = "proto-igmp")]
  1558. use phy::{Device, RxToken, TxToken};
  1559. use time::Instant;
  1560. use socket::SocketSet;
  1561. #[cfg(feature = "proto-ipv4")]
  1562. use wire::{ArpOperation, ArpPacket, ArpRepr};
  1563. use wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
  1564. use wire::{IpAddress, IpCidr, IpProtocol, IpRepr};
  1565. #[cfg(feature = "proto-ipv4")]
  1566. use wire::{Ipv4Address, Ipv4Repr};
  1567. #[cfg(feature = "proto-igmp")]
  1568. use wire::Ipv4Packet;
  1569. #[cfg(feature = "proto-ipv4")]
  1570. use wire::{Icmpv4Repr, Icmpv4DstUnreachable};
  1571. #[cfg(feature = "proto-igmp")]
  1572. use wire::{IgmpPacket, IgmpRepr, IgmpVersion};
  1573. #[cfg(all(feature = "socket-udp", any(feature = "proto-ipv4", feature = "proto-ipv6")))]
  1574. use wire::{UdpPacket, UdpRepr};
  1575. #[cfg(feature = "proto-ipv6")]
  1576. use wire::{Ipv6Address, Ipv6Repr};
  1577. #[cfg(feature = "proto-ipv6")]
  1578. use wire::{Icmpv6Packet, Icmpv6Repr, Icmpv6ParamProblem};
  1579. #[cfg(feature = "proto-ipv6")]
  1580. use wire::{NdiscNeighborFlags, NdiscRepr};
  1581. #[cfg(feature = "proto-ipv6")]
  1582. use wire::{Ipv6HopByHopHeader, Ipv6Option, Ipv6OptionRepr};
  1583. use super::Packet;
  1584. fn create_loopback<'a, 'b, 'c>() -> (EthernetInterface<'static, 'b, 'c, Loopback>,
  1585. SocketSet<'static, 'a, 'b>) {
  1586. // Create a basic device
  1587. let device = Loopback::new();
  1588. let ip_addrs = [
  1589. #[cfg(feature = "proto-ipv4")]
  1590. IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8),
  1591. #[cfg(feature = "proto-ipv6")]
  1592. IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 128),
  1593. #[cfg(feature = "proto-ipv6")]
  1594. IpCidr::new(IpAddress::v6(0xfdbe, 0, 0, 0, 0, 0, 0, 1), 64),
  1595. ];
  1596. let iface_builder = InterfaceBuilder::new(device)
  1597. .ethernet_addr(EthernetAddress::default())
  1598. .neighbor_cache(NeighborCache::new(BTreeMap::new()))
  1599. .ip_addrs(ip_addrs);
  1600. #[cfg(feature = "proto-igmp")]
  1601. let iface_builder = iface_builder
  1602. .ipv4_multicast_groups(BTreeMap::new());
  1603. let iface = iface_builder
  1604. .finalize();
  1605. (iface, SocketSet::new(vec![]))
  1606. }
  1607. #[cfg(feature = "proto-igmp")]
  1608. fn recv_all<'b>(iface: &mut EthernetInterface<'static, 'b, 'static, Loopback>, timestamp: Instant) -> Vec<Vec<u8>> {
  1609. let mut pkts = Vec::new();
  1610. while let Some((rx, _tx)) = iface.device.receive() {
  1611. rx.consume(timestamp, |pkt| {
  1612. pkts.push(pkt.iter().cloned().collect());
  1613. Ok(())
  1614. }).unwrap();
  1615. }
  1616. pkts
  1617. }
  1618. #[derive(Debug, PartialEq)]
  1619. struct MockTxToken;
  1620. impl phy::TxToken for MockTxToken {
  1621. fn consume<R, F>(self, _: Instant, _: usize, _: F) -> Result<R>
  1622. where F: FnOnce(&mut [u8]) -> Result<R> {
  1623. Err(Error::__Nonexhaustive)
  1624. }
  1625. }
  1626. #[test]
  1627. #[should_panic(expected = "a required option was not set")]
  1628. fn test_builder_initialization_panic() {
  1629. InterfaceBuilder::new(Loopback::new()).finalize();
  1630. }
  1631. #[test]
  1632. fn test_no_icmp_no_unicast() {
  1633. let (mut iface, mut socket_set) = create_loopback();
  1634. let mut eth_bytes = vec![0u8; 54];
  1635. // Unknown Ipv4 Protocol
  1636. //
  1637. // Because the destination is the broadcast address
  1638. // this should not trigger and Destination Unreachable
  1639. // response. See RFC 1122 § 3.2.2.
  1640. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1641. let repr = IpRepr::Ipv4(Ipv4Repr {
  1642. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1643. dst_addr: Ipv4Address::BROADCAST,
  1644. protocol: IpProtocol::Unknown(0x0c),
  1645. payload_len: 0,
  1646. hop_limit: 0x40
  1647. });
  1648. #[cfg(feature = "proto-ipv6")]
  1649. let repr = IpRepr::Ipv6(Ipv6Repr {
  1650. src_addr: Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1),
  1651. dst_addr: Ipv6Address::LINK_LOCAL_ALL_NODES,
  1652. next_header: IpProtocol::Unknown(0x0c),
  1653. payload_len: 0,
  1654. hop_limit: 0x40
  1655. });
  1656. let frame = {
  1657. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  1658. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1659. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1660. frame.set_ethertype(EthernetProtocol::Ipv4);
  1661. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1662. EthernetFrame::new_unchecked(&*frame.into_inner())
  1663. };
  1664. // Ensure that the unknown protocol frame does not trigger an
  1665. // ICMP error response when the destination address is a
  1666. // broadcast address
  1667. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1668. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  1669. Ok(Packet::None));
  1670. #[cfg(feature = "proto-ipv6")]
  1671. assert_eq!(iface.inner.process_ipv6(&mut socket_set, Instant::from_millis(0), &frame),
  1672. Ok(Packet::None));
  1673. }
  1674. #[test]
  1675. #[cfg(feature = "proto-ipv4")]
  1676. fn test_icmp_error_no_payload() {
  1677. static NO_BYTES: [u8; 0] = [];
  1678. let (mut iface, mut socket_set) = create_loopback();
  1679. let mut eth_bytes = vec![0u8; 34];
  1680. // Unknown Ipv4 Protocol with no payload
  1681. let repr = IpRepr::Ipv4(Ipv4Repr {
  1682. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1683. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1684. protocol: IpProtocol::Unknown(0x0c),
  1685. payload_len: 0,
  1686. hop_limit: 0x40
  1687. });
  1688. // emit the above repr to a frame
  1689. let frame = {
  1690. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  1691. frame.set_dst_addr(EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  1692. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1693. frame.set_ethertype(EthernetProtocol::Ipv4);
  1694. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1695. EthernetFrame::new_unchecked(&*frame.into_inner())
  1696. };
  1697. // The expected Destination Unreachable response due to the
  1698. // unknown protocol
  1699. let icmp_repr = Icmpv4Repr::DstUnreachable {
  1700. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  1701. header: Ipv4Repr {
  1702. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1703. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1704. protocol: IpProtocol::Unknown(12),
  1705. payload_len: 0,
  1706. hop_limit: 64
  1707. },
  1708. data: &NO_BYTES
  1709. };
  1710. let expected_repr = Packet::Icmpv4((
  1711. Ipv4Repr {
  1712. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1713. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1714. protocol: IpProtocol::Icmp,
  1715. payload_len: icmp_repr.buffer_len(),
  1716. hop_limit: 64
  1717. },
  1718. icmp_repr
  1719. ));
  1720. // Ensure that the unknown protocol triggers an error response.
  1721. // And we correctly handle no payload.
  1722. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  1723. Ok(expected_repr));
  1724. }
  1725. #[test]
  1726. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1727. fn test_icmp_error_port_unreachable() {
  1728. static UDP_PAYLOAD: [u8; 12] = [
  1729. 0x48, 0x65, 0x6c, 0x6c,
  1730. 0x6f, 0x2c, 0x20, 0x57,
  1731. 0x6f, 0x6c, 0x64, 0x21
  1732. ];
  1733. let (iface, mut socket_set) = create_loopback();
  1734. let mut udp_bytes_unicast = vec![0u8; 20];
  1735. let mut udp_bytes_broadcast = vec![0u8; 20];
  1736. let mut packet_unicast = UdpPacket::new_unchecked(&mut udp_bytes_unicast);
  1737. let mut packet_broadcast = UdpPacket::new_unchecked(&mut udp_bytes_broadcast);
  1738. let udp_repr = UdpRepr {
  1739. src_port: 67,
  1740. dst_port: 68,
  1741. payload: &UDP_PAYLOAD
  1742. };
  1743. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1744. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1745. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1746. protocol: IpProtocol::Udp,
  1747. payload_len: udp_repr.buffer_len(),
  1748. hop_limit: 64
  1749. });
  1750. // Emit the representations to a packet
  1751. udp_repr.emit(&mut packet_unicast, &ip_repr.src_addr(),
  1752. &ip_repr.dst_addr(), &ChecksumCapabilities::default());
  1753. let data = packet_unicast.into_inner();
  1754. // The expected Destination Unreachable ICMPv4 error response due
  1755. // to no sockets listening on the destination port.
  1756. let icmp_repr = Icmpv4Repr::DstUnreachable {
  1757. reason: Icmpv4DstUnreachable::PortUnreachable,
  1758. header: Ipv4Repr {
  1759. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1760. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1761. protocol: IpProtocol::Udp,
  1762. payload_len: udp_repr.buffer_len(),
  1763. hop_limit: 64
  1764. },
  1765. data: &data
  1766. };
  1767. let expected_repr = Packet::Icmpv4((
  1768. Ipv4Repr {
  1769. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1770. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1771. protocol: IpProtocol::Icmp,
  1772. payload_len: icmp_repr.buffer_len(),
  1773. hop_limit: 64
  1774. },
  1775. icmp_repr
  1776. ));
  1777. // Ensure that the unknown protocol triggers an error response.
  1778. // And we correctly handle no payload.
  1779. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, data),
  1780. Ok(expected_repr));
  1781. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1782. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1783. dst_addr: Ipv4Address::BROADCAST,
  1784. protocol: IpProtocol::Udp,
  1785. payload_len: udp_repr.buffer_len(),
  1786. hop_limit: 64
  1787. });
  1788. // Emit the representations to a packet
  1789. udp_repr.emit(&mut packet_broadcast, &ip_repr.src_addr(),
  1790. &IpAddress::Ipv4(Ipv4Address::BROADCAST),
  1791. &ChecksumCapabilities::default());
  1792. // Ensure that the port unreachable error does not trigger an
  1793. // ICMP error response when the destination address is a
  1794. // broadcast address and no socket is bound to the port.
  1795. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr,
  1796. packet_broadcast.into_inner()), Ok(Packet::None));
  1797. }
  1798. #[test]
  1799. #[cfg(feature = "socket-udp")]
  1800. fn test_handle_udp_broadcast() {
  1801. use socket::{UdpSocket, UdpSocketBuffer, UdpPacketMetadata};
  1802. use wire::IpEndpoint;
  1803. static UDP_PAYLOAD: [u8; 5] = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
  1804. let (iface, mut socket_set) = create_loopback();
  1805. let rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  1806. let tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  1807. let udp_socket = UdpSocket::new(rx_buffer, tx_buffer);
  1808. let mut udp_bytes = vec![0u8; 13];
  1809. let mut packet = UdpPacket::new_unchecked(&mut udp_bytes);
  1810. let socket_handle = socket_set.add(udp_socket);
  1811. #[cfg(feature = "proto-ipv6")]
  1812. let src_ip = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  1813. #[cfg(all(not(feature = "proto-ipv6"), feature = "proto-ipv4"))]
  1814. let src_ip = Ipv4Address::new(0x7f, 0x00, 0x00, 0x02);
  1815. let udp_repr = UdpRepr {
  1816. src_port: 67,
  1817. dst_port: 68,
  1818. payload: &UDP_PAYLOAD
  1819. };
  1820. #[cfg(feature = "proto-ipv6")]
  1821. let ip_repr = IpRepr::Ipv6(Ipv6Repr {
  1822. src_addr: src_ip,
  1823. dst_addr: Ipv6Address::LINK_LOCAL_ALL_NODES,
  1824. next_header: IpProtocol::Udp,
  1825. payload_len: udp_repr.buffer_len(),
  1826. hop_limit: 0x40
  1827. });
  1828. #[cfg(all(not(feature = "proto-ipv6"), feature = "proto-ipv4"))]
  1829. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1830. src_addr: src_ip,
  1831. dst_addr: Ipv4Address::BROADCAST,
  1832. protocol: IpProtocol::Udp,
  1833. payload_len: udp_repr.buffer_len(),
  1834. hop_limit: 0x40
  1835. });
  1836. {
  1837. // Bind the socket to port 68
  1838. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1839. assert_eq!(socket.bind(68), Ok(()));
  1840. assert!(!socket.can_recv());
  1841. assert!(socket.can_send());
  1842. }
  1843. udp_repr.emit(&mut packet, &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1844. &ChecksumCapabilities::default());
  1845. // Packet should be handled by bound UDP socket
  1846. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, packet.into_inner()),
  1847. Ok(Packet::None));
  1848. {
  1849. // Make sure the payload to the UDP packet processed by process_udp is
  1850. // appended to the bound sockets rx_buffer
  1851. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1852. assert!(socket.can_recv());
  1853. assert_eq!(socket.recv(), Ok((&UDP_PAYLOAD[..], IpEndpoint::new(src_ip.into(), 67))));
  1854. }
  1855. }
  1856. #[test]
  1857. #[cfg(feature = "proto-ipv4")]
  1858. fn test_handle_ipv4_broadcast() {
  1859. use wire::{Ipv4Packet, Icmpv4Repr, Icmpv4Packet};
  1860. let (mut iface, mut socket_set) = create_loopback();
  1861. let our_ipv4_addr = iface.ipv4_address().unwrap();
  1862. let src_ipv4_addr = Ipv4Address([127, 0, 0, 2]);
  1863. // ICMPv4 echo request
  1864. let icmpv4_data: [u8; 4] = [0xaa, 0x00, 0x00, 0xff];
  1865. let icmpv4_repr = Icmpv4Repr::EchoRequest {
  1866. ident: 0x1234, seq_no: 0xabcd, data: &icmpv4_data
  1867. };
  1868. // Send to IPv4 broadcast address
  1869. let ipv4_repr = Ipv4Repr {
  1870. src_addr: src_ipv4_addr,
  1871. dst_addr: Ipv4Address::BROADCAST,
  1872. protocol: IpProtocol::Icmp,
  1873. hop_limit: 64,
  1874. payload_len: icmpv4_repr.buffer_len(),
  1875. };
  1876. // Emit to ethernet frame
  1877. let mut eth_bytes = vec![0u8;
  1878. EthernetFrame::<&[u8]>::header_len() +
  1879. ipv4_repr.buffer_len() + icmpv4_repr.buffer_len()
  1880. ];
  1881. let frame = {
  1882. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  1883. ipv4_repr.emit(
  1884. &mut Ipv4Packet::new_unchecked(frame.payload_mut()),
  1885. &ChecksumCapabilities::default());
  1886. icmpv4_repr.emit(
  1887. &mut Icmpv4Packet::new_unchecked(
  1888. &mut frame.payload_mut()[ipv4_repr.buffer_len()..]),
  1889. &ChecksumCapabilities::default());
  1890. EthernetFrame::new_unchecked(&*frame.into_inner())
  1891. };
  1892. // Expected ICMPv4 echo reply
  1893. let expected_icmpv4_repr = Icmpv4Repr::EchoReply {
  1894. ident: 0x1234, seq_no: 0xabcd, data: &icmpv4_data };
  1895. let expected_ipv4_repr = Ipv4Repr {
  1896. src_addr: our_ipv4_addr,
  1897. dst_addr: src_ipv4_addr,
  1898. protocol: IpProtocol::Icmp,
  1899. hop_limit: 64,
  1900. payload_len: expected_icmpv4_repr.buffer_len(),
  1901. };
  1902. let expected_packet = Packet::Icmpv4((expected_ipv4_repr, expected_icmpv4_repr));
  1903. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  1904. Ok(expected_packet));
  1905. }
  1906. #[test]
  1907. #[cfg(feature = "socket-udp")]
  1908. fn test_icmp_reply_size() {
  1909. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1910. use wire::IPV4_MIN_MTU as MIN_MTU;
  1911. #[cfg(feature = "proto-ipv6")]
  1912. use wire::Icmpv6DstUnreachable;
  1913. #[cfg(feature = "proto-ipv6")]
  1914. use wire::IPV6_MIN_MTU as MIN_MTU;
  1915. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1916. const MAX_PAYLOAD_LEN: usize = 528;
  1917. #[cfg(feature = "proto-ipv6")]
  1918. const MAX_PAYLOAD_LEN: usize = 1192;
  1919. let (iface, mut socket_set) = create_loopback();
  1920. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1921. let src_addr = Ipv4Address([192, 168, 1, 1]);
  1922. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1923. let dst_addr = Ipv4Address([192, 168, 1, 2]);
  1924. #[cfg(feature = "proto-ipv6")]
  1925. let src_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  1926. #[cfg(feature = "proto-ipv6")]
  1927. let dst_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
  1928. // UDP packet that if not tructated will cause a icmp port unreachable reply
  1929. // to exeed the minimum mtu bytes in length.
  1930. let udp_repr = UdpRepr {
  1931. src_port: 67,
  1932. dst_port: 68,
  1933. payload: &[0x2a; MAX_PAYLOAD_LEN]
  1934. };
  1935. let mut bytes = vec![0xff; udp_repr.buffer_len()];
  1936. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  1937. udp_repr.emit(&mut packet, &src_addr.into(), &dst_addr.into(), &ChecksumCapabilities::default());
  1938. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1939. let ip_repr = Ipv4Repr {
  1940. src_addr: src_addr,
  1941. dst_addr: dst_addr,
  1942. protocol: IpProtocol::Udp,
  1943. hop_limit: 64,
  1944. payload_len: udp_repr.buffer_len()
  1945. };
  1946. #[cfg(feature = "proto-ipv6")]
  1947. let ip_repr = Ipv6Repr {
  1948. src_addr: src_addr,
  1949. dst_addr: dst_addr,
  1950. next_header: IpProtocol::Udp,
  1951. hop_limit: 64,
  1952. payload_len: udp_repr.buffer_len()
  1953. };
  1954. let payload = packet.into_inner();
  1955. // Expected packets
  1956. #[cfg(feature = "proto-ipv6")]
  1957. let expected_icmp_repr = Icmpv6Repr::DstUnreachable {
  1958. reason: Icmpv6DstUnreachable::PortUnreachable,
  1959. header: ip_repr,
  1960. data: &payload[..MAX_PAYLOAD_LEN]
  1961. };
  1962. #[cfg(feature = "proto-ipv6")]
  1963. let expected_ip_repr = Ipv6Repr {
  1964. src_addr: dst_addr,
  1965. dst_addr: src_addr,
  1966. next_header: IpProtocol::Icmpv6,
  1967. hop_limit: 64,
  1968. payload_len: expected_icmp_repr.buffer_len()
  1969. };
  1970. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1971. let expected_icmp_repr = Icmpv4Repr::DstUnreachable {
  1972. reason: Icmpv4DstUnreachable::PortUnreachable,
  1973. header: ip_repr,
  1974. data: &payload[..MAX_PAYLOAD_LEN]
  1975. };
  1976. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1977. let expected_ip_repr = Ipv4Repr {
  1978. src_addr: dst_addr,
  1979. dst_addr: src_addr,
  1980. protocol: IpProtocol::Icmp,
  1981. hop_limit: 64,
  1982. payload_len: expected_icmp_repr.buffer_len()
  1983. };
  1984. // The expected packet does not exceed the IPV4_MIN_MTU
  1985. assert_eq!(expected_ip_repr.buffer_len() + expected_icmp_repr.buffer_len(), MIN_MTU);
  1986. // The expected packet and the generated packet are equal
  1987. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1988. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr.into(), payload),
  1989. Ok(Packet::Icmpv4((expected_ip_repr, expected_icmp_repr))));
  1990. #[cfg(feature = "proto-ipv6")]
  1991. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr.into(), payload),
  1992. Ok(Packet::Icmpv6((expected_ip_repr, expected_icmp_repr))));
  1993. }
  1994. #[test]
  1995. #[cfg(feature = "proto-ipv4")]
  1996. fn test_handle_valid_arp_request() {
  1997. let (mut iface, mut socket_set) = create_loopback();
  1998. let mut eth_bytes = vec![0u8; 42];
  1999. let local_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x01]);
  2000. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  2001. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  2002. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  2003. let repr = ArpRepr::EthernetIpv4 {
  2004. operation: ArpOperation::Request,
  2005. source_hardware_addr: remote_hw_addr,
  2006. source_protocol_addr: remote_ip_addr,
  2007. target_hardware_addr: EthernetAddress::default(),
  2008. target_protocol_addr: local_ip_addr,
  2009. };
  2010. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2011. frame.set_dst_addr(EthernetAddress::BROADCAST);
  2012. frame.set_src_addr(remote_hw_addr);
  2013. frame.set_ethertype(EthernetProtocol::Arp);
  2014. {
  2015. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  2016. repr.emit(&mut packet);
  2017. }
  2018. // Ensure an ARP Request for us triggers an ARP Reply
  2019. assert_eq!(iface.inner.process_ethernet(&mut socket_set, Instant::from_millis(0), frame.into_inner()),
  2020. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  2021. operation: ArpOperation::Reply,
  2022. source_hardware_addr: local_hw_addr,
  2023. source_protocol_addr: local_ip_addr,
  2024. target_hardware_addr: remote_hw_addr,
  2025. target_protocol_addr: remote_ip_addr
  2026. })));
  2027. // Ensure the address of the requestor was entered in the cache
  2028. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  2029. &IpAddress::Ipv4(local_ip_addr), &IpAddress::Ipv4(remote_ip_addr)),
  2030. Ok((remote_hw_addr, MockTxToken)));
  2031. }
  2032. #[test]
  2033. #[cfg(feature = "proto-ipv6")]
  2034. fn test_handle_valid_ndisc_request() {
  2035. let (mut iface, mut socket_set) = create_loopback();
  2036. let mut eth_bytes = vec![0u8; 86];
  2037. let local_ip_addr = Ipv6Address::new(0xfdbe, 0, 0, 0, 0, 0, 0, 1);
  2038. let remote_ip_addr = Ipv6Address::new(0xfdbe, 0, 0, 0, 0, 0, 0, 2);
  2039. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  2040. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  2041. let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit {
  2042. target_addr: local_ip_addr,
  2043. lladdr: Some(remote_hw_addr),
  2044. });
  2045. let ip_repr = IpRepr::Ipv6(Ipv6Repr {
  2046. src_addr: remote_ip_addr,
  2047. dst_addr: local_ip_addr.solicited_node(),
  2048. next_header: IpProtocol::Icmpv6,
  2049. hop_limit: 0xff,
  2050. payload_len: solicit.buffer_len()
  2051. });
  2052. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2053. frame.set_dst_addr(EthernetAddress([0x33, 0x33, 0x00, 0x00, 0x00, 0x00]));
  2054. frame.set_src_addr(remote_hw_addr);
  2055. frame.set_ethertype(EthernetProtocol::Ipv6);
  2056. {
  2057. ip_repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  2058. solicit.emit(&remote_ip_addr.into(), &local_ip_addr.solicited_node().into(),
  2059. &mut Icmpv6Packet::new_unchecked(
  2060. &mut frame.payload_mut()[ip_repr.buffer_len()..]),
  2061. &ChecksumCapabilities::default());
  2062. }
  2063. let icmpv6_expected = Icmpv6Repr::Ndisc(NdiscRepr::NeighborAdvert {
  2064. flags: NdiscNeighborFlags::SOLICITED,
  2065. target_addr: local_ip_addr,
  2066. lladdr: Some(local_hw_addr)
  2067. });
  2068. let ipv6_expected = Ipv6Repr {
  2069. src_addr: local_ip_addr,
  2070. dst_addr: remote_ip_addr,
  2071. next_header: IpProtocol::Icmpv6,
  2072. hop_limit: 0xff,
  2073. payload_len: icmpv6_expected.buffer_len()
  2074. };
  2075. // Ensure an Neighbor Solicitation triggers a Neighbor Advertisement
  2076. assert_eq!(iface.inner.process_ethernet(&mut socket_set, Instant::from_millis(0), frame.into_inner()),
  2077. Ok(Packet::Icmpv6((ipv6_expected, icmpv6_expected))));
  2078. // Ensure the address of the requestor was entered in the cache
  2079. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  2080. &IpAddress::Ipv6(local_ip_addr), &IpAddress::Ipv6(remote_ip_addr)),
  2081. Ok((remote_hw_addr, MockTxToken)));
  2082. }
  2083. #[test]
  2084. #[cfg(feature = "proto-ipv4")]
  2085. fn test_handle_other_arp_request() {
  2086. let (mut iface, mut socket_set) = create_loopback();
  2087. let mut eth_bytes = vec![0u8; 42];
  2088. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  2089. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  2090. let repr = ArpRepr::EthernetIpv4 {
  2091. operation: ArpOperation::Request,
  2092. source_hardware_addr: remote_hw_addr,
  2093. source_protocol_addr: remote_ip_addr,
  2094. target_hardware_addr: EthernetAddress::default(),
  2095. target_protocol_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x03]),
  2096. };
  2097. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2098. frame.set_dst_addr(EthernetAddress::BROADCAST);
  2099. frame.set_src_addr(remote_hw_addr);
  2100. frame.set_ethertype(EthernetProtocol::Arp);
  2101. {
  2102. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  2103. repr.emit(&mut packet);
  2104. }
  2105. // Ensure an ARP Request for someone else does not trigger an ARP Reply
  2106. assert_eq!(iface.inner.process_ethernet(&mut socket_set, Instant::from_millis(0), frame.into_inner()),
  2107. Ok(Packet::None));
  2108. // Ensure the address of the requestor was entered in the cache
  2109. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  2110. &IpAddress::Ipv4(Ipv4Address([0x7f, 0x00, 0x00, 0x01])),
  2111. &IpAddress::Ipv4(remote_ip_addr)),
  2112. Ok((remote_hw_addr, MockTxToken)));
  2113. }
  2114. #[test]
  2115. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  2116. fn test_icmpv4_socket() {
  2117. use socket::{IcmpSocket, IcmpEndpoint, IcmpSocketBuffer, IcmpPacketMetadata};
  2118. use wire::Icmpv4Packet;
  2119. let (iface, mut socket_set) = create_loopback();
  2120. let rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 24]);
  2121. let tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 24]);
  2122. let icmpv4_socket = IcmpSocket::new(rx_buffer, tx_buffer);
  2123. let socket_handle = socket_set.add(icmpv4_socket);
  2124. let ident = 0x1234;
  2125. let seq_no = 0x5432;
  2126. let echo_data = &[0xff; 16];
  2127. {
  2128. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  2129. // Bind to the ID 0x1234
  2130. assert_eq!(socket.bind(IcmpEndpoint::Ident(ident)), Ok(()));
  2131. }
  2132. // Ensure the ident we bound to and the ident of the packet are the same.
  2133. let mut bytes = [0xff; 24];
  2134. let mut packet = Icmpv4Packet::new_unchecked(&mut bytes);
  2135. let echo_repr = Icmpv4Repr::EchoRequest{ ident, seq_no, data: echo_data };
  2136. echo_repr.emit(&mut packet, &ChecksumCapabilities::default());
  2137. let icmp_data = &packet.into_inner()[..];
  2138. let ipv4_repr = Ipv4Repr {
  2139. src_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x02),
  2140. dst_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x01),
  2141. protocol: IpProtocol::Icmp,
  2142. payload_len: 24,
  2143. hop_limit: 64
  2144. };
  2145. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  2146. // Open a socket and ensure the packet is handled due to the listening
  2147. // socket.
  2148. {
  2149. assert!(!socket_set.get::<IcmpSocket>(socket_handle).can_recv());
  2150. }
  2151. // Confirm we still get EchoReply from `smoltcp` even with the ICMP socket listening
  2152. let echo_reply = Icmpv4Repr::EchoReply{ ident, seq_no, data: echo_data };
  2153. let ipv4_reply = Ipv4Repr {
  2154. src_addr: ipv4_repr.dst_addr,
  2155. dst_addr: ipv4_repr.src_addr,
  2156. ..ipv4_repr
  2157. };
  2158. assert_eq!(iface.inner.process_icmpv4(&mut socket_set, ip_repr, icmp_data),
  2159. Ok(Packet::Icmpv4((ipv4_reply, echo_reply))));
  2160. {
  2161. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  2162. assert!(socket.can_recv());
  2163. assert_eq!(socket.recv(),
  2164. Ok((&icmp_data[..],
  2165. IpAddress::Ipv4(Ipv4Address::new(0x7f, 0x00, 0x00, 0x02)))));
  2166. }
  2167. }
  2168. #[test]
  2169. #[cfg(feature = "proto-ipv6")]
  2170. fn test_solicited_node_addrs() {
  2171. let (mut iface, _) = create_loopback();
  2172. let mut new_addrs = vec![IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 1, 2, 0, 2), 64),
  2173. IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 3, 4, 0, 0xffff), 64)];
  2174. iface.update_ip_addrs(|addrs| {
  2175. new_addrs.extend(addrs.to_vec());
  2176. *addrs = From::from(new_addrs);
  2177. });
  2178. assert!(iface.inner.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0x0002)));
  2179. assert!(iface.inner.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0xffff)));
  2180. assert!(!iface.inner.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0x0003)));
  2181. }
  2182. #[test]
  2183. #[cfg(feature = "proto-ipv6")]
  2184. fn test_icmpv6_nxthdr_unknown() {
  2185. let (mut iface, mut socket_set) = create_loopback();
  2186. let remote_ip_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  2187. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x01]);
  2188. let mut eth_bytes = vec![0; 66];
  2189. let payload = [0x12, 0x34, 0x56, 0x78];
  2190. let ipv6_repr = Ipv6Repr {
  2191. src_addr: remote_ip_addr,
  2192. dst_addr: Ipv6Address::LOOPBACK,
  2193. next_header: IpProtocol::HopByHop,
  2194. payload_len: 12,
  2195. hop_limit: 0x40,
  2196. };
  2197. let frame = {
  2198. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2199. let ip_repr = IpRepr::Ipv6(ipv6_repr);
  2200. frame.set_dst_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  2201. frame.set_src_addr(remote_hw_addr);
  2202. frame.set_ethertype(EthernetProtocol::Ipv6);
  2203. ip_repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  2204. let mut offset = ipv6_repr.buffer_len();
  2205. {
  2206. let mut hbh_pkt =
  2207. Ipv6HopByHopHeader::new_unchecked(&mut frame.payload_mut()[offset..]);
  2208. hbh_pkt.set_next_header(IpProtocol::Unknown(0x0c));
  2209. hbh_pkt.set_header_len(0);
  2210. offset += 8;
  2211. {
  2212. let mut pad_pkt = Ipv6Option::new_unchecked(&mut hbh_pkt.options_mut()[..]);
  2213. Ipv6OptionRepr::PadN(3).emit(&mut pad_pkt);
  2214. }
  2215. {
  2216. let mut pad_pkt = Ipv6Option::new_unchecked(&mut hbh_pkt.options_mut()[5..]);
  2217. Ipv6OptionRepr::Pad1.emit(&mut pad_pkt);
  2218. }
  2219. }
  2220. frame.payload_mut()[offset..].copy_from_slice(&payload);
  2221. EthernetFrame::new_unchecked(&*frame.into_inner())
  2222. };
  2223. let reply_icmp_repr = Icmpv6Repr::ParamProblem {
  2224. reason: Icmpv6ParamProblem::UnrecognizedNxtHdr,
  2225. pointer: 40,
  2226. header: ipv6_repr,
  2227. data: &payload[..]
  2228. };
  2229. let reply_ipv6_repr = Ipv6Repr {
  2230. src_addr: Ipv6Address::LOOPBACK,
  2231. dst_addr: remote_ip_addr,
  2232. next_header: IpProtocol::Icmpv6,
  2233. payload_len: reply_icmp_repr.buffer_len(),
  2234. hop_limit: 0x40,
  2235. };
  2236. // Ensure the unknown next header causes a ICMPv6 Parameter Problem
  2237. // error message to be sent to the sender.
  2238. assert_eq!(iface.inner.process_ipv6(&mut socket_set, Instant::from_millis(0), &frame),
  2239. Ok(Packet::Icmpv6((reply_ipv6_repr, reply_icmp_repr))));
  2240. // Ensure the address of the requestor was entered in the cache
  2241. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  2242. &IpAddress::Ipv6(Ipv6Address::LOOPBACK),
  2243. &IpAddress::Ipv6(remote_ip_addr)),
  2244. Ok((remote_hw_addr, MockTxToken)));
  2245. }
  2246. #[test]
  2247. #[cfg(feature = "proto-igmp")]
  2248. fn test_handle_igmp() {
  2249. fn recv_igmp<'b>(mut iface: &mut EthernetInterface<'static, 'b, 'static, Loopback>, timestamp: Instant) -> Vec<(Ipv4Repr, IgmpRepr)> {
  2250. let checksum_caps = &iface.device.capabilities().checksum;
  2251. recv_all(&mut iface, timestamp)
  2252. .iter()
  2253. .filter_map(|frame| {
  2254. let eth_frame = EthernetFrame::new_checked(frame).ok()?;
  2255. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload()).ok()?;
  2256. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &checksum_caps).ok()?;
  2257. let ip_payload = ipv4_packet.payload();
  2258. let igmp_packet = IgmpPacket::new_checked(ip_payload).ok()?;
  2259. let igmp_repr = IgmpRepr::parse(&igmp_packet).ok()?;
  2260. Some((ipv4_repr, igmp_repr))
  2261. })
  2262. .collect::<Vec<_>>()
  2263. }
  2264. let groups = [
  2265. Ipv4Address::new(224, 0, 0, 22),
  2266. Ipv4Address::new(224, 0, 0, 56),
  2267. ];
  2268. let (mut iface, mut socket_set) = create_loopback();
  2269. // Join multicast groups
  2270. let timestamp = Instant::now();
  2271. for group in &groups {
  2272. iface.join_multicast_group(*group, timestamp)
  2273. .unwrap();
  2274. }
  2275. let reports = recv_igmp(&mut iface, timestamp);
  2276. assert_eq!(reports.len(), 2);
  2277. for (i, group_addr) in groups.iter().enumerate() {
  2278. assert_eq!(reports[i].0.protocol, IpProtocol::Igmp);
  2279. assert_eq!(reports[i].0.dst_addr, *group_addr);
  2280. assert_eq!(reports[i].1, IgmpRepr::MembershipReport {
  2281. group_addr: *group_addr,
  2282. version: IgmpVersion::Version2,
  2283. });
  2284. }
  2285. // General query
  2286. let timestamp = Instant::now();
  2287. const GENERAL_QUERY_BYTES: &[u8] = &[
  2288. 0x01, 0x00, 0x5e, 0x00, 0x00, 0x01, 0x0a, 0x14,
  2289. 0x48, 0x01, 0x21, 0x01, 0x08, 0x00, 0x46, 0xc0,
  2290. 0x00, 0x24, 0xed, 0xb4, 0x00, 0x00, 0x01, 0x02,
  2291. 0x47, 0x43, 0xac, 0x16, 0x63, 0x04, 0xe0, 0x00,
  2292. 0x00, 0x01, 0x94, 0x04, 0x00, 0x00, 0x11, 0x64,
  2293. 0xec, 0x8f, 0x00, 0x00, 0x00, 0x00, 0x02, 0x0c,
  2294. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  2295. 0x00, 0x00, 0x00, 0x00
  2296. ];
  2297. {
  2298. // Transmit GENERAL_QUERY_BYTES into loopback
  2299. let tx_token = iface.device.transmit().unwrap();
  2300. tx_token.consume(
  2301. timestamp, GENERAL_QUERY_BYTES.len(),
  2302. |buffer| {
  2303. buffer.copy_from_slice(GENERAL_QUERY_BYTES);
  2304. Ok(())
  2305. }).unwrap();
  2306. }
  2307. // Trigger processing until all packets received through the
  2308. // loopback have been processed, including responses to
  2309. // GENERAL_QUERY_BYTES. Therefore `recv_all()` would return 0
  2310. // pkts that could be checked.
  2311. iface.socket_ingress(&mut socket_set, timestamp).unwrap();
  2312. // Leave multicast groups
  2313. let timestamp = Instant::now();
  2314. for group in &groups {
  2315. iface.leave_multicast_group(group.clone(), timestamp)
  2316. .unwrap();
  2317. }
  2318. let leaves = recv_igmp(&mut iface, timestamp);
  2319. assert_eq!(leaves.len(), 2);
  2320. for (i, group_addr) in groups.iter().cloned().enumerate() {
  2321. assert_eq!(leaves[i].0.protocol, IpProtocol::Igmp);
  2322. assert_eq!(leaves[i].0.dst_addr, Ipv4Address::MULTICAST_ALL_ROUTERS);
  2323. assert_eq!(leaves[i].1, IgmpRepr::LeaveGroup { group_addr });
  2324. }
  2325. }
  2326. }