interface.rs 149 KB

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