ethernet.rs 113 KB

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