interface.rs 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880
  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::{ManagedMap, ManagedSlice};
  6. use crate::iface::Routes;
  7. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  8. use crate::iface::{NeighborAnswer, NeighborCache};
  9. use crate::phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken};
  10. use crate::socket::*;
  11. use crate::time::{Duration, Instant};
  12. use crate::wire::*;
  13. use crate::{Error, Result};
  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(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  32. neighbor_cache: Option<NeighborCache<'a>>,
  33. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  34. hardware_addr: Option<HardwareAddress>,
  35. #[cfg(feature = "medium-ieee802154")]
  36. sequence_no: u8,
  37. #[cfg(feature = "medium-ieee802154")]
  38. pan_id: Option<Ieee802154Pan>,
  39. ip_addrs: ManagedSlice<'a, IpCidr>,
  40. #[cfg(feature = "proto-ipv4")]
  41. any_ip: bool,
  42. routes: Routes<'a>,
  43. #[cfg(feature = "proto-igmp")]
  44. ipv4_multicast_groups: ManagedMap<'a, Ipv4Address, ()>,
  45. /// When to report for (all or) the next multicast group membership via IGMP
  46. #[cfg(feature = "proto-igmp")]
  47. igmp_report_state: IgmpReportState,
  48. }
  49. /// A builder structure used for creating a network interface.
  50. pub struct InterfaceBuilder<'a, DeviceT: for<'d> Device<'d>> {
  51. device: DeviceT,
  52. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  53. hardware_addr: Option<HardwareAddress>,
  54. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  55. neighbor_cache: Option<NeighborCache<'a>>,
  56. #[cfg(feature = "medium-ieee802154")]
  57. sequence_no: u8,
  58. #[cfg(feature = "medium-ieee802154")]
  59. pan_id: Option<Ieee802154Pan>,
  60. ip_addrs: ManagedSlice<'a, IpCidr>,
  61. #[cfg(feature = "proto-ipv4")]
  62. any_ip: bool,
  63. routes: Routes<'a>,
  64. /// Does not share storage with `ipv6_multicast_groups` to avoid IPv6 size overhead.
  65. #[cfg(feature = "proto-igmp")]
  66. ipv4_multicast_groups: ManagedMap<'a, Ipv4Address, ()>,
  67. }
  68. impl<'a, DeviceT> InterfaceBuilder<'a, DeviceT>
  69. where
  70. DeviceT: for<'d> Device<'d>,
  71. {
  72. /// Create a builder used for creating a network interface using the
  73. /// given device and address.
  74. #[cfg_attr(
  75. feature = "medium-ethernet",
  76. doc = r##"
  77. # Examples
  78. ```
  79. # use std::collections::BTreeMap;
  80. use smoltcp::iface::{InterfaceBuilder, NeighborCache};
  81. # use smoltcp::phy::{Loopback, Medium};
  82. use smoltcp::wire::{EthernetAddress, IpCidr, IpAddress};
  83. let device = // ...
  84. # Loopback::new(Medium::Ethernet);
  85. let hw_addr = // ...
  86. # EthernetAddress::default();
  87. let neighbor_cache = // ...
  88. # NeighborCache::new(BTreeMap::new());
  89. let ip_addrs = // ...
  90. # [];
  91. let iface = InterfaceBuilder::new(device)
  92. .hardware_addr(hw_addr.into())
  93. .neighbor_cache(neighbor_cache)
  94. .ip_addrs(ip_addrs)
  95. .finalize();
  96. ```
  97. "##
  98. )]
  99. pub fn new(device: DeviceT) -> Self {
  100. InterfaceBuilder {
  101. device: device,
  102. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  103. hardware_addr: None,
  104. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  105. neighbor_cache: None,
  106. #[cfg(feature = "medium-ieee802154")]
  107. sequence_no: 1,
  108. #[cfg(feature = "medium-ieee802154")]
  109. pan_id: None,
  110. ip_addrs: ManagedSlice::Borrowed(&mut []),
  111. #[cfg(feature = "proto-ipv4")]
  112. any_ip: false,
  113. routes: Routes::new(ManagedMap::Borrowed(&mut [])),
  114. #[cfg(feature = "proto-igmp")]
  115. ipv4_multicast_groups: ManagedMap::Borrowed(&mut []),
  116. }
  117. }
  118. /// Set the Hardware address the interface will use. See also
  119. /// [ethernet_addr].
  120. ///
  121. /// # Panics
  122. /// This function panics if the address is not unicast.
  123. ///
  124. /// [ethernet_addr]: struct.Interface.html#method.ethernet_addr
  125. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  126. pub fn hardware_addr(mut self, addr: HardwareAddress) -> Self {
  127. InterfaceInner::check_hardware_addr(&addr);
  128. self.hardware_addr = Some(addr);
  129. self
  130. }
  131. /// Set the initial IEEE802.15.4 sequence number the interface will use.
  132. ///
  133. /// **NOTE**: this needs to be initailized randomly and not equal to 0.
  134. #[cfg(feature = "medium-ieee802154")]
  135. pub fn sequence_no(mut self, sequence_no: u8) -> Self {
  136. self.sequence_no = sequence_no;
  137. self
  138. }
  139. /// Set the IEEE802.15.4 PAN ID the interface will use.
  140. ///
  141. /// **NOTE**: we use the same PAN ID for destination and source.
  142. #[cfg(feature = "medium-ieee802154")]
  143. pub fn pan_id(mut self, pan_id: Ieee802154Pan) -> Self {
  144. self.pan_id = Some(pan_id);
  145. self
  146. }
  147. /// Set the IP addresses the interface will use. See also
  148. /// [ip_addrs].
  149. ///
  150. /// # Panics
  151. /// This function panics if any of the addresses are not unicast.
  152. ///
  153. /// [ip_addrs]: struct.Interface.html#method.ip_addrs
  154. pub fn ip_addrs<T>(mut self, ip_addrs: T) -> Self
  155. where
  156. T: Into<ManagedSlice<'a, IpCidr>>,
  157. {
  158. let ip_addrs = ip_addrs.into();
  159. InterfaceInner::check_ip_addrs(&ip_addrs);
  160. self.ip_addrs = ip_addrs;
  161. self
  162. }
  163. /// Enable or disable the AnyIP capability, allowing packets to be received
  164. /// locally on IPv4 addresses other than the interface's configured [ip_addrs].
  165. /// When AnyIP is enabled and a route prefix in [routes] specifies one of
  166. /// the interface's [ip_addrs] as its gateway, the interface will accept
  167. /// packets addressed to that prefix.
  168. ///
  169. /// # IPv6
  170. ///
  171. /// This option is not available or required for IPv6 as packets sent to
  172. /// the interface are not filtered by IPv6 address.
  173. ///
  174. /// [routes]: struct.Interface.html#method.routes
  175. /// [ip_addrs]: struct.Interface.html#method.ip_addrs
  176. #[cfg(feature = "proto-ipv4")]
  177. pub fn any_ip(mut self, enabled: bool) -> Self {
  178. self.any_ip = enabled;
  179. self
  180. }
  181. /// Set the IP routes the interface will use. See also
  182. /// [routes].
  183. ///
  184. /// [routes]: struct.Interface.html#method.routes
  185. pub fn routes<T>(mut self, routes: T) -> InterfaceBuilder<'a, DeviceT>
  186. where
  187. T: Into<Routes<'a>>,
  188. {
  189. self.routes = routes.into();
  190. self
  191. }
  192. /// Provide storage for multicast groups.
  193. ///
  194. /// Join multicast groups by calling [`join_multicast_group()`] on an `Interface`.
  195. /// Using [`join_multicast_group()`] will send initial membership reports.
  196. ///
  197. /// A previously destroyed interface can be recreated by reusing the multicast group
  198. /// storage, i.e. providing a non-empty storage to `ipv4_multicast_groups()`.
  199. /// Note that this way initial membership reports are **not** sent.
  200. ///
  201. /// [`join_multicast_group()`]: struct.Interface.html#method.join_multicast_group
  202. #[cfg(feature = "proto-igmp")]
  203. pub fn ipv4_multicast_groups<T>(mut self, ipv4_multicast_groups: T) -> Self
  204. where
  205. T: Into<ManagedMap<'a, Ipv4Address, ()>>,
  206. {
  207. self.ipv4_multicast_groups = ipv4_multicast_groups.into();
  208. self
  209. }
  210. /// Set the Neighbor Cache the interface will use.
  211. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  212. pub fn neighbor_cache(mut self, neighbor_cache: NeighborCache<'a>) -> Self {
  213. self.neighbor_cache = Some(neighbor_cache);
  214. self
  215. }
  216. /// Create a network interface using the previously provided configuration.
  217. ///
  218. /// # Panics
  219. /// If a required option is not provided, this function will panic. Required
  220. /// options are:
  221. ///
  222. /// - [ethernet_addr]
  223. /// - [neighbor_cache]
  224. ///
  225. /// [ethernet_addr]: #method.ethernet_addr
  226. /// [neighbor_cache]: #method.neighbor_cache
  227. pub fn finalize(self) -> Interface<'a, DeviceT> {
  228. let device_capabilities = self.device.capabilities();
  229. let (hardware_addr, neighbor_cache) = match device_capabilities.medium {
  230. #[cfg(feature = "medium-ethernet")]
  231. Medium::Ethernet => (
  232. Some(
  233. self.hardware_addr
  234. .expect("hardware_addr required option was not set"),
  235. ),
  236. Some(
  237. self.neighbor_cache
  238. .expect("neighbor_cache required option was not set"),
  239. ),
  240. ),
  241. #[cfg(feature = "medium-ip")]
  242. Medium::Ip => {
  243. assert!(
  244. self.hardware_addr.is_none(),
  245. "hardware_addr is set, but device medium is IP"
  246. );
  247. assert!(
  248. self.neighbor_cache.is_none(),
  249. "neighbor_cache is set, but device medium is IP"
  250. );
  251. (None, None)
  252. }
  253. #[cfg(feature = "medium-ieee802154")]
  254. Medium::Ieee802154 => (
  255. Some(
  256. self.hardware_addr
  257. .expect("hardware_addr required option was not set"),
  258. ),
  259. Some(
  260. self.neighbor_cache
  261. .expect("neighbor_cache required option was not set"),
  262. ),
  263. ),
  264. };
  265. Interface {
  266. device: self.device,
  267. inner: InterfaceInner {
  268. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  269. hardware_addr,
  270. ip_addrs: self.ip_addrs,
  271. #[cfg(feature = "proto-ipv4")]
  272. any_ip: self.any_ip,
  273. routes: self.routes,
  274. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  275. neighbor_cache,
  276. #[cfg(feature = "proto-igmp")]
  277. ipv4_multicast_groups: self.ipv4_multicast_groups,
  278. #[cfg(feature = "proto-igmp")]
  279. igmp_report_state: IgmpReportState::Inactive,
  280. #[cfg(feature = "medium-ieee802154")]
  281. sequence_no: self.sequence_no,
  282. #[cfg(feature = "medium-ieee802154")]
  283. pan_id: self.pan_id,
  284. },
  285. }
  286. }
  287. }
  288. #[derive(Debug, PartialEq)]
  289. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  290. #[cfg(feature = "medium-ethernet")]
  291. enum EthernetPacket<'a> {
  292. #[cfg(feature = "proto-ipv4")]
  293. Arp(ArpRepr),
  294. Ip(IpPacket<'a>),
  295. }
  296. #[derive(Debug, PartialEq)]
  297. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  298. pub(crate) enum IpPacket<'a> {
  299. #[cfg(feature = "proto-ipv4")]
  300. Icmpv4((Ipv4Repr, Icmpv4Repr<'a>)),
  301. #[cfg(feature = "proto-igmp")]
  302. Igmp((Ipv4Repr, IgmpRepr)),
  303. #[cfg(feature = "proto-ipv6")]
  304. Icmpv6((Ipv6Repr, Icmpv6Repr<'a>)),
  305. #[cfg(feature = "socket-raw")]
  306. Raw((IpRepr, &'a [u8])),
  307. #[cfg(feature = "socket-udp")]
  308. Udp((IpRepr, UdpRepr, &'a [u8])),
  309. #[cfg(feature = "socket-tcp")]
  310. Tcp((IpRepr, TcpRepr<'a>)),
  311. #[cfg(feature = "socket-dhcpv4")]
  312. Dhcpv4((Ipv4Repr, UdpRepr, DhcpRepr<'a>)),
  313. }
  314. impl<'a> IpPacket<'a> {
  315. pub(crate) fn ip_repr(&self) -> IpRepr {
  316. match self {
  317. #[cfg(feature = "proto-ipv4")]
  318. IpPacket::Icmpv4((ipv4_repr, _)) => IpRepr::Ipv4(*ipv4_repr),
  319. #[cfg(feature = "proto-igmp")]
  320. IpPacket::Igmp((ipv4_repr, _)) => IpRepr::Ipv4(*ipv4_repr),
  321. #[cfg(feature = "proto-ipv6")]
  322. IpPacket::Icmpv6((ipv6_repr, _)) => IpRepr::Ipv6(*ipv6_repr),
  323. #[cfg(feature = "socket-raw")]
  324. IpPacket::Raw((ip_repr, _)) => ip_repr.clone(),
  325. #[cfg(feature = "socket-udp")]
  326. IpPacket::Udp((ip_repr, _, _)) => ip_repr.clone(),
  327. #[cfg(feature = "socket-tcp")]
  328. IpPacket::Tcp((ip_repr, _)) => ip_repr.clone(),
  329. #[cfg(feature = "socket-dhcpv4")]
  330. IpPacket::Dhcpv4((ipv4_repr, _, _)) => IpRepr::Ipv4(*ipv4_repr),
  331. }
  332. }
  333. pub(crate) fn emit_payload(
  334. &self,
  335. _ip_repr: IpRepr,
  336. payload: &mut [u8],
  337. caps: &DeviceCapabilities,
  338. ) {
  339. match self {
  340. #[cfg(feature = "proto-ipv4")]
  341. IpPacket::Icmpv4((_, icmpv4_repr)) => {
  342. icmpv4_repr.emit(&mut Icmpv4Packet::new_unchecked(payload), &caps.checksum)
  343. }
  344. #[cfg(feature = "proto-igmp")]
  345. IpPacket::Igmp((_, igmp_repr)) => {
  346. igmp_repr.emit(&mut IgmpPacket::new_unchecked(payload))
  347. }
  348. #[cfg(feature = "proto-ipv6")]
  349. IpPacket::Icmpv6((_, icmpv6_repr)) => icmpv6_repr.emit(
  350. &_ip_repr.src_addr(),
  351. &_ip_repr.dst_addr(),
  352. &mut Icmpv6Packet::new_unchecked(payload),
  353. &caps.checksum,
  354. ),
  355. #[cfg(feature = "socket-raw")]
  356. IpPacket::Raw((_, raw_packet)) => payload.copy_from_slice(raw_packet),
  357. #[cfg(feature = "socket-udp")]
  358. IpPacket::Udp((_, udp_repr, inner_payload)) => udp_repr.emit(
  359. &mut UdpPacket::new_unchecked(payload),
  360. &_ip_repr.src_addr(),
  361. &_ip_repr.dst_addr(),
  362. inner_payload.len(),
  363. |buf| buf.copy_from_slice(inner_payload),
  364. &caps.checksum,
  365. ),
  366. #[cfg(feature = "socket-tcp")]
  367. IpPacket::Tcp((_, mut tcp_repr)) => {
  368. // This is a terrible hack to make TCP performance more acceptable on systems
  369. // where the TCP buffers are significantly larger than network buffers,
  370. // e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
  371. // together with four 1500 B Ethernet receive buffers. If left untreated,
  372. // this would result in our peer pushing our window and sever packet loss.
  373. //
  374. // I'm really not happy about this "solution" but I don't know what else to do.
  375. if let Some(max_burst_size) = caps.max_burst_size {
  376. let mut max_segment_size = caps.max_transmission_unit;
  377. max_segment_size -= _ip_repr.buffer_len();
  378. max_segment_size -= tcp_repr.header_len();
  379. let max_window_size = max_burst_size * max_segment_size;
  380. if tcp_repr.window_len as usize > max_window_size {
  381. tcp_repr.window_len = max_window_size as u16;
  382. }
  383. }
  384. tcp_repr.emit(
  385. &mut TcpPacket::new_unchecked(payload),
  386. &_ip_repr.src_addr(),
  387. &_ip_repr.dst_addr(),
  388. &caps.checksum,
  389. );
  390. }
  391. #[cfg(feature = "socket-dhcpv4")]
  392. IpPacket::Dhcpv4((_, udp_repr, dhcp_repr)) => udp_repr.emit(
  393. &mut UdpPacket::new_unchecked(payload),
  394. &_ip_repr.src_addr(),
  395. &_ip_repr.dst_addr(),
  396. dhcp_repr.buffer_len(),
  397. |buf| dhcp_repr.emit(&mut DhcpPacket::new_unchecked(buf)).unwrap(),
  398. &caps.checksum,
  399. ),
  400. }
  401. }
  402. }
  403. #[cfg(any(feature = "proto-ipv4", feature = "proto-ipv6"))]
  404. fn icmp_reply_payload_len(len: usize, mtu: usize, header_len: usize) -> usize {
  405. // Send back as much of the original payload as will fit within
  406. // the minimum MTU required by IPv4. See RFC 1812 § 4.3.2.3 for
  407. // more details.
  408. //
  409. // Since the entire network layer packet must fit within the minumum
  410. // MTU supported, the payload must not exceed the following:
  411. //
  412. // <min mtu> - IP Header Size * 2 - ICMPv4 DstUnreachable hdr size
  413. cmp::min(len, mtu - header_len * 2 - 8)
  414. }
  415. #[cfg(feature = "proto-igmp")]
  416. enum IgmpReportState {
  417. Inactive,
  418. ToGeneralQuery {
  419. version: IgmpVersion,
  420. timeout: Instant,
  421. interval: Duration,
  422. next_index: usize,
  423. },
  424. ToSpecificQuery {
  425. version: IgmpVersion,
  426. timeout: Instant,
  427. group: Ipv4Address,
  428. },
  429. }
  430. impl<'a, DeviceT> Interface<'a, DeviceT>
  431. where
  432. DeviceT: for<'d> Device<'d>,
  433. {
  434. /// Get the HardwareAddress address of the interface.
  435. ///
  436. /// # Panics
  437. /// This function panics if the medium is not Ethernet or Ieee802154.
  438. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  439. pub fn hardware_addr(&self) -> HardwareAddress {
  440. #[cfg(all(feature = "medium-ethernet", not(feature = "medium-ieee802154")))]
  441. assert!(self.device().capabilities().medium == Medium::Ethernet);
  442. #[cfg(all(feature = "medium-ieee802154", not(feature = "medium-ethernet")))]
  443. assert!(self.device().capabilities().medium == Medium::Ieee802154);
  444. #[cfg(all(feature = "medium-ieee802154", feature = "medium-ethernet"))]
  445. assert!(
  446. self.device().capabilities().medium == Medium::Ethernet
  447. || self.device().capabilities().medium == Medium::Ethernet
  448. );
  449. self.inner.hardware_addr.unwrap()
  450. }
  451. /// Set the HardwareAddress address of the interface.
  452. ///
  453. /// # Panics
  454. /// This function panics if the address is not unicast, and if the medium is not Ethernet or
  455. /// Ieee802154.
  456. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  457. pub fn set_hardware_addr(&mut self, addr: HardwareAddress) {
  458. #[cfg(all(feature = "medium-ethernet", not(feature = "medium-ieee802154")))]
  459. assert!(self.device().capabilities().medium == Medium::Ethernet);
  460. #[cfg(all(feature = "medium-ieee802154", not(feature = "medium-ethernet")))]
  461. assert!(self.device().capabilities().medium == Medium::Ieee802154);
  462. #[cfg(all(feature = "medium-ieee802154", feature = "medium-ethernet"))]
  463. assert!(
  464. self.device().capabilities().medium == Medium::Ethernet
  465. || self.device().capabilities().medium == Medium::Ethernet
  466. );
  467. InterfaceInner::check_hardware_addr(&addr);
  468. self.inner.hardware_addr = Some(addr);
  469. }
  470. /// Get a reference to the inner device.
  471. pub fn device(&self) -> &DeviceT {
  472. &self.device
  473. }
  474. /// Get a mutable reference to the inner device.
  475. ///
  476. /// There are no invariants imposed on the device by the interface itself. Furthermore the
  477. /// trait implementations, required for references of all lifetimes, guarantees that the
  478. /// mutable reference can not invalidate the device as such. For some devices, such access may
  479. /// still allow modifications with adverse effects on the usability as a `phy` device. You
  480. /// should not use them this way.
  481. pub fn device_mut(&mut self) -> &mut DeviceT {
  482. &mut self.device
  483. }
  484. /// Add an address to a list of subscribed multicast IP addresses.
  485. ///
  486. /// Returns `Ok(announce_sent)` if the address was added successfully, where `annouce_sent`
  487. /// indicates whether an initial immediate announcement has been sent.
  488. pub fn join_multicast_group<T: Into<IpAddress>>(
  489. &mut self,
  490. addr: T,
  491. _timestamp: Instant,
  492. ) -> Result<bool> {
  493. match addr.into() {
  494. #[cfg(feature = "proto-igmp")]
  495. IpAddress::Ipv4(addr) => {
  496. let is_not_new = self
  497. .inner
  498. .ipv4_multicast_groups
  499. .insert(addr, ())
  500. .map_err(|_| Error::Exhausted)?
  501. .is_some();
  502. if is_not_new {
  503. Ok(false)
  504. } else if let Some(pkt) = self.inner.igmp_report_packet(IgmpVersion::Version2, addr)
  505. {
  506. let cx = self.context(_timestamp);
  507. // Send initial membership report
  508. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  509. self.inner.dispatch_ip(&cx, tx_token, pkt)?;
  510. Ok(true)
  511. } else {
  512. Ok(false)
  513. }
  514. }
  515. // Multicast is not yet implemented for other address families
  516. _ => Err(Error::Unaddressable),
  517. }
  518. }
  519. /// Remove an address from the subscribed multicast IP addresses.
  520. ///
  521. /// Returns `Ok(leave_sent)` if the address was removed successfully, where `leave_sent`
  522. /// indicates whether an immediate leave packet has been sent.
  523. pub fn leave_multicast_group<T: Into<IpAddress>>(
  524. &mut self,
  525. addr: T,
  526. _timestamp: Instant,
  527. ) -> Result<bool> {
  528. match addr.into() {
  529. #[cfg(feature = "proto-igmp")]
  530. IpAddress::Ipv4(addr) => {
  531. let was_not_present = self.inner.ipv4_multicast_groups.remove(&addr).is_none();
  532. if was_not_present {
  533. Ok(false)
  534. } else if let Some(pkt) = self.inner.igmp_leave_packet(addr) {
  535. let cx = self.context(_timestamp);
  536. // Send group leave packet
  537. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  538. self.inner.dispatch_ip(&cx, tx_token, pkt)?;
  539. Ok(true)
  540. } else {
  541. Ok(false)
  542. }
  543. }
  544. // Multicast is not yet implemented for other address families
  545. _ => Err(Error::Unaddressable),
  546. }
  547. }
  548. /// Check whether the interface listens to given destination multicast IP address.
  549. pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
  550. self.inner.has_multicast_group(addr)
  551. }
  552. /// Get the IP addresses of the interface.
  553. pub fn ip_addrs(&self) -> &[IpCidr] {
  554. self.inner.ip_addrs.as_ref()
  555. }
  556. /// Get the first IPv4 address if present.
  557. #[cfg(feature = "proto-ipv4")]
  558. pub fn ipv4_addr(&self) -> Option<Ipv4Address> {
  559. self.ip_addrs()
  560. .iter()
  561. .filter_map(|cidr| match cidr.address() {
  562. IpAddress::Ipv4(addr) => Some(addr),
  563. _ => None,
  564. })
  565. .next()
  566. }
  567. /// Update the IP addresses of the interface.
  568. ///
  569. /// # Panics
  570. /// This function panics if any of the addresses are not unicast.
  571. pub fn update_ip_addrs<F: FnOnce(&mut ManagedSlice<'a, IpCidr>)>(&mut self, f: F) {
  572. f(&mut self.inner.ip_addrs);
  573. InterfaceInner::check_ip_addrs(&self.inner.ip_addrs)
  574. }
  575. /// Check whether the interface has the given IP address assigned.
  576. pub fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  577. self.inner.has_ip_addr(addr)
  578. }
  579. /// Get the first IPv4 address of the interface.
  580. #[cfg(feature = "proto-ipv4")]
  581. pub fn ipv4_address(&self) -> Option<Ipv4Address> {
  582. self.inner.ipv4_address()
  583. }
  584. pub fn routes(&self) -> &Routes<'a> {
  585. &self.inner.routes
  586. }
  587. pub fn routes_mut(&mut self) -> &mut Routes<'a> {
  588. &mut self.inner.routes
  589. }
  590. /// Transmit packets queued in the given sockets, and receive packets queued
  591. /// in the device.
  592. ///
  593. /// This function returns a boolean value indicating whether any packets were
  594. /// processed or emitted, and thus, whether the readiness of any socket might
  595. /// have changed.
  596. ///
  597. /// # Errors
  598. /// This method will routinely return errors in response to normal network
  599. /// activity as well as certain boundary conditions such as buffer exhaustion.
  600. /// These errors are provided as an aid for troubleshooting, and are meant
  601. /// to be logged and ignored.
  602. ///
  603. /// As a special case, `Err(Error::Unrecognized)` is returned in response to
  604. /// packets containing any unsupported protocol, option, or form, which is
  605. /// a very common occurrence and on a production system it should not even
  606. /// be logged.
  607. pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
  608. let cx = self.context(timestamp);
  609. let mut readiness_may_have_changed = false;
  610. loop {
  611. let processed_any = self.socket_ingress(&cx, sockets);
  612. let emitted_any = self.socket_egress(&cx, sockets)?;
  613. #[cfg(feature = "proto-igmp")]
  614. self.igmp_egress(&cx, timestamp)?;
  615. if processed_any || emitted_any {
  616. readiness_may_have_changed = true;
  617. } else {
  618. break;
  619. }
  620. }
  621. Ok(readiness_may_have_changed)
  622. }
  623. /// Return a _soft deadline_ for calling [poll] the next time.
  624. /// The [Instant] returned is the time at which you should call [poll] next.
  625. /// It is harmless (but wastes energy) to call it before the [Instant], and
  626. /// potentially harmful (impacting quality of service) to call it after the
  627. /// [Instant]
  628. ///
  629. /// [poll]: #method.poll
  630. /// [Instant]: struct.Instant.html
  631. pub fn poll_at(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Instant> {
  632. let cx = self.context(timestamp);
  633. sockets
  634. .iter()
  635. .filter_map(|socket| {
  636. let socket_poll_at = socket.poll_at(&cx);
  637. match socket.meta().poll_at(socket_poll_at, |ip_addr| {
  638. self.inner.has_neighbor(&cx, &ip_addr)
  639. }) {
  640. PollAt::Ingress => None,
  641. PollAt::Time(instant) => Some(instant),
  642. PollAt::Now => Some(Instant::from_millis(0)),
  643. }
  644. })
  645. .min()
  646. }
  647. /// Return an _advisory wait time_ for calling [poll] the next time.
  648. /// The [Duration] returned is the time left to wait before calling [poll] next.
  649. /// It is harmless (but wastes energy) to call it before the [Duration] has passed,
  650. /// and potentially harmful (impacting quality of service) to call it after the
  651. /// [Duration] has passed.
  652. ///
  653. /// [poll]: #method.poll
  654. /// [Duration]: struct.Duration.html
  655. pub fn poll_delay(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Duration> {
  656. match self.poll_at(sockets, timestamp) {
  657. Some(poll_at) if timestamp < poll_at => Some(poll_at - timestamp),
  658. Some(_) => Some(Duration::from_millis(0)),
  659. _ => None,
  660. }
  661. }
  662. fn socket_ingress(&mut self, cx: &Context, sockets: &mut SocketSet) -> bool {
  663. let mut processed_any = false;
  664. let &mut Self {
  665. ref mut device,
  666. ref mut inner,
  667. } = self;
  668. while let Some((rx_token, tx_token)) = device.receive() {
  669. if let Err(err) = rx_token.consume(cx.now, |frame| match cx.caps.medium {
  670. #[cfg(feature = "medium-ethernet")]
  671. Medium::Ethernet => match inner.process_ethernet(cx, sockets, &frame) {
  672. Ok(response) => {
  673. processed_any = true;
  674. if let Some(packet) = response {
  675. if let Err(err) = inner.dispatch(cx, tx_token, packet) {
  676. net_debug!("Failed to send response: {}", err);
  677. }
  678. }
  679. Ok(())
  680. }
  681. Err(err) => {
  682. net_debug!("cannot process ingress packet: {}", err);
  683. #[cfg(not(feature = "defmt"))]
  684. net_debug!(
  685. "packet dump follows:\n{}",
  686. PrettyPrinter::<EthernetFrame<&[u8]>>::new("", &frame)
  687. );
  688. Err(err)
  689. }
  690. },
  691. #[cfg(feature = "medium-ip")]
  692. Medium::Ip => match inner.process_ip(cx, sockets, &frame) {
  693. Ok(response) => {
  694. processed_any = true;
  695. if let Some(packet) = response {
  696. if let Err(err) = inner.dispatch_ip(cx, tx_token, packet) {
  697. net_debug!("Failed to send response: {}", err);
  698. }
  699. }
  700. Ok(())
  701. }
  702. Err(err) => {
  703. net_debug!("cannot process ingress packet: {}", err);
  704. Err(err)
  705. }
  706. },
  707. #[cfg(feature = "medium-ieee802154")]
  708. Medium::Ieee802154 => match inner.process_ieee802154(cx, sockets, &frame) {
  709. Ok(response) => {
  710. processed_any = true;
  711. if let Some(packet) = response {
  712. if let Err(err) = inner.dispatch_ieee802154(cx, tx_token, packet) {
  713. net_debug!("Failed to send response: {}", err);
  714. }
  715. }
  716. Ok(())
  717. }
  718. Err(err) => {
  719. net_debug!("cannot process ingress packet: {}", err);
  720. Err(err)
  721. }
  722. },
  723. }) {
  724. net_debug!("Failed to consume RX token: {}", err);
  725. }
  726. }
  727. processed_any
  728. }
  729. fn socket_egress(&mut self, cx: &Context, sockets: &mut SocketSet) -> Result<bool> {
  730. let _caps = self.device.capabilities();
  731. let mut emitted_any = false;
  732. for mut socket in sockets.iter_mut() {
  733. if !socket
  734. .meta_mut()
  735. .egress_permitted(cx.now, |ip_addr| self.inner.has_neighbor(cx, &ip_addr))
  736. {
  737. continue;
  738. }
  739. let mut neighbor_addr = None;
  740. let mut device_result = Ok(());
  741. let &mut Self {
  742. ref mut device,
  743. ref mut inner,
  744. } = self;
  745. macro_rules! respond {
  746. ($response:expr) => {{
  747. let response = $response;
  748. neighbor_addr = Some(response.ip_repr().dst_addr());
  749. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  750. device_result = inner.dispatch_ip(cx, tx_token, response);
  751. device_result
  752. }};
  753. }
  754. let socket_result = match *socket {
  755. #[cfg(feature = "socket-raw")]
  756. Socket::Raw(ref mut socket) => {
  757. socket.dispatch(cx, |response| respond!(IpPacket::Raw(response)))
  758. }
  759. #[cfg(all(
  760. feature = "socket-icmp",
  761. any(feature = "proto-ipv4", feature = "proto-ipv6")
  762. ))]
  763. Socket::Icmp(ref mut socket) => socket.dispatch(cx, |response| match response {
  764. #[cfg(feature = "proto-ipv4")]
  765. (IpRepr::Ipv4(ipv4_repr), IcmpRepr::Ipv4(icmpv4_repr)) => {
  766. respond!(IpPacket::Icmpv4((ipv4_repr, icmpv4_repr)))
  767. }
  768. #[cfg(feature = "proto-ipv6")]
  769. (IpRepr::Ipv6(ipv6_repr), IcmpRepr::Ipv6(icmpv6_repr)) => {
  770. respond!(IpPacket::Icmpv6((ipv6_repr, icmpv6_repr)))
  771. }
  772. _ => Err(Error::Unaddressable),
  773. }),
  774. #[cfg(feature = "socket-udp")]
  775. Socket::Udp(ref mut socket) => {
  776. socket.dispatch(cx, |response| respond!(IpPacket::Udp(response)))
  777. }
  778. #[cfg(feature = "socket-tcp")]
  779. Socket::Tcp(ref mut socket) => {
  780. socket.dispatch(cx, |response| respond!(IpPacket::Tcp(response)))
  781. }
  782. #[cfg(feature = "socket-dhcpv4")]
  783. Socket::Dhcpv4(ref mut socket) =>
  784. // todo don't unwrap
  785. {
  786. socket.dispatch(cx, |response| respond!(IpPacket::Dhcpv4(response)))
  787. }
  788. };
  789. match (device_result, socket_result) {
  790. (Err(Error::Exhausted), _) => break, // nowhere to transmit
  791. (Ok(()), Err(Error::Exhausted)) => (), // nothing to transmit
  792. (Err(Error::Unaddressable), _) => {
  793. // `NeighborCache` already takes care of rate limiting the neighbor discovery
  794. // requests from the socket. However, without an additional rate limiting
  795. // mechanism, we would spin on every socket that has yet to discover its
  796. // neighboor.
  797. socket
  798. .meta_mut()
  799. .neighbor_missing(cx.now, neighbor_addr.expect("non-IP response packet"));
  800. break;
  801. }
  802. (Err(err), _) | (_, Err(err)) => {
  803. net_debug!(
  804. "{}: cannot dispatch egress packet: {}",
  805. socket.meta().handle,
  806. err
  807. );
  808. return Err(err);
  809. }
  810. (Ok(()), Ok(())) => emitted_any = true,
  811. }
  812. }
  813. Ok(emitted_any)
  814. }
  815. /// Depending on `igmp_report_state` and the therein contained
  816. /// timeouts, send IGMP membership reports.
  817. #[cfg(feature = "proto-igmp")]
  818. fn igmp_egress(&mut self, cx: &Context, timestamp: Instant) -> Result<bool> {
  819. match self.inner.igmp_report_state {
  820. IgmpReportState::ToSpecificQuery {
  821. version,
  822. timeout,
  823. group,
  824. } if timestamp >= timeout => {
  825. if let Some(pkt) = self.inner.igmp_report_packet(version, group) {
  826. // Send initial membership report
  827. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  828. self.inner.dispatch_ip(cx, tx_token, pkt)?;
  829. }
  830. self.inner.igmp_report_state = IgmpReportState::Inactive;
  831. Ok(true)
  832. }
  833. IgmpReportState::ToGeneralQuery {
  834. version,
  835. timeout,
  836. interval,
  837. next_index,
  838. } if timestamp >= timeout => {
  839. let addr = self
  840. .inner
  841. .ipv4_multicast_groups
  842. .iter()
  843. .nth(next_index)
  844. .map(|(addr, ())| *addr);
  845. match addr {
  846. Some(addr) => {
  847. if let Some(pkt) = self.inner.igmp_report_packet(version, addr) {
  848. // Send initial membership report
  849. let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
  850. self.inner.dispatch_ip(cx, tx_token, pkt)?;
  851. }
  852. let next_timeout = (timeout + interval).max(timestamp);
  853. self.inner.igmp_report_state = IgmpReportState::ToGeneralQuery {
  854. version,
  855. timeout: next_timeout,
  856. interval,
  857. next_index: next_index + 1,
  858. };
  859. Ok(true)
  860. }
  861. None => {
  862. self.inner.igmp_report_state = IgmpReportState::Inactive;
  863. Ok(false)
  864. }
  865. }
  866. }
  867. _ => Ok(false),
  868. }
  869. }
  870. fn context(&self, now: Instant) -> Context {
  871. Context {
  872. now,
  873. caps: self.device.capabilities(),
  874. #[cfg(all(
  875. any(feature = "medium-ethernet", feature = "medium-ieee802154"),
  876. feature = "socket-dhcpv4"
  877. ))]
  878. hardware_addr: self.inner.hardware_addr,
  879. #[cfg(feature = "medium-ieee802154")]
  880. pan_id: self.inner.pan_id,
  881. }
  882. }
  883. }
  884. impl<'a> InterfaceInner<'a> {
  885. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  886. fn check_hardware_addr(addr: &HardwareAddress) {
  887. if !addr.is_unicast() {
  888. panic!("Ethernet address {} is not unicast", addr)
  889. }
  890. }
  891. fn check_ip_addrs(addrs: &[IpCidr]) {
  892. for cidr in addrs {
  893. if !cidr.address().is_unicast() && !cidr.address().is_unspecified() {
  894. panic!("IP address {} is not unicast", cidr.address())
  895. }
  896. }
  897. }
  898. #[cfg(feature = "medium-ieee802154")]
  899. fn get_sequence_number(&mut self) -> u8 {
  900. let no = self.sequence_no;
  901. self.sequence_no = self.sequence_no.wrapping_add(1);
  902. no
  903. }
  904. /// Determine if the given `Ipv6Address` is the solicited node
  905. /// multicast address for a IPv6 addresses assigned to the interface.
  906. /// See [RFC 4291 § 2.7.1] for more details.
  907. ///
  908. /// [RFC 4291 § 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1
  909. #[cfg(feature = "proto-ipv6")]
  910. pub fn has_solicited_node(&self, addr: Ipv6Address) -> bool {
  911. self.ip_addrs.iter().any(|cidr| {
  912. match *cidr {
  913. IpCidr::Ipv6(cidr) if cidr.address() != Ipv6Address::LOOPBACK => {
  914. // Take the lower order 24 bits of the IPv6 address and
  915. // append those bits to FF02:0:0:0:0:1:FF00::/104.
  916. addr.as_bytes()[14..] == cidr.address().as_bytes()[14..]
  917. }
  918. _ => false,
  919. }
  920. })
  921. }
  922. /// Check whether the interface has the given IP address assigned.
  923. fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  924. let addr = addr.into();
  925. self.ip_addrs.iter().any(|probe| probe.address() == addr)
  926. }
  927. /// Get the first IPv4 address of the interface.
  928. #[cfg(feature = "proto-ipv4")]
  929. pub fn ipv4_address(&self) -> Option<Ipv4Address> {
  930. self.ip_addrs
  931. .iter()
  932. .filter_map(|addr| match *addr {
  933. IpCidr::Ipv4(cidr) => Some(cidr.address()),
  934. #[cfg(feature = "proto-ipv6")]
  935. IpCidr::Ipv6(_) => None,
  936. })
  937. .next()
  938. }
  939. /// Check whether the interface listens to given destination multicast IP address.
  940. ///
  941. /// If built without feature `proto-igmp` this function will
  942. /// always return `false`.
  943. pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
  944. match addr.into() {
  945. #[cfg(feature = "proto-igmp")]
  946. IpAddress::Ipv4(key) => {
  947. key == Ipv4Address::MULTICAST_ALL_SYSTEMS
  948. || self.ipv4_multicast_groups.get(&key).is_some()
  949. }
  950. _ => false,
  951. }
  952. }
  953. #[cfg(feature = "medium-ethernet")]
  954. fn process_ethernet<'frame, T: AsRef<[u8]>>(
  955. &mut self,
  956. cx: &Context,
  957. sockets: &mut SocketSet,
  958. frame: &'frame T,
  959. ) -> Result<Option<EthernetPacket<'frame>>> {
  960. let eth_frame = EthernetFrame::new_checked(frame)?;
  961. // Ignore any packets not directed to our hardware address or any of the multicast groups.
  962. if !eth_frame.dst_addr().is_broadcast()
  963. && !eth_frame.dst_addr().is_multicast()
  964. && HardwareAddress::Ethernet(eth_frame.dst_addr()) != self.hardware_addr.unwrap()
  965. {
  966. return Ok(None);
  967. }
  968. match eth_frame.ethertype() {
  969. #[cfg(feature = "proto-ipv4")]
  970. EthernetProtocol::Arp => self.process_arp(cx.now, &eth_frame),
  971. #[cfg(feature = "proto-ipv4")]
  972. EthernetProtocol::Ipv4 => {
  973. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
  974. self.process_ipv4(cx, sockets, &ipv4_packet)
  975. .map(|o| o.map(EthernetPacket::Ip))
  976. }
  977. #[cfg(feature = "proto-ipv6")]
  978. EthernetProtocol::Ipv6 => {
  979. let ipv6_packet = Ipv6Packet::new_checked(eth_frame.payload())?;
  980. self.process_ipv6(cx, sockets, &ipv6_packet)
  981. .map(|o| o.map(EthernetPacket::Ip))
  982. }
  983. // Drop all other traffic.
  984. _ => Err(Error::Unrecognized),
  985. }
  986. }
  987. #[cfg(feature = "medium-ip")]
  988. fn process_ip<'frame, T: AsRef<[u8]>>(
  989. &mut self,
  990. cx: &Context,
  991. sockets: &mut SocketSet,
  992. ip_payload: &'frame T,
  993. ) -> Result<Option<IpPacket<'frame>>> {
  994. match IpVersion::of_packet(ip_payload.as_ref()) {
  995. #[cfg(feature = "proto-ipv4")]
  996. Ok(IpVersion::Ipv4) => {
  997. let ipv4_packet = Ipv4Packet::new_checked(ip_payload)?;
  998. self.process_ipv4(cx, sockets, &ipv4_packet)
  999. }
  1000. #[cfg(feature = "proto-ipv6")]
  1001. Ok(IpVersion::Ipv6) => {
  1002. let ipv6_packet = Ipv6Packet::new_checked(ip_payload)?;
  1003. self.process_ipv6(cx, sockets, &ipv6_packet)
  1004. }
  1005. // Drop all other traffic.
  1006. _ => Err(Error::Unrecognized),
  1007. }
  1008. }
  1009. #[cfg(feature = "medium-ieee802154")]
  1010. fn process_ieee802154<'frame, T: AsRef<[u8]> + ?Sized>(
  1011. &mut self,
  1012. cx: &Context,
  1013. sockets: &mut SocketSet,
  1014. sixlowpan_payload: &'frame T,
  1015. ) -> Result<Option<IpPacket<'frame>>> {
  1016. let ieee802154_frame = Ieee802154Frame::new_checked(sixlowpan_payload)?;
  1017. let ieee802154_repr = Ieee802154Repr::parse(&ieee802154_frame)?;
  1018. if ieee802154_repr.dst_pan_id != cx.pan_id {
  1019. // We sillently drop frames that have the wrong PAN id.
  1020. // NOTE: this is most of the time already implememted in hardware.
  1021. return Ok(None);
  1022. }
  1023. match ieee802154_frame.payload() {
  1024. Some(payload) => self.process_sixlowpan(cx, sockets, &ieee802154_repr, payload),
  1025. None => Ok(None),
  1026. }
  1027. }
  1028. #[cfg(feature = "proto-sixlowpan")]
  1029. fn process_sixlowpan<'frame, T: AsRef<[u8]> + ?Sized>(
  1030. &mut self,
  1031. cx: &Context,
  1032. sockets: &mut SocketSet,
  1033. ieee802154_repr: &Ieee802154Repr,
  1034. payload: &'frame T,
  1035. ) -> Result<Option<IpPacket<'frame>>> {
  1036. // The first header needs to be an IPHC header.
  1037. let iphc_packet = SixlowpanIphcPacket::new_checked(payload)?;
  1038. let iphc_repr = SixlowpanIphcRepr::parse(
  1039. &iphc_packet,
  1040. ieee802154_repr.src_addr,
  1041. ieee802154_repr.dst_addr,
  1042. )?;
  1043. let payload = iphc_packet.payload();
  1044. let ip_repr = IpRepr::Sixlowpan(iphc_repr);
  1045. // Currently we assume the next header is a UDP, so we mark all the rest with todo.
  1046. match iphc_repr.next_header {
  1047. SixlowpanNextHeader::Compressed => {
  1048. match SixlowpanNhcPacket::dispatch(payload)? {
  1049. SixlowpanNhcPacket::ExtensionHeader(_) => {
  1050. net_debug!("Extension headers are currently not supported for 6LoWPAN");
  1051. Ok(None)
  1052. }
  1053. SixlowpanNhcPacket::UdpHeader(udp_packet) => {
  1054. // Handle the UDP
  1055. let udp_repr = SixlowpanUdpRepr::parse(
  1056. &udp_packet,
  1057. &iphc_repr.src_addr,
  1058. &iphc_repr.dst_addr,
  1059. udp_packet.checksum(),
  1060. )?;
  1061. // Look for UDP sockets that will accept the UDP packet.
  1062. // If it does not accept the packet, then send an ICMP message.
  1063. for mut udp_socket in sockets.iter_mut().filter_map(UdpSocket::downcast) {
  1064. if !udp_socket.accepts(&ip_repr, &udp_repr) {
  1065. continue;
  1066. }
  1067. match udp_socket.process(cx, &ip_repr, &udp_repr, udp_packet.payload())
  1068. {
  1069. Ok(()) => return Ok(None),
  1070. Err(e) => return Err(e),
  1071. }
  1072. }
  1073. // TODO(thvdveld): verify this implementation of sending an ICMP
  1074. let src_addr = match ip_repr.src_addr() {
  1075. IpAddress::Ipv6(addr) => addr,
  1076. _ => unreachable!(),
  1077. };
  1078. let dst_addr = match ip_repr.dst_addr() {
  1079. IpAddress::Ipv6(addr) => addr,
  1080. _ => unreachable!(),
  1081. };
  1082. let ipv6_repr = Ipv6Repr {
  1083. src_addr,
  1084. dst_addr,
  1085. hop_limit: ip_repr.hop_limit(),
  1086. next_header: IpProtocol::Unknown(0),
  1087. payload_len: ip_repr.payload_len(),
  1088. };
  1089. let payload_len = icmp_reply_payload_len(
  1090. payload.len(),
  1091. IPV6_MIN_MTU,
  1092. ipv6_repr.buffer_len(),
  1093. );
  1094. let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable {
  1095. reason: Icmpv6DstUnreachable::PortUnreachable,
  1096. header: ipv6_repr,
  1097. data: &payload[0..payload_len],
  1098. };
  1099. Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr))
  1100. }
  1101. }
  1102. }
  1103. SixlowpanNextHeader::Uncompressed(nxt_hdr) => match nxt_hdr {
  1104. IpProtocol::Icmpv6 => {
  1105. self.process_icmpv6(cx, sockets, ip_repr, iphc_packet.payload())
  1106. }
  1107. _ => {
  1108. net_debug!("Headers other than ICMPv6 and compressed headers are currently not supported for 6LoWPAN");
  1109. Ok(None)
  1110. }
  1111. },
  1112. }
  1113. }
  1114. #[cfg(all(feature = "medium-ethernet", feature = "proto-ipv4"))]
  1115. fn process_arp<'frame, T: AsRef<[u8]>>(
  1116. &mut self,
  1117. timestamp: Instant,
  1118. eth_frame: &EthernetFrame<&'frame T>,
  1119. ) -> Result<Option<EthernetPacket<'frame>>> {
  1120. let arp_packet = ArpPacket::new_checked(eth_frame.payload())?;
  1121. let arp_repr = ArpRepr::parse(&arp_packet)?;
  1122. match arp_repr {
  1123. ArpRepr::EthernetIpv4 {
  1124. operation,
  1125. source_hardware_addr,
  1126. source_protocol_addr,
  1127. target_protocol_addr,
  1128. ..
  1129. } => {
  1130. // Only process ARP packets for us.
  1131. if !self.has_ip_addr(target_protocol_addr) {
  1132. return Ok(None);
  1133. }
  1134. // Only process REQUEST and RESPONSE.
  1135. if let ArpOperation::Unknown(_) = operation {
  1136. net_debug!("arp: unknown operation code");
  1137. return Err(Error::Malformed);
  1138. }
  1139. // Discard packets with non-unicast source addresses.
  1140. if !source_protocol_addr.is_unicast() || !source_hardware_addr.is_unicast() {
  1141. net_debug!("arp: non-unicast source address");
  1142. return Err(Error::Malformed);
  1143. }
  1144. if !self.in_same_network(&IpAddress::Ipv4(source_protocol_addr)) {
  1145. net_debug!("arp: source IP address not in same network as us");
  1146. return Err(Error::Malformed);
  1147. }
  1148. // Fill the ARP cache from any ARP packet aimed at us (both request or response).
  1149. // We fill from requests too because if someone is requesting our address they
  1150. // are probably going to talk to us, so we avoid having to request their address
  1151. // when we later reply to them.
  1152. self.neighbor_cache.as_mut().unwrap().fill(
  1153. source_protocol_addr.into(),
  1154. source_hardware_addr.into(),
  1155. timestamp,
  1156. );
  1157. if operation == ArpOperation::Request {
  1158. let src_hardware_addr = match self.hardware_addr {
  1159. Some(HardwareAddress::Ethernet(addr)) => addr,
  1160. _ => unreachable!(),
  1161. };
  1162. Ok(Some(EthernetPacket::Arp(ArpRepr::EthernetIpv4 {
  1163. operation: ArpOperation::Reply,
  1164. source_hardware_addr: src_hardware_addr,
  1165. source_protocol_addr: target_protocol_addr,
  1166. target_hardware_addr: source_hardware_addr,
  1167. target_protocol_addr: source_protocol_addr,
  1168. })))
  1169. } else {
  1170. Ok(None)
  1171. }
  1172. }
  1173. }
  1174. }
  1175. #[cfg(all(
  1176. any(feature = "proto-ipv4", feature = "proto-ipv6"),
  1177. feature = "socket-raw"
  1178. ))]
  1179. fn raw_socket_filter<'frame>(
  1180. &mut self,
  1181. cx: &Context,
  1182. sockets: &mut SocketSet,
  1183. ip_repr: &IpRepr,
  1184. ip_payload: &'frame [u8],
  1185. ) -> bool {
  1186. let mut handled_by_raw_socket = false;
  1187. // Pass every IP packet to all raw sockets we have registered.
  1188. for mut raw_socket in sockets.iter_mut().filter_map(RawSocket::downcast) {
  1189. if !raw_socket.accepts(ip_repr) {
  1190. continue;
  1191. }
  1192. match raw_socket.process(cx, ip_repr, ip_payload) {
  1193. // The packet is valid and handled by socket.
  1194. Ok(()) => handled_by_raw_socket = true,
  1195. // The socket buffer is full or the packet was truncated
  1196. Err(Error::Exhausted) | Err(Error::Truncated) => (),
  1197. // Raw sockets don't validate the packets in any way.
  1198. Err(_) => unreachable!(),
  1199. }
  1200. }
  1201. handled_by_raw_socket
  1202. }
  1203. #[cfg(feature = "proto-ipv6")]
  1204. fn process_ipv6<'frame, T: AsRef<[u8]> + ?Sized>(
  1205. &mut self,
  1206. cx: &Context,
  1207. sockets: &mut SocketSet,
  1208. ipv6_packet: &Ipv6Packet<&'frame T>,
  1209. ) -> Result<Option<IpPacket<'frame>>> {
  1210. let ipv6_repr = Ipv6Repr::parse(ipv6_packet)?;
  1211. if !ipv6_repr.src_addr.is_unicast() {
  1212. // Discard packets with non-unicast source addresses.
  1213. net_debug!("non-unicast source address");
  1214. return Err(Error::Malformed);
  1215. }
  1216. let ip_payload = ipv6_packet.payload();
  1217. #[cfg(feature = "socket-raw")]
  1218. let handled_by_raw_socket =
  1219. self.raw_socket_filter(cx, sockets, &ipv6_repr.into(), ip_payload);
  1220. #[cfg(not(feature = "socket-raw"))]
  1221. let handled_by_raw_socket = false;
  1222. self.process_nxt_hdr(
  1223. cx,
  1224. sockets,
  1225. ipv6_repr,
  1226. ipv6_repr.next_header,
  1227. handled_by_raw_socket,
  1228. ip_payload,
  1229. )
  1230. }
  1231. /// Given the next header value forward the payload onto the correct process
  1232. /// function.
  1233. #[cfg(feature = "proto-ipv6")]
  1234. fn process_nxt_hdr<'frame>(
  1235. &mut self,
  1236. cx: &Context,
  1237. sockets: &mut SocketSet,
  1238. ipv6_repr: Ipv6Repr,
  1239. nxt_hdr: IpProtocol,
  1240. handled_by_raw_socket: bool,
  1241. ip_payload: &'frame [u8],
  1242. ) -> Result<Option<IpPacket<'frame>>> {
  1243. match nxt_hdr {
  1244. IpProtocol::Icmpv6 => self.process_icmpv6(cx, sockets, ipv6_repr.into(), ip_payload),
  1245. #[cfg(feature = "socket-udp")]
  1246. IpProtocol::Udp => self.process_udp(
  1247. cx,
  1248. sockets,
  1249. ipv6_repr.into(),
  1250. handled_by_raw_socket,
  1251. ip_payload,
  1252. ),
  1253. #[cfg(feature = "socket-tcp")]
  1254. IpProtocol::Tcp => self.process_tcp(cx, sockets, ipv6_repr.into(), ip_payload),
  1255. IpProtocol::HopByHop => {
  1256. self.process_hopbyhop(cx, sockets, ipv6_repr, handled_by_raw_socket, ip_payload)
  1257. }
  1258. #[cfg(feature = "socket-raw")]
  1259. _ if handled_by_raw_socket => Ok(None),
  1260. _ => {
  1261. // Send back as much of the original payload as we can.
  1262. let payload_len =
  1263. icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU, ipv6_repr.buffer_len());
  1264. let icmp_reply_repr = Icmpv6Repr::ParamProblem {
  1265. reason: Icmpv6ParamProblem::UnrecognizedNxtHdr,
  1266. // The offending packet is after the IPv6 header.
  1267. pointer: ipv6_repr.buffer_len() as u32,
  1268. header: ipv6_repr,
  1269. data: &ip_payload[0..payload_len],
  1270. };
  1271. Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
  1272. }
  1273. }
  1274. }
  1275. #[cfg(feature = "proto-ipv4")]
  1276. fn process_ipv4<'frame, T: AsRef<[u8]> + ?Sized>(
  1277. &mut self,
  1278. cx: &Context,
  1279. sockets: &mut SocketSet,
  1280. ipv4_packet: &Ipv4Packet<&'frame T>,
  1281. ) -> Result<Option<IpPacket<'frame>>> {
  1282. let ipv4_repr = Ipv4Repr::parse(ipv4_packet, &cx.caps.checksum)?;
  1283. if !self.is_unicast_v4(ipv4_repr.src_addr) {
  1284. // Discard packets with non-unicast source addresses.
  1285. net_debug!("non-unicast source address");
  1286. return Err(Error::Malformed);
  1287. }
  1288. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  1289. let ip_payload = ipv4_packet.payload();
  1290. #[cfg(feature = "socket-raw")]
  1291. let handled_by_raw_socket = self.raw_socket_filter(cx, sockets, &ip_repr, ip_payload);
  1292. #[cfg(not(feature = "socket-raw"))]
  1293. let handled_by_raw_socket = false;
  1294. #[cfg(feature = "socket-dhcpv4")]
  1295. {
  1296. if ipv4_repr.protocol == IpProtocol::Udp && self.hardware_addr.is_some() {
  1297. // First check for source and dest ports, then do `UdpRepr::parse` if they match.
  1298. // This way we avoid validating the UDP checksum twice for all non-DHCP UDP packets (one here, one in `process_udp`)
  1299. let udp_packet = UdpPacket::new_checked(ip_payload)?;
  1300. if udp_packet.src_port() == DHCP_SERVER_PORT
  1301. && udp_packet.dst_port() == DHCP_CLIENT_PORT
  1302. {
  1303. if let Some(mut dhcp_socket) =
  1304. sockets.iter_mut().filter_map(Dhcpv4Socket::downcast).next()
  1305. {
  1306. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  1307. let udp_repr =
  1308. UdpRepr::parse(&udp_packet, &src_addr, &dst_addr, &cx.caps.checksum)?;
  1309. let udp_payload = udp_packet.payload();
  1310. match dhcp_socket.process(cx, &ipv4_repr, &udp_repr, udp_payload) {
  1311. // The packet is valid and handled by socket.
  1312. Ok(()) => return Ok(None),
  1313. // The packet is malformed, or the socket buffer is full.
  1314. Err(e) => return Err(e),
  1315. }
  1316. }
  1317. }
  1318. }
  1319. }
  1320. if !self.has_ip_addr(ipv4_repr.dst_addr)
  1321. && !self.has_multicast_group(ipv4_repr.dst_addr)
  1322. && !self.is_broadcast_v4(ipv4_repr.dst_addr)
  1323. {
  1324. // Ignore IP packets not directed at us, or broadcast, or any of the multicast groups.
  1325. // If AnyIP is enabled, also check if the packet is routed locally.
  1326. if !self.any_ip
  1327. || !ipv4_repr.dst_addr.is_unicast()
  1328. || self
  1329. .routes
  1330. .lookup(&IpAddress::Ipv4(ipv4_repr.dst_addr), cx.now)
  1331. .map_or(true, |router_addr| !self.has_ip_addr(router_addr))
  1332. {
  1333. return Ok(None);
  1334. }
  1335. }
  1336. match ipv4_repr.protocol {
  1337. IpProtocol::Icmp => self.process_icmpv4(cx, sockets, ip_repr, ip_payload),
  1338. #[cfg(feature = "proto-igmp")]
  1339. IpProtocol::Igmp => self.process_igmp(cx, ipv4_repr, ip_payload),
  1340. #[cfg(feature = "socket-udp")]
  1341. IpProtocol::Udp => {
  1342. self.process_udp(cx, sockets, ip_repr, handled_by_raw_socket, ip_payload)
  1343. }
  1344. #[cfg(feature = "socket-tcp")]
  1345. IpProtocol::Tcp => self.process_tcp(cx, sockets, ip_repr, ip_payload),
  1346. _ if handled_by_raw_socket => Ok(None),
  1347. _ => {
  1348. // Send back as much of the original payload as we can.
  1349. let payload_len =
  1350. icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU, ipv4_repr.buffer_len());
  1351. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  1352. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  1353. header: ipv4_repr,
  1354. data: &ip_payload[0..payload_len],
  1355. };
  1356. Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr))
  1357. }
  1358. }
  1359. }
  1360. /// Checks if an incoming packet has a broadcast address for the interfaces
  1361. /// associated ipv4 addresses.
  1362. #[cfg(feature = "proto-ipv4")]
  1363. fn is_subnet_broadcast(&self, address: Ipv4Address) -> bool {
  1364. self.ip_addrs
  1365. .iter()
  1366. .filter_map(|own_cidr| match own_cidr {
  1367. IpCidr::Ipv4(own_ip) => Some(own_ip.broadcast()?),
  1368. #[cfg(feature = "proto-ipv6")]
  1369. IpCidr::Ipv6(_) => None,
  1370. })
  1371. .any(|broadcast_address| address == broadcast_address)
  1372. }
  1373. /// Checks if an ipv4 address is broadcast, taking into account subnet broadcast addresses
  1374. #[cfg(feature = "proto-ipv4")]
  1375. fn is_broadcast_v4(&self, address: Ipv4Address) -> bool {
  1376. address.is_broadcast() || self.is_subnet_broadcast(address)
  1377. }
  1378. /// Checks if an ipv4 address is unicast, taking into account subnet broadcast addresses
  1379. #[cfg(feature = "proto-ipv4")]
  1380. fn is_unicast_v4(&self, address: Ipv4Address) -> bool {
  1381. address.is_unicast() && !self.is_subnet_broadcast(address)
  1382. }
  1383. /// Host duties of the **IGMPv2** protocol.
  1384. ///
  1385. /// Sets up `igmp_report_state` for responding to IGMP general/specific membership queries.
  1386. /// Membership must not be reported immediately in order to avoid flooding the network
  1387. /// after a query is broadcasted by a router; this is not currently done.
  1388. #[cfg(feature = "proto-igmp")]
  1389. fn process_igmp<'frame>(
  1390. &mut self,
  1391. cx: &Context,
  1392. ipv4_repr: Ipv4Repr,
  1393. ip_payload: &'frame [u8],
  1394. ) -> Result<Option<IpPacket<'frame>>> {
  1395. let igmp_packet = IgmpPacket::new_checked(ip_payload)?;
  1396. let igmp_repr = IgmpRepr::parse(&igmp_packet)?;
  1397. // FIXME: report membership after a delay
  1398. match igmp_repr {
  1399. IgmpRepr::MembershipQuery {
  1400. group_addr,
  1401. version,
  1402. max_resp_time,
  1403. } => {
  1404. // General query
  1405. if group_addr.is_unspecified()
  1406. && ipv4_repr.dst_addr == Ipv4Address::MULTICAST_ALL_SYSTEMS
  1407. {
  1408. // Are we member in any groups?
  1409. if self.ipv4_multicast_groups.iter().next().is_some() {
  1410. let interval = match version {
  1411. IgmpVersion::Version1 => Duration::from_millis(100),
  1412. IgmpVersion::Version2 => {
  1413. // No dependence on a random generator
  1414. // (see [#24](https://github.com/m-labs/smoltcp/issues/24))
  1415. // but at least spread reports evenly across max_resp_time.
  1416. let intervals = self.ipv4_multicast_groups.len() as u32 + 1;
  1417. max_resp_time / intervals
  1418. }
  1419. };
  1420. self.igmp_report_state = IgmpReportState::ToGeneralQuery {
  1421. version,
  1422. timeout: cx.now + interval,
  1423. interval,
  1424. next_index: 0,
  1425. };
  1426. }
  1427. } else {
  1428. // Group-specific query
  1429. if self.has_multicast_group(group_addr) && ipv4_repr.dst_addr == group_addr {
  1430. // Don't respond immediately
  1431. let timeout = max_resp_time / 4;
  1432. self.igmp_report_state = IgmpReportState::ToSpecificQuery {
  1433. version,
  1434. timeout: cx.now + timeout,
  1435. group: group_addr,
  1436. };
  1437. }
  1438. }
  1439. }
  1440. // Ignore membership reports
  1441. IgmpRepr::MembershipReport { .. } => (),
  1442. // Ignore hosts leaving groups
  1443. IgmpRepr::LeaveGroup { .. } => (),
  1444. }
  1445. Ok(None)
  1446. }
  1447. #[cfg(feature = "proto-ipv6")]
  1448. fn process_icmpv6<'frame>(
  1449. &mut self,
  1450. cx: &Context,
  1451. _sockets: &mut SocketSet,
  1452. ip_repr: IpRepr,
  1453. ip_payload: &'frame [u8],
  1454. ) -> Result<Option<IpPacket<'frame>>> {
  1455. let icmp_packet = Icmpv6Packet::new_checked(ip_payload)?;
  1456. let icmp_repr = Icmpv6Repr::parse(
  1457. &ip_repr.src_addr(),
  1458. &ip_repr.dst_addr(),
  1459. &icmp_packet,
  1460. &cx.caps.checksum,
  1461. )?;
  1462. #[cfg(feature = "socket-icmp")]
  1463. let mut handled_by_icmp_socket = false;
  1464. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv6"))]
  1465. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  1466. if !icmp_socket.accepts(cx, &ip_repr, &icmp_repr.into()) {
  1467. continue;
  1468. }
  1469. match icmp_socket.process(cx, &ip_repr, &icmp_repr.into()) {
  1470. // The packet is valid and handled by socket.
  1471. Ok(()) => handled_by_icmp_socket = true,
  1472. // The socket buffer is full.
  1473. Err(Error::Exhausted) => (),
  1474. // ICMP sockets don't validate the packets in any way.
  1475. Err(_) => unreachable!(),
  1476. }
  1477. }
  1478. match icmp_repr {
  1479. // Respond to echo requests.
  1480. Icmpv6Repr::EchoRequest {
  1481. ident,
  1482. seq_no,
  1483. data,
  1484. } => match ip_repr {
  1485. IpRepr::Ipv6(ipv6_repr) => {
  1486. let icmp_reply_repr = Icmpv6Repr::EchoReply {
  1487. ident,
  1488. seq_no,
  1489. data,
  1490. };
  1491. Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr))
  1492. }
  1493. #[cfg(feature = "medium-ieee802154")]
  1494. IpRepr::Sixlowpan(sixlowpan_repr) => {
  1495. let icmp_reply_repr = Icmpv6Repr::EchoReply {
  1496. ident,
  1497. seq_no,
  1498. data,
  1499. };
  1500. Ok(self.icmpv6_reply(
  1501. Ipv6Repr {
  1502. src_addr: sixlowpan_repr.src_addr,
  1503. dst_addr: sixlowpan_repr.dst_addr,
  1504. next_header: IpProtocol::Unknown(0),
  1505. payload_len: data.len(),
  1506. hop_limit: 64,
  1507. },
  1508. icmp_reply_repr,
  1509. ))
  1510. }
  1511. _ => Err(Error::Unrecognized),
  1512. },
  1513. // Ignore any echo replies.
  1514. Icmpv6Repr::EchoReply { .. } => Ok(None),
  1515. // Forward any NDISC packets to the ndisc packet handler
  1516. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  1517. Icmpv6Repr::Ndisc(repr) if ip_repr.hop_limit() == 0xff => match ip_repr {
  1518. IpRepr::Ipv6(ipv6_repr) => self.process_ndisc(cx, ipv6_repr, repr),
  1519. #[cfg(feature = "medium-ieee802154")]
  1520. IpRepr::Sixlowpan(sixlowpan_repr) => {
  1521. self.process_ndisc(
  1522. cx,
  1523. Ipv6Repr {
  1524. src_addr: sixlowpan_repr.src_addr,
  1525. dst_addr: sixlowpan_repr.dst_addr,
  1526. next_header: IpProtocol::Unknown(0),
  1527. payload_len: 10, // 2 + 8
  1528. hop_limit: sixlowpan_repr.hop_limit,
  1529. },
  1530. repr,
  1531. )
  1532. }
  1533. _ => Ok(None),
  1534. },
  1535. // Don't report an error if a packet with unknown type
  1536. // has been handled by an ICMP socket
  1537. #[cfg(feature = "socket-icmp")]
  1538. _ if handled_by_icmp_socket => Ok(None),
  1539. // FIXME: do something correct here?
  1540. _ => Err(Error::Unrecognized),
  1541. }
  1542. }
  1543. #[cfg(all(
  1544. any(feature = "medium-ethernet", feature = "medium-ieee802154"),
  1545. feature = "proto-ipv6"
  1546. ))]
  1547. fn process_ndisc<'frame>(
  1548. &mut self,
  1549. cx: &Context,
  1550. ip_repr: Ipv6Repr,
  1551. repr: NdiscRepr<'frame>,
  1552. ) -> Result<Option<IpPacket<'frame>>> {
  1553. match repr {
  1554. NdiscRepr::NeighborAdvert {
  1555. lladdr,
  1556. target_addr,
  1557. flags,
  1558. } => {
  1559. let ip_addr = ip_repr.src_addr.into();
  1560. if let Some(lladdr) = lladdr {
  1561. let lladdr = lladdr.parse(cx.caps.medium)?;
  1562. if !lladdr.is_unicast() || !target_addr.is_unicast() {
  1563. return Err(Error::Malformed);
  1564. }
  1565. if flags.contains(NdiscNeighborFlags::OVERRIDE)
  1566. || !self
  1567. .neighbor_cache
  1568. .as_mut()
  1569. .unwrap()
  1570. .lookup(&ip_addr, cx.now)
  1571. .found()
  1572. {
  1573. self.neighbor_cache
  1574. .as_mut()
  1575. .unwrap()
  1576. .fill(ip_addr, lladdr, cx.now)
  1577. }
  1578. }
  1579. Ok(None)
  1580. }
  1581. NdiscRepr::NeighborSolicit {
  1582. target_addr,
  1583. lladdr,
  1584. ..
  1585. } => {
  1586. if let Some(lladdr) = lladdr {
  1587. let lladdr = lladdr.parse(cx.caps.medium)?;
  1588. if !lladdr.is_unicast() || !target_addr.is_unicast() {
  1589. return Err(Error::Malformed);
  1590. }
  1591. self.neighbor_cache.as_mut().unwrap().fill(
  1592. ip_repr.src_addr.into(),
  1593. lladdr,
  1594. cx.now,
  1595. );
  1596. }
  1597. if self.has_solicited_node(ip_repr.dst_addr) && self.has_ip_addr(target_addr) {
  1598. let advert = Icmpv6Repr::Ndisc(NdiscRepr::NeighborAdvert {
  1599. flags: NdiscNeighborFlags::SOLICITED,
  1600. target_addr,
  1601. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  1602. lladdr: Some(self.hardware_addr.unwrap().into()),
  1603. });
  1604. let ip_repr = Ipv6Repr {
  1605. src_addr: target_addr,
  1606. dst_addr: ip_repr.src_addr,
  1607. next_header: IpProtocol::Icmpv6,
  1608. hop_limit: 0xff,
  1609. payload_len: advert.buffer_len(),
  1610. };
  1611. Ok(Some(IpPacket::Icmpv6((ip_repr, advert))))
  1612. } else {
  1613. Ok(None)
  1614. }
  1615. }
  1616. _ => Ok(None),
  1617. }
  1618. }
  1619. #[cfg(feature = "proto-ipv6")]
  1620. fn process_hopbyhop<'frame>(
  1621. &mut self,
  1622. cx: &Context,
  1623. sockets: &mut SocketSet,
  1624. ipv6_repr: Ipv6Repr,
  1625. handled_by_raw_socket: bool,
  1626. ip_payload: &'frame [u8],
  1627. ) -> Result<Option<IpPacket<'frame>>> {
  1628. let hbh_pkt = Ipv6HopByHopHeader::new_checked(ip_payload)?;
  1629. let hbh_repr = Ipv6HopByHopRepr::parse(&hbh_pkt)?;
  1630. for result in hbh_repr.options() {
  1631. let opt_repr = result?;
  1632. match opt_repr {
  1633. Ipv6OptionRepr::Pad1 | Ipv6OptionRepr::PadN(_) => (),
  1634. Ipv6OptionRepr::Unknown { type_, .. } => {
  1635. match Ipv6OptionFailureType::from(type_) {
  1636. Ipv6OptionFailureType::Skip => (),
  1637. Ipv6OptionFailureType::Discard => {
  1638. return Ok(None);
  1639. }
  1640. _ => {
  1641. // FIXME(dlrobertson): Send an ICMPv6 parameter problem message
  1642. // here.
  1643. return Err(Error::Unrecognized);
  1644. }
  1645. }
  1646. }
  1647. }
  1648. }
  1649. self.process_nxt_hdr(
  1650. cx,
  1651. sockets,
  1652. ipv6_repr,
  1653. hbh_repr.next_header,
  1654. handled_by_raw_socket,
  1655. &ip_payload[hbh_repr.buffer_len()..],
  1656. )
  1657. }
  1658. #[cfg(feature = "proto-ipv4")]
  1659. fn process_icmpv4<'frame>(
  1660. &self,
  1661. cx: &Context,
  1662. _sockets: &mut SocketSet,
  1663. ip_repr: IpRepr,
  1664. ip_payload: &'frame [u8],
  1665. ) -> Result<Option<IpPacket<'frame>>> {
  1666. let icmp_packet = Icmpv4Packet::new_checked(ip_payload)?;
  1667. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &cx.caps.checksum)?;
  1668. #[cfg(feature = "socket-icmp")]
  1669. let mut handled_by_icmp_socket = false;
  1670. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  1671. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  1672. if !icmp_socket.accepts(cx, &ip_repr, &icmp_repr.into()) {
  1673. continue;
  1674. }
  1675. match icmp_socket.process(cx, &ip_repr, &icmp_repr.into()) {
  1676. // The packet is valid and handled by socket.
  1677. Ok(()) => handled_by_icmp_socket = true,
  1678. // The socket buffer is full.
  1679. Err(Error::Exhausted) => (),
  1680. // ICMP sockets don't validate the packets in any way.
  1681. Err(_) => unreachable!(),
  1682. }
  1683. }
  1684. match icmp_repr {
  1685. // Respond to echo requests.
  1686. #[cfg(feature = "proto-ipv4")]
  1687. Icmpv4Repr::EchoRequest {
  1688. ident,
  1689. seq_no,
  1690. data,
  1691. } => {
  1692. let icmp_reply_repr = Icmpv4Repr::EchoReply {
  1693. ident,
  1694. seq_no,
  1695. data,
  1696. };
  1697. match ip_repr {
  1698. IpRepr::Ipv4(ipv4_repr) => Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr)),
  1699. _ => Err(Error::Unrecognized),
  1700. }
  1701. }
  1702. // Ignore any echo replies.
  1703. Icmpv4Repr::EchoReply { .. } => Ok(None),
  1704. // Don't report an error if a packet with unknown type
  1705. // has been handled by an ICMP socket
  1706. #[cfg(feature = "socket-icmp")]
  1707. _ if handled_by_icmp_socket => Ok(None),
  1708. // FIXME: do something correct here?
  1709. _ => Err(Error::Unrecognized),
  1710. }
  1711. }
  1712. #[cfg(feature = "proto-ipv4")]
  1713. fn icmpv4_reply<'frame, 'icmp: 'frame>(
  1714. &self,
  1715. ipv4_repr: Ipv4Repr,
  1716. icmp_repr: Icmpv4Repr<'icmp>,
  1717. ) -> Option<IpPacket<'frame>> {
  1718. if !self.is_unicast_v4(ipv4_repr.src_addr) {
  1719. // Do not send ICMP replies to non-unicast sources
  1720. None
  1721. } else if self.is_unicast_v4(ipv4_repr.dst_addr) {
  1722. // Reply as normal when src_addr and dst_addr are both unicast
  1723. let ipv4_reply_repr = Ipv4Repr {
  1724. src_addr: ipv4_repr.dst_addr,
  1725. dst_addr: ipv4_repr.src_addr,
  1726. protocol: IpProtocol::Icmp,
  1727. payload_len: icmp_repr.buffer_len(),
  1728. hop_limit: 64,
  1729. };
  1730. Some(IpPacket::Icmpv4((ipv4_reply_repr, icmp_repr)))
  1731. } else if self.is_broadcast_v4(ipv4_repr.dst_addr) {
  1732. // Only reply to broadcasts for echo replies and not other ICMP messages
  1733. match icmp_repr {
  1734. Icmpv4Repr::EchoReply { .. } => match self.ipv4_address() {
  1735. Some(src_addr) => {
  1736. let ipv4_reply_repr = Ipv4Repr {
  1737. src_addr: src_addr,
  1738. dst_addr: ipv4_repr.src_addr,
  1739. protocol: IpProtocol::Icmp,
  1740. payload_len: icmp_repr.buffer_len(),
  1741. hop_limit: 64,
  1742. };
  1743. Some(IpPacket::Icmpv4((ipv4_reply_repr, icmp_repr)))
  1744. }
  1745. None => None,
  1746. },
  1747. _ => None,
  1748. }
  1749. } else {
  1750. None
  1751. }
  1752. }
  1753. #[cfg(feature = "proto-ipv6")]
  1754. fn icmpv6_reply<'frame, 'icmp: 'frame>(
  1755. &self,
  1756. ipv6_repr: Ipv6Repr,
  1757. icmp_repr: Icmpv6Repr<'icmp>,
  1758. ) -> Option<IpPacket<'frame>> {
  1759. if ipv6_repr.dst_addr.is_unicast() {
  1760. let ipv6_reply_repr = Ipv6Repr {
  1761. src_addr: ipv6_repr.dst_addr,
  1762. dst_addr: ipv6_repr.src_addr,
  1763. next_header: IpProtocol::Icmpv6,
  1764. payload_len: icmp_repr.buffer_len(),
  1765. hop_limit: 64,
  1766. };
  1767. Some(IpPacket::Icmpv6((ipv6_reply_repr, icmp_repr)))
  1768. } else {
  1769. // Do not send any ICMP replies to a broadcast destination address.
  1770. None
  1771. }
  1772. }
  1773. #[cfg(feature = "socket-udp")]
  1774. fn process_udp<'frame>(
  1775. &self,
  1776. cx: &Context,
  1777. sockets: &mut SocketSet,
  1778. ip_repr: IpRepr,
  1779. handled_by_raw_socket: bool,
  1780. ip_payload: &'frame [u8],
  1781. ) -> Result<Option<IpPacket<'frame>>> {
  1782. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  1783. let udp_packet = UdpPacket::new_checked(ip_payload)?;
  1784. let udp_repr = UdpRepr::parse(&udp_packet, &src_addr, &dst_addr, &cx.caps.checksum)?;
  1785. let udp_payload = udp_packet.payload();
  1786. for mut udp_socket in sockets.iter_mut().filter_map(UdpSocket::downcast) {
  1787. if !udp_socket.accepts(&ip_repr, &udp_repr) {
  1788. continue;
  1789. }
  1790. match udp_socket.process(cx, &ip_repr, &udp_repr, udp_payload) {
  1791. // The packet is valid and handled by socket.
  1792. Ok(()) => return Ok(None),
  1793. // The packet is malformed, or the socket buffer is full.
  1794. Err(e) => return Err(e),
  1795. }
  1796. }
  1797. // The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  1798. match ip_repr {
  1799. #[cfg(feature = "proto-ipv4")]
  1800. IpRepr::Ipv4(_) if handled_by_raw_socket => Ok(None),
  1801. #[cfg(feature = "proto-ipv6")]
  1802. IpRepr::Ipv6(_) if handled_by_raw_socket => Ok(None),
  1803. #[cfg(feature = "proto-ipv4")]
  1804. IpRepr::Ipv4(ipv4_repr) => {
  1805. let payload_len =
  1806. icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU, ipv4_repr.buffer_len());
  1807. let icmpv4_reply_repr = Icmpv4Repr::DstUnreachable {
  1808. reason: Icmpv4DstUnreachable::PortUnreachable,
  1809. header: ipv4_repr,
  1810. data: &ip_payload[0..payload_len],
  1811. };
  1812. Ok(self.icmpv4_reply(ipv4_repr, icmpv4_reply_repr))
  1813. }
  1814. #[cfg(feature = "proto-ipv6")]
  1815. IpRepr::Ipv6(ipv6_repr) => {
  1816. let payload_len =
  1817. icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU, ipv6_repr.buffer_len());
  1818. let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable {
  1819. reason: Icmpv6DstUnreachable::PortUnreachable,
  1820. header: ipv6_repr,
  1821. data: &ip_payload[0..payload_len],
  1822. };
  1823. Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr))
  1824. }
  1825. #[cfg(feature = "proto-sixlowpan")]
  1826. IpRepr::Sixlowpan(sixlowpan_repr) => {
  1827. let ipv6_repr = Ipv6Repr {
  1828. src_addr: sixlowpan_repr.src_addr,
  1829. dst_addr: sixlowpan_repr.dst_addr,
  1830. next_header: IpProtocol::Udp, // XXX
  1831. payload_len: ip_payload.len(),
  1832. hop_limit: sixlowpan_repr.hop_limit,
  1833. };
  1834. let payload_len = icmp_reply_payload_len(
  1835. ip_payload.len(),
  1836. IPV6_MIN_MTU,
  1837. sixlowpan_repr.buffer_len(),
  1838. );
  1839. let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable {
  1840. reason: Icmpv6DstUnreachable::PortUnreachable,
  1841. header: ipv6_repr,
  1842. data: &ip_payload[0..payload_len],
  1843. };
  1844. Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr))
  1845. }
  1846. IpRepr::Unspecified { .. } => Err(Error::Unaddressable),
  1847. }
  1848. }
  1849. #[cfg(feature = "socket-tcp")]
  1850. fn process_tcp<'frame>(
  1851. &self,
  1852. cx: &Context,
  1853. sockets: &mut SocketSet,
  1854. ip_repr: IpRepr,
  1855. ip_payload: &'frame [u8],
  1856. ) -> Result<Option<IpPacket<'frame>>> {
  1857. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  1858. let tcp_packet = TcpPacket::new_checked(ip_payload)?;
  1859. let tcp_repr = TcpRepr::parse(&tcp_packet, &src_addr, &dst_addr, &cx.caps.checksum)?;
  1860. for mut tcp_socket in sockets.iter_mut().filter_map(TcpSocket::downcast) {
  1861. if !tcp_socket.accepts(&ip_repr, &tcp_repr) {
  1862. continue;
  1863. }
  1864. match tcp_socket.process(cx, &ip_repr, &tcp_repr) {
  1865. // The packet is valid and handled by socket.
  1866. Ok(reply) => return Ok(reply.map(IpPacket::Tcp)),
  1867. // The packet is malformed, or doesn't match the socket state,
  1868. // or the socket buffer is full.
  1869. Err(e) => return Err(e),
  1870. }
  1871. }
  1872. if tcp_repr.control == TcpControl::Rst {
  1873. // Never reply to a TCP RST packet with another TCP RST packet.
  1874. Ok(None)
  1875. } else {
  1876. // The packet wasn't handled by a socket, send a TCP RST packet.
  1877. Ok(Some(IpPacket::Tcp(TcpSocket::rst_reply(
  1878. &ip_repr, &tcp_repr,
  1879. ))))
  1880. }
  1881. }
  1882. #[cfg(feature = "medium-ethernet")]
  1883. fn dispatch<Tx>(&mut self, cx: &Context, tx_token: Tx, packet: EthernetPacket) -> Result<()>
  1884. where
  1885. Tx: TxToken,
  1886. {
  1887. match packet {
  1888. #[cfg(feature = "proto-ipv4")]
  1889. EthernetPacket::Arp(arp_repr) => {
  1890. let dst_hardware_addr = match arp_repr {
  1891. ArpRepr::EthernetIpv4 {
  1892. target_hardware_addr,
  1893. ..
  1894. } => target_hardware_addr,
  1895. };
  1896. self.dispatch_ethernet(cx, tx_token, arp_repr.buffer_len(), |mut frame| {
  1897. frame.set_dst_addr(dst_hardware_addr);
  1898. frame.set_ethertype(EthernetProtocol::Arp);
  1899. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  1900. arp_repr.emit(&mut packet);
  1901. })
  1902. }
  1903. EthernetPacket::Ip(packet) => self.dispatch_ip(cx, tx_token, packet),
  1904. }
  1905. }
  1906. #[cfg(feature = "medium-ethernet")]
  1907. fn dispatch_ethernet<Tx, F>(
  1908. &mut self,
  1909. cx: &Context,
  1910. tx_token: Tx,
  1911. buffer_len: usize,
  1912. f: F,
  1913. ) -> Result<()>
  1914. where
  1915. Tx: TxToken,
  1916. F: FnOnce(EthernetFrame<&mut [u8]>),
  1917. {
  1918. let tx_len = EthernetFrame::<&[u8]>::buffer_len(buffer_len);
  1919. tx_token.consume(cx.now, tx_len, |tx_buffer| {
  1920. debug_assert!(tx_buffer.as_ref().len() == tx_len);
  1921. let mut frame = EthernetFrame::new_unchecked(tx_buffer);
  1922. let src_addr = if let Some(HardwareAddress::Ethernet(addr)) = self.hardware_addr {
  1923. addr
  1924. } else {
  1925. return Err(Error::Malformed);
  1926. };
  1927. frame.set_src_addr(src_addr);
  1928. f(frame);
  1929. Ok(())
  1930. })
  1931. }
  1932. fn in_same_network(&self, addr: &IpAddress) -> bool {
  1933. self.ip_addrs.iter().any(|cidr| cidr.contains_addr(addr))
  1934. }
  1935. fn route(&self, addr: &IpAddress, timestamp: Instant) -> Result<IpAddress> {
  1936. // Send directly.
  1937. if self.in_same_network(addr) || addr.is_broadcast() {
  1938. return Ok(*addr);
  1939. }
  1940. // Route via a router.
  1941. match self.routes.lookup(addr, timestamp) {
  1942. Some(router_addr) => Ok(router_addr),
  1943. None => Err(Error::Unaddressable),
  1944. }
  1945. }
  1946. fn has_neighbor(&self, cx: &Context, addr: &IpAddress) -> bool {
  1947. match self.route(addr, cx.now) {
  1948. Ok(_routed_addr) => match cx.caps.medium {
  1949. #[cfg(feature = "medium-ethernet")]
  1950. Medium::Ethernet => self
  1951. .neighbor_cache
  1952. .as_ref()
  1953. .unwrap()
  1954. .lookup(&_routed_addr, cx.now)
  1955. .found(),
  1956. #[cfg(feature = "medium-ieee802154")]
  1957. Medium::Ieee802154 => self
  1958. .neighbor_cache
  1959. .as_ref()
  1960. .unwrap()
  1961. .lookup(&_routed_addr, cx.now)
  1962. .found(),
  1963. #[cfg(feature = "medium-ip")]
  1964. Medium::Ip => true,
  1965. },
  1966. Err(_) => false,
  1967. }
  1968. }
  1969. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  1970. fn lookup_hardware_addr<Tx>(
  1971. &mut self,
  1972. cx: &Context,
  1973. tx_token: Tx,
  1974. src_addr: &IpAddress,
  1975. dst_addr: &IpAddress,
  1976. ) -> Result<(HardwareAddress, Tx)>
  1977. where
  1978. Tx: TxToken,
  1979. {
  1980. if dst_addr.is_broadcast() {
  1981. let hardware_addr = match cx.caps.medium {
  1982. #[cfg(feature = "medium-ethernet")]
  1983. Medium::Ethernet => HardwareAddress::Ethernet(EthernetAddress::BROADCAST),
  1984. #[cfg(feature = "medium-ieee802154")]
  1985. Medium::Ieee802154 => HardwareAddress::Ieee802154(Ieee802154Address::BROADCAST),
  1986. #[cfg(feature = "medium-ip")]
  1987. Medium::Ip => unreachable!(),
  1988. };
  1989. return Ok((hardware_addr, tx_token));
  1990. }
  1991. if dst_addr.is_multicast() {
  1992. let b = dst_addr.as_bytes();
  1993. let hardware_addr = match *dst_addr {
  1994. IpAddress::Unspecified => unreachable!(),
  1995. #[cfg(feature = "proto-ipv4")]
  1996. IpAddress::Ipv4(_addr) => {
  1997. HardwareAddress::Ethernet(EthernetAddress::from_bytes(&[
  1998. 0x01,
  1999. 0x00,
  2000. 0x5e,
  2001. b[1] & 0x7F,
  2002. b[2],
  2003. b[3],
  2004. ]))
  2005. }
  2006. #[cfg(feature = "proto-ipv6")]
  2007. IpAddress::Ipv6(_addr) => match cx.caps.medium {
  2008. #[cfg(feature = "medium-ethernet")]
  2009. Medium::Ethernet => HardwareAddress::Ethernet(EthernetAddress::from_bytes(&[
  2010. 0x33, 0x33, b[12], b[13], b[14], b[15],
  2011. ])),
  2012. #[cfg(feature = "medium-ieee802154")]
  2013. Medium::Ieee802154 => {
  2014. // Not sure if this is correct
  2015. HardwareAddress::Ieee802154(Ieee802154Address::BROADCAST)
  2016. }
  2017. #[cfg(feature = "medium-ip")]
  2018. Medium::Ip => unreachable!(),
  2019. },
  2020. };
  2021. return Ok((hardware_addr, tx_token));
  2022. }
  2023. let dst_addr = self.route(dst_addr, cx.now)?;
  2024. match self
  2025. .neighbor_cache
  2026. .as_mut()
  2027. .unwrap()
  2028. .lookup(&dst_addr, cx.now)
  2029. {
  2030. NeighborAnswer::Found(hardware_addr) => return Ok((hardware_addr, tx_token)),
  2031. NeighborAnswer::RateLimited => return Err(Error::Unaddressable),
  2032. _ => (), // XXX
  2033. }
  2034. match (src_addr, dst_addr) {
  2035. #[cfg(feature = "proto-ipv4")]
  2036. (&IpAddress::Ipv4(src_addr), IpAddress::Ipv4(dst_addr)) => {
  2037. net_debug!(
  2038. "address {} not in neighbor cache, sending ARP request",
  2039. dst_addr
  2040. );
  2041. let src_hardware_addr =
  2042. if let Some(HardwareAddress::Ethernet(addr)) = self.hardware_addr {
  2043. addr
  2044. } else {
  2045. return Err(Error::Malformed);
  2046. };
  2047. let arp_repr = ArpRepr::EthernetIpv4 {
  2048. operation: ArpOperation::Request,
  2049. source_hardware_addr: src_hardware_addr,
  2050. source_protocol_addr: src_addr,
  2051. target_hardware_addr: EthernetAddress::BROADCAST,
  2052. target_protocol_addr: dst_addr,
  2053. };
  2054. self.dispatch_ethernet(cx, tx_token, arp_repr.buffer_len(), |mut frame| {
  2055. frame.set_dst_addr(EthernetAddress::BROADCAST);
  2056. frame.set_ethertype(EthernetProtocol::Arp);
  2057. arp_repr.emit(&mut ArpPacket::new_unchecked(frame.payload_mut()))
  2058. })?;
  2059. }
  2060. #[cfg(feature = "proto-ipv6")]
  2061. (&IpAddress::Ipv6(src_addr), IpAddress::Ipv6(dst_addr)) => {
  2062. net_debug!(
  2063. "address {} not in neighbor cache, sending Neighbor Solicitation",
  2064. dst_addr
  2065. );
  2066. let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit {
  2067. target_addr: dst_addr,
  2068. lladdr: Some(self.hardware_addr.unwrap().into()),
  2069. });
  2070. let packet = IpPacket::Icmpv6((
  2071. Ipv6Repr {
  2072. src_addr,
  2073. dst_addr: dst_addr.solicited_node(),
  2074. next_header: IpProtocol::Icmpv6,
  2075. payload_len: solicit.buffer_len(),
  2076. hop_limit: 0xff,
  2077. },
  2078. solicit,
  2079. ));
  2080. self.dispatch_ip(cx, tx_token, packet)?;
  2081. }
  2082. _ => (),
  2083. }
  2084. // The request got dispatched, limit the rate on the cache.
  2085. self.neighbor_cache.as_mut().unwrap().limit_rate(cx.now);
  2086. Err(Error::Unaddressable)
  2087. }
  2088. fn dispatch_ip<Tx: TxToken>(
  2089. &mut self,
  2090. cx: &Context,
  2091. tx_token: Tx,
  2092. packet: IpPacket,
  2093. ) -> Result<()> {
  2094. let ip_repr = packet.ip_repr().lower(&self.ip_addrs)?;
  2095. match cx.caps.medium {
  2096. #[cfg(feature = "medium-ethernet")]
  2097. Medium::Ethernet => {
  2098. let (dst_hardware_addr, tx_token) = match self.lookup_hardware_addr(
  2099. cx,
  2100. tx_token,
  2101. &ip_repr.src_addr(),
  2102. &ip_repr.dst_addr(),
  2103. )? {
  2104. (HardwareAddress::Ethernet(addr), tx_token) => (addr, tx_token),
  2105. #[cfg(feature = "medium-ieee802154")]
  2106. (HardwareAddress::Ieee802154(_), _) => unreachable!(),
  2107. };
  2108. self.dispatch_ethernet(cx, tx_token, ip_repr.total_len(), |mut frame| {
  2109. frame.set_dst_addr(dst_hardware_addr);
  2110. match ip_repr {
  2111. #[cfg(feature = "proto-ipv4")]
  2112. IpRepr::Ipv4(_) => frame.set_ethertype(EthernetProtocol::Ipv4),
  2113. #[cfg(feature = "proto-ipv6")]
  2114. IpRepr::Ipv6(_) => frame.set_ethertype(EthernetProtocol::Ipv6),
  2115. _ => return,
  2116. }
  2117. ip_repr.emit(frame.payload_mut(), &cx.caps.checksum);
  2118. let payload = &mut frame.payload_mut()[ip_repr.buffer_len()..];
  2119. packet.emit_payload(ip_repr, payload, &cx.caps);
  2120. })
  2121. }
  2122. #[cfg(feature = "medium-ip")]
  2123. Medium::Ip => {
  2124. let tx_len = ip_repr.total_len();
  2125. tx_token.consume(cx.now, tx_len, |mut tx_buffer| {
  2126. debug_assert!(tx_buffer.as_ref().len() == tx_len);
  2127. ip_repr.emit(&mut tx_buffer, &cx.caps.checksum);
  2128. let payload = &mut tx_buffer[ip_repr.buffer_len()..];
  2129. packet.emit_payload(ip_repr, payload, &cx.caps);
  2130. Ok(())
  2131. })
  2132. }
  2133. #[cfg(feature = "medium-ieee802154")]
  2134. Medium::Ieee802154 => self.dispatch_ieee802154(cx, tx_token, packet),
  2135. }
  2136. }
  2137. #[cfg(feature = "medium-ieee802154")]
  2138. fn dispatch_ieee802154<Tx: TxToken>(
  2139. &mut self,
  2140. cx: &Context,
  2141. tx_token: Tx,
  2142. packet: IpPacket,
  2143. ) -> Result<()> {
  2144. let ip_repr = packet.ip_repr().lower(&self.ip_addrs)?;
  2145. match cx.caps.medium {
  2146. #[cfg(feature = "medium-ieee802154")]
  2147. Medium::Ieee802154 => {
  2148. let (dst_hardware_addr, tx_token) = match self.lookup_hardware_addr(
  2149. cx,
  2150. tx_token,
  2151. &ip_repr.src_addr(),
  2152. &ip_repr.dst_addr(),
  2153. )? {
  2154. (HardwareAddress::Ieee802154(addr), tx_token) => (addr, tx_token),
  2155. _ => unreachable!(),
  2156. };
  2157. let ack_request = dst_hardware_addr.is_unicast();
  2158. let ack_request = match packet {
  2159. IpPacket::Icmpv6(_) => false,
  2160. _ => ack_request,
  2161. };
  2162. let mut tx_len = 0;
  2163. let ll_src_addr =
  2164. if let Some(HardwareAddress::Ieee802154(addr)) = self.hardware_addr {
  2165. Some(addr)
  2166. } else {
  2167. return Err(Error::Malformed);
  2168. };
  2169. let ieee_repr = Ieee802154Repr {
  2170. frame_type: Ieee802154FrameType::Data,
  2171. security_enabled: false,
  2172. frame_pending: false,
  2173. ack_request,
  2174. sequence_number: Some(self.get_sequence_number()),
  2175. pan_id_compression: true,
  2176. frame_version: Ieee802154FrameVersion::Ieee802154_2003,
  2177. dst_pan_id: cx.pan_id,
  2178. dst_addr: Some(dst_hardware_addr),
  2179. src_pan_id: cx.pan_id,
  2180. src_addr: ll_src_addr,
  2181. };
  2182. let (src_addr, dst_addr) = match (ip_repr.src_addr(), ip_repr.dst_addr()) {
  2183. (IpAddress::Ipv6(src_addr), IpAddress::Ipv6(dst_addr)) => (src_addr, dst_addr),
  2184. _ => return Err(Error::Unaddressable),
  2185. };
  2186. let next_header = match &packet {
  2187. IpPacket::Udp(_) => SixlowpanNextHeader::Compressed,
  2188. IpPacket::Icmpv6(_) => SixlowpanNextHeader::Uncompressed(IpProtocol::Icmpv6),
  2189. _ => return Err(Error::Unrecognized),
  2190. };
  2191. let hop_limit = match packet {
  2192. IpPacket::Icmpv6((_, Icmpv6Repr::Ndisc(_))) => 255,
  2193. IpPacket::Icmpv6((_, Icmpv6Repr::EchoReply { .. })) => 64,
  2194. IpPacket::Udp(..) => 64,
  2195. _ => return Err(Error::Unrecognized),
  2196. };
  2197. let iphc_repr = SixlowpanIphcRepr {
  2198. src_addr,
  2199. ll_src_addr,
  2200. dst_addr,
  2201. ll_dst_addr: Some(dst_hardware_addr),
  2202. next_header,
  2203. hop_limit,
  2204. };
  2205. tx_len += ieee_repr.buffer_len();
  2206. tx_len += iphc_repr.buffer_len();
  2207. match &packet {
  2208. IpPacket::Udp((_, udp_repr, payload)) => {
  2209. let udp_repr = SixlowpanUdpRepr(*udp_repr);
  2210. tx_len += udp_repr.header_len() + payload.len();
  2211. }
  2212. IpPacket::Icmpv6((_, icmp)) => {
  2213. tx_len += icmp.buffer_len();
  2214. }
  2215. _ => return Err(Error::Unrecognized),
  2216. }
  2217. tx_token.consume(cx.now, tx_len, |mut tx_buffer| {
  2218. // 1. Create the header of 802.15.4
  2219. let mut ieee_packet = Ieee802154Frame::new_unchecked(&mut tx_buffer);
  2220. ieee_repr.emit(&mut ieee_packet);
  2221. let mut start = ieee_repr.buffer_len();
  2222. // 2. Create the header for 6LoWPAN IPHC
  2223. let mut iphc_packet =
  2224. SixlowpanIphcPacket::new_unchecked(&mut tx_buffer[start..tx_len]);
  2225. iphc_repr.emit(&mut iphc_packet);
  2226. start += iphc_repr.buffer_len();
  2227. match packet {
  2228. IpPacket::Udp((_, udp_repr, payload)) => {
  2229. // 3. Create the header for 6LoWPAN UDP
  2230. let mut udp_packet =
  2231. SixlowpanUdpPacket::new_unchecked(&mut tx_buffer[start..tx_len]);
  2232. SixlowpanUdpRepr(udp_repr).emit(
  2233. &mut udp_packet,
  2234. &iphc_repr.src_addr,
  2235. &iphc_repr.dst_addr,
  2236. payload.len(),
  2237. |buf| buf.copy_from_slice(payload),
  2238. );
  2239. }
  2240. IpPacket::Icmpv6((_, icmp_repr)) => {
  2241. // 3. Create the header for ICMPv6
  2242. let mut icmp_packet =
  2243. Icmpv6Packet::new_unchecked(&mut tx_buffer[start..tx_len]);
  2244. icmp_repr.emit(
  2245. &iphc_repr.src_addr.into(),
  2246. &iphc_repr.dst_addr.into(),
  2247. &mut icmp_packet,
  2248. &cx.caps.checksum,
  2249. );
  2250. }
  2251. _ => return Err(Error::Unrecognized),
  2252. }
  2253. Ok(())
  2254. })
  2255. }
  2256. _ => Err(Error::NotSupported),
  2257. }
  2258. }
  2259. #[cfg(feature = "proto-igmp")]
  2260. fn igmp_report_packet<'any>(
  2261. &self,
  2262. version: IgmpVersion,
  2263. group_addr: Ipv4Address,
  2264. ) -> Option<IpPacket<'any>> {
  2265. let iface_addr = self.ipv4_address()?;
  2266. let igmp_repr = IgmpRepr::MembershipReport {
  2267. group_addr,
  2268. version,
  2269. };
  2270. let pkt = IpPacket::Igmp((
  2271. Ipv4Repr {
  2272. src_addr: iface_addr,
  2273. // Send to the group being reported
  2274. dst_addr: group_addr,
  2275. protocol: IpProtocol::Igmp,
  2276. payload_len: igmp_repr.buffer_len(),
  2277. hop_limit: 1,
  2278. // TODO: add Router Alert IPv4 header option. See
  2279. // [#183](https://github.com/m-labs/smoltcp/issues/183).
  2280. },
  2281. igmp_repr,
  2282. ));
  2283. Some(pkt)
  2284. }
  2285. #[cfg(feature = "proto-igmp")]
  2286. fn igmp_leave_packet<'any>(&self, group_addr: Ipv4Address) -> Option<IpPacket<'any>> {
  2287. self.ipv4_address().map(|iface_addr| {
  2288. let igmp_repr = IgmpRepr::LeaveGroup { group_addr };
  2289. IpPacket::Igmp((
  2290. Ipv4Repr {
  2291. src_addr: iface_addr,
  2292. dst_addr: Ipv4Address::MULTICAST_ALL_ROUTERS,
  2293. protocol: IpProtocol::Igmp,
  2294. payload_len: igmp_repr.buffer_len(),
  2295. hop_limit: 1,
  2296. },
  2297. igmp_repr,
  2298. ))
  2299. })
  2300. }
  2301. }
  2302. #[cfg(test)]
  2303. mod test {
  2304. use std::collections::BTreeMap;
  2305. #[cfg(feature = "proto-igmp")]
  2306. use std::vec::Vec;
  2307. use super::*;
  2308. use crate::iface::Interface;
  2309. #[cfg(feature = "medium-ethernet")]
  2310. use crate::iface::NeighborCache;
  2311. use crate::phy::{ChecksumCapabilities, Loopback};
  2312. use crate::socket::SocketSet;
  2313. #[cfg(feature = "proto-igmp")]
  2314. use crate::time::Instant;
  2315. use crate::{Error, Result};
  2316. #[allow(unused)]
  2317. fn fill_slice(s: &mut [u8], val: u8) {
  2318. for x in s.iter_mut() {
  2319. *x = val
  2320. }
  2321. }
  2322. fn create_loopback<'a>() -> (Interface<'a, Loopback>, SocketSet<'a>) {
  2323. #[cfg(feature = "medium-ethernet")]
  2324. return create_loopback_ethernet();
  2325. #[cfg(not(feature = "medium-ethernet"))]
  2326. return create_loopback_ip();
  2327. }
  2328. #[cfg(all(feature = "medium-ip"))]
  2329. #[allow(unused)]
  2330. fn create_loopback_ip<'a>() -> (Interface<'a, Loopback>, SocketSet<'a>) {
  2331. // Create a basic device
  2332. let device = Loopback::new(Medium::Ip);
  2333. let ip_addrs = [
  2334. #[cfg(feature = "proto-ipv4")]
  2335. IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8),
  2336. #[cfg(feature = "proto-ipv6")]
  2337. IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 128),
  2338. #[cfg(feature = "proto-ipv6")]
  2339. IpCidr::new(IpAddress::v6(0xfdbe, 0, 0, 0, 0, 0, 0, 1), 64),
  2340. ];
  2341. let iface_builder = InterfaceBuilder::new(device).ip_addrs(ip_addrs);
  2342. #[cfg(feature = "proto-igmp")]
  2343. let iface_builder = iface_builder.ipv4_multicast_groups(BTreeMap::new());
  2344. let iface = iface_builder.finalize();
  2345. (iface, SocketSet::new(vec![]))
  2346. }
  2347. #[cfg(all(feature = "medium-ethernet"))]
  2348. fn create_loopback_ethernet<'a>() -> (Interface<'a, Loopback>, SocketSet<'a>) {
  2349. // Create a basic device
  2350. let device = Loopback::new(Medium::Ethernet);
  2351. let ip_addrs = [
  2352. #[cfg(feature = "proto-ipv4")]
  2353. IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8),
  2354. #[cfg(feature = "proto-ipv6")]
  2355. IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 128),
  2356. #[cfg(feature = "proto-ipv6")]
  2357. IpCidr::new(IpAddress::v6(0xfdbe, 0, 0, 0, 0, 0, 0, 1), 64),
  2358. ];
  2359. let iface_builder = InterfaceBuilder::new(device)
  2360. .hardware_addr(EthernetAddress::default().into())
  2361. .neighbor_cache(NeighborCache::new(BTreeMap::new()))
  2362. .ip_addrs(ip_addrs);
  2363. #[cfg(feature = "proto-igmp")]
  2364. let iface_builder = iface_builder.ipv4_multicast_groups(BTreeMap::new());
  2365. let iface = iface_builder.finalize();
  2366. (iface, SocketSet::new(vec![]))
  2367. }
  2368. #[cfg(feature = "proto-igmp")]
  2369. fn recv_all(iface: &mut Interface<'_, Loopback>, timestamp: Instant) -> Vec<Vec<u8>> {
  2370. let mut pkts = Vec::new();
  2371. while let Some((rx, _tx)) = iface.device.receive() {
  2372. rx.consume(timestamp, |pkt| {
  2373. pkts.push(pkt.to_vec());
  2374. Ok(())
  2375. })
  2376. .unwrap();
  2377. }
  2378. pkts
  2379. }
  2380. #[derive(Debug, PartialEq)]
  2381. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  2382. struct MockTxToken;
  2383. impl TxToken for MockTxToken {
  2384. fn consume<R, F>(self, _: Instant, _: usize, _: F) -> Result<R>
  2385. where
  2386. F: FnOnce(&mut [u8]) -> Result<R>,
  2387. {
  2388. Err(Error::Unaddressable)
  2389. }
  2390. }
  2391. #[test]
  2392. #[should_panic(expected = "hardware_addr required option was not set")]
  2393. #[cfg(all(feature = "medium-ethernet"))]
  2394. fn test_builder_initialization_panic() {
  2395. InterfaceBuilder::new(Loopback::new(Medium::Ethernet)).finalize();
  2396. }
  2397. #[test]
  2398. #[cfg(feature = "proto-ipv4")]
  2399. fn test_no_icmp_no_unicast_ipv4() {
  2400. let (mut iface, mut socket_set) = create_loopback();
  2401. // Unknown Ipv4 Protocol
  2402. //
  2403. // Because the destination is the broadcast address
  2404. // this should not trigger and Destination Unreachable
  2405. // response. See RFC 1122 § 3.2.2.
  2406. let repr = IpRepr::Ipv4(Ipv4Repr {
  2407. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  2408. dst_addr: Ipv4Address::BROADCAST,
  2409. protocol: IpProtocol::Unknown(0x0c),
  2410. payload_len: 0,
  2411. hop_limit: 0x40,
  2412. });
  2413. let mut bytes = vec![0u8; 54];
  2414. repr.emit(&mut bytes, &ChecksumCapabilities::default());
  2415. let frame = Ipv4Packet::new_unchecked(&bytes);
  2416. // Ensure that the unknown protocol frame does not trigger an
  2417. // ICMP error response when the destination address is a
  2418. // broadcast address
  2419. let cx = iface.context(Instant::from_secs(0));
  2420. assert_eq!(
  2421. iface.inner.process_ipv4(&cx, &mut socket_set, &frame),
  2422. Ok(None)
  2423. );
  2424. }
  2425. #[test]
  2426. #[cfg(feature = "proto-ipv6")]
  2427. fn test_no_icmp_no_unicast_ipv6() {
  2428. let (mut iface, mut socket_set) = create_loopback();
  2429. // Unknown Ipv6 Protocol
  2430. //
  2431. // Because the destination is the broadcast address
  2432. // this should not trigger and Destination Unreachable
  2433. // response. See RFC 1122 § 3.2.2.
  2434. let repr = IpRepr::Ipv6(Ipv6Repr {
  2435. src_addr: Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1),
  2436. dst_addr: Ipv6Address::LINK_LOCAL_ALL_NODES,
  2437. next_header: IpProtocol::Unknown(0x0c),
  2438. payload_len: 0,
  2439. hop_limit: 0x40,
  2440. });
  2441. let mut bytes = vec![0u8; 54];
  2442. repr.emit(&mut bytes, &ChecksumCapabilities::default());
  2443. let frame = Ipv6Packet::new_unchecked(&bytes);
  2444. // Ensure that the unknown protocol frame does not trigger an
  2445. // ICMP error response when the destination address is a
  2446. // broadcast address
  2447. let cx = iface.context(Instant::from_secs(0));
  2448. assert_eq!(
  2449. iface.inner.process_ipv6(&cx, &mut socket_set, &frame),
  2450. Ok(None)
  2451. );
  2452. }
  2453. #[test]
  2454. #[cfg(feature = "proto-ipv4")]
  2455. fn test_icmp_error_no_payload() {
  2456. static NO_BYTES: [u8; 0] = [];
  2457. let (mut iface, mut socket_set) = create_loopback();
  2458. // Unknown Ipv4 Protocol with no payload
  2459. let repr = IpRepr::Ipv4(Ipv4Repr {
  2460. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  2461. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  2462. protocol: IpProtocol::Unknown(0x0c),
  2463. payload_len: 0,
  2464. hop_limit: 0x40,
  2465. });
  2466. let mut bytes = vec![0u8; 34];
  2467. repr.emit(&mut bytes, &ChecksumCapabilities::default());
  2468. let frame = Ipv4Packet::new_unchecked(&bytes);
  2469. // The expected Destination Unreachable response due to the
  2470. // unknown protocol
  2471. let icmp_repr = Icmpv4Repr::DstUnreachable {
  2472. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  2473. header: Ipv4Repr {
  2474. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  2475. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  2476. protocol: IpProtocol::Unknown(12),
  2477. payload_len: 0,
  2478. hop_limit: 64,
  2479. },
  2480. data: &NO_BYTES,
  2481. };
  2482. let expected_repr = IpPacket::Icmpv4((
  2483. Ipv4Repr {
  2484. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  2485. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  2486. protocol: IpProtocol::Icmp,
  2487. payload_len: icmp_repr.buffer_len(),
  2488. hop_limit: 64,
  2489. },
  2490. icmp_repr,
  2491. ));
  2492. // Ensure that the unknown protocol triggers an error response.
  2493. // And we correctly handle no payload.
  2494. let cx = iface.context(Instant::from_secs(0));
  2495. assert_eq!(
  2496. iface.inner.process_ipv4(&cx, &mut socket_set, &frame),
  2497. Ok(Some(expected_repr))
  2498. );
  2499. }
  2500. #[test]
  2501. #[cfg(feature = "proto-ipv4")]
  2502. fn test_local_subnet_broadcasts() {
  2503. let (mut iface, _) = create_loopback();
  2504. iface.update_ip_addrs(|addrs| {
  2505. addrs.iter_mut().next().map(|addr| {
  2506. *addr = IpCidr::Ipv4(Ipv4Cidr::new(Ipv4Address([192, 168, 1, 23]), 24));
  2507. });
  2508. });
  2509. assert!(iface
  2510. .inner
  2511. .is_subnet_broadcast(Ipv4Address([192, 168, 1, 255])),);
  2512. assert!(!iface
  2513. .inner
  2514. .is_subnet_broadcast(Ipv4Address([192, 168, 1, 254])),);
  2515. iface.update_ip_addrs(|addrs| {
  2516. addrs.iter_mut().next().map(|addr| {
  2517. *addr = IpCidr::Ipv4(Ipv4Cidr::new(Ipv4Address([192, 168, 23, 24]), 16));
  2518. });
  2519. });
  2520. assert!(!iface
  2521. .inner
  2522. .is_subnet_broadcast(Ipv4Address([192, 168, 23, 255])),);
  2523. assert!(!iface
  2524. .inner
  2525. .is_subnet_broadcast(Ipv4Address([192, 168, 23, 254])),);
  2526. assert!(!iface
  2527. .inner
  2528. .is_subnet_broadcast(Ipv4Address([192, 168, 255, 254])),);
  2529. assert!(iface
  2530. .inner
  2531. .is_subnet_broadcast(Ipv4Address([192, 168, 255, 255])),);
  2532. iface.update_ip_addrs(|addrs| {
  2533. addrs.iter_mut().next().map(|addr| {
  2534. *addr = IpCidr::Ipv4(Ipv4Cidr::new(Ipv4Address([192, 168, 23, 24]), 8));
  2535. });
  2536. });
  2537. assert!(!iface
  2538. .inner
  2539. .is_subnet_broadcast(Ipv4Address([192, 23, 1, 255])),);
  2540. assert!(!iface
  2541. .inner
  2542. .is_subnet_broadcast(Ipv4Address([192, 23, 1, 254])),);
  2543. assert!(!iface
  2544. .inner
  2545. .is_subnet_broadcast(Ipv4Address([192, 255, 255, 254])),);
  2546. assert!(iface
  2547. .inner
  2548. .is_subnet_broadcast(Ipv4Address([192, 255, 255, 255])),);
  2549. }
  2550. #[test]
  2551. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  2552. fn test_icmp_error_port_unreachable() {
  2553. static UDP_PAYLOAD: [u8; 12] = [
  2554. 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x6c, 0x64, 0x21,
  2555. ];
  2556. let (iface, mut socket_set) = create_loopback();
  2557. let mut udp_bytes_unicast = vec![0u8; 20];
  2558. let mut udp_bytes_broadcast = vec![0u8; 20];
  2559. let mut packet_unicast = UdpPacket::new_unchecked(&mut udp_bytes_unicast);
  2560. let mut packet_broadcast = UdpPacket::new_unchecked(&mut udp_bytes_broadcast);
  2561. let udp_repr = UdpRepr {
  2562. src_port: 67,
  2563. dst_port: 68,
  2564. };
  2565. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  2566. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  2567. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  2568. protocol: IpProtocol::Udp,
  2569. payload_len: udp_repr.header_len() + UDP_PAYLOAD.len(),
  2570. hop_limit: 64,
  2571. });
  2572. // Emit the representations to a packet
  2573. udp_repr.emit(
  2574. &mut packet_unicast,
  2575. &ip_repr.src_addr(),
  2576. &ip_repr.dst_addr(),
  2577. UDP_PAYLOAD.len(),
  2578. |buf| buf.copy_from_slice(&UDP_PAYLOAD),
  2579. &ChecksumCapabilities::default(),
  2580. );
  2581. let data = packet_unicast.into_inner();
  2582. // The expected Destination Unreachable ICMPv4 error response due
  2583. // to no sockets listening on the destination port.
  2584. let icmp_repr = Icmpv4Repr::DstUnreachable {
  2585. reason: Icmpv4DstUnreachable::PortUnreachable,
  2586. header: Ipv4Repr {
  2587. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  2588. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  2589. protocol: IpProtocol::Udp,
  2590. payload_len: udp_repr.header_len() + UDP_PAYLOAD.len(),
  2591. hop_limit: 64,
  2592. },
  2593. data: data,
  2594. };
  2595. let expected_repr = IpPacket::Icmpv4((
  2596. Ipv4Repr {
  2597. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  2598. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  2599. protocol: IpProtocol::Icmp,
  2600. payload_len: icmp_repr.buffer_len(),
  2601. hop_limit: 64,
  2602. },
  2603. icmp_repr,
  2604. ));
  2605. // Ensure that the unknown protocol triggers an error response.
  2606. // And we correctly handle no payload.
  2607. let cx = iface.context(Instant::from_secs(0));
  2608. assert_eq!(
  2609. iface
  2610. .inner
  2611. .process_udp(&cx, &mut socket_set, ip_repr, false, data),
  2612. Ok(Some(expected_repr))
  2613. );
  2614. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  2615. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  2616. dst_addr: Ipv4Address::BROADCAST,
  2617. protocol: IpProtocol::Udp,
  2618. payload_len: udp_repr.header_len() + UDP_PAYLOAD.len(),
  2619. hop_limit: 64,
  2620. });
  2621. // Emit the representations to a packet
  2622. udp_repr.emit(
  2623. &mut packet_broadcast,
  2624. &ip_repr.src_addr(),
  2625. &IpAddress::Ipv4(Ipv4Address::BROADCAST),
  2626. UDP_PAYLOAD.len(),
  2627. |buf| buf.copy_from_slice(&UDP_PAYLOAD),
  2628. &ChecksumCapabilities::default(),
  2629. );
  2630. // Ensure that the port unreachable error does not trigger an
  2631. // ICMP error response when the destination address is a
  2632. // broadcast address and no socket is bound to the port.
  2633. assert_eq!(
  2634. iface.inner.process_udp(
  2635. &cx,
  2636. &mut socket_set,
  2637. ip_repr,
  2638. false,
  2639. packet_broadcast.into_inner()
  2640. ),
  2641. Ok(None)
  2642. );
  2643. }
  2644. #[test]
  2645. #[cfg(feature = "socket-udp")]
  2646. fn test_handle_udp_broadcast() {
  2647. use crate::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer};
  2648. use crate::wire::IpEndpoint;
  2649. static UDP_PAYLOAD: [u8; 5] = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
  2650. let (iface, mut socket_set) = create_loopback();
  2651. let rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  2652. let tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  2653. let udp_socket = UdpSocket::new(rx_buffer, tx_buffer);
  2654. let mut udp_bytes = vec![0u8; 13];
  2655. let mut packet = UdpPacket::new_unchecked(&mut udp_bytes);
  2656. let socket_handle = socket_set.add(udp_socket);
  2657. #[cfg(feature = "proto-ipv6")]
  2658. let src_ip = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  2659. #[cfg(all(not(feature = "proto-ipv6"), feature = "proto-ipv4"))]
  2660. let src_ip = Ipv4Address::new(0x7f, 0x00, 0x00, 0x02);
  2661. let udp_repr = UdpRepr {
  2662. src_port: 67,
  2663. dst_port: 68,
  2664. };
  2665. #[cfg(feature = "proto-ipv6")]
  2666. let ip_repr = IpRepr::Ipv6(Ipv6Repr {
  2667. src_addr: src_ip,
  2668. dst_addr: Ipv6Address::LINK_LOCAL_ALL_NODES,
  2669. next_header: IpProtocol::Udp,
  2670. payload_len: udp_repr.header_len() + UDP_PAYLOAD.len(),
  2671. hop_limit: 0x40,
  2672. });
  2673. #[cfg(all(not(feature = "proto-ipv6"), feature = "proto-ipv4"))]
  2674. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  2675. src_addr: src_ip,
  2676. dst_addr: Ipv4Address::BROADCAST,
  2677. protocol: IpProtocol::Udp,
  2678. payload_len: udp_repr.header_len() + UDP_PAYLOAD.len(),
  2679. hop_limit: 0x40,
  2680. });
  2681. {
  2682. // Bind the socket to port 68
  2683. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  2684. assert_eq!(socket.bind(68), Ok(()));
  2685. assert!(!socket.can_recv());
  2686. assert!(socket.can_send());
  2687. }
  2688. udp_repr.emit(
  2689. &mut packet,
  2690. &ip_repr.src_addr(),
  2691. &ip_repr.dst_addr(),
  2692. UDP_PAYLOAD.len(),
  2693. |buf| buf.copy_from_slice(&UDP_PAYLOAD),
  2694. &ChecksumCapabilities::default(),
  2695. );
  2696. // Packet should be handled by bound UDP socket
  2697. let cx = iface.context(Instant::from_secs(0));
  2698. assert_eq!(
  2699. iface
  2700. .inner
  2701. .process_udp(&cx, &mut socket_set, ip_repr, false, packet.into_inner()),
  2702. Ok(None)
  2703. );
  2704. {
  2705. // Make sure the payload to the UDP packet processed by process_udp is
  2706. // appended to the bound sockets rx_buffer
  2707. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  2708. assert!(socket.can_recv());
  2709. assert_eq!(
  2710. socket.recv(),
  2711. Ok((&UDP_PAYLOAD[..], IpEndpoint::new(src_ip.into(), 67)))
  2712. );
  2713. }
  2714. }
  2715. #[test]
  2716. #[cfg(feature = "proto-ipv4")]
  2717. fn test_handle_ipv4_broadcast() {
  2718. use crate::wire::{Icmpv4Packet, Icmpv4Repr, Ipv4Packet};
  2719. let (mut iface, mut socket_set) = create_loopback();
  2720. let our_ipv4_addr = iface.ipv4_address().unwrap();
  2721. let src_ipv4_addr = Ipv4Address([127, 0, 0, 2]);
  2722. // ICMPv4 echo request
  2723. let icmpv4_data: [u8; 4] = [0xaa, 0x00, 0x00, 0xff];
  2724. let icmpv4_repr = Icmpv4Repr::EchoRequest {
  2725. ident: 0x1234,
  2726. seq_no: 0xabcd,
  2727. data: &icmpv4_data,
  2728. };
  2729. // Send to IPv4 broadcast address
  2730. let ipv4_repr = Ipv4Repr {
  2731. src_addr: src_ipv4_addr,
  2732. dst_addr: Ipv4Address::BROADCAST,
  2733. protocol: IpProtocol::Icmp,
  2734. hop_limit: 64,
  2735. payload_len: icmpv4_repr.buffer_len(),
  2736. };
  2737. // Emit to ip frame
  2738. let mut bytes = vec![0u8; ipv4_repr.buffer_len() + icmpv4_repr.buffer_len()];
  2739. let frame = {
  2740. ipv4_repr.emit(
  2741. &mut Ipv4Packet::new_unchecked(&mut bytes),
  2742. &ChecksumCapabilities::default(),
  2743. );
  2744. icmpv4_repr.emit(
  2745. &mut Icmpv4Packet::new_unchecked(&mut bytes[ipv4_repr.buffer_len()..]),
  2746. &ChecksumCapabilities::default(),
  2747. );
  2748. Ipv4Packet::new_unchecked(&bytes)
  2749. };
  2750. // Expected ICMPv4 echo reply
  2751. let expected_icmpv4_repr = Icmpv4Repr::EchoReply {
  2752. ident: 0x1234,
  2753. seq_no: 0xabcd,
  2754. data: &icmpv4_data,
  2755. };
  2756. let expected_ipv4_repr = Ipv4Repr {
  2757. src_addr: our_ipv4_addr,
  2758. dst_addr: src_ipv4_addr,
  2759. protocol: IpProtocol::Icmp,
  2760. hop_limit: 64,
  2761. payload_len: expected_icmpv4_repr.buffer_len(),
  2762. };
  2763. let expected_packet = IpPacket::Icmpv4((expected_ipv4_repr, expected_icmpv4_repr));
  2764. let cx = iface.context(Instant::from_secs(0));
  2765. assert_eq!(
  2766. iface.inner.process_ipv4(&cx, &mut socket_set, &frame),
  2767. Ok(Some(expected_packet))
  2768. );
  2769. }
  2770. #[test]
  2771. #[cfg(feature = "socket-udp")]
  2772. fn test_icmp_reply_size() {
  2773. #[cfg(feature = "proto-ipv6")]
  2774. use crate::wire::Icmpv6DstUnreachable;
  2775. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2776. use crate::wire::IPV4_MIN_MTU as MIN_MTU;
  2777. #[cfg(feature = "proto-ipv6")]
  2778. use crate::wire::IPV6_MIN_MTU as MIN_MTU;
  2779. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2780. const MAX_PAYLOAD_LEN: usize = 528;
  2781. #[cfg(feature = "proto-ipv6")]
  2782. const MAX_PAYLOAD_LEN: usize = 1192;
  2783. let (iface, mut socket_set) = create_loopback();
  2784. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2785. let src_addr = Ipv4Address([192, 168, 1, 1]);
  2786. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2787. let dst_addr = Ipv4Address([192, 168, 1, 2]);
  2788. #[cfg(feature = "proto-ipv6")]
  2789. let src_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  2790. #[cfg(feature = "proto-ipv6")]
  2791. let dst_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
  2792. // UDP packet that if not tructated will cause a icmp port unreachable reply
  2793. // to exeed the minimum mtu bytes in length.
  2794. let udp_repr = UdpRepr {
  2795. src_port: 67,
  2796. dst_port: 68,
  2797. };
  2798. let mut bytes = vec![0xff; udp_repr.header_len() + MAX_PAYLOAD_LEN];
  2799. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  2800. udp_repr.emit(
  2801. &mut packet,
  2802. &src_addr.into(),
  2803. &dst_addr.into(),
  2804. MAX_PAYLOAD_LEN,
  2805. |buf| fill_slice(buf, 0x2a),
  2806. &ChecksumCapabilities::default(),
  2807. );
  2808. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2809. let ip_repr = Ipv4Repr {
  2810. src_addr: src_addr,
  2811. dst_addr: dst_addr,
  2812. protocol: IpProtocol::Udp,
  2813. hop_limit: 64,
  2814. payload_len: udp_repr.header_len() + MAX_PAYLOAD_LEN,
  2815. };
  2816. #[cfg(feature = "proto-ipv6")]
  2817. let ip_repr = Ipv6Repr {
  2818. src_addr: src_addr,
  2819. dst_addr: dst_addr,
  2820. next_header: IpProtocol::Udp,
  2821. hop_limit: 64,
  2822. payload_len: udp_repr.header_len() + MAX_PAYLOAD_LEN,
  2823. };
  2824. let payload = packet.into_inner();
  2825. // Expected packets
  2826. #[cfg(feature = "proto-ipv6")]
  2827. let expected_icmp_repr = Icmpv6Repr::DstUnreachable {
  2828. reason: Icmpv6DstUnreachable::PortUnreachable,
  2829. header: ip_repr,
  2830. data: &payload[..MAX_PAYLOAD_LEN],
  2831. };
  2832. #[cfg(feature = "proto-ipv6")]
  2833. let expected_ip_repr = Ipv6Repr {
  2834. src_addr: dst_addr,
  2835. dst_addr: src_addr,
  2836. next_header: IpProtocol::Icmpv6,
  2837. hop_limit: 64,
  2838. payload_len: expected_icmp_repr.buffer_len(),
  2839. };
  2840. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2841. let expected_icmp_repr = Icmpv4Repr::DstUnreachable {
  2842. reason: Icmpv4DstUnreachable::PortUnreachable,
  2843. header: ip_repr,
  2844. data: &payload[..MAX_PAYLOAD_LEN],
  2845. };
  2846. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2847. let expected_ip_repr = Ipv4Repr {
  2848. src_addr: dst_addr,
  2849. dst_addr: src_addr,
  2850. protocol: IpProtocol::Icmp,
  2851. hop_limit: 64,
  2852. payload_len: expected_icmp_repr.buffer_len(),
  2853. };
  2854. let cx = iface.context(Instant::from_secs(0));
  2855. // The expected packet does not exceed the IPV4_MIN_MTU
  2856. #[cfg(feature = "proto-ipv6")]
  2857. assert_eq!(
  2858. expected_ip_repr.buffer_len() + expected_icmp_repr.buffer_len(),
  2859. MIN_MTU
  2860. );
  2861. // The expected packet does not exceed the IPV4_MIN_MTU
  2862. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2863. assert_eq!(
  2864. expected_ip_repr.buffer_len() + expected_icmp_repr.buffer_len(),
  2865. MIN_MTU
  2866. );
  2867. // The expected packet and the generated packet are equal
  2868. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2869. assert_eq!(
  2870. iface
  2871. .inner
  2872. .process_udp(&cx, &mut socket_set, ip_repr.into(), false, payload),
  2873. Ok(Some(IpPacket::Icmpv4((
  2874. expected_ip_repr,
  2875. expected_icmp_repr
  2876. ))))
  2877. );
  2878. #[cfg(feature = "proto-ipv6")]
  2879. assert_eq!(
  2880. iface
  2881. .inner
  2882. .process_udp(&cx, &mut socket_set, ip_repr.into(), false, payload),
  2883. Ok(Some(IpPacket::Icmpv6((
  2884. expected_ip_repr,
  2885. expected_icmp_repr
  2886. ))))
  2887. );
  2888. }
  2889. #[test]
  2890. #[cfg(all(feature = "medium-ethernet", feature = "proto-ipv4"))]
  2891. fn test_handle_valid_arp_request() {
  2892. let (mut iface, mut socket_set) = create_loopback_ethernet();
  2893. let mut eth_bytes = vec![0u8; 42];
  2894. let local_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x01]);
  2895. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  2896. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  2897. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  2898. let repr = ArpRepr::EthernetIpv4 {
  2899. operation: ArpOperation::Request,
  2900. source_hardware_addr: remote_hw_addr,
  2901. source_protocol_addr: remote_ip_addr,
  2902. target_hardware_addr: EthernetAddress::default(),
  2903. target_protocol_addr: local_ip_addr,
  2904. };
  2905. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2906. frame.set_dst_addr(EthernetAddress::BROADCAST);
  2907. frame.set_src_addr(remote_hw_addr);
  2908. frame.set_ethertype(EthernetProtocol::Arp);
  2909. {
  2910. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  2911. repr.emit(&mut packet);
  2912. }
  2913. let cx = iface.context(Instant::from_secs(0));
  2914. // Ensure an ARP Request for us triggers an ARP Reply
  2915. assert_eq!(
  2916. iface
  2917. .inner
  2918. .process_ethernet(&cx, &mut socket_set, frame.into_inner()),
  2919. Ok(Some(EthernetPacket::Arp(ArpRepr::EthernetIpv4 {
  2920. operation: ArpOperation::Reply,
  2921. source_hardware_addr: local_hw_addr,
  2922. source_protocol_addr: local_ip_addr,
  2923. target_hardware_addr: remote_hw_addr,
  2924. target_protocol_addr: remote_ip_addr
  2925. })))
  2926. );
  2927. // Ensure the address of the requestor was entered in the cache
  2928. assert_eq!(
  2929. iface.inner.lookup_hardware_addr(
  2930. &cx,
  2931. MockTxToken,
  2932. &IpAddress::Ipv4(local_ip_addr),
  2933. &IpAddress::Ipv4(remote_ip_addr)
  2934. ),
  2935. Ok((HardwareAddress::Ethernet(remote_hw_addr), MockTxToken))
  2936. );
  2937. }
  2938. #[test]
  2939. #[cfg(all(feature = "medium-ethernet", feature = "proto-ipv6"))]
  2940. fn test_handle_valid_ndisc_request() {
  2941. let (mut iface, mut socket_set) = create_loopback_ethernet();
  2942. let mut eth_bytes = vec![0u8; 86];
  2943. let local_ip_addr = Ipv6Address::new(0xfdbe, 0, 0, 0, 0, 0, 0, 1);
  2944. let remote_ip_addr = Ipv6Address::new(0xfdbe, 0, 0, 0, 0, 0, 0, 2);
  2945. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  2946. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  2947. let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit {
  2948. target_addr: local_ip_addr,
  2949. lladdr: Some(remote_hw_addr.into()),
  2950. });
  2951. let ip_repr = IpRepr::Ipv6(Ipv6Repr {
  2952. src_addr: remote_ip_addr,
  2953. dst_addr: local_ip_addr.solicited_node(),
  2954. next_header: IpProtocol::Icmpv6,
  2955. hop_limit: 0xff,
  2956. payload_len: solicit.buffer_len(),
  2957. });
  2958. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  2959. frame.set_dst_addr(EthernetAddress([0x33, 0x33, 0x00, 0x00, 0x00, 0x00]));
  2960. frame.set_src_addr(remote_hw_addr);
  2961. frame.set_ethertype(EthernetProtocol::Ipv6);
  2962. {
  2963. ip_repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  2964. solicit.emit(
  2965. &remote_ip_addr.into(),
  2966. &local_ip_addr.solicited_node().into(),
  2967. &mut Icmpv6Packet::new_unchecked(&mut frame.payload_mut()[ip_repr.buffer_len()..]),
  2968. &ChecksumCapabilities::default(),
  2969. );
  2970. }
  2971. let icmpv6_expected = Icmpv6Repr::Ndisc(NdiscRepr::NeighborAdvert {
  2972. flags: NdiscNeighborFlags::SOLICITED,
  2973. target_addr: local_ip_addr,
  2974. lladdr: Some(local_hw_addr.into()),
  2975. });
  2976. let ipv6_expected = Ipv6Repr {
  2977. src_addr: local_ip_addr,
  2978. dst_addr: remote_ip_addr,
  2979. next_header: IpProtocol::Icmpv6,
  2980. hop_limit: 0xff,
  2981. payload_len: icmpv6_expected.buffer_len(),
  2982. };
  2983. let cx = iface.context(Instant::from_secs(0));
  2984. // Ensure an Neighbor Solicitation triggers a Neighbor Advertisement
  2985. assert_eq!(
  2986. iface
  2987. .inner
  2988. .process_ethernet(&cx, &mut socket_set, frame.into_inner()),
  2989. Ok(Some(EthernetPacket::Ip(IpPacket::Icmpv6((
  2990. ipv6_expected,
  2991. icmpv6_expected
  2992. )))))
  2993. );
  2994. // Ensure the address of the requestor was entered in the cache
  2995. assert_eq!(
  2996. iface.inner.lookup_hardware_addr(
  2997. &cx,
  2998. MockTxToken,
  2999. &IpAddress::Ipv6(local_ip_addr),
  3000. &IpAddress::Ipv6(remote_ip_addr)
  3001. ),
  3002. Ok((HardwareAddress::Ethernet(remote_hw_addr), MockTxToken))
  3003. );
  3004. }
  3005. #[test]
  3006. #[cfg(all(feature = "medium-ethernet", feature = "proto-ipv4"))]
  3007. fn test_handle_other_arp_request() {
  3008. let (mut iface, mut socket_set) = create_loopback_ethernet();
  3009. let mut eth_bytes = vec![0u8; 42];
  3010. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  3011. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  3012. let repr = ArpRepr::EthernetIpv4 {
  3013. operation: ArpOperation::Request,
  3014. source_hardware_addr: remote_hw_addr,
  3015. source_protocol_addr: remote_ip_addr,
  3016. target_hardware_addr: EthernetAddress::default(),
  3017. target_protocol_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x03]),
  3018. };
  3019. let mut frame = EthernetFrame::new_unchecked(&mut eth_bytes);
  3020. frame.set_dst_addr(EthernetAddress::BROADCAST);
  3021. frame.set_src_addr(remote_hw_addr);
  3022. frame.set_ethertype(EthernetProtocol::Arp);
  3023. {
  3024. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  3025. repr.emit(&mut packet);
  3026. }
  3027. let cx = iface.context(Instant::from_secs(0));
  3028. // Ensure an ARP Request for someone else does not trigger an ARP Reply
  3029. assert_eq!(
  3030. iface
  3031. .inner
  3032. .process_ethernet(&cx, &mut socket_set, frame.into_inner()),
  3033. Ok(None)
  3034. );
  3035. // Ensure the address of the requestor was NOT entered in the cache
  3036. assert_eq!(
  3037. iface.inner.lookup_hardware_addr(
  3038. &cx,
  3039. MockTxToken,
  3040. &IpAddress::Ipv4(Ipv4Address([0x7f, 0x00, 0x00, 0x01])),
  3041. &IpAddress::Ipv4(remote_ip_addr)
  3042. ),
  3043. Err(Error::Unaddressable)
  3044. );
  3045. }
  3046. #[test]
  3047. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  3048. fn test_icmpv4_socket() {
  3049. use crate::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer};
  3050. use crate::wire::Icmpv4Packet;
  3051. let (iface, mut socket_set) = create_loopback();
  3052. let rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 24]);
  3053. let tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 24]);
  3054. let icmpv4_socket = IcmpSocket::new(rx_buffer, tx_buffer);
  3055. let socket_handle = socket_set.add(icmpv4_socket);
  3056. let ident = 0x1234;
  3057. let seq_no = 0x5432;
  3058. let echo_data = &[0xff; 16];
  3059. {
  3060. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  3061. // Bind to the ID 0x1234
  3062. assert_eq!(socket.bind(IcmpEndpoint::Ident(ident)), Ok(()));
  3063. }
  3064. // Ensure the ident we bound to and the ident of the packet are the same.
  3065. let mut bytes = [0xff; 24];
  3066. let mut packet = Icmpv4Packet::new_unchecked(&mut bytes);
  3067. let echo_repr = Icmpv4Repr::EchoRequest {
  3068. ident,
  3069. seq_no,
  3070. data: echo_data,
  3071. };
  3072. echo_repr.emit(&mut packet, &ChecksumCapabilities::default());
  3073. let icmp_data = &packet.into_inner()[..];
  3074. let ipv4_repr = Ipv4Repr {
  3075. src_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x02),
  3076. dst_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x01),
  3077. protocol: IpProtocol::Icmp,
  3078. payload_len: 24,
  3079. hop_limit: 64,
  3080. };
  3081. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  3082. // Open a socket and ensure the packet is handled due to the listening
  3083. // socket.
  3084. {
  3085. assert!(!socket_set.get::<IcmpSocket>(socket_handle).can_recv());
  3086. }
  3087. // Confirm we still get EchoReply from `smoltcp` even with the ICMP socket listening
  3088. let echo_reply = Icmpv4Repr::EchoReply {
  3089. ident,
  3090. seq_no,
  3091. data: echo_data,
  3092. };
  3093. let ipv4_reply = Ipv4Repr {
  3094. src_addr: ipv4_repr.dst_addr,
  3095. dst_addr: ipv4_repr.src_addr,
  3096. ..ipv4_repr
  3097. };
  3098. let cx = iface.context(Instant::from_secs(0));
  3099. assert_eq!(
  3100. iface
  3101. .inner
  3102. .process_icmpv4(&cx, &mut socket_set, ip_repr, icmp_data),
  3103. Ok(Some(IpPacket::Icmpv4((ipv4_reply, echo_reply))))
  3104. );
  3105. {
  3106. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  3107. assert!(socket.can_recv());
  3108. assert_eq!(
  3109. socket.recv(),
  3110. Ok((
  3111. icmp_data,
  3112. IpAddress::Ipv4(Ipv4Address::new(0x7f, 0x00, 0x00, 0x02))
  3113. ))
  3114. );
  3115. }
  3116. }
  3117. #[test]
  3118. #[cfg(feature = "proto-ipv6")]
  3119. fn test_solicited_node_addrs() {
  3120. let (mut iface, _) = create_loopback();
  3121. let mut new_addrs = vec![
  3122. IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 1, 2, 0, 2), 64),
  3123. IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 3, 4, 0, 0xffff), 64),
  3124. ];
  3125. iface.update_ip_addrs(|addrs| {
  3126. new_addrs.extend(addrs.to_vec());
  3127. *addrs = From::from(new_addrs);
  3128. });
  3129. assert!(iface
  3130. .inner
  3131. .has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0x0002)));
  3132. assert!(iface
  3133. .inner
  3134. .has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0xffff)));
  3135. assert!(!iface
  3136. .inner
  3137. .has_solicited_node(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff00, 0x0003)));
  3138. }
  3139. #[test]
  3140. #[cfg(feature = "proto-ipv6")]
  3141. fn test_icmpv6_nxthdr_unknown() {
  3142. let (mut iface, mut socket_set) = create_loopback();
  3143. let remote_ip_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  3144. let payload = [0x12, 0x34, 0x56, 0x78];
  3145. let ipv6_repr = Ipv6Repr {
  3146. src_addr: remote_ip_addr,
  3147. dst_addr: Ipv6Address::LOOPBACK,
  3148. next_header: IpProtocol::HopByHop,
  3149. payload_len: 12,
  3150. hop_limit: 0x40,
  3151. };
  3152. let mut bytes = vec![0; 52];
  3153. let frame = {
  3154. let ip_repr = IpRepr::Ipv6(ipv6_repr);
  3155. ip_repr.emit(&mut bytes, &ChecksumCapabilities::default());
  3156. let mut offset = ipv6_repr.buffer_len();
  3157. {
  3158. let mut hbh_pkt = Ipv6HopByHopHeader::new_unchecked(&mut bytes[offset..]);
  3159. hbh_pkt.set_next_header(IpProtocol::Unknown(0x0c));
  3160. hbh_pkt.set_header_len(0);
  3161. offset += 8;
  3162. {
  3163. let mut pad_pkt = Ipv6Option::new_unchecked(&mut *hbh_pkt.options_mut());
  3164. Ipv6OptionRepr::PadN(3).emit(&mut pad_pkt);
  3165. }
  3166. {
  3167. let mut pad_pkt = Ipv6Option::new_unchecked(&mut hbh_pkt.options_mut()[5..]);
  3168. Ipv6OptionRepr::Pad1.emit(&mut pad_pkt);
  3169. }
  3170. }
  3171. bytes[offset..].copy_from_slice(&payload);
  3172. Ipv6Packet::new_unchecked(&bytes)
  3173. };
  3174. let reply_icmp_repr = Icmpv6Repr::ParamProblem {
  3175. reason: Icmpv6ParamProblem::UnrecognizedNxtHdr,
  3176. pointer: 40,
  3177. header: ipv6_repr,
  3178. data: &payload[..],
  3179. };
  3180. let reply_ipv6_repr = Ipv6Repr {
  3181. src_addr: Ipv6Address::LOOPBACK,
  3182. dst_addr: remote_ip_addr,
  3183. next_header: IpProtocol::Icmpv6,
  3184. payload_len: reply_icmp_repr.buffer_len(),
  3185. hop_limit: 0x40,
  3186. };
  3187. let cx = iface.context(Instant::from_secs(0));
  3188. // Ensure the unknown next header causes a ICMPv6 Parameter Problem
  3189. // error message to be sent to the sender.
  3190. assert_eq!(
  3191. iface.inner.process_ipv6(&cx, &mut socket_set, &frame),
  3192. Ok(Some(IpPacket::Icmpv6((reply_ipv6_repr, reply_icmp_repr))))
  3193. );
  3194. }
  3195. #[test]
  3196. #[cfg(feature = "proto-igmp")]
  3197. fn test_handle_igmp() {
  3198. fn recv_igmp(
  3199. mut iface: &mut Interface<'_, Loopback>,
  3200. timestamp: Instant,
  3201. ) -> Vec<(Ipv4Repr, IgmpRepr)> {
  3202. let caps = iface.device.capabilities();
  3203. let checksum_caps = &caps.checksum;
  3204. recv_all(&mut iface, timestamp)
  3205. .iter()
  3206. .filter_map(|frame| {
  3207. let ipv4_packet = match caps.medium {
  3208. #[cfg(feature = "medium-ethernet")]
  3209. Medium::Ethernet => {
  3210. let eth_frame = EthernetFrame::new_checked(frame).ok()?;
  3211. Ipv4Packet::new_checked(eth_frame.payload()).ok()?
  3212. }
  3213. #[cfg(feature = "medium-ip")]
  3214. Medium::Ip => Ipv4Packet::new_checked(&frame[..]).ok()?,
  3215. #[cfg(feature = "medium-ieee802154")]
  3216. Medium::Ieee802154 => todo!(),
  3217. };
  3218. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, checksum_caps).ok()?;
  3219. let ip_payload = ipv4_packet.payload();
  3220. let igmp_packet = IgmpPacket::new_checked(ip_payload).ok()?;
  3221. let igmp_repr = IgmpRepr::parse(&igmp_packet).ok()?;
  3222. Some((ipv4_repr, igmp_repr))
  3223. })
  3224. .collect::<Vec<_>>()
  3225. }
  3226. let groups = [
  3227. Ipv4Address::new(224, 0, 0, 22),
  3228. Ipv4Address::new(224, 0, 0, 56),
  3229. ];
  3230. let (mut iface, mut socket_set) = create_loopback();
  3231. // Join multicast groups
  3232. let timestamp = Instant::now();
  3233. for group in &groups {
  3234. iface.join_multicast_group(*group, timestamp).unwrap();
  3235. }
  3236. let reports = recv_igmp(&mut iface, timestamp);
  3237. assert_eq!(reports.len(), 2);
  3238. for (i, group_addr) in groups.iter().enumerate() {
  3239. assert_eq!(reports[i].0.protocol, IpProtocol::Igmp);
  3240. assert_eq!(reports[i].0.dst_addr, *group_addr);
  3241. assert_eq!(
  3242. reports[i].1,
  3243. IgmpRepr::MembershipReport {
  3244. group_addr: *group_addr,
  3245. version: IgmpVersion::Version2,
  3246. }
  3247. );
  3248. }
  3249. // General query
  3250. let timestamp = Instant::now();
  3251. const GENERAL_QUERY_BYTES: &[u8] = &[
  3252. 0x46, 0xc0, 0x00, 0x24, 0xed, 0xb4, 0x00, 0x00, 0x01, 0x02, 0x47, 0x43, 0xac, 0x16,
  3253. 0x63, 0x04, 0xe0, 0x00, 0x00, 0x01, 0x94, 0x04, 0x00, 0x00, 0x11, 0x64, 0xec, 0x8f,
  3254. 0x00, 0x00, 0x00, 0x00, 0x02, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  3255. 0x00, 0x00, 0x00, 0x00,
  3256. ];
  3257. {
  3258. // Transmit GENERAL_QUERY_BYTES into loopback
  3259. let tx_token = iface.device.transmit().unwrap();
  3260. tx_token
  3261. .consume(timestamp, GENERAL_QUERY_BYTES.len(), |buffer| {
  3262. buffer.copy_from_slice(GENERAL_QUERY_BYTES);
  3263. Ok(())
  3264. })
  3265. .unwrap();
  3266. }
  3267. // Trigger processing until all packets received through the
  3268. // loopback have been processed, including responses to
  3269. // GENERAL_QUERY_BYTES. Therefore `recv_all()` would return 0
  3270. // pkts that could be checked.
  3271. let cx = iface.context(timestamp);
  3272. iface.socket_ingress(&cx, &mut socket_set);
  3273. // Leave multicast groups
  3274. let timestamp = Instant::now();
  3275. for group in &groups {
  3276. iface.leave_multicast_group(*group, timestamp).unwrap();
  3277. }
  3278. let leaves = recv_igmp(&mut iface, timestamp);
  3279. assert_eq!(leaves.len(), 2);
  3280. for (i, group_addr) in groups.iter().cloned().enumerate() {
  3281. assert_eq!(leaves[i].0.protocol, IpProtocol::Igmp);
  3282. assert_eq!(leaves[i].0.dst_addr, Ipv4Address::MULTICAST_ALL_ROUTERS);
  3283. assert_eq!(leaves[i].1, IgmpRepr::LeaveGroup { group_addr });
  3284. }
  3285. }
  3286. #[test]
  3287. #[cfg(all(feature = "proto-ipv4", feature = "socket-raw"))]
  3288. fn test_raw_socket_no_reply() {
  3289. use crate::socket::{RawPacketMetadata, RawSocket, RawSocketBuffer};
  3290. use crate::wire::{IpVersion, Ipv4Packet, UdpPacket, UdpRepr};
  3291. let (mut iface, mut socket_set) = create_loopback();
  3292. let packets = 1;
  3293. let rx_buffer =
  3294. RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * 1]);
  3295. let tx_buffer = RawSocketBuffer::new(
  3296. vec![RawPacketMetadata::EMPTY; packets],
  3297. vec![0; 48 * packets],
  3298. );
  3299. let raw_socket = RawSocket::new(IpVersion::Ipv4, IpProtocol::Udp, rx_buffer, tx_buffer);
  3300. socket_set.add(raw_socket);
  3301. let src_addr = Ipv4Address([127, 0, 0, 2]);
  3302. let dst_addr = Ipv4Address([127, 0, 0, 1]);
  3303. const PAYLOAD_LEN: usize = 10;
  3304. let udp_repr = UdpRepr {
  3305. src_port: 67,
  3306. dst_port: 68,
  3307. };
  3308. let mut bytes = vec![0xff; udp_repr.header_len() + PAYLOAD_LEN];
  3309. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  3310. udp_repr.emit(
  3311. &mut packet,
  3312. &src_addr.into(),
  3313. &dst_addr.into(),
  3314. PAYLOAD_LEN,
  3315. |buf| fill_slice(buf, 0x2a),
  3316. &ChecksumCapabilities::default(),
  3317. );
  3318. let ipv4_repr = Ipv4Repr {
  3319. src_addr: src_addr,
  3320. dst_addr: dst_addr,
  3321. protocol: IpProtocol::Udp,
  3322. hop_limit: 64,
  3323. payload_len: udp_repr.header_len() + PAYLOAD_LEN,
  3324. };
  3325. // Emit to frame
  3326. let mut bytes = vec![0u8; ipv4_repr.buffer_len() + udp_repr.header_len() + PAYLOAD_LEN];
  3327. let frame = {
  3328. ipv4_repr.emit(
  3329. &mut Ipv4Packet::new_unchecked(&mut bytes),
  3330. &ChecksumCapabilities::default(),
  3331. );
  3332. udp_repr.emit(
  3333. &mut UdpPacket::new_unchecked(&mut bytes[ipv4_repr.buffer_len()..]),
  3334. &src_addr.into(),
  3335. &dst_addr.into(),
  3336. PAYLOAD_LEN,
  3337. |buf| fill_slice(buf, 0x2a),
  3338. &ChecksumCapabilities::default(),
  3339. );
  3340. Ipv4Packet::new_unchecked(&bytes)
  3341. };
  3342. let cx = iface.context(Instant::from_millis(0));
  3343. assert_eq!(
  3344. iface.inner.process_ipv4(&cx, &mut socket_set, &frame),
  3345. Ok(None)
  3346. );
  3347. }
  3348. #[test]
  3349. #[cfg(all(feature = "proto-ipv4", feature = "socket-raw"))]
  3350. fn test_raw_socket_truncated_packet() {
  3351. use crate::socket::{RawPacketMetadata, RawSocket, RawSocketBuffer};
  3352. use crate::wire::{IpVersion, Ipv4Packet, UdpPacket, UdpRepr};
  3353. let (mut iface, mut socket_set) = create_loopback();
  3354. let packets = 1;
  3355. let rx_buffer =
  3356. RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * 1]);
  3357. let tx_buffer = RawSocketBuffer::new(
  3358. vec![RawPacketMetadata::EMPTY; packets],
  3359. vec![0; 48 * packets],
  3360. );
  3361. let raw_socket = RawSocket::new(IpVersion::Ipv4, IpProtocol::Udp, rx_buffer, tx_buffer);
  3362. socket_set.add(raw_socket);
  3363. let src_addr = Ipv4Address([127, 0, 0, 2]);
  3364. let dst_addr = Ipv4Address([127, 0, 0, 1]);
  3365. const PAYLOAD_LEN: usize = 49; // 49 > 48, hence packet will be truncated
  3366. let udp_repr = UdpRepr {
  3367. src_port: 67,
  3368. dst_port: 68,
  3369. };
  3370. let mut bytes = vec![0xff; udp_repr.header_len() + PAYLOAD_LEN];
  3371. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  3372. udp_repr.emit(
  3373. &mut packet,
  3374. &src_addr.into(),
  3375. &dst_addr.into(),
  3376. PAYLOAD_LEN,
  3377. |buf| fill_slice(buf, 0x2a),
  3378. &ChecksumCapabilities::default(),
  3379. );
  3380. let ipv4_repr = Ipv4Repr {
  3381. src_addr: src_addr,
  3382. dst_addr: dst_addr,
  3383. protocol: IpProtocol::Udp,
  3384. hop_limit: 64,
  3385. payload_len: udp_repr.header_len() + PAYLOAD_LEN,
  3386. };
  3387. // Emit to frame
  3388. let mut bytes = vec![0u8; ipv4_repr.buffer_len() + udp_repr.header_len() + PAYLOAD_LEN];
  3389. let frame = {
  3390. ipv4_repr.emit(
  3391. &mut Ipv4Packet::new_unchecked(&mut bytes),
  3392. &ChecksumCapabilities::default(),
  3393. );
  3394. udp_repr.emit(
  3395. &mut UdpPacket::new_unchecked(&mut bytes[ipv4_repr.buffer_len()..]),
  3396. &src_addr.into(),
  3397. &dst_addr.into(),
  3398. PAYLOAD_LEN,
  3399. |buf| fill_slice(buf, 0x2a),
  3400. &ChecksumCapabilities::default(),
  3401. );
  3402. Ipv4Packet::new_unchecked(&bytes)
  3403. };
  3404. let cx = iface.context(Instant::from_millis(0));
  3405. let frame = iface.inner.process_ipv4(&cx, &mut socket_set, &frame);
  3406. // because the packet could not be handled we should send an Icmp message
  3407. assert!(match frame {
  3408. Ok(Some(IpPacket::Icmpv4(_))) => true,
  3409. _ => false,
  3410. });
  3411. }
  3412. #[test]
  3413. #[cfg(all(feature = "proto-ipv4", feature = "socket-raw", feature = "socket-udp"))]
  3414. fn test_raw_socket_with_udp_socket() {
  3415. use crate::socket::{
  3416. RawPacketMetadata, RawSocket, RawSocketBuffer, UdpPacketMetadata, UdpSocket,
  3417. UdpSocketBuffer,
  3418. };
  3419. use crate::wire::{IpEndpoint, IpVersion, Ipv4Packet, UdpPacket, UdpRepr};
  3420. static UDP_PAYLOAD: [u8; 5] = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
  3421. let (mut iface, mut socket_set) = create_loopback();
  3422. let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  3423. let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 15]);
  3424. let udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer);
  3425. let udp_socket_handle = socket_set.add(udp_socket);
  3426. {
  3427. // Bind the socket to port 68
  3428. let mut socket = socket_set.get::<UdpSocket>(udp_socket_handle);
  3429. assert_eq!(socket.bind(68), Ok(()));
  3430. assert!(!socket.can_recv());
  3431. assert!(socket.can_send());
  3432. }
  3433. let packets = 1;
  3434. let raw_rx_buffer =
  3435. RawSocketBuffer::new(vec![RawPacketMetadata::EMPTY; packets], vec![0; 48 * 1]);
  3436. let raw_tx_buffer = RawSocketBuffer::new(
  3437. vec![RawPacketMetadata::EMPTY; packets],
  3438. vec![0; 48 * packets],
  3439. );
  3440. let raw_socket = RawSocket::new(
  3441. IpVersion::Ipv4,
  3442. IpProtocol::Udp,
  3443. raw_rx_buffer,
  3444. raw_tx_buffer,
  3445. );
  3446. socket_set.add(raw_socket);
  3447. let src_addr = Ipv4Address([127, 0, 0, 2]);
  3448. let dst_addr = Ipv4Address([127, 0, 0, 1]);
  3449. let udp_repr = UdpRepr {
  3450. src_port: 67,
  3451. dst_port: 68,
  3452. };
  3453. let mut bytes = vec![0xff; udp_repr.header_len() + UDP_PAYLOAD.len()];
  3454. let mut packet = UdpPacket::new_unchecked(&mut bytes[..]);
  3455. udp_repr.emit(
  3456. &mut packet,
  3457. &src_addr.into(),
  3458. &dst_addr.into(),
  3459. UDP_PAYLOAD.len(),
  3460. |buf| buf.copy_from_slice(&UDP_PAYLOAD),
  3461. &ChecksumCapabilities::default(),
  3462. );
  3463. let ipv4_repr = Ipv4Repr {
  3464. src_addr: src_addr,
  3465. dst_addr: dst_addr,
  3466. protocol: IpProtocol::Udp,
  3467. hop_limit: 64,
  3468. payload_len: udp_repr.header_len() + UDP_PAYLOAD.len(),
  3469. };
  3470. // Emit to frame
  3471. let mut bytes =
  3472. vec![0u8; ipv4_repr.buffer_len() + udp_repr.header_len() + UDP_PAYLOAD.len()];
  3473. let frame = {
  3474. ipv4_repr.emit(
  3475. &mut Ipv4Packet::new_unchecked(&mut bytes),
  3476. &ChecksumCapabilities::default(),
  3477. );
  3478. udp_repr.emit(
  3479. &mut UdpPacket::new_unchecked(&mut bytes[ipv4_repr.buffer_len()..]),
  3480. &src_addr.into(),
  3481. &dst_addr.into(),
  3482. UDP_PAYLOAD.len(),
  3483. |buf| buf.copy_from_slice(&UDP_PAYLOAD),
  3484. &ChecksumCapabilities::default(),
  3485. );
  3486. Ipv4Packet::new_unchecked(&bytes)
  3487. };
  3488. let cx = iface.context(Instant::from_millis(0));
  3489. assert_eq!(
  3490. iface.inner.process_ipv4(&cx, &mut socket_set, &frame),
  3491. Ok(None)
  3492. );
  3493. {
  3494. // Make sure the UDP socket can still receive in presence of a Raw socket that handles UDP
  3495. let mut socket = socket_set.get::<UdpSocket>(udp_socket_handle);
  3496. assert!(socket.can_recv());
  3497. assert_eq!(
  3498. socket.recv(),
  3499. Ok((&UDP_PAYLOAD[..], IpEndpoint::new(src_addr.into(), 67)))
  3500. );
  3501. }
  3502. }
  3503. }