interface.rs 121 KB

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