interface.rs 146 KB

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