interface.rs 145 KB

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