ethernet.rs 115 KB

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