ethernet.rs 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807
  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. /// Get the first IPv4 address if present.
  409. #[cfg(feature = "proto-ipv4")]
  410. pub fn ipv4_addr(&self) -> Option<Ipv4Address> {
  411. self.ip_addrs().iter()
  412. .filter_map(|cidr| match cidr.address() {
  413. IpAddress::Ipv4(addr) => Some(addr),
  414. _ => None,
  415. }).next()
  416. }
  417. /// Update the IP addresses of the interface.
  418. ///
  419. /// # Panics
  420. /// This function panics if any of the addresses are not unicast.
  421. pub fn update_ip_addrs<F: FnOnce(&mut ManagedSlice<'c, IpCidr>)>(&mut self, f: F) {
  422. f(&mut self.inner.ip_addrs);
  423. InterfaceInner::check_ip_addrs(&self.inner.ip_addrs)
  424. }
  425. /// Check whether the interface has the given IP address assigned.
  426. pub fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  427. self.inner.has_ip_addr(addr)
  428. }
  429. /// Get the first IPv4 address of the interface.
  430. #[cfg(feature = "proto-ipv4")]
  431. pub fn ipv4_address(&self) -> Option<Ipv4Address> {
  432. self.inner.ipv4_address()
  433. }
  434. pub fn routes(&self) -> &Routes<'e> {
  435. &self.inner.routes
  436. }
  437. pub fn routes_mut(&mut self) -> &mut Routes<'e> {
  438. &mut self.inner.routes
  439. }
  440. /// Transmit packets queued in the given sockets, and receive packets queued
  441. /// in the device.
  442. ///
  443. /// This function returns a boolean value indicating whether any packets were
  444. /// processed or emitted, and thus, whether the readiness of any socket might
  445. /// have changed.
  446. ///
  447. /// # Errors
  448. /// This method will routinely return errors in response to normal network
  449. /// activity as well as certain boundary conditions such as buffer exhaustion.
  450. /// These errors are provided as an aid for troubleshooting, and are meant
  451. /// to be logged and ignored.
  452. ///
  453. /// As a special case, `Err(Error::Unrecognized)` is returned in response to
  454. /// packets containing any unsupported protocol, option, or form, which is
  455. /// a very common occurrence and on a production system it should not even
  456. /// be logged.
  457. pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  458. let mut readiness_may_have_changed = false;
  459. loop {
  460. let processed_any = self.socket_ingress(sockets, timestamp)?;
  461. let emitted_any = self.socket_egress(sockets, timestamp)?;
  462. #[cfg(feature = "proto-igmp")]
  463. self.igmp_egress(timestamp)?;
  464. if processed_any || emitted_any {
  465. readiness_may_have_changed = true;
  466. } else {
  467. break
  468. }
  469. }
  470. Ok(readiness_may_have_changed)
  471. }
  472. /// Return a _soft deadline_ for calling [poll] the next time.
  473. /// The [Instant] returned is the time at which you should call [poll] next.
  474. /// It is harmless (but wastes energy) to call it before the [Instant], and
  475. /// potentially harmful (impacting quality of service) to call it after the
  476. /// [Instant]
  477. ///
  478. /// [poll]: #method.poll
  479. /// [Instant]: struct.Instant.html
  480. pub fn poll_at(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Instant> {
  481. sockets.iter().filter_map(|socket| {
  482. let socket_poll_at = socket.poll_at();
  483. match socket.meta().poll_at(socket_poll_at, |ip_addr|
  484. self.inner.has_neighbor(&ip_addr, timestamp)) {
  485. PollAt::Ingress => None,
  486. PollAt::Time(instant) => Some(instant),
  487. PollAt::Now => Some(Instant::from_millis(0)),
  488. }
  489. }).min()
  490. }
  491. /// Return an _advisory wait time_ for calling [poll] the next time.
  492. /// The [Duration] returned is the time left to wait before calling [poll] next.
  493. /// It is harmless (but wastes energy) to call it before the [Duration] has passed,
  494. /// and potentially harmful (impacting quality of service) to call it after the
  495. /// [Duration] has passed.
  496. ///
  497. /// [poll]: #method.poll
  498. /// [Duration]: struct.Duration.html
  499. pub fn poll_delay(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Duration> {
  500. match self.poll_at(sockets, timestamp) {
  501. Some(poll_at) if timestamp < poll_at => {
  502. Some(poll_at - timestamp)
  503. }
  504. Some(_) => {
  505. Some(Duration::from_millis(0))
  506. }
  507. _ => None
  508. }
  509. }
  510. fn socket_ingress(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  511. let mut processed_any = false;
  512. loop {
  513. let &mut Self { ref mut device, ref mut inner } = self;
  514. let (rx_token, tx_token) = match device.receive() {
  515. None => break,
  516. Some(tokens) => tokens,
  517. };
  518. rx_token.consume(timestamp, |frame| {
  519. inner.process_ethernet(sockets, timestamp, &frame).map_err(|err| {
  520. net_debug!("cannot process ingress packet: {}", err);
  521. net_debug!("packet dump follows:\n{}",
  522. PrettyPrinter::<EthernetFrame<&[u8]>>::new("", &frame));
  523. err
  524. }).and_then(|response| {
  525. processed_any = true;
  526. inner.dispatch(tx_token, timestamp, response).map_err(|err| {
  527. net_debug!("cannot dispatch response packet: {}", err);
  528. err
  529. })
  530. })
  531. })?;
  532. }
  533. Ok(processed_any)
  534. }
  535. fn socket_egress(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  536. let mut caps = self.device.capabilities();
  537. caps.max_transmission_unit -= EthernetFrame::<&[u8]>::header_len();
  538. let mut emitted_any = false;
  539. for mut socket in sockets.iter_mut() {
  540. if !socket.meta_mut().egress_permitted(timestamp, |ip_addr|
  541. self.inner.has_neighbor(&ip_addr, timestamp)) {
  542. continue
  543. }
  544. let mut neighbor_addr = None;
  545. let mut device_result = Ok(());
  546. let &mut Self { ref mut device, ref mut inner } = self;
  547. macro_rules! respond {
  548. ($response:expr) => ({
  549. let response = $response;
  550. neighbor_addr = response.neighbor_addr();
  551. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  552. device_result = inner.dispatch(tx_token, timestamp, response);
  553. device_result
  554. })
  555. }
  556. let socket_result =
  557. match *socket {
  558. #[cfg(feature = "socket-raw")]
  559. Socket::Raw(ref mut socket) =>
  560. socket.dispatch(&caps.checksum, |response|
  561. respond!(Packet::Raw(response))),
  562. #[cfg(all(feature = "socket-icmp", any(feature = "proto-ipv4", feature = "proto-ipv6")))]
  563. Socket::Icmp(ref mut socket) =>
  564. socket.dispatch(&caps, |response| {
  565. match response {
  566. #[cfg(feature = "proto-ipv4")]
  567. (IpRepr::Ipv4(ipv4_repr), IcmpRepr::Ipv4(icmpv4_repr)) =>
  568. respond!(Packet::Icmpv4((ipv4_repr, icmpv4_repr))),
  569. #[cfg(feature = "proto-ipv6")]
  570. (IpRepr::Ipv6(ipv6_repr), IcmpRepr::Ipv6(icmpv6_repr)) =>
  571. respond!(Packet::Icmpv6((ipv6_repr, icmpv6_repr))),
  572. _ => Err(Error::Unaddressable)
  573. }
  574. }),
  575. #[cfg(feature = "socket-udp")]
  576. Socket::Udp(ref mut socket) =>
  577. socket.dispatch(|response|
  578. respond!(Packet::Udp(response))),
  579. #[cfg(feature = "socket-tcp")]
  580. Socket::Tcp(ref mut socket) =>
  581. socket.dispatch(timestamp, &caps, |response|
  582. respond!(Packet::Tcp(response))),
  583. Socket::__Nonexhaustive(_) => unreachable!()
  584. };
  585. match (device_result, socket_result) {
  586. (Err(Error::Exhausted), _) => break, // nowhere to transmit
  587. (Ok(()), Err(Error::Exhausted)) => (), // nothing to transmit
  588. (Err(Error::Unaddressable), _) => {
  589. // `NeighborCache` already takes care of rate limiting the neighbor discovery
  590. // requests from the socket. However, without an additional rate limiting
  591. // mechanism, we would spin on every socket that has yet to discover its
  592. // neighboor.
  593. socket.meta_mut().neighbor_missing(timestamp,
  594. neighbor_addr.expect("non-IP response packet"));
  595. break
  596. }
  597. (Err(err), _) | (_, Err(err)) => {
  598. net_debug!("{}: cannot dispatch egress packet: {}",
  599. socket.meta().handle, err);
  600. return Err(err)
  601. }
  602. (Ok(()), Ok(())) => emitted_any = true
  603. }
  604. }
  605. Ok(emitted_any)
  606. }
  607. /// Depending on `igmp_report_state` and the therein contained
  608. /// timeouts, send IGMP membership reports.
  609. #[cfg(feature = "proto-igmp")]
  610. fn igmp_egress(&mut self, timestamp: Instant) -> Result<bool> {
  611. match self.inner.igmp_report_state {
  612. IgmpReportState::ToSpecificQuery { version, timeout, group }
  613. if timestamp >= timeout => {
  614. if let Some(pkt) = self.inner.igmp_report_packet(version, group) {
  615. // Send initial membership report
  616. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  617. self.inner.dispatch(tx_token, timestamp, pkt)?;
  618. }
  619. self.inner.igmp_report_state = IgmpReportState::Inactive;
  620. Ok(true)
  621. }
  622. IgmpReportState::ToGeneralQuery { version, timeout, interval, next_index }
  623. if timestamp >= timeout => {
  624. let addr = self.inner.ipv4_multicast_groups
  625. .iter()
  626. .nth(next_index)
  627. .map(|(addr, ())| *addr);
  628. match addr {
  629. Some(addr) => {
  630. if let Some(pkt) = self.inner.igmp_report_packet(version, addr) {
  631. // Send initial membership report
  632. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  633. self.inner.dispatch(tx_token, timestamp, pkt)?;
  634. }
  635. let next_timeout = (timeout + interval).max(timestamp);
  636. self.inner.igmp_report_state = IgmpReportState::ToGeneralQuery {
  637. version, timeout: next_timeout, interval, next_index: next_index + 1
  638. };
  639. Ok(true)
  640. }
  641. None => {
  642. self.inner.igmp_report_state = IgmpReportState::Inactive;
  643. Ok(false)
  644. }
  645. }
  646. }
  647. _ => Ok(false)
  648. }
  649. }
  650. }
  651. impl<'b, 'c, 'e> InterfaceInner<'b, 'c, 'e> {
  652. fn check_ethernet_addr(addr: &EthernetAddress) {
  653. if addr.is_multicast() {
  654. panic!("Ethernet address {} is not unicast", addr)
  655. }
  656. }
  657. fn check_ip_addrs(addrs: &[IpCidr]) {
  658. for cidr in addrs {
  659. if !cidr.address().is_unicast() && !cidr.address().is_unspecified() {
  660. panic!("IP address {} is not unicast", cidr.address())
  661. }
  662. }
  663. }
  664. /// Determine if the given `Ipv6Address` is the solicited node
  665. /// multicast address for a IPv6 addresses assigned to the interface.
  666. /// See [RFC 4291 § 2.7.1] for more details.
  667. ///
  668. /// [RFC 4291 § 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1
  669. #[cfg(feature = "proto-ipv6")]
  670. pub fn has_solicited_node(&self, addr: Ipv6Address) -> bool {
  671. self.ip_addrs.iter().find(|cidr| {
  672. match *cidr {
  673. &IpCidr::Ipv6(cidr) if cidr.address() != Ipv6Address::LOOPBACK=> {
  674. // Take the lower order 24 bits of the IPv6 address and
  675. // append those bits to FF02:0:0:0:0:1:FF00::/104.
  676. addr.as_bytes()[14..] == cidr.address().as_bytes()[14..]
  677. }
  678. _ => false,
  679. }
  680. }).is_some()
  681. }
  682. /// Check whether the interface has the given IP address assigned.
  683. fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  684. let addr = addr.into();
  685. self.ip_addrs.iter().any(|probe| probe.address() == addr)
  686. }
  687. /// Get the first IPv4 address of the interface.
  688. #[cfg(feature = "proto-ipv4")]
  689. pub fn ipv4_address(&self) -> Option<Ipv4Address> {
  690. self.ip_addrs.iter()
  691. .filter_map(
  692. |addr| match addr {
  693. &IpCidr::Ipv4(cidr) => Some(cidr.address()),
  694. _ => None,
  695. })
  696. .next()
  697. }
  698. /// Check whether the interface listens to given destination multicast IP address.
  699. ///
  700. /// If built without feature `proto-igmp` this function will
  701. /// always return `false`.
  702. pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
  703. match addr.into() {
  704. #[cfg(feature = "proto-igmp")]
  705. IpAddress::Ipv4(key) =>
  706. key == Ipv4Address::MULTICAST_ALL_SYSTEMS ||
  707. self.ipv4_multicast_groups.get(&key).is_some(),
  708. _ =>
  709. false,
  710. }
  711. }
  712. fn process_ethernet<'frame, T: AsRef<[u8]>>
  713. (&mut self, sockets: &mut SocketSet, timestamp: Instant, frame: &'frame T) ->
  714. Result<Packet<'frame>>
  715. {
  716. let eth_frame = EthernetFrame::new_checked(frame)?;
  717. // Ignore any packets not directed to our hardware address or any of the multicast groups.
  718. if !eth_frame.dst_addr().is_broadcast() &&
  719. !eth_frame.dst_addr().is_multicast() &&
  720. eth_frame.dst_addr() != self.ethernet_addr
  721. {
  722. return Ok(Packet::None)
  723. }
  724. match eth_frame.ethertype() {
  725. #[cfg(feature = "proto-ipv4")]
  726. EthernetProtocol::Arp =>
  727. self.process_arp(timestamp, &eth_frame),
  728. #[cfg(feature = "proto-ipv4")]
  729. EthernetProtocol::Ipv4 =>
  730. self.process_ipv4(sockets, timestamp, &eth_frame),
  731. #[cfg(feature = "proto-ipv6")]
  732. EthernetProtocol::Ipv6 =>
  733. self.process_ipv6(sockets, timestamp, &eth_frame),
  734. // Drop all other traffic.
  735. _ => Err(Error::Unrecognized),
  736. }
  737. }
  738. #[cfg(feature = "proto-ipv4")]
  739. fn process_arp<'frame, T: AsRef<[u8]>>
  740. (&mut self, timestamp: Instant, eth_frame: &EthernetFrame<&'frame T>) ->
  741. Result<Packet<'frame>>
  742. {
  743. let arp_packet = ArpPacket::new_checked(eth_frame.payload())?;
  744. let arp_repr = ArpRepr::parse(&arp_packet)?;
  745. match arp_repr {
  746. // Respond to ARP requests aimed at us, and fill the ARP cache from all ARP
  747. // requests and replies, to minimize the chance that we have to perform
  748. // an explicit ARP request.
  749. ArpRepr::EthernetIpv4 {
  750. operation, source_hardware_addr, source_protocol_addr, target_protocol_addr, ..
  751. } => {
  752. if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() {
  753. self.neighbor_cache.fill(source_protocol_addr.into(),
  754. source_hardware_addr,
  755. timestamp);
  756. } else {
  757. // Discard packets with non-unicast source addresses.
  758. net_debug!("non-unicast source address");
  759. return Err(Error::Malformed)
  760. }
  761. if operation == ArpOperation::Request && self.has_ip_addr(target_protocol_addr) {
  762. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  763. operation: ArpOperation::Reply,
  764. source_hardware_addr: self.ethernet_addr,
  765. source_protocol_addr: target_protocol_addr,
  766. target_hardware_addr: source_hardware_addr,
  767. target_protocol_addr: source_protocol_addr
  768. }))
  769. } else {
  770. Ok(Packet::None)
  771. }
  772. }
  773. _ => Err(Error::Unrecognized)
  774. }
  775. }
  776. #[cfg(all(any(feature = "proto-ipv4", feature = "proto-ipv6"), feature = "socket-raw"))]
  777. fn raw_socket_filter<'frame>(&mut self, sockets: &mut SocketSet, ip_repr: &IpRepr,
  778. ip_payload: &'frame [u8]) -> bool {
  779. let checksum_caps = self.device_capabilities.checksum.clone();
  780. let mut handled_by_raw_socket = false;
  781. // Pass every IP packet to all raw sockets we have registered.
  782. for mut raw_socket in sockets.iter_mut().filter_map(RawSocket::downcast) {
  783. if !raw_socket.accepts(&ip_repr) { continue }
  784. match raw_socket.process(&ip_repr, ip_payload, &checksum_caps) {
  785. // The packet is valid and handled by socket.
  786. Ok(()) => handled_by_raw_socket = true,
  787. // The socket buffer is full or the packet was truncated
  788. Err(Error::Exhausted) | Err(Error::Truncated) => (),
  789. // Raw sockets don't validate the packets in any way.
  790. Err(_) => unreachable!(),
  791. }
  792. }
  793. handled_by_raw_socket
  794. }
  795. #[cfg(feature = "proto-ipv6")]
  796. fn process_ipv6<'frame, T: AsRef<[u8]>>
  797. (&mut self, sockets: &mut SocketSet, timestamp: Instant,
  798. eth_frame: &EthernetFrame<&'frame T>) ->
  799. Result<Packet<'frame>>
  800. {
  801. let ipv6_packet = Ipv6Packet::new_checked(eth_frame.payload())?;
  802. let ipv6_repr = Ipv6Repr::parse(&ipv6_packet)?;
  803. if !ipv6_repr.src_addr.is_unicast() {
  804. // Discard packets with non-unicast source addresses.
  805. net_debug!("non-unicast source address");
  806. return Err(Error::Malformed)
  807. }
  808. if eth_frame.src_addr().is_unicast() {
  809. // Fill the neighbor cache from IP header of unicast frames.
  810. let ip_addr = IpAddress::Ipv6(ipv6_repr.src_addr);
  811. if self.in_same_network(&ip_addr) &&
  812. !self.neighbor_cache.lookup(&ip_addr, timestamp).found() {
  813. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  814. }
  815. }
  816. let ip_payload = ipv6_packet.payload();
  817. #[cfg(feature = "socket-raw")]
  818. let handled_by_raw_socket = self.raw_socket_filter(sockets, &ipv6_repr.into(), ip_payload);
  819. #[cfg(not(feature = "socket-raw"))]
  820. let handled_by_raw_socket = false;
  821. self.process_nxt_hdr(sockets, timestamp, ipv6_repr, ipv6_repr.next_header,
  822. handled_by_raw_socket, ip_payload)
  823. }
  824. /// Given the next header value forward the payload onto the correct process
  825. /// function.
  826. #[cfg(feature = "proto-ipv6")]
  827. fn process_nxt_hdr<'frame>
  828. (&mut self, sockets: &mut SocketSet, timestamp: Instant, ipv6_repr: Ipv6Repr,
  829. nxt_hdr: IpProtocol, handled_by_raw_socket: bool, ip_payload: &'frame [u8])
  830. -> Result<Packet<'frame>>
  831. {
  832. match nxt_hdr {
  833. IpProtocol::Icmpv6 =>
  834. self.process_icmpv6(sockets, timestamp, ipv6_repr.into(), ip_payload),
  835. #[cfg(feature = "socket-udp")]
  836. IpProtocol::Udp =>
  837. self.process_udp(sockets, ipv6_repr.into(), handled_by_raw_socket, ip_payload),
  838. #[cfg(feature = "socket-tcp")]
  839. IpProtocol::Tcp =>
  840. self.process_tcp(sockets, timestamp, ipv6_repr.into(), ip_payload),
  841. IpProtocol::HopByHop =>
  842. self.process_hopbyhop(sockets, timestamp, ipv6_repr, handled_by_raw_socket, ip_payload),
  843. #[cfg(feature = "socket-raw")]
  844. _ if handled_by_raw_socket =>
  845. Ok(Packet::None),
  846. _ => {
  847. // Send back as much of the original payload as we can.
  848. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU,
  849. ipv6_repr.buffer_len());
  850. let icmp_reply_repr = Icmpv6Repr::ParamProblem {
  851. reason: Icmpv6ParamProblem::UnrecognizedNxtHdr,
  852. // The offending packet is after the IPv6 header.
  853. pointer: ipv6_repr.buffer_len() as u32,
  854. header: ipv6_repr,
  855. data: &ip_payload[0..payload_len]
  856. };
  857. Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
  858. },
  859. }
  860. }
  861. #[cfg(feature = "proto-ipv4")]
  862. fn process_ipv4<'frame, T: AsRef<[u8]>>
  863. (&mut self, sockets: &mut SocketSet, timestamp: Instant,
  864. eth_frame: &EthernetFrame<&'frame T>) ->
  865. Result<Packet<'frame>>
  866. {
  867. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
  868. let checksum_caps = self.device_capabilities.checksum.clone();
  869. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &checksum_caps)?;
  870. if !ipv4_repr.src_addr.is_unicast() {
  871. // Discard packets with non-unicast source addresses.
  872. net_debug!("non-unicast source address");
  873. return Err(Error::Malformed)
  874. }
  875. if eth_frame.src_addr().is_unicast() {
  876. // Fill the neighbor cache from IP header of unicast frames.
  877. let ip_addr = IpAddress::Ipv4(ipv4_repr.src_addr);
  878. if self.in_same_network(&ip_addr) {
  879. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  880. }
  881. }
  882. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  883. let ip_payload = ipv4_packet.payload();
  884. #[cfg(feature = "socket-raw")]
  885. let handled_by_raw_socket = self.raw_socket_filter(sockets, &ip_repr, ip_payload);
  886. #[cfg(not(feature = "socket-raw"))]
  887. let handled_by_raw_socket = false;
  888. if !self.has_ip_addr(ipv4_repr.dst_addr) &&
  889. !ipv4_repr.dst_addr.is_broadcast() &&
  890. !self.has_multicast_group(ipv4_repr.dst_addr) {
  891. // Ignore IP packets not directed at us, or broadcast, or any of the multicast groups.
  892. // If AnyIP is enabled, also check if the packet is routed locally.
  893. if !self.any_ip {
  894. return Ok(Packet::None);
  895. } else if match self.routes.lookup(&IpAddress::Ipv4(ipv4_repr.dst_addr), timestamp) {
  896. Some(router_addr) => !self.has_ip_addr(router_addr),
  897. None => true,
  898. } {
  899. return Ok(Packet::None);
  900. }
  901. }
  902. match ipv4_repr.protocol {
  903. IpProtocol::Icmp =>
  904. self.process_icmpv4(sockets, ip_repr, ip_payload),
  905. #[cfg(feature = "proto-igmp")]
  906. IpProtocol::Igmp =>
  907. self.process_igmp(timestamp, ipv4_repr, ip_payload),
  908. #[cfg(feature = "socket-udp")]
  909. IpProtocol::Udp =>
  910. self.process_udp(sockets, ip_repr, handled_by_raw_socket, ip_payload),
  911. #[cfg(feature = "socket-tcp")]
  912. IpProtocol::Tcp =>
  913. self.process_tcp(sockets, timestamp, ip_repr, ip_payload),
  914. _ if handled_by_raw_socket =>
  915. Ok(Packet::None),
  916. _ => {
  917. // Send back as much of the original payload as we can.
  918. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU,
  919. ipv4_repr.buffer_len());
  920. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  921. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  922. header: ipv4_repr,
  923. data: &ip_payload[0..payload_len]
  924. };
  925. Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr))
  926. }
  927. }
  928. }
  929. /// Host duties of the **IGMPv2** protocol.
  930. ///
  931. /// Sets up `igmp_report_state` for responding to IGMP general/specific membership queries.
  932. /// Membership must not be reported immediately in order to avoid flooding the network
  933. /// after a query is broadcasted by a router; this is not currently done.
  934. #[cfg(feature = "proto-igmp")]
  935. fn process_igmp<'frame>(&mut self, timestamp: Instant, ipv4_repr: Ipv4Repr,
  936. ip_payload: &'frame [u8]) -> Result<Packet<'frame>> {
  937. let igmp_packet = IgmpPacket::new_checked(ip_payload)?;
  938. let igmp_repr = IgmpRepr::parse(&igmp_packet)?;
  939. // FIXME: report membership after a delay
  940. match igmp_repr {
  941. IgmpRepr::MembershipQuery { group_addr, version, max_resp_time } => {
  942. // General query
  943. if group_addr.is_unspecified() &&
  944. ipv4_repr.dst_addr == Ipv4Address::MULTICAST_ALL_SYSTEMS {
  945. // Are we member in any groups?
  946. if self.ipv4_multicast_groups.iter().next().is_some() {
  947. let interval = match version {
  948. IgmpVersion::Version1 =>
  949. Duration::from_millis(100),
  950. IgmpVersion::Version2 => {
  951. // No dependence on a random generator
  952. // (see [#24](https://github.com/m-labs/smoltcp/issues/24))
  953. // but at least spread reports evenly across max_resp_time.
  954. let intervals = self.ipv4_multicast_groups.len() as u32 + 1;
  955. max_resp_time / intervals
  956. }
  957. };
  958. self.igmp_report_state = IgmpReportState::ToGeneralQuery {
  959. version, timeout: timestamp + interval, interval, next_index: 0
  960. };
  961. }
  962. } else {
  963. // Group-specific query
  964. if self.has_multicast_group(group_addr) && ipv4_repr.dst_addr == group_addr {
  965. // Don't respond immediately
  966. let timeout = max_resp_time / 4;
  967. self.igmp_report_state = IgmpReportState::ToSpecificQuery {
  968. version, timeout: timestamp + timeout, group: group_addr
  969. };
  970. }
  971. }
  972. },
  973. // Ignore membership reports
  974. IgmpRepr::MembershipReport { .. } => (),
  975. // Ignore hosts leaving groups
  976. IgmpRepr::LeaveGroup{ .. } => (),
  977. }
  978. Ok(Packet::None)
  979. }
  980. #[cfg(feature = "proto-ipv6")]
  981. fn process_icmpv6<'frame>(&mut self, _sockets: &mut SocketSet, timestamp: Instant,
  982. ip_repr: IpRepr, ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  983. {
  984. let icmp_packet = Icmpv6Packet::new_checked(ip_payload)?;
  985. let checksum_caps = self.device_capabilities.checksum.clone();
  986. let icmp_repr = Icmpv6Repr::parse(&ip_repr.src_addr(), &ip_repr.dst_addr(),
  987. &icmp_packet, &checksum_caps)?;
  988. #[cfg(feature = "socket-icmp")]
  989. let mut handled_by_icmp_socket = false;
  990. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv6"))]
  991. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  992. if !icmp_socket.accepts(&ip_repr, &icmp_repr.into(), &checksum_caps) { continue }
  993. match icmp_socket.process(&ip_repr, &icmp_repr.into(), &checksum_caps) {
  994. // The packet is valid and handled by socket.
  995. Ok(()) => handled_by_icmp_socket = true,
  996. // The socket buffer is full.
  997. Err(Error::Exhausted) => (),
  998. // ICMP sockets don't validate the packets in any way.
  999. Err(_) => unreachable!(),
  1000. }
  1001. }
  1002. match icmp_repr {
  1003. // Respond to echo requests.
  1004. Icmpv6Repr::EchoRequest { ident, seq_no, data } => {
  1005. match ip_repr {
  1006. IpRepr::Ipv6(ipv6_repr) => {
  1007. let icmp_reply_repr = Icmpv6Repr::EchoReply {
  1008. ident: ident,
  1009. seq_no: seq_no,
  1010. data: data
  1011. };
  1012. Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
  1013. },
  1014. _ => Err(Error::Unrecognized),
  1015. }
  1016. }
  1017. // Ignore any echo replies.
  1018. Icmpv6Repr::EchoReply { .. } => Ok(Packet::None),
  1019. // Forward any NDISC packets to the ndisc packet handler
  1020. Icmpv6Repr::Ndisc(repr) if ip_repr.hop_limit() == 0xff => match ip_repr {
  1021. IpRepr::Ipv6(ipv6_repr) => self.process_ndisc(timestamp, ipv6_repr, repr),
  1022. _ => Ok(Packet::None)
  1023. },
  1024. // Don't report an error if a packet with unknown type
  1025. // has been handled by an ICMP socket
  1026. #[cfg(feature = "socket-icmp")]
  1027. _ if handled_by_icmp_socket => Ok(Packet::None),
  1028. // FIXME: do something correct here?
  1029. _ => Err(Error::Unrecognized),
  1030. }
  1031. }
  1032. #[cfg(feature = "proto-ipv6")]
  1033. fn process_ndisc<'frame>(&mut self, timestamp: Instant, ip_repr: Ipv6Repr,
  1034. repr: NdiscRepr<'frame>) -> Result<Packet<'frame>> {
  1035. let packet = match repr {
  1036. NdiscRepr::NeighborAdvert { lladdr, target_addr, flags } => {
  1037. let ip_addr = ip_repr.src_addr.into();
  1038. match lladdr {
  1039. Some(lladdr) if lladdr.is_unicast() && target_addr.is_unicast() => {
  1040. if flags.contains(NdiscNeighborFlags::OVERRIDE) {
  1041. self.neighbor_cache.fill(ip_addr, lladdr, timestamp)
  1042. } else {
  1043. if !self.neighbor_cache.lookup(&ip_addr, timestamp).found() {
  1044. self.neighbor_cache.fill(ip_addr, lladdr, timestamp)
  1045. }
  1046. }
  1047. },
  1048. _ => (),
  1049. }
  1050. Ok(Packet::None)
  1051. }
  1052. NdiscRepr::NeighborSolicit { target_addr, lladdr, .. } => {
  1053. match lladdr {
  1054. Some(lladdr) if lladdr.is_unicast() && target_addr.is_unicast() => {
  1055. self.neighbor_cache.fill(ip_repr.src_addr.into(), lladdr, timestamp)
  1056. },
  1057. _ => (),
  1058. }
  1059. if self.has_solicited_node(ip_repr.dst_addr) && self.has_ip_addr(target_addr) {
  1060. let advert = Icmpv6Repr::Ndisc(NdiscRepr::NeighborAdvert {
  1061. flags: NdiscNeighborFlags::SOLICITED,
  1062. target_addr: target_addr,
  1063. lladdr: Some(self.ethernet_addr)
  1064. });
  1065. let ip_repr = Ipv6Repr {
  1066. src_addr: target_addr,
  1067. dst_addr: ip_repr.src_addr,
  1068. next_header: IpProtocol::Icmpv6,
  1069. hop_limit: 0xff,
  1070. payload_len: advert.buffer_len()
  1071. };
  1072. Ok(Packet::Icmpv6((ip_repr, advert)))
  1073. } else {
  1074. Ok(Packet::None)
  1075. }
  1076. }
  1077. _ => Ok(Packet::None)
  1078. };
  1079. packet
  1080. }
  1081. #[cfg(feature = "proto-ipv6")]
  1082. fn process_hopbyhop<'frame>(&mut self, sockets: &mut SocketSet, timestamp: Instant,
  1083. ipv6_repr: Ipv6Repr, handled_by_raw_socket: bool,
  1084. ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  1085. {
  1086. let hbh_pkt = Ipv6HopByHopHeader::new_checked(ip_payload)?;
  1087. let hbh_repr = Ipv6HopByHopRepr::parse(&hbh_pkt)?;
  1088. for result in hbh_repr.options() {
  1089. let opt_repr = result?;
  1090. match opt_repr {
  1091. Ipv6OptionRepr::Pad1 | Ipv6OptionRepr::PadN(_) => (),
  1092. Ipv6OptionRepr::Unknown { type_, .. } => {
  1093. match Ipv6OptionFailureType::from(type_) {
  1094. Ipv6OptionFailureType::Skip => (),
  1095. Ipv6OptionFailureType::Discard => {
  1096. return Ok(Packet::None);
  1097. },
  1098. _ => {
  1099. // FIXME(dlrobertson): Send an ICMPv6 parameter problem message
  1100. // here.
  1101. return Err(Error::Unrecognized);
  1102. }
  1103. }
  1104. }
  1105. _ => return Err(Error::Unrecognized),
  1106. }
  1107. }
  1108. self.process_nxt_hdr(sockets, timestamp, ipv6_repr, hbh_repr.next_header,
  1109. handled_by_raw_socket, &ip_payload[hbh_repr.buffer_len()..])
  1110. }
  1111. #[cfg(feature = "proto-ipv4")]
  1112. fn process_icmpv4<'frame>(&self, _sockets: &mut SocketSet, ip_repr: IpRepr,
  1113. ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  1114. {
  1115. let icmp_packet = Icmpv4Packet::new_checked(ip_payload)?;
  1116. let checksum_caps = self.device_capabilities.checksum.clone();
  1117. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &checksum_caps)?;
  1118. #[cfg(feature = "socket-icmp")]
  1119. let mut handled_by_icmp_socket = false;
  1120. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  1121. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  1122. if !icmp_socket.accepts(&ip_repr, &icmp_repr.into(), &checksum_caps) { continue }
  1123. match icmp_socket.process(&ip_repr, &icmp_repr.into(), &checksum_caps) {
  1124. // The packet is valid and handled by socket.
  1125. Ok(()) => handled_by_icmp_socket = true,
  1126. // The socket buffer is full.
  1127. Err(Error::Exhausted) => (),
  1128. // ICMP sockets don't validate the packets in any way.
  1129. Err(_) => unreachable!(),
  1130. }
  1131. }
  1132. match icmp_repr {
  1133. // Respond to echo requests.
  1134. #[cfg(feature = "proto-ipv4")]
  1135. Icmpv4Repr::EchoRequest { ident, seq_no, data } => {
  1136. let icmp_reply_repr = Icmpv4Repr::EchoReply {
  1137. ident: ident,
  1138. seq_no: seq_no,
  1139. data: data
  1140. };
  1141. match ip_repr {
  1142. IpRepr::Ipv4(ipv4_repr) => Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr)),
  1143. _ => Err(Error::Unrecognized),
  1144. }
  1145. },
  1146. // Ignore any echo replies.
  1147. Icmpv4Repr::EchoReply { .. } => Ok(Packet::None),
  1148. // Don't report an error if a packet with unknown type
  1149. // has been handled by an ICMP socket
  1150. #[cfg(feature = "socket-icmp")]
  1151. _ if handled_by_icmp_socket => Ok(Packet::None),
  1152. // FIXME: do something correct here?
  1153. _ => Err(Error::Unrecognized),
  1154. }
  1155. }
  1156. #[cfg(feature = "proto-ipv4")]
  1157. fn icmpv4_reply<'frame, 'icmp: 'frame>
  1158. (&self, ipv4_repr: Ipv4Repr, icmp_repr: Icmpv4Repr<'icmp>) ->
  1159. Packet<'frame>
  1160. {
  1161. if !ipv4_repr.src_addr.is_unicast() {
  1162. // Do not send ICMP replies to non-unicast sources
  1163. Packet::None
  1164. } else if ipv4_repr.dst_addr.is_unicast() {
  1165. // Reply as normal when src_addr and dst_addr are both unicast
  1166. let ipv4_reply_repr = Ipv4Repr {
  1167. src_addr: ipv4_repr.dst_addr,
  1168. dst_addr: ipv4_repr.src_addr,
  1169. protocol: IpProtocol::Icmp,
  1170. payload_len: icmp_repr.buffer_len(),
  1171. hop_limit: 64
  1172. };
  1173. Packet::Icmpv4((ipv4_reply_repr, icmp_repr))
  1174. } else if ipv4_repr.dst_addr.is_broadcast() {
  1175. // Only reply to broadcasts for echo replies and not other ICMP messages
  1176. match icmp_repr {
  1177. Icmpv4Repr::EchoReply {..} => match self.ipv4_address() {
  1178. Some(src_addr) => {
  1179. let ipv4_reply_repr = Ipv4Repr {
  1180. src_addr: src_addr,
  1181. dst_addr: ipv4_repr.src_addr,
  1182. protocol: IpProtocol::Icmp,
  1183. payload_len: icmp_repr.buffer_len(),
  1184. hop_limit: 64
  1185. };
  1186. Packet::Icmpv4((ipv4_reply_repr, icmp_repr))
  1187. },
  1188. None => Packet::None,
  1189. },
  1190. _ => Packet::None,
  1191. }
  1192. } else {
  1193. Packet::None
  1194. }
  1195. }
  1196. #[cfg(feature = "proto-ipv6")]
  1197. fn icmpv6_reply<'frame, 'icmp: 'frame>
  1198. (&self, ipv6_repr: Ipv6Repr, icmp_repr: Icmpv6Repr<'icmp>) ->
  1199. Packet<'frame>
  1200. {
  1201. if ipv6_repr.dst_addr.is_unicast() {
  1202. let ipv6_reply_repr = Ipv6Repr {
  1203. src_addr: ipv6_repr.dst_addr,
  1204. dst_addr: ipv6_repr.src_addr,
  1205. next_header: IpProtocol::Icmpv6,
  1206. payload_len: icmp_repr.buffer_len(),
  1207. hop_limit: 64
  1208. };
  1209. Packet::Icmpv6((ipv6_reply_repr, icmp_repr))
  1210. } else {
  1211. // Do not send any ICMP replies to a broadcast destination address.
  1212. Packet::None
  1213. }
  1214. }
  1215. #[cfg(feature = "socket-udp")]
  1216. fn process_udp<'frame>(&self, sockets: &mut SocketSet,
  1217. ip_repr: IpRepr, handled_by_raw_socket: bool, ip_payload: &'frame [u8]) ->
  1218. Result<Packet<'frame>>
  1219. {
  1220. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  1221. let udp_packet = UdpPacket::new_checked(ip_payload)?;
  1222. let checksum_caps = self.device_capabilities.checksum.clone();
  1223. let udp_repr = UdpRepr::parse(&udp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  1224. for mut udp_socket in sockets.iter_mut().filter_map(UdpSocket::downcast) {
  1225. if !udp_socket.accepts(&ip_repr, &udp_repr) { continue }
  1226. match udp_socket.process(&ip_repr, &udp_repr) {
  1227. // The packet is valid and handled by socket.
  1228. Ok(()) => return Ok(Packet::None),
  1229. // The packet is malformed, or the socket buffer is full.
  1230. Err(e) => return Err(e)
  1231. }
  1232. }
  1233. // The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  1234. match ip_repr {
  1235. #[cfg(feature = "proto-ipv4")]
  1236. IpRepr::Ipv4(_) if handled_by_raw_socket =>
  1237. Ok(Packet::None),
  1238. #[cfg(feature = "proto-ipv6")]
  1239. IpRepr::Ipv6(_) if handled_by_raw_socket =>
  1240. Ok(Packet::None),
  1241. #[cfg(feature = "proto-ipv4")]
  1242. IpRepr::Ipv4(ipv4_repr) => {
  1243. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU,
  1244. ipv4_repr.buffer_len());
  1245. let icmpv4_reply_repr = Icmpv4Repr::DstUnreachable {
  1246. reason: Icmpv4DstUnreachable::PortUnreachable,
  1247. header: ipv4_repr,
  1248. data: &ip_payload[0..payload_len]
  1249. };
  1250. Ok(self.icmpv4_reply(ipv4_repr, icmpv4_reply_repr))
  1251. },
  1252. #[cfg(feature = "proto-ipv6")]
  1253. IpRepr::Ipv6(ipv6_repr) => {
  1254. let payload_len = icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU,
  1255. ipv6_repr.buffer_len());
  1256. let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable {
  1257. reason: Icmpv6DstUnreachable::PortUnreachable,
  1258. header: ipv6_repr,
  1259. data: &ip_payload[0..payload_len]
  1260. };
  1261. Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr))
  1262. },
  1263. IpRepr::Unspecified { .. } |
  1264. IpRepr::__Nonexhaustive => Err(Error::Unaddressable),
  1265. }
  1266. }
  1267. #[cfg(feature = "socket-tcp")]
  1268. fn process_tcp<'frame>(&self, sockets: &mut SocketSet, timestamp: Instant,
  1269. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  1270. Result<Packet<'frame>>
  1271. {
  1272. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  1273. let tcp_packet = TcpPacket::new_checked(ip_payload)?;
  1274. let checksum_caps = self.device_capabilities.checksum.clone();
  1275. let tcp_repr = TcpRepr::parse(&tcp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  1276. for mut tcp_socket in sockets.iter_mut().filter_map(TcpSocket::downcast) {
  1277. if !tcp_socket.accepts(&ip_repr, &tcp_repr) { continue }
  1278. match tcp_socket.process(timestamp, &ip_repr, &tcp_repr) {
  1279. // The packet is valid and handled by socket.
  1280. Ok(reply) => return Ok(reply.map_or(Packet::None, Packet::Tcp)),
  1281. // The packet is malformed, or doesn't match the socket state,
  1282. // or the socket buffer is full.
  1283. Err(e) => return Err(e)
  1284. }
  1285. }
  1286. if tcp_repr.control == TcpControl::Rst {
  1287. // Never reply to a TCP RST packet with another TCP RST packet.
  1288. Ok(Packet::None)
  1289. } else {
  1290. // The packet wasn't handled by a socket, send a TCP RST packet.
  1291. Ok(Packet::Tcp(TcpSocket::rst_reply(&ip_repr, &tcp_repr)))
  1292. }
  1293. }
  1294. fn dispatch<Tx>(&mut self, tx_token: Tx, timestamp: Instant,
  1295. packet: Packet) -> Result<()>
  1296. where Tx: TxToken
  1297. {
  1298. let checksum_caps = self.device_capabilities.checksum.clone();
  1299. match packet {
  1300. #[cfg(feature = "proto-ipv4")]
  1301. Packet::Arp(arp_repr) => {
  1302. let dst_hardware_addr =
  1303. match arp_repr {
  1304. ArpRepr::EthernetIpv4 { target_hardware_addr, .. } => target_hardware_addr,
  1305. _ => unreachable!()
  1306. };
  1307. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  1308. frame.set_dst_addr(dst_hardware_addr);
  1309. frame.set_ethertype(EthernetProtocol::Arp);
  1310. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  1311. arp_repr.emit(&mut packet);
  1312. })
  1313. },
  1314. #[cfg(feature = "proto-ipv4")]
  1315. Packet::Icmpv4((ipv4_repr, icmpv4_repr)) => {
  1316. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv4(ipv4_repr),
  1317. |_ip_repr, payload| {
  1318. icmpv4_repr.emit(&mut Icmpv4Packet::new_unchecked(payload), &checksum_caps);
  1319. })
  1320. }
  1321. #[cfg(feature = "proto-igmp")]
  1322. Packet::Igmp((ipv4_repr, igmp_repr)) => {
  1323. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv4(ipv4_repr), |_ip_repr, payload| {
  1324. igmp_repr.emit(&mut IgmpPacket::new_unchecked(payload));
  1325. })
  1326. }
  1327. #[cfg(feature = "proto-ipv6")]
  1328. Packet::Icmpv6((ipv6_repr, icmpv6_repr)) => {
  1329. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv6(ipv6_repr),
  1330. |ip_repr, payload| {
  1331. icmpv6_repr.emit(&ip_repr.src_addr(), &ip_repr.dst_addr(),
  1332. &mut Icmpv6Packet::new_unchecked(payload), &checksum_caps);
  1333. })
  1334. }
  1335. #[cfg(feature = "socket-raw")]
  1336. Packet::Raw((ip_repr, raw_packet)) => {
  1337. self.dispatch_ip(tx_token, timestamp, ip_repr, |_ip_repr, payload| {
  1338. payload.copy_from_slice(raw_packet);
  1339. })
  1340. }
  1341. #[cfg(feature = "socket-udp")]
  1342. Packet::Udp((ip_repr, udp_repr)) => {
  1343. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  1344. udp_repr.emit(&mut UdpPacket::new_unchecked(payload),
  1345. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1346. &checksum_caps);
  1347. })
  1348. }
  1349. #[cfg(feature = "socket-tcp")]
  1350. Packet::Tcp((ip_repr, mut tcp_repr)) => {
  1351. let caps = self.device_capabilities.clone();
  1352. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  1353. // This is a terrible hack to make TCP performance more acceptable on systems
  1354. // where the TCP buffers are significantly larger than network buffers,
  1355. // e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
  1356. // together with four 1500 B Ethernet receive buffers. If left untreated,
  1357. // this would result in our peer pushing our window and sever packet loss.
  1358. //
  1359. // I'm really not happy about this "solution" but I don't know what else to do.
  1360. if let Some(max_burst_size) = caps.max_burst_size {
  1361. let mut max_segment_size = caps.max_transmission_unit;
  1362. max_segment_size -= EthernetFrame::<&[u8]>::header_len();
  1363. max_segment_size -= ip_repr.buffer_len();
  1364. max_segment_size -= tcp_repr.header_len();
  1365. let max_window_size = max_burst_size * max_segment_size;
  1366. if tcp_repr.window_len as usize > max_window_size {
  1367. tcp_repr.window_len = max_window_size as u16;
  1368. }
  1369. }
  1370. tcp_repr.emit(&mut TcpPacket::new_unchecked(payload),
  1371. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1372. &checksum_caps);
  1373. })
  1374. }
  1375. Packet::None => Ok(())
  1376. }
  1377. }
  1378. fn dispatch_ethernet<Tx, F>(&mut self, tx_token: Tx, timestamp: Instant,
  1379. buffer_len: usize, f: F) -> Result<()>
  1380. where Tx: TxToken, F: FnOnce(EthernetFrame<&mut [u8]>)
  1381. {
  1382. let tx_len = EthernetFrame::<&[u8]>::buffer_len(buffer_len);
  1383. tx_token.consume(timestamp, tx_len, |tx_buffer| {
  1384. debug_assert!(tx_buffer.as_ref().len() == tx_len);
  1385. let mut frame = EthernetFrame::new_unchecked(tx_buffer.as_mut());
  1386. frame.set_src_addr(self.ethernet_addr);
  1387. f(frame);
  1388. Ok(())
  1389. })
  1390. }
  1391. fn in_same_network(&self, addr: &IpAddress) -> bool {
  1392. self.ip_addrs
  1393. .iter()
  1394. .find(|cidr| cidr.contains_addr(addr))
  1395. .is_some()
  1396. }
  1397. fn route(&self, addr: &IpAddress, timestamp: Instant) -> Result<IpAddress> {
  1398. // Send directly.
  1399. if self.in_same_network(addr) || addr.is_broadcast() {
  1400. return Ok(*addr)
  1401. }
  1402. // Route via a router.
  1403. match self.routes.lookup(addr, timestamp) {
  1404. Some(router_addr) => Ok(router_addr),
  1405. None => Err(Error::Unaddressable),
  1406. }
  1407. }
  1408. fn has_neighbor<'a>(&self, addr: &'a IpAddress, timestamp: Instant) -> bool {
  1409. match self.route(addr, timestamp) {
  1410. Ok(routed_addr) => {
  1411. self.neighbor_cache
  1412. .lookup(&routed_addr, timestamp)
  1413. .found()
  1414. }
  1415. Err(_) => false
  1416. }
  1417. }
  1418. fn lookup_hardware_addr<Tx>(&mut self, tx_token: Tx, timestamp: Instant,
  1419. src_addr: &IpAddress, dst_addr: &IpAddress) ->
  1420. Result<(EthernetAddress, Tx)>
  1421. where Tx: TxToken
  1422. {
  1423. if dst_addr.is_multicast() {
  1424. let b = dst_addr.as_bytes();
  1425. let hardware_addr =
  1426. match dst_addr {
  1427. &IpAddress::Unspecified =>
  1428. None,
  1429. #[cfg(feature = "proto-ipv4")]
  1430. &IpAddress::Ipv4(_addr) =>
  1431. Some(EthernetAddress::from_bytes(&[
  1432. 0x01, 0x00,
  1433. 0x5e, b[1] & 0x7F,
  1434. b[2], b[3],
  1435. ])),
  1436. #[cfg(feature = "proto-ipv6")]
  1437. &IpAddress::Ipv6(_addr) =>
  1438. Some(EthernetAddress::from_bytes(&[
  1439. 0x33, 0x33,
  1440. b[12], b[13],
  1441. b[14], b[15],
  1442. ])),
  1443. &IpAddress::__Nonexhaustive =>
  1444. unreachable!()
  1445. };
  1446. match hardware_addr {
  1447. Some(hardware_addr) =>
  1448. // Destination is multicast
  1449. return Ok((hardware_addr, tx_token)),
  1450. None =>
  1451. // Continue
  1452. (),
  1453. }
  1454. }
  1455. let dst_addr = self.route(dst_addr, timestamp)?;
  1456. match self.neighbor_cache.lookup(&dst_addr, timestamp) {
  1457. NeighborAnswer::Found(hardware_addr) =>
  1458. return Ok((hardware_addr, tx_token)),
  1459. NeighborAnswer::RateLimited =>
  1460. return Err(Error::Unaddressable),
  1461. NeighborAnswer::NotFound => (),
  1462. }
  1463. match (src_addr, dst_addr) {
  1464. #[cfg(feature = "proto-ipv4")]
  1465. (&IpAddress::Ipv4(src_addr), IpAddress::Ipv4(dst_addr)) => {
  1466. net_debug!("address {} not in neighbor cache, sending ARP request",
  1467. dst_addr);
  1468. let arp_repr = ArpRepr::EthernetIpv4 {
  1469. operation: ArpOperation::Request,
  1470. source_hardware_addr: self.ethernet_addr,
  1471. source_protocol_addr: src_addr,
  1472. target_hardware_addr: EthernetAddress::BROADCAST,
  1473. target_protocol_addr: dst_addr,
  1474. };
  1475. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  1476. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1477. frame.set_ethertype(EthernetProtocol::Arp);
  1478. arp_repr.emit(&mut ArpPacket::new_unchecked(frame.payload_mut()))
  1479. })?;
  1480. }
  1481. #[cfg(feature = "proto-ipv6")]
  1482. (&IpAddress::Ipv6(src_addr), IpAddress::Ipv6(dst_addr)) => {
  1483. net_debug!("address {} not in neighbor cache, sending Neighbor Solicitation",
  1484. dst_addr);
  1485. let checksum_caps = self.device_capabilities.checksum.clone();
  1486. let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit {
  1487. target_addr: src_addr,
  1488. lladdr: Some(self.ethernet_addr),
  1489. });
  1490. let ip_repr = IpRepr::Ipv6(Ipv6Repr {
  1491. src_addr: src_addr,
  1492. dst_addr: dst_addr.solicited_node(),
  1493. next_header: IpProtocol::Icmpv6,
  1494. payload_len: solicit.buffer_len(),
  1495. hop_limit: 0xff
  1496. });
  1497. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  1498. solicit.emit(&ip_repr.src_addr(), &ip_repr.dst_addr(),
  1499. &mut Icmpv6Packet::new_unchecked(payload), &checksum_caps);
  1500. })?;
  1501. }
  1502. _ => ()
  1503. }
  1504. // The request got dispatched, limit the rate on the cache.
  1505. self.neighbor_cache.limit_rate(timestamp);
  1506. Err(Error::Unaddressable)
  1507. }
  1508. fn dispatch_ip<Tx, F>(&mut self, tx_token: Tx, timestamp: Instant,
  1509. ip_repr: IpRepr, f: F) -> Result<()>
  1510. where Tx: TxToken, F: FnOnce(IpRepr, &mut [u8])
  1511. {
  1512. let ip_repr = ip_repr.lower(&self.ip_addrs)?;
  1513. let checksum_caps = self.device_capabilities.checksum.clone();
  1514. let (dst_hardware_addr, tx_token) =
  1515. self.lookup_hardware_addr(tx_token, timestamp,
  1516. &ip_repr.src_addr(), &ip_repr.dst_addr())?;
  1517. self.dispatch_ethernet(tx_token, timestamp, ip_repr.total_len(), |mut frame| {
  1518. frame.set_dst_addr(dst_hardware_addr);
  1519. match ip_repr {
  1520. #[cfg(feature = "proto-ipv4")]
  1521. IpRepr::Ipv4(_) => frame.set_ethertype(EthernetProtocol::Ipv4),
  1522. #[cfg(feature = "proto-ipv6")]
  1523. IpRepr::Ipv6(_) => frame.set_ethertype(EthernetProtocol::Ipv6),
  1524. _ => return
  1525. }
  1526. ip_repr.emit(frame.payload_mut(), &checksum_caps);
  1527. let payload = &mut frame.payload_mut()[ip_repr.buffer_len()..];
  1528. f(ip_repr, payload)
  1529. })
  1530. }
  1531. #[cfg(feature = "proto-igmp")]
  1532. fn igmp_report_packet<'any>(&self, version: IgmpVersion, group_addr: Ipv4Address) -> Option<Packet<'any>> {
  1533. let iface_addr = self.ipv4_address()?;
  1534. let igmp_repr = IgmpRepr::MembershipReport {
  1535. group_addr,
  1536. version,
  1537. };
  1538. let pkt = Packet::Igmp((Ipv4Repr {
  1539. src_addr: iface_addr,
  1540. // Send to the group being reported
  1541. dst_addr: group_addr,
  1542. protocol: IpProtocol::Igmp,
  1543. payload_len: igmp_repr.buffer_len(),
  1544. hop_limit: 1,
  1545. // TODO: add Router Alert IPv4 header option. See
  1546. // [#183](https://github.com/m-labs/smoltcp/issues/183).
  1547. }, igmp_repr));
  1548. Some(pkt)
  1549. }
  1550. #[cfg(feature = "proto-igmp")]
  1551. fn igmp_leave_packet<'any>(&self, group_addr: Ipv4Address) -> Option<Packet<'any>> {
  1552. self.ipv4_address().map(|iface_addr| {
  1553. let igmp_repr = IgmpRepr::LeaveGroup { group_addr };
  1554. let pkt = Packet::Igmp((Ipv4Repr {
  1555. src_addr: iface_addr,
  1556. dst_addr: Ipv4Address::MULTICAST_ALL_ROUTERS,
  1557. protocol: IpProtocol::Igmp,
  1558. payload_len: igmp_repr.buffer_len(),
  1559. hop_limit: 1,
  1560. }, igmp_repr));
  1561. pkt
  1562. })
  1563. }
  1564. }
  1565. #[cfg(test)]
  1566. mod test {
  1567. #[cfg(feature = "proto-igmp")]
  1568. use std::vec::Vec;
  1569. use std::collections::BTreeMap;
  1570. use {Result, Error};
  1571. use super::InterfaceBuilder;
  1572. use iface::{NeighborCache, EthernetInterface};
  1573. use phy::{self, Loopback, ChecksumCapabilities};
  1574. #[cfg(feature = "proto-igmp")]
  1575. use phy::{Device, RxToken, TxToken};
  1576. use time::Instant;
  1577. use socket::SocketSet;
  1578. #[cfg(feature = "proto-ipv4")]
  1579. use wire::{ArpOperation, ArpPacket, ArpRepr};
  1580. use wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
  1581. use wire::{IpAddress, IpCidr, IpProtocol, IpRepr};
  1582. #[cfg(feature = "proto-ipv4")]
  1583. use wire::{Ipv4Address, Ipv4Repr};
  1584. #[cfg(feature = "proto-igmp")]
  1585. use wire::Ipv4Packet;
  1586. #[cfg(feature = "proto-ipv4")]
  1587. use wire::{Icmpv4Repr, Icmpv4DstUnreachable};
  1588. #[cfg(feature = "proto-igmp")]
  1589. use wire::{IgmpPacket, IgmpRepr, IgmpVersion};
  1590. #[cfg(all(feature = "socket-udp", any(feature = "proto-ipv4", feature = "proto-ipv6")))]
  1591. use wire::{UdpPacket, UdpRepr};
  1592. #[cfg(feature = "proto-ipv6")]
  1593. use wire::{Ipv6Address, Ipv6Repr};
  1594. #[cfg(feature = "proto-ipv6")]
  1595. use wire::{Icmpv6Packet, Icmpv6Repr, Icmpv6ParamProblem};
  1596. #[cfg(feature = "proto-ipv6")]
  1597. use wire::{NdiscNeighborFlags, NdiscRepr};
  1598. #[cfg(feature = "proto-ipv6")]
  1599. use wire::{Ipv6HopByHopHeader, Ipv6Option, Ipv6OptionRepr};
  1600. use super::Packet;
  1601. fn create_loopback<'a, 'b, 'c>() -> (EthernetInterface<'static, 'b, 'c, Loopback>,
  1602. SocketSet<'static, 'a, 'b>) {
  1603. // Create a basic device
  1604. let device = Loopback::new();
  1605. let ip_addrs = [
  1606. #[cfg(feature = "proto-ipv4")]
  1607. IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8),
  1608. #[cfg(feature = "proto-ipv6")]
  1609. IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 128),
  1610. #[cfg(feature = "proto-ipv6")]
  1611. IpCidr::new(IpAddress::v6(0xfdbe, 0, 0, 0, 0, 0, 0, 1), 64),
  1612. ];
  1613. let iface_builder = InterfaceBuilder::new(device)
  1614. .ethernet_addr(EthernetAddress::default())
  1615. .neighbor_cache(NeighborCache::new(BTreeMap::new()))
  1616. .ip_addrs(ip_addrs);
  1617. #[cfg(feature = "proto-igmp")]
  1618. let iface_builder = iface_builder
  1619. .ipv4_multicast_groups(BTreeMap::new());
  1620. let iface = iface_builder
  1621. .finalize();
  1622. (iface, SocketSet::new(vec![]))
  1623. }
  1624. #[cfg(feature = "proto-igmp")]
  1625. fn recv_all<'b>(iface: &mut EthernetInterface<'static, 'b, 'static, Loopback>, timestamp: Instant) -> Vec<Vec<u8>> {
  1626. let mut pkts = Vec::new();
  1627. while let Some((rx, _tx)) = iface.device.receive() {
  1628. rx.consume(timestamp, |pkt| {
  1629. pkts.push(pkt.iter().cloned().collect());
  1630. Ok(())
  1631. }).unwrap();
  1632. }
  1633. pkts
  1634. }
  1635. #[derive(Debug, PartialEq)]
  1636. struct MockTxToken;
  1637. impl phy::TxToken for MockTxToken {
  1638. fn consume<R, F>(self, _: Instant, _: usize, _: F) -> Result<R>
  1639. where F: FnOnce(&mut [u8]) -> Result<R> {
  1640. Err(Error::__Nonexhaustive)
  1641. }
  1642. }
  1643. #[test]
  1644. #[should_panic(expected = "a required option was not set")]
  1645. fn test_builder_initialization_panic() {
  1646. InterfaceBuilder::new(Loopback::new()).finalize();
  1647. }
  1648. #[test]
  1649. fn test_no_icmp_no_unicast() {
  1650. let (mut iface, mut socket_set) = create_loopback();
  1651. let mut eth_bytes = vec![0u8; 54];
  1652. // Unknown Ipv4 Protocol
  1653. //
  1654. // Because the destination is the broadcast address
  1655. // this should not trigger and Destination Unreachable
  1656. // response. See RFC 1122 § 3.2.2.
  1657. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1658. let repr = IpRepr::Ipv4(Ipv4Repr {
  1659. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1660. dst_addr: Ipv4Address::BROADCAST,
  1661. protocol: IpProtocol::Unknown(0x0c),
  1662. payload_len: 0,
  1663. hop_limit: 0x40
  1664. });
  1665. #[cfg(feature = "proto-ipv6")]
  1666. let repr = IpRepr::Ipv6(Ipv6Repr {
  1667. src_addr: Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1),
  1668. dst_addr: Ipv6Address::LINK_LOCAL_ALL_NODES,
  1669. next_header: IpProtocol::Unknown(0x0c),
  1670. payload_len: 0,
  1671. hop_limit: 0x40
  1672. });
  1673. let frame = {
  1674. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  1675. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1676. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1677. frame.set_ethertype(EthernetProtocol::Ipv4);
  1678. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1679. EthernetFrame::new_unchecked(&*frame.into_inner())
  1680. };
  1681. // Ensure that the unknown protocol frame does not trigger an
  1682. // ICMP error response when the destination address is a
  1683. // broadcast address
  1684. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1685. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  1686. Ok(Packet::None));
  1687. #[cfg(feature = "proto-ipv6")]
  1688. assert_eq!(iface.inner.process_ipv6(&mut socket_set, Instant::from_millis(0), &frame),
  1689. Ok(Packet::None));
  1690. }
  1691. #[test]
  1692. #[cfg(feature = "proto-ipv4")]
  1693. fn test_icmp_error_no_payload() {
  1694. static NO_BYTES: [u8; 0] = [];
  1695. let (mut iface, mut socket_set) = create_loopback();
  1696. let mut eth_bytes = vec![0u8; 34];
  1697. // Unknown Ipv4 Protocol with no payload
  1698. let repr = IpRepr::Ipv4(Ipv4Repr {
  1699. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1700. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1701. protocol: IpProtocol::Unknown(0x0c),
  1702. payload_len: 0,
  1703. hop_limit: 0x40
  1704. });
  1705. // emit the above repr to a frame
  1706. let frame = {
  1707. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  1708. frame.set_dst_addr(EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  1709. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1710. frame.set_ethertype(EthernetProtocol::Ipv4);
  1711. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1712. EthernetFrame::new_unchecked(&*frame.into_inner())
  1713. };
  1714. // The expected Destination Unreachable response due to the
  1715. // unknown protocol
  1716. let icmp_repr = Icmpv4Repr::DstUnreachable {
  1717. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  1718. header: Ipv4Repr {
  1719. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1720. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1721. protocol: IpProtocol::Unknown(12),
  1722. payload_len: 0,
  1723. hop_limit: 64
  1724. },
  1725. data: &NO_BYTES
  1726. };
  1727. let expected_repr = Packet::Icmpv4((
  1728. Ipv4Repr {
  1729. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1730. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1731. protocol: IpProtocol::Icmp,
  1732. payload_len: icmp_repr.buffer_len(),
  1733. hop_limit: 64
  1734. },
  1735. icmp_repr
  1736. ));
  1737. // Ensure that the unknown protocol triggers an error response.
  1738. // And we correctly handle no payload.
  1739. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  1740. Ok(expected_repr));
  1741. }
  1742. #[test]
  1743. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1744. fn test_icmp_error_port_unreachable() {
  1745. static UDP_PAYLOAD: [u8; 12] = [
  1746. 0x48, 0x65, 0x6c, 0x6c,
  1747. 0x6f, 0x2c, 0x20, 0x57,
  1748. 0x6f, 0x6c, 0x64, 0x21
  1749. ];
  1750. let (iface, mut socket_set) = create_loopback();
  1751. let mut udp_bytes_unicast = vec![0u8; 20];
  1752. let mut udp_bytes_broadcast = vec![0u8; 20];
  1753. let mut packet_unicast = UdpPacket::new_unchecked(&mut udp_bytes_unicast);
  1754. let mut packet_broadcast = UdpPacket::new_unchecked(&mut udp_bytes_broadcast);
  1755. let udp_repr = UdpRepr {
  1756. src_port: 67,
  1757. dst_port: 68,
  1758. payload: &UDP_PAYLOAD
  1759. };
  1760. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1761. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1762. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1763. protocol: IpProtocol::Udp,
  1764. payload_len: udp_repr.buffer_len(),
  1765. hop_limit: 64
  1766. });
  1767. // Emit the representations to a packet
  1768. udp_repr.emit(&mut packet_unicast, &ip_repr.src_addr(),
  1769. &ip_repr.dst_addr(), &ChecksumCapabilities::default());
  1770. let data = packet_unicast.into_inner();
  1771. // The expected Destination Unreachable ICMPv4 error response due
  1772. // to no sockets listening on the destination port.
  1773. let icmp_repr = Icmpv4Repr::DstUnreachable {
  1774. reason: Icmpv4DstUnreachable::PortUnreachable,
  1775. header: Ipv4Repr {
  1776. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1777. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1778. protocol: IpProtocol::Udp,
  1779. payload_len: udp_repr.buffer_len(),
  1780. hop_limit: 64
  1781. },
  1782. data: &data
  1783. };
  1784. let expected_repr = Packet::Icmpv4((
  1785. Ipv4Repr {
  1786. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1787. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1788. protocol: IpProtocol::Icmp,
  1789. payload_len: icmp_repr.buffer_len(),
  1790. hop_limit: 64
  1791. },
  1792. icmp_repr
  1793. ));
  1794. // Ensure that the unknown protocol triggers an error response.
  1795. // And we correctly handle no payload.
  1796. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, false, data),
  1797. Ok(expected_repr));
  1798. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1799. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1800. dst_addr: Ipv4Address::BROADCAST,
  1801. protocol: IpProtocol::Udp,
  1802. payload_len: udp_repr.buffer_len(),
  1803. hop_limit: 64
  1804. });
  1805. // Emit the representations to a packet
  1806. udp_repr.emit(&mut packet_broadcast, &ip_repr.src_addr(),
  1807. &IpAddress::Ipv4(Ipv4Address::BROADCAST),
  1808. &ChecksumCapabilities::default());
  1809. // Ensure that the port unreachable error does not trigger an
  1810. // ICMP error response when the destination address is a
  1811. // broadcast address and no socket is bound to the port.
  1812. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr,
  1813. false, packet_broadcast.into_inner()), Ok(Packet::None));
  1814. }
  1815. #[test]
  1816. #[cfg(feature = "socket-udp")]
  1817. fn test_handle_udp_broadcast() {
  1818. use socket::{UdpSocket, UdpSocketBuffer, UdpPacketMetadata};
  1819. use wire::IpEndpoint;
  1820. static UDP_PAYLOAD: [u8; 5] = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
  1821. let (iface, mut socket_set) = create_loopback();
  1822. let rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  1823. let tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  1824. let udp_socket = UdpSocket::new(rx_buffer, tx_buffer);
  1825. let mut udp_bytes = vec![0u8; 13];
  1826. let mut packet = UdpPacket::new_unchecked(&mut udp_bytes);
  1827. let socket_handle = socket_set.add(udp_socket);
  1828. #[cfg(feature = "proto-ipv6")]
  1829. let src_ip = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  1830. #[cfg(all(not(feature = "proto-ipv6"), feature = "proto-ipv4"))]
  1831. let src_ip = Ipv4Address::new(0x7f, 0x00, 0x00, 0x02);
  1832. let udp_repr = UdpRepr {
  1833. src_port: 67,
  1834. dst_port: 68,
  1835. payload: &UDP_PAYLOAD
  1836. };
  1837. #[cfg(feature = "proto-ipv6")]
  1838. let ip_repr = IpRepr::Ipv6(Ipv6Repr {
  1839. src_addr: src_ip,
  1840. dst_addr: Ipv6Address::LINK_LOCAL_ALL_NODES,
  1841. next_header: IpProtocol::Udp,
  1842. payload_len: udp_repr.buffer_len(),
  1843. hop_limit: 0x40
  1844. });
  1845. #[cfg(all(not(feature = "proto-ipv6"), feature = "proto-ipv4"))]
  1846. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1847. src_addr: src_ip,
  1848. dst_addr: Ipv4Address::BROADCAST,
  1849. protocol: IpProtocol::Udp,
  1850. payload_len: udp_repr.buffer_len(),
  1851. hop_limit: 0x40
  1852. });
  1853. {
  1854. // Bind the socket to port 68
  1855. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1856. assert_eq!(socket.bind(68), Ok(()));
  1857. assert!(!socket.can_recv());
  1858. assert!(socket.can_send());
  1859. }
  1860. udp_repr.emit(&mut packet, &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1861. &ChecksumCapabilities::default());
  1862. // Packet should be handled by bound UDP socket
  1863. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, false, packet.into_inner()),
  1864. Ok(Packet::None));
  1865. {
  1866. // Make sure the payload to the UDP packet processed by process_udp is
  1867. // appended to the bound sockets rx_buffer
  1868. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1869. assert!(socket.can_recv());
  1870. assert_eq!(socket.recv(), Ok((&UDP_PAYLOAD[..], IpEndpoint::new(src_ip.into(), 67))));
  1871. }
  1872. }
  1873. #[test]
  1874. #[cfg(feature = "proto-ipv4")]
  1875. fn test_handle_ipv4_broadcast() {
  1876. use wire::{Ipv4Packet, Icmpv4Repr, Icmpv4Packet};
  1877. let (mut iface, mut socket_set) = create_loopback();
  1878. let our_ipv4_addr = iface.ipv4_address().unwrap();
  1879. let src_ipv4_addr = Ipv4Address([127, 0, 0, 2]);
  1880. // ICMPv4 echo request
  1881. let icmpv4_data: [u8; 4] = [0xaa, 0x00, 0x00, 0xff];
  1882. let icmpv4_repr = Icmpv4Repr::EchoRequest {
  1883. ident: 0x1234, seq_no: 0xabcd, data: &icmpv4_data
  1884. };
  1885. // Send to IPv4 broadcast address
  1886. let ipv4_repr = Ipv4Repr {
  1887. src_addr: src_ipv4_addr,
  1888. dst_addr: Ipv4Address::BROADCAST,
  1889. protocol: IpProtocol::Icmp,
  1890. hop_limit: 64,
  1891. payload_len: icmpv4_repr.buffer_len(),
  1892. };
  1893. // Emit to ethernet frame
  1894. let mut eth_bytes = vec![0u8;
  1895. EthernetFrame::<&[u8]>::header_len() +
  1896. ipv4_repr.buffer_len() + icmpv4_repr.buffer_len()
  1897. ];
  1898. let frame = {
  1899. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  1900. ipv4_repr.emit(
  1901. &mut Ipv4Packet::new_unchecked(frame.payload_mut()),
  1902. &ChecksumCapabilities::default());
  1903. icmpv4_repr.emit(
  1904. &mut Icmpv4Packet::new_unchecked(
  1905. &mut frame.payload_mut()[ipv4_repr.buffer_len()..]),
  1906. &ChecksumCapabilities::default());
  1907. EthernetFrame::new_unchecked(&*frame.into_inner())
  1908. };
  1909. // Expected ICMPv4 echo reply
  1910. let expected_icmpv4_repr = Icmpv4Repr::EchoReply {
  1911. ident: 0x1234, seq_no: 0xabcd, data: &icmpv4_data };
  1912. let expected_ipv4_repr = Ipv4Repr {
  1913. src_addr: our_ipv4_addr,
  1914. dst_addr: src_ipv4_addr,
  1915. protocol: IpProtocol::Icmp,
  1916. hop_limit: 64,
  1917. payload_len: expected_icmpv4_repr.buffer_len(),
  1918. };
  1919. let expected_packet = Packet::Icmpv4((expected_ipv4_repr, expected_icmpv4_repr));
  1920. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  1921. Ok(expected_packet));
  1922. }
  1923. #[test]
  1924. #[cfg(feature = "socket-udp")]
  1925. fn test_icmp_reply_size() {
  1926. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1927. use wire::IPV4_MIN_MTU as MIN_MTU;
  1928. #[cfg(feature = "proto-ipv6")]
  1929. use wire::Icmpv6DstUnreachable;
  1930. #[cfg(feature = "proto-ipv6")]
  1931. use wire::IPV6_MIN_MTU as MIN_MTU;
  1932. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1933. const MAX_PAYLOAD_LEN: usize = 528;
  1934. #[cfg(feature = "proto-ipv6")]
  1935. const MAX_PAYLOAD_LEN: usize = 1192;
  1936. let (iface, mut socket_set) = create_loopback();
  1937. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1938. let src_addr = Ipv4Address([192, 168, 1, 1]);
  1939. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1940. let dst_addr = Ipv4Address([192, 168, 1, 2]);
  1941. #[cfg(feature = "proto-ipv6")]
  1942. let src_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  1943. #[cfg(feature = "proto-ipv6")]
  1944. let dst_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
  1945. // UDP packet that if not tructated will cause a icmp port unreachable reply
  1946. // to exeed the minimum mtu bytes in length.
  1947. let udp_repr = UdpRepr {
  1948. src_port: 67,
  1949. dst_port: 68,
  1950. payload: &[0x2a; MAX_PAYLOAD_LEN]
  1951. };
  1952. let mut bytes = vec![0xff; udp_repr.buffer_len()];
  1953. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  1954. udp_repr.emit(&mut packet, &src_addr.into(), &dst_addr.into(), &ChecksumCapabilities::default());
  1955. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1956. let ip_repr = Ipv4Repr {
  1957. src_addr: src_addr,
  1958. dst_addr: dst_addr,
  1959. protocol: IpProtocol::Udp,
  1960. hop_limit: 64,
  1961. payload_len: udp_repr.buffer_len()
  1962. };
  1963. #[cfg(feature = "proto-ipv6")]
  1964. let ip_repr = Ipv6Repr {
  1965. src_addr: src_addr,
  1966. dst_addr: dst_addr,
  1967. next_header: IpProtocol::Udp,
  1968. hop_limit: 64,
  1969. payload_len: udp_repr.buffer_len()
  1970. };
  1971. let payload = packet.into_inner();
  1972. // Expected packets
  1973. #[cfg(feature = "proto-ipv6")]
  1974. let expected_icmp_repr = Icmpv6Repr::DstUnreachable {
  1975. reason: Icmpv6DstUnreachable::PortUnreachable,
  1976. header: ip_repr,
  1977. data: &payload[..MAX_PAYLOAD_LEN]
  1978. };
  1979. #[cfg(feature = "proto-ipv6")]
  1980. let expected_ip_repr = Ipv6Repr {
  1981. src_addr: dst_addr,
  1982. dst_addr: src_addr,
  1983. next_header: IpProtocol::Icmpv6,
  1984. hop_limit: 64,
  1985. payload_len: expected_icmp_repr.buffer_len()
  1986. };
  1987. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1988. let expected_icmp_repr = Icmpv4Repr::DstUnreachable {
  1989. reason: Icmpv4DstUnreachable::PortUnreachable,
  1990. header: ip_repr,
  1991. data: &payload[..MAX_PAYLOAD_LEN]
  1992. };
  1993. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1994. let expected_ip_repr = Ipv4Repr {
  1995. src_addr: dst_addr,
  1996. dst_addr: src_addr,
  1997. protocol: IpProtocol::Icmp,
  1998. hop_limit: 64,
  1999. payload_len: expected_icmp_repr.buffer_len()
  2000. };
  2001. // The expected packet does not exceed the IPV4_MIN_MTU
  2002. assert_eq!(expected_ip_repr.buffer_len() + expected_icmp_repr.buffer_len(), MIN_MTU);
  2003. // The expected packet and the generated packet are equal
  2004. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2005. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr.into(), false, payload),
  2006. Ok(Packet::Icmpv4((expected_ip_repr, expected_icmp_repr))));
  2007. #[cfg(feature = "proto-ipv6")]
  2008. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr.into(), false, payload),
  2009. Ok(Packet::Icmpv6((expected_ip_repr, expected_icmp_repr))));
  2010. }
  2011. #[test]
  2012. #[cfg(feature = "proto-ipv4")]
  2013. fn test_handle_valid_arp_request() {
  2014. let (mut iface, mut socket_set) = create_loopback();
  2015. let mut eth_bytes = vec![0u8; 42];
  2016. let local_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x01]);
  2017. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  2018. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  2019. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  2020. let repr = ArpRepr::EthernetIpv4 {
  2021. operation: ArpOperation::Request,
  2022. source_hardware_addr: remote_hw_addr,
  2023. source_protocol_addr: remote_ip_addr,
  2024. target_hardware_addr: EthernetAddress::default(),
  2025. target_protocol_addr: local_ip_addr,
  2026. };
  2027. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2028. frame.set_dst_addr(EthernetAddress::BROADCAST);
  2029. frame.set_src_addr(remote_hw_addr);
  2030. frame.set_ethertype(EthernetProtocol::Arp);
  2031. {
  2032. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  2033. repr.emit(&mut packet);
  2034. }
  2035. // Ensure an ARP Request for us triggers an ARP Reply
  2036. assert_eq!(iface.inner.process_ethernet(&mut socket_set, Instant::from_millis(0), frame.into_inner()),
  2037. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  2038. operation: ArpOperation::Reply,
  2039. source_hardware_addr: local_hw_addr,
  2040. source_protocol_addr: local_ip_addr,
  2041. target_hardware_addr: remote_hw_addr,
  2042. target_protocol_addr: remote_ip_addr
  2043. })));
  2044. // Ensure the address of the requestor was entered in the cache
  2045. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  2046. &IpAddress::Ipv4(local_ip_addr), &IpAddress::Ipv4(remote_ip_addr)),
  2047. Ok((remote_hw_addr, MockTxToken)));
  2048. }
  2049. #[test]
  2050. #[cfg(feature = "proto-ipv6")]
  2051. fn test_handle_valid_ndisc_request() {
  2052. let (mut iface, mut socket_set) = create_loopback();
  2053. let mut eth_bytes = vec![0u8; 86];
  2054. let local_ip_addr = Ipv6Address::new(0xfdbe, 0, 0, 0, 0, 0, 0, 1);
  2055. let remote_ip_addr = Ipv6Address::new(0xfdbe, 0, 0, 0, 0, 0, 0, 2);
  2056. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  2057. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  2058. let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit {
  2059. target_addr: local_ip_addr,
  2060. lladdr: Some(remote_hw_addr),
  2061. });
  2062. let ip_repr = IpRepr::Ipv6(Ipv6Repr {
  2063. src_addr: remote_ip_addr,
  2064. dst_addr: local_ip_addr.solicited_node(),
  2065. next_header: IpProtocol::Icmpv6,
  2066. hop_limit: 0xff,
  2067. payload_len: solicit.buffer_len()
  2068. });
  2069. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2070. frame.set_dst_addr(EthernetAddress([0x33, 0x33, 0x00, 0x00, 0x00, 0x00]));
  2071. frame.set_src_addr(remote_hw_addr);
  2072. frame.set_ethertype(EthernetProtocol::Ipv6);
  2073. {
  2074. ip_repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  2075. solicit.emit(&remote_ip_addr.into(), &local_ip_addr.solicited_node().into(),
  2076. &mut Icmpv6Packet::new_unchecked(
  2077. &mut frame.payload_mut()[ip_repr.buffer_len()..]),
  2078. &ChecksumCapabilities::default());
  2079. }
  2080. let icmpv6_expected = Icmpv6Repr::Ndisc(NdiscRepr::NeighborAdvert {
  2081. flags: NdiscNeighborFlags::SOLICITED,
  2082. target_addr: local_ip_addr,
  2083. lladdr: Some(local_hw_addr)
  2084. });
  2085. let ipv6_expected = Ipv6Repr {
  2086. src_addr: local_ip_addr,
  2087. dst_addr: remote_ip_addr,
  2088. next_header: IpProtocol::Icmpv6,
  2089. hop_limit: 0xff,
  2090. payload_len: icmpv6_expected.buffer_len()
  2091. };
  2092. // Ensure an Neighbor Solicitation triggers a Neighbor Advertisement
  2093. assert_eq!(iface.inner.process_ethernet(&mut socket_set, Instant::from_millis(0), frame.into_inner()),
  2094. Ok(Packet::Icmpv6((ipv6_expected, icmpv6_expected))));
  2095. // Ensure the address of the requestor was entered in the cache
  2096. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  2097. &IpAddress::Ipv6(local_ip_addr), &IpAddress::Ipv6(remote_ip_addr)),
  2098. Ok((remote_hw_addr, MockTxToken)));
  2099. }
  2100. #[test]
  2101. #[cfg(feature = "proto-ipv4")]
  2102. fn test_handle_other_arp_request() {
  2103. let (mut iface, mut socket_set) = create_loopback();
  2104. let mut eth_bytes = vec![0u8; 42];
  2105. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  2106. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  2107. let repr = ArpRepr::EthernetIpv4 {
  2108. operation: ArpOperation::Request,
  2109. source_hardware_addr: remote_hw_addr,
  2110. source_protocol_addr: remote_ip_addr,
  2111. target_hardware_addr: EthernetAddress::default(),
  2112. target_protocol_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x03]),
  2113. };
  2114. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2115. frame.set_dst_addr(EthernetAddress::BROADCAST);
  2116. frame.set_src_addr(remote_hw_addr);
  2117. frame.set_ethertype(EthernetProtocol::Arp);
  2118. {
  2119. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  2120. repr.emit(&mut packet);
  2121. }
  2122. // Ensure an ARP Request for someone else does not trigger an ARP Reply
  2123. assert_eq!(iface.inner.process_ethernet(&mut socket_set, Instant::from_millis(0), frame.into_inner()),
  2124. Ok(Packet::None));
  2125. // Ensure the address of the requestor was entered in the cache
  2126. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  2127. &IpAddress::Ipv4(Ipv4Address([0x7f, 0x00, 0x00, 0x01])),
  2128. &IpAddress::Ipv4(remote_ip_addr)),
  2129. Ok((remote_hw_addr, MockTxToken)));
  2130. }
  2131. #[test]
  2132. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  2133. fn test_icmpv4_socket() {
  2134. use socket::{IcmpSocket, IcmpEndpoint, IcmpSocketBuffer, IcmpPacketMetadata};
  2135. use wire::Icmpv4Packet;
  2136. let (iface, mut socket_set) = create_loopback();
  2137. let rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 24]);
  2138. let tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 24]);
  2139. let icmpv4_socket = IcmpSocket::new(rx_buffer, tx_buffer);
  2140. let socket_handle = socket_set.add(icmpv4_socket);
  2141. let ident = 0x1234;
  2142. let seq_no = 0x5432;
  2143. let echo_data = &[0xff; 16];
  2144. {
  2145. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  2146. // Bind to the ID 0x1234
  2147. assert_eq!(socket.bind(IcmpEndpoint::Ident(ident)), Ok(()));
  2148. }
  2149. // Ensure the ident we bound to and the ident of the packet are the same.
  2150. let mut bytes = [0xff; 24];
  2151. let mut packet = Icmpv4Packet::new_unchecked(&mut bytes);
  2152. let echo_repr = Icmpv4Repr::EchoRequest{ ident, seq_no, data: echo_data };
  2153. echo_repr.emit(&mut packet, &ChecksumCapabilities::default());
  2154. let icmp_data = &packet.into_inner()[..];
  2155. let ipv4_repr = Ipv4Repr {
  2156. src_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x02),
  2157. dst_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x01),
  2158. protocol: IpProtocol::Icmp,
  2159. payload_len: 24,
  2160. hop_limit: 64
  2161. };
  2162. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  2163. // Open a socket and ensure the packet is handled due to the listening
  2164. // socket.
  2165. {
  2166. assert!(!socket_set.get::<IcmpSocket>(socket_handle).can_recv());
  2167. }
  2168. // Confirm we still get EchoReply from `smoltcp` even with the ICMP socket listening
  2169. let echo_reply = Icmpv4Repr::EchoReply{ ident, seq_no, data: echo_data };
  2170. let ipv4_reply = Ipv4Repr {
  2171. src_addr: ipv4_repr.dst_addr,
  2172. dst_addr: ipv4_repr.src_addr,
  2173. ..ipv4_repr
  2174. };
  2175. assert_eq!(iface.inner.process_icmpv4(&mut socket_set, ip_repr, icmp_data),
  2176. Ok(Packet::Icmpv4((ipv4_reply, echo_reply))));
  2177. {
  2178. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  2179. assert!(socket.can_recv());
  2180. assert_eq!(socket.recv(),
  2181. Ok((&icmp_data[..],
  2182. IpAddress::Ipv4(Ipv4Address::new(0x7f, 0x00, 0x00, 0x02)))));
  2183. }
  2184. }
  2185. #[test]
  2186. #[cfg(feature = "proto-ipv6")]
  2187. fn test_solicited_node_addrs() {
  2188. let (mut iface, _) = create_loopback();
  2189. let mut new_addrs = vec![IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 1, 2, 0, 2), 64),
  2190. IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 3, 4, 0, 0xffff), 64)];
  2191. iface.update_ip_addrs(|addrs| {
  2192. new_addrs.extend(addrs.to_vec());
  2193. *addrs = From::from(new_addrs);
  2194. });
  2195. assert!(iface.inner.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0x0002)));
  2196. assert!(iface.inner.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0xffff)));
  2197. assert!(!iface.inner.has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0x0003)));
  2198. }
  2199. #[test]
  2200. #[cfg(feature = "proto-ipv6")]
  2201. fn test_icmpv6_nxthdr_unknown() {
  2202. let (mut iface, mut socket_set) = create_loopback();
  2203. let remote_ip_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  2204. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x01]);
  2205. let mut eth_bytes = vec![0; 66];
  2206. let payload = [0x12, 0x34, 0x56, 0x78];
  2207. let ipv6_repr = Ipv6Repr {
  2208. src_addr: remote_ip_addr,
  2209. dst_addr: Ipv6Address::LOOPBACK,
  2210. next_header: IpProtocol::HopByHop,
  2211. payload_len: 12,
  2212. hop_limit: 0x40,
  2213. };
  2214. let frame = {
  2215. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2216. let ip_repr = IpRepr::Ipv6(ipv6_repr);
  2217. frame.set_dst_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  2218. frame.set_src_addr(remote_hw_addr);
  2219. frame.set_ethertype(EthernetProtocol::Ipv6);
  2220. ip_repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  2221. let mut offset = ipv6_repr.buffer_len();
  2222. {
  2223. let mut hbh_pkt =
  2224. Ipv6HopByHopHeader::new_unchecked(&mut frame.payload_mut()[offset..]);
  2225. hbh_pkt.set_next_header(IpProtocol::Unknown(0x0c));
  2226. hbh_pkt.set_header_len(0);
  2227. offset += 8;
  2228. {
  2229. let mut pad_pkt = Ipv6Option::new_unchecked(&mut hbh_pkt.options_mut()[..]);
  2230. Ipv6OptionRepr::PadN(3).emit(&mut pad_pkt);
  2231. }
  2232. {
  2233. let mut pad_pkt = Ipv6Option::new_unchecked(&mut hbh_pkt.options_mut()[5..]);
  2234. Ipv6OptionRepr::Pad1.emit(&mut pad_pkt);
  2235. }
  2236. }
  2237. frame.payload_mut()[offset..].copy_from_slice(&payload);
  2238. EthernetFrame::new_unchecked(&*frame.into_inner())
  2239. };
  2240. let reply_icmp_repr = Icmpv6Repr::ParamProblem {
  2241. reason: Icmpv6ParamProblem::UnrecognizedNxtHdr,
  2242. pointer: 40,
  2243. header: ipv6_repr,
  2244. data: &payload[..]
  2245. };
  2246. let reply_ipv6_repr = Ipv6Repr {
  2247. src_addr: Ipv6Address::LOOPBACK,
  2248. dst_addr: remote_ip_addr,
  2249. next_header: IpProtocol::Icmpv6,
  2250. payload_len: reply_icmp_repr.buffer_len(),
  2251. hop_limit: 0x40,
  2252. };
  2253. // Ensure the unknown next header causes a ICMPv6 Parameter Problem
  2254. // error message to be sent to the sender.
  2255. assert_eq!(iface.inner.process_ipv6(&mut socket_set, Instant::from_millis(0), &frame),
  2256. Ok(Packet::Icmpv6((reply_ipv6_repr, reply_icmp_repr))));
  2257. // Ensure the address of the requestor was entered in the cache
  2258. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, Instant::from_secs(0),
  2259. &IpAddress::Ipv6(Ipv6Address::LOOPBACK),
  2260. &IpAddress::Ipv6(remote_ip_addr)),
  2261. Ok((remote_hw_addr, MockTxToken)));
  2262. }
  2263. #[test]
  2264. #[cfg(feature = "proto-igmp")]
  2265. fn test_handle_igmp() {
  2266. fn recv_igmp<'b>(mut iface: &mut EthernetInterface<'static, 'b, 'static, Loopback>, timestamp: Instant) -> Vec<(Ipv4Repr, IgmpRepr)> {
  2267. let checksum_caps = &iface.device.capabilities().checksum;
  2268. recv_all(&mut iface, timestamp)
  2269. .iter()
  2270. .filter_map(|frame| {
  2271. let eth_frame = EthernetFrame::new_checked(frame).ok()?;
  2272. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload()).ok()?;
  2273. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &checksum_caps).ok()?;
  2274. let ip_payload = ipv4_packet.payload();
  2275. let igmp_packet = IgmpPacket::new_checked(ip_payload).ok()?;
  2276. let igmp_repr = IgmpRepr::parse(&igmp_packet).ok()?;
  2277. Some((ipv4_repr, igmp_repr))
  2278. })
  2279. .collect::<Vec<_>>()
  2280. }
  2281. let groups = [
  2282. Ipv4Address::new(224, 0, 0, 22),
  2283. Ipv4Address::new(224, 0, 0, 56),
  2284. ];
  2285. let (mut iface, mut socket_set) = create_loopback();
  2286. // Join multicast groups
  2287. let timestamp = Instant::now();
  2288. for group in &groups {
  2289. iface.join_multicast_group(*group, timestamp)
  2290. .unwrap();
  2291. }
  2292. let reports = recv_igmp(&mut iface, timestamp);
  2293. assert_eq!(reports.len(), 2);
  2294. for (i, group_addr) in groups.iter().enumerate() {
  2295. assert_eq!(reports[i].0.protocol, IpProtocol::Igmp);
  2296. assert_eq!(reports[i].0.dst_addr, *group_addr);
  2297. assert_eq!(reports[i].1, IgmpRepr::MembershipReport {
  2298. group_addr: *group_addr,
  2299. version: IgmpVersion::Version2,
  2300. });
  2301. }
  2302. // General query
  2303. let timestamp = Instant::now();
  2304. const GENERAL_QUERY_BYTES: &[u8] = &[
  2305. 0x01, 0x00, 0x5e, 0x00, 0x00, 0x01, 0x0a, 0x14,
  2306. 0x48, 0x01, 0x21, 0x01, 0x08, 0x00, 0x46, 0xc0,
  2307. 0x00, 0x24, 0xed, 0xb4, 0x00, 0x00, 0x01, 0x02,
  2308. 0x47, 0x43, 0xac, 0x16, 0x63, 0x04, 0xe0, 0x00,
  2309. 0x00, 0x01, 0x94, 0x04, 0x00, 0x00, 0x11, 0x64,
  2310. 0xec, 0x8f, 0x00, 0x00, 0x00, 0x00, 0x02, 0x0c,
  2311. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  2312. 0x00, 0x00, 0x00, 0x00
  2313. ];
  2314. {
  2315. // Transmit GENERAL_QUERY_BYTES into loopback
  2316. let tx_token = iface.device.transmit().unwrap();
  2317. tx_token.consume(
  2318. timestamp, GENERAL_QUERY_BYTES.len(),
  2319. |buffer| {
  2320. buffer.copy_from_slice(GENERAL_QUERY_BYTES);
  2321. Ok(())
  2322. }).unwrap();
  2323. }
  2324. // Trigger processing until all packets received through the
  2325. // loopback have been processed, including responses to
  2326. // GENERAL_QUERY_BYTES. Therefore `recv_all()` would return 0
  2327. // pkts that could be checked.
  2328. iface.socket_ingress(&mut socket_set, timestamp).unwrap();
  2329. // Leave multicast groups
  2330. let timestamp = Instant::now();
  2331. for group in &groups {
  2332. iface.leave_multicast_group(group.clone(), timestamp)
  2333. .unwrap();
  2334. }
  2335. let leaves = recv_igmp(&mut iface, timestamp);
  2336. assert_eq!(leaves.len(), 2);
  2337. for (i, group_addr) in groups.iter().cloned().enumerate() {
  2338. assert_eq!(leaves[i].0.protocol, IpProtocol::Igmp);
  2339. assert_eq!(leaves[i].0.dst_addr, Ipv4Address::MULTICAST_ALL_ROUTERS);
  2340. assert_eq!(leaves[i].1, IgmpRepr::LeaveGroup { group_addr });
  2341. }
  2342. }
  2343. #[test]
  2344. #[cfg(all(feature = "proto-ipv4", feature = "socket-raw"))]
  2345. fn test_raw_socket_no_reply() {
  2346. use socket::{RawSocket, RawSocketBuffer, RawPacketMetadata};
  2347. use wire::{IpVersion, Ipv4Packet, UdpPacket, UdpRepr};
  2348. let (mut iface, mut socket_set) = create_loopback();
  2349. let packets = 1;
  2350. let rx_buffer = RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * 1]);
  2351. let tx_buffer = RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * packets]);
  2352. let raw_socket = RawSocket::new(IpVersion::Ipv4, IpProtocol::Udp, rx_buffer, tx_buffer);
  2353. socket_set.add(raw_socket);
  2354. let src_addr = Ipv4Address([127, 0, 0, 2]);
  2355. let dst_addr = Ipv4Address([127, 0, 0, 1]);
  2356. let udp_repr = UdpRepr {
  2357. src_port: 67,
  2358. dst_port: 68,
  2359. payload: &[0x2a; 10]
  2360. };
  2361. let mut bytes = vec![0xff; udp_repr.buffer_len()];
  2362. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  2363. udp_repr.emit(&mut packet, &src_addr.into(), &dst_addr.into(), &ChecksumCapabilities::default());
  2364. let ipv4_repr = Ipv4Repr {
  2365. src_addr: src_addr,
  2366. dst_addr: dst_addr,
  2367. protocol: IpProtocol::Udp,
  2368. hop_limit: 64,
  2369. payload_len: udp_repr.buffer_len()
  2370. };
  2371. // Emit to ethernet frame
  2372. let mut eth_bytes = vec![0u8;
  2373. EthernetFrame::<&[u8]>::header_len() +
  2374. ipv4_repr.buffer_len() + udp_repr.buffer_len()
  2375. ];
  2376. let frame = {
  2377. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2378. ipv4_repr.emit(
  2379. &mut Ipv4Packet::new_unchecked(frame.payload_mut()),
  2380. &ChecksumCapabilities::default());
  2381. udp_repr.emit(
  2382. &mut UdpPacket::new_unchecked(
  2383. &mut frame.payload_mut()[ipv4_repr.buffer_len()..]),
  2384. &src_addr.into(),
  2385. &dst_addr.into(),
  2386. &ChecksumCapabilities::default());
  2387. EthernetFrame::new_unchecked(&*frame.into_inner())
  2388. };
  2389. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  2390. Ok(Packet::None));
  2391. }
  2392. #[test]
  2393. #[cfg(all(feature = "proto-ipv4", feature = "socket-raw"))]
  2394. fn test_raw_socket_truncated_packet() {
  2395. use socket::{RawSocket, RawSocketBuffer, RawPacketMetadata};
  2396. use wire::{IpVersion, Ipv4Packet, UdpPacket, UdpRepr};
  2397. let (mut iface, mut socket_set) = create_loopback();
  2398. let packets = 1;
  2399. let rx_buffer = RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * 1]);
  2400. let tx_buffer = RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * packets]);
  2401. let raw_socket = RawSocket::new(IpVersion::Ipv4, IpProtocol::Udp, rx_buffer, tx_buffer);
  2402. socket_set.add(raw_socket);
  2403. let src_addr = Ipv4Address([127, 0, 0, 2]);
  2404. let dst_addr = Ipv4Address([127, 0, 0, 1]);
  2405. let udp_repr = UdpRepr {
  2406. src_port: 67,
  2407. dst_port: 68,
  2408. payload: &[0x2a; 49] // 49 > 48, hence packet will be truncated
  2409. };
  2410. let mut bytes = vec![0xff; udp_repr.buffer_len()];
  2411. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  2412. udp_repr.emit(&mut packet, &src_addr.into(), &dst_addr.into(), &ChecksumCapabilities::default());
  2413. let ipv4_repr = Ipv4Repr {
  2414. src_addr: src_addr,
  2415. dst_addr: dst_addr,
  2416. protocol: IpProtocol::Udp,
  2417. hop_limit: 64,
  2418. payload_len: udp_repr.buffer_len()
  2419. };
  2420. // Emit to ethernet frame
  2421. let mut eth_bytes = vec![0u8;
  2422. EthernetFrame::<&[u8]>::header_len() +
  2423. ipv4_repr.buffer_len() + udp_repr.buffer_len()
  2424. ];
  2425. let frame = {
  2426. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2427. ipv4_repr.emit(
  2428. &mut Ipv4Packet::new_unchecked(frame.payload_mut()),
  2429. &ChecksumCapabilities::default());
  2430. udp_repr.emit(
  2431. &mut UdpPacket::new_unchecked(
  2432. &mut frame.payload_mut()[ipv4_repr.buffer_len()..]),
  2433. &src_addr.into(),
  2434. &dst_addr.into(),
  2435. &ChecksumCapabilities::default());
  2436. EthernetFrame::new_unchecked(&*frame.into_inner())
  2437. };
  2438. let frame = iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame);
  2439. // because the packet could not be handled we should send an Icmp message
  2440. assert!(match frame {
  2441. Ok(Packet::Icmpv4(_)) => true,
  2442. _ => false,
  2443. });
  2444. }
  2445. #[test]
  2446. #[cfg(all(feature = "proto-ipv4", feature = "socket-raw", feature = "socket-udp"))]
  2447. fn test_raw_socket_with_udp_socket() {
  2448. use socket::{UdpSocket, UdpSocketBuffer, UdpPacketMetadata,
  2449. RawSocket, RawSocketBuffer, RawPacketMetadata};
  2450. use wire::{IpVersion, IpEndpoint, Ipv4Packet, UdpPacket, UdpRepr};
  2451. static UDP_PAYLOAD: [u8; 5] = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
  2452. let (mut iface, mut socket_set) = create_loopback();
  2453. let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  2454. let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  2455. let udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer);
  2456. let udp_socket_handle = socket_set.add(udp_socket);
  2457. {
  2458. // Bind the socket to port 68
  2459. let mut socket = socket_set.get::<UdpSocket>(udp_socket_handle);
  2460. assert_eq!(socket.bind(68), Ok(()));
  2461. assert!(!socket.can_recv());
  2462. assert!(socket.can_send());
  2463. }
  2464. let packets = 1;
  2465. let raw_rx_buffer = RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * 1]);
  2466. let raw_tx_buffer = RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * packets]);
  2467. let raw_socket = RawSocket::new(IpVersion::Ipv4, IpProtocol::Udp, raw_rx_buffer, raw_tx_buffer);
  2468. socket_set.add(raw_socket);
  2469. let src_addr = Ipv4Address([127, 0, 0, 2]);
  2470. let dst_addr = Ipv4Address([127, 0, 0, 1]);
  2471. let udp_repr = UdpRepr {
  2472. src_port: 67,
  2473. dst_port: 68,
  2474. payload: &UDP_PAYLOAD
  2475. };
  2476. let mut bytes = vec![0xff; udp_repr.buffer_len()];
  2477. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  2478. udp_repr.emit(&mut packet, &src_addr.into(), &dst_addr.into(), &ChecksumCapabilities::default());
  2479. let ipv4_repr = Ipv4Repr {
  2480. src_addr: src_addr,
  2481. dst_addr: dst_addr,
  2482. protocol: IpProtocol::Udp,
  2483. hop_limit: 64,
  2484. payload_len: udp_repr.buffer_len()
  2485. };
  2486. // Emit to ethernet frame
  2487. let mut eth_bytes = vec![0u8;
  2488. EthernetFrame::<&[u8]>::header_len() +
  2489. ipv4_repr.buffer_len() + udp_repr.buffer_len()
  2490. ];
  2491. let frame = {
  2492. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2493. ipv4_repr.emit(
  2494. &mut Ipv4Packet::new_unchecked(frame.payload_mut()),
  2495. &ChecksumCapabilities::default());
  2496. udp_repr.emit(
  2497. &mut UdpPacket::new_unchecked(
  2498. &mut frame.payload_mut()[ipv4_repr.buffer_len()..]),
  2499. &src_addr.into(),
  2500. &dst_addr.into(),
  2501. &ChecksumCapabilities::default());
  2502. EthernetFrame::new_unchecked(&*frame.into_inner())
  2503. };
  2504. assert_eq!(iface.inner.process_ipv4(&mut socket_set, Instant::from_millis(0), &frame),
  2505. Ok(Packet::None));
  2506. {
  2507. // Make sure the UDP socket can still receive in presence of a Raw socket that handles UDP
  2508. let mut socket = socket_set.get::<UdpSocket>(udp_socket_handle);
  2509. assert!(socket.can_recv());
  2510. assert_eq!(socket.recv(), Ok((&UDP_PAYLOAD[..], IpEndpoint::new(src_addr.into(), 67))));
  2511. }
  2512. }
  2513. }