ethernet.rs 115 KB

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