mod.rs 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303
  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. #[cfg(test)]
  5. mod tests;
  6. #[cfg(feature = "medium-ethernet")]
  7. mod ethernet;
  8. #[cfg(feature = "proto-sixlowpan")]
  9. mod sixlowpan;
  10. #[cfg(feature = "proto-ipv4")]
  11. mod ipv4;
  12. #[cfg(feature = "proto-ipv6")]
  13. mod ipv6;
  14. use core::cmp;
  15. use managed::{ManagedMap, ManagedSlice};
  16. #[cfg(any(feature = "proto-ipv4", feature = "proto-sixlowpan"))]
  17. use super::fragmentation::PacketAssemblerSet;
  18. use super::socket_set::SocketSet;
  19. use crate::iface::Routes;
  20. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  21. use crate::iface::{NeighborAnswer, NeighborCache};
  22. use crate::phy::{ChecksumCapabilities, Device, DeviceCapabilities, Medium, RxToken, TxToken};
  23. use crate::rand::Rand;
  24. #[cfg(feature = "socket-dns")]
  25. use crate::socket::dns;
  26. use crate::socket::*;
  27. use crate::time::{Duration, Instant};
  28. use crate::wire::*;
  29. use crate::{Error, Result};
  30. pub(crate) struct FragmentsBuffer<'a> {
  31. #[cfg(feature = "proto-ipv4-fragmentation")]
  32. pub(crate) ipv4_fragments: PacketAssemblerSet<'a, Ipv4FragKey>,
  33. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  34. sixlowpan_fragments: PacketAssemblerSet<'a, SixlowpanFragKey>,
  35. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  36. sixlowpan_fragments_cache_timeout: Duration,
  37. #[cfg(not(any(
  38. feature = "proto-ipv4-fragmentation",
  39. feature = "proto-sixlowpan-fragmentation"
  40. )))]
  41. _lifetime: core::marker::PhantomData<&'a ()>,
  42. }
  43. pub(crate) struct OutPackets<'a> {
  44. #[cfg(feature = "proto-ipv4-fragmentation")]
  45. ipv4_out_packet: Ipv4OutPacket<'a>,
  46. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  47. sixlowpan_out_packet: SixlowpanOutPacket<'a>,
  48. #[cfg(not(feature = "proto-sixlowpan-fragmentation"))]
  49. _lifetime: core::marker::PhantomData<&'a ()>,
  50. }
  51. impl<'a> OutPackets<'a> {
  52. #[cfg(any(
  53. feature = "proto-ipv4-fragmentation",
  54. feature = "proto-sixlowpan-fragmentation"
  55. ))]
  56. /// Returns `true` when all the data of the outgoing buffers are transmitted.
  57. fn all_transmitted(&self) -> bool {
  58. #[cfg(feature = "proto-ipv4-fragmentation")]
  59. if !self.ipv4_out_packet.is_empty() {
  60. return false;
  61. }
  62. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  63. if !self.sixlowpan_out_packet.is_empty() {
  64. return false;
  65. }
  66. true
  67. }
  68. }
  69. #[allow(unused)]
  70. #[cfg(feature = "proto-ipv4-fragmentation")]
  71. pub(crate) struct Ipv4OutPacket<'a> {
  72. /// The buffer that holds the unfragmented 6LoWPAN packet.
  73. buffer: ManagedSlice<'a, u8>,
  74. /// The size of the packet without the IEEE802.15.4 header and the fragmentation headers.
  75. packet_len: usize,
  76. /// The amount of bytes that already have been transmitted.
  77. sent_bytes: usize,
  78. /// The IPv4 representation.
  79. repr: Ipv4Repr,
  80. /// The destination hardware address.
  81. #[cfg(feature = "medium-ethernet")]
  82. dst_hardware_addr: EthernetAddress,
  83. /// The offset of the next fragment.
  84. frag_offset: u16,
  85. /// The identifier of the stream.
  86. ident: u16,
  87. }
  88. #[cfg(feature = "proto-ipv4-fragmentation")]
  89. impl<'a> Ipv4OutPacket<'a> {
  90. pub(crate) fn new(buffer: ManagedSlice<'a, u8>) -> Self {
  91. Self {
  92. buffer,
  93. packet_len: 0,
  94. sent_bytes: 0,
  95. repr: Ipv4Repr {
  96. src_addr: Ipv4Address::default(),
  97. dst_addr: Ipv4Address::default(),
  98. next_header: IpProtocol::Unknown(0),
  99. payload_len: 0,
  100. hop_limit: 0,
  101. },
  102. #[cfg(feature = "medium-ethernet")]
  103. dst_hardware_addr: EthernetAddress::default(),
  104. frag_offset: 0,
  105. ident: 0,
  106. }
  107. }
  108. /// Return `true` when everything is transmitted.
  109. #[inline]
  110. fn finished(&self) -> bool {
  111. self.packet_len == self.sent_bytes
  112. }
  113. /// Returns `true` when there is nothing to transmit.
  114. #[inline]
  115. fn is_empty(&self) -> bool {
  116. self.packet_len == 0
  117. }
  118. // Reset the buffer.
  119. fn reset(&mut self) {
  120. self.packet_len = 0;
  121. self.sent_bytes = 0;
  122. self.repr = Ipv4Repr {
  123. src_addr: Ipv4Address::default(),
  124. dst_addr: Ipv4Address::default(),
  125. next_header: IpProtocol::Unknown(0),
  126. payload_len: 0,
  127. hop_limit: 0,
  128. };
  129. #[cfg(feature = "medium-ethernet")]
  130. {
  131. self.dst_hardware_addr = EthernetAddress::default();
  132. }
  133. }
  134. }
  135. #[allow(unused)]
  136. #[cfg(feature = "proto-sixlowpan")]
  137. pub(crate) struct SixlowpanOutPacket<'a> {
  138. /// The buffer that holds the unfragmented 6LoWPAN packet.
  139. buffer: ManagedSlice<'a, u8>,
  140. /// The size of the packet without the IEEE802.15.4 header and the fragmentation headers.
  141. packet_len: usize,
  142. /// The amount of bytes that already have been transmitted.
  143. sent_bytes: usize,
  144. /// The datagram size that is used for the fragmentation headers.
  145. datagram_size: u16,
  146. /// The datagram tag that is used for the fragmentation headers.
  147. datagram_tag: u16,
  148. datagram_offset: usize,
  149. /// The size of the FRAG_N packets.
  150. fragn_size: usize,
  151. /// The link layer IEEE802.15.4 source address.
  152. ll_dst_addr: Ieee802154Address,
  153. /// The link layer IEEE802.15.4 source address.
  154. ll_src_addr: Ieee802154Address,
  155. }
  156. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  157. impl<'a> SixlowpanOutPacket<'a> {
  158. pub(crate) fn new(buffer: ManagedSlice<'a, u8>) -> Self {
  159. Self {
  160. buffer,
  161. packet_len: 0,
  162. datagram_size: 0,
  163. datagram_tag: 0,
  164. datagram_offset: 0,
  165. sent_bytes: 0,
  166. fragn_size: 0,
  167. ll_dst_addr: Ieee802154Address::Absent,
  168. ll_src_addr: Ieee802154Address::Absent,
  169. }
  170. }
  171. /// Return `true` when everything is transmitted.
  172. #[inline]
  173. fn finished(&self) -> bool {
  174. self.packet_len == self.sent_bytes
  175. }
  176. /// Returns `true` when there is nothing to transmit.
  177. #[inline]
  178. fn is_empty(&self) -> bool {
  179. self.packet_len == 0
  180. }
  181. // Reset the buffer.
  182. fn reset(&mut self) {
  183. self.packet_len = 0;
  184. self.datagram_size = 0;
  185. self.datagram_tag = 0;
  186. self.sent_bytes = 0;
  187. self.fragn_size = 0;
  188. self.ll_dst_addr = Ieee802154Address::Absent;
  189. self.ll_src_addr = Ieee802154Address::Absent;
  190. }
  191. }
  192. macro_rules! check {
  193. ($e:expr) => {
  194. match $e {
  195. Ok(x) => x,
  196. Err(_) => {
  197. // concat!/stringify! doesn't work with defmt macros
  198. #[cfg(not(feature = "defmt"))]
  199. net_trace!(concat!("iface: malformed ", stringify!($e)));
  200. #[cfg(feature = "defmt")]
  201. net_trace!("iface: malformed");
  202. return Default::default();
  203. }
  204. }
  205. };
  206. }
  207. use check;
  208. /// A network interface.
  209. ///
  210. /// The network interface logically owns a number of other data structures; to avoid
  211. /// a dependency on heap allocation, it instead owns a `BorrowMut<[T]>`, which can be
  212. /// a `&mut [T]`, or `Vec<T>` if a heap is available.
  213. pub struct Interface<'a> {
  214. inner: InterfaceInner<'a>,
  215. fragments: FragmentsBuffer<'a>,
  216. out_packets: OutPackets<'a>,
  217. }
  218. /// The device independent part of an Ethernet network interface.
  219. ///
  220. /// Separating the device from the data required for processing and dispatching makes
  221. /// it possible to borrow them independently. For example, the tx and rx tokens borrow
  222. /// the `device` mutably until they're used, which makes it impossible to call other
  223. /// methods on the `Interface` in this time (since its `device` field is borrowed
  224. /// exclusively). However, it is still possible to call methods on its `inner` field.
  225. pub struct InterfaceInner<'a> {
  226. caps: DeviceCapabilities,
  227. now: Instant,
  228. rand: Rand,
  229. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  230. neighbor_cache: Option<NeighborCache<'a>>,
  231. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  232. hardware_addr: Option<HardwareAddress>,
  233. #[cfg(feature = "medium-ieee802154")]
  234. sequence_no: u8,
  235. #[cfg(feature = "medium-ieee802154")]
  236. pan_id: Option<Ieee802154Pan>,
  237. #[cfg(feature = "proto-ipv4-fragmentation")]
  238. ipv4_id: u16,
  239. #[cfg(feature = "proto-sixlowpan")]
  240. sixlowpan_address_context: &'a [SixlowpanAddressContext<'a>],
  241. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  242. tag: u16,
  243. ip_addrs: ManagedSlice<'a, IpCidr>,
  244. #[cfg(feature = "proto-ipv4")]
  245. any_ip: bool,
  246. routes: Routes<'a>,
  247. #[cfg(feature = "proto-igmp")]
  248. ipv4_multicast_groups: ManagedMap<'a, Ipv4Address, ()>,
  249. /// When to report for (all or) the next multicast group membership via IGMP
  250. #[cfg(feature = "proto-igmp")]
  251. igmp_report_state: IgmpReportState,
  252. }
  253. /// A builder structure used for creating a network interface.
  254. pub struct InterfaceBuilder<'a> {
  255. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  256. hardware_addr: Option<HardwareAddress>,
  257. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  258. neighbor_cache: Option<NeighborCache<'a>>,
  259. #[cfg(feature = "medium-ieee802154")]
  260. pan_id: Option<Ieee802154Pan>,
  261. ip_addrs: ManagedSlice<'a, IpCidr>,
  262. #[cfg(feature = "proto-ipv4")]
  263. any_ip: bool,
  264. routes: Routes<'a>,
  265. /// Does not share storage with `ipv6_multicast_groups` to avoid IPv6 size overhead.
  266. #[cfg(feature = "proto-igmp")]
  267. ipv4_multicast_groups: ManagedMap<'a, Ipv4Address, ()>,
  268. random_seed: u64,
  269. #[cfg(feature = "proto-ipv4-fragmentation")]
  270. ipv4_fragments: PacketAssemblerSet<'a, Ipv4FragKey>,
  271. #[cfg(feature = "proto-ipv4-fragmentation")]
  272. ipv4_out_buffer: ManagedSlice<'a, u8>,
  273. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  274. sixlowpan_fragments: PacketAssemblerSet<'a, SixlowpanFragKey>,
  275. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  276. sixlowpan_reassembly_buffer_timeout: Duration,
  277. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  278. sixlowpan_out_buffer: ManagedSlice<'a, u8>,
  279. #[cfg(feature = "proto-sixlowpan")]
  280. sixlowpan_address_context: &'a [SixlowpanAddressContext<'a>],
  281. }
  282. impl<'a> InterfaceBuilder<'a> {
  283. /// Create a builder used for creating a network interface using the
  284. /// given device and address.
  285. #[cfg_attr(
  286. all(feature = "medium-ethernet", not(feature = "proto-sixlowpan")),
  287. doc = r##"
  288. # Examples
  289. ```
  290. # use std::collections::BTreeMap;
  291. #[cfg(feature = "proto-ipv4-fragmentation")]
  292. use smoltcp::iface::ReassemblyBuffer;
  293. use smoltcp::iface::{InterfaceBuilder, NeighborCache};
  294. # use smoltcp::phy::{Loopback, Medium};
  295. use smoltcp::wire::{EthernetAddress, IpCidr, IpAddress};
  296. let mut device = // ...
  297. # Loopback::new(Medium::Ethernet);
  298. let hw_addr = // ...
  299. # EthernetAddress::default();
  300. let neighbor_cache = // ...
  301. # NeighborCache::new(BTreeMap::new());
  302. # #[cfg(feature = "proto-ipv4-fragmentation")]
  303. # let ipv4_frag_cache = // ...
  304. # ReassemblyBuffer::new(vec![], BTreeMap::new());
  305. let ip_addrs = // ...
  306. # [];
  307. let builder = InterfaceBuilder::new()
  308. .hardware_addr(hw_addr.into())
  309. .neighbor_cache(neighbor_cache)
  310. .ip_addrs(ip_addrs);
  311. # #[cfg(feature = "proto-ipv4-fragmentation")]
  312. let builder = builder
  313. .ipv4_reassembly_buffer(ipv4_frag_cache)
  314. .ipv4_fragmentation_buffer(vec![]);
  315. let iface = builder.finalize(&mut device);
  316. ```
  317. "##
  318. )]
  319. #[allow(clippy::new_without_default)]
  320. pub fn new() -> Self {
  321. InterfaceBuilder {
  322. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  323. hardware_addr: None,
  324. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  325. neighbor_cache: None,
  326. #[cfg(feature = "medium-ieee802154")]
  327. pan_id: None,
  328. ip_addrs: ManagedSlice::Borrowed(&mut []),
  329. #[cfg(feature = "proto-ipv4")]
  330. any_ip: false,
  331. routes: Routes::new(ManagedMap::Borrowed(&mut [])),
  332. #[cfg(feature = "proto-igmp")]
  333. ipv4_multicast_groups: ManagedMap::Borrowed(&mut []),
  334. random_seed: 0,
  335. #[cfg(feature = "proto-ipv4-fragmentation")]
  336. ipv4_fragments: PacketAssemblerSet::new(&mut [][..], &mut [][..]),
  337. #[cfg(feature = "proto-ipv4-fragmentation")]
  338. ipv4_out_buffer: ManagedSlice::Borrowed(&mut [][..]),
  339. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  340. sixlowpan_fragments: PacketAssemblerSet::new(&mut [][..], &mut [][..]),
  341. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  342. sixlowpan_reassembly_buffer_timeout: Duration::from_secs(60),
  343. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  344. sixlowpan_out_buffer: ManagedSlice::Borrowed(&mut [][..]),
  345. #[cfg(feature = "proto-sixlowpan")]
  346. sixlowpan_address_context: &[],
  347. }
  348. }
  349. /// Set the random seed for this interface.
  350. ///
  351. /// It is strongly recommended that the random seed is different on each boot,
  352. /// to avoid problems with TCP port/sequence collisions.
  353. ///
  354. /// The seed doesn't have to be cryptographically secure.
  355. pub fn random_seed(mut self, random_seed: u64) -> Self {
  356. self.random_seed = random_seed;
  357. self
  358. }
  359. /// Set the Hardware address the interface will use. See also
  360. /// [hardware_addr].
  361. ///
  362. /// # Panics
  363. /// This function panics if the address is not unicast.
  364. ///
  365. /// [hardware_addr]: struct.Interface.html#method.hardware_addr
  366. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  367. pub fn hardware_addr(mut self, addr: HardwareAddress) -> Self {
  368. InterfaceInner::check_hardware_addr(&addr);
  369. self.hardware_addr = Some(addr);
  370. self
  371. }
  372. /// Set the IEEE802.15.4 PAN ID the interface will use.
  373. ///
  374. /// **NOTE**: we use the same PAN ID for destination and source.
  375. #[cfg(feature = "medium-ieee802154")]
  376. pub fn pan_id(mut self, pan_id: Ieee802154Pan) -> Self {
  377. self.pan_id = Some(pan_id);
  378. self
  379. }
  380. /// Set the IP addresses the interface will use. See also
  381. /// [ip_addrs].
  382. ///
  383. /// # Panics
  384. /// This function panics if any of the addresses are not unicast.
  385. ///
  386. /// [ip_addrs]: struct.Interface.html#method.ip_addrs
  387. pub fn ip_addrs<T>(mut self, ip_addrs: T) -> Self
  388. where
  389. T: Into<ManagedSlice<'a, IpCidr>>,
  390. {
  391. let ip_addrs = ip_addrs.into();
  392. InterfaceInner::check_ip_addrs(&ip_addrs);
  393. self.ip_addrs = ip_addrs;
  394. self
  395. }
  396. /// Enable or disable the AnyIP capability, allowing packets to be received
  397. /// locally on IPv4 addresses other than the interface's configured [ip_addrs].
  398. /// When AnyIP is enabled and a route prefix in [routes] specifies one of
  399. /// the interface's [ip_addrs] as its gateway, the interface will accept
  400. /// packets addressed to that prefix.
  401. ///
  402. /// # IPv6
  403. ///
  404. /// This option is not available or required for IPv6 as packets sent to
  405. /// the interface are not filtered by IPv6 address.
  406. ///
  407. /// [routes]: struct.Interface.html#method.routes
  408. /// [ip_addrs]: struct.Interface.html#method.ip_addrs
  409. #[cfg(feature = "proto-ipv4")]
  410. pub fn any_ip(mut self, enabled: bool) -> Self {
  411. self.any_ip = enabled;
  412. self
  413. }
  414. /// Set the IP routes the interface will use. See also
  415. /// [routes].
  416. ///
  417. /// [routes]: struct.Interface.html#method.routes
  418. pub fn routes<T>(mut self, routes: T) -> InterfaceBuilder<'a>
  419. where
  420. T: Into<Routes<'a>>,
  421. {
  422. self.routes = routes.into();
  423. self
  424. }
  425. /// Provide storage for multicast groups.
  426. ///
  427. /// Join multicast groups by calling [`join_multicast_group()`] on an `Interface`.
  428. /// Using [`join_multicast_group()`] will send initial membership reports.
  429. ///
  430. /// A previously destroyed interface can be recreated by reusing the multicast group
  431. /// storage, i.e. providing a non-empty storage to `ipv4_multicast_groups()`.
  432. /// Note that this way initial membership reports are **not** sent.
  433. ///
  434. /// [`join_multicast_group()`]: struct.Interface.html#method.join_multicast_group
  435. #[cfg(feature = "proto-igmp")]
  436. pub fn ipv4_multicast_groups<T>(mut self, ipv4_multicast_groups: T) -> Self
  437. where
  438. T: Into<ManagedMap<'a, Ipv4Address, ()>>,
  439. {
  440. self.ipv4_multicast_groups = ipv4_multicast_groups.into();
  441. self
  442. }
  443. /// Set the Neighbor Cache the interface will use.
  444. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  445. pub fn neighbor_cache(mut self, neighbor_cache: NeighborCache<'a>) -> Self {
  446. self.neighbor_cache = Some(neighbor_cache);
  447. self
  448. }
  449. /// Set the IPv4 reassembly buffer the interface will use.
  450. #[cfg(feature = "proto-ipv4-fragmentation")]
  451. pub fn ipv4_reassembly_buffer(mut self, storage: PacketAssemblerSet<'a, Ipv4FragKey>) -> Self {
  452. self.ipv4_fragments = storage;
  453. self
  454. }
  455. /// Set the IPv4 fragments buffer the interface will use.
  456. #[cfg(feature = "proto-ipv4-fragmentation")]
  457. pub fn ipv4_fragmentation_buffer<T>(mut self, storage: T) -> Self
  458. where
  459. T: Into<ManagedSlice<'a, u8>>,
  460. {
  461. self.ipv4_out_buffer = storage.into();
  462. self
  463. }
  464. /// Set the address contexts the interface will use.
  465. #[cfg(feature = "proto-sixlowpan")]
  466. pub fn sixlowpan_address_context(
  467. mut self,
  468. sixlowpan_address_context: &'a [SixlowpanAddressContext<'a>],
  469. ) -> Self {
  470. self.sixlowpan_address_context = sixlowpan_address_context;
  471. self
  472. }
  473. /// Set the 6LoWPAN reassembly buffer the interface will use.
  474. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  475. pub fn sixlowpan_reassembly_buffer(
  476. mut self,
  477. storage: PacketAssemblerSet<'a, SixlowpanFragKey>,
  478. ) -> Self {
  479. self.sixlowpan_fragments = storage;
  480. self
  481. }
  482. /// Set the timeout value the 6LoWPAN reassembly buffer will use.
  483. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  484. pub fn sixlowpan_reassembly_buffer_timeout(mut self, timeout: Duration) -> Self {
  485. if timeout > Duration::from_secs(60) {
  486. net_debug!("RFC 4944 specifies that the reassembly timeout MUST be set to a maximum of 60 seconds");
  487. }
  488. self.sixlowpan_reassembly_buffer_timeout = timeout;
  489. self
  490. }
  491. /// Set the 6LoWPAN fragments buffer the interface will use.
  492. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  493. pub fn sixlowpan_fragmentation_buffer<T>(mut self, storage: T) -> Self
  494. where
  495. T: Into<ManagedSlice<'a, u8>>,
  496. {
  497. self.sixlowpan_out_buffer = storage.into();
  498. self
  499. }
  500. /// Create a network interface using the previously provided configuration.
  501. ///
  502. /// # Panics
  503. /// If a required option is not provided, this function will panic. Required
  504. /// options are:
  505. ///
  506. /// - [ethernet_addr]
  507. /// - [neighbor_cache]
  508. ///
  509. /// [ethernet_addr]: #method.ethernet_addr
  510. /// [neighbor_cache]: #method.neighbor_cache
  511. pub fn finalize<D>(self, device: &mut D) -> Interface<'a>
  512. where
  513. D: Device + ?Sized,
  514. {
  515. let caps = device.capabilities();
  516. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  517. let (hardware_addr, neighbor_cache) = match caps.medium {
  518. #[cfg(feature = "medium-ethernet")]
  519. Medium::Ethernet => (
  520. Some(
  521. self.hardware_addr
  522. .expect("hardware_addr required option was not set"),
  523. ),
  524. Some(
  525. self.neighbor_cache
  526. .expect("neighbor_cache required option was not set"),
  527. ),
  528. ),
  529. #[cfg(feature = "medium-ip")]
  530. Medium::Ip => {
  531. assert!(
  532. self.hardware_addr.is_none(),
  533. "hardware_addr is set, but device medium is IP"
  534. );
  535. assert!(
  536. self.neighbor_cache.is_none(),
  537. "neighbor_cache is set, but device medium is IP"
  538. );
  539. (None, None)
  540. }
  541. #[cfg(feature = "medium-ieee802154")]
  542. Medium::Ieee802154 => (
  543. Some(
  544. self.hardware_addr
  545. .expect("hardware_addr required option was not set"),
  546. ),
  547. Some(
  548. self.neighbor_cache
  549. .expect("neighbor_cache required option was not set"),
  550. ),
  551. ),
  552. };
  553. let mut rand = Rand::new(self.random_seed);
  554. #[cfg(feature = "medium-ieee802154")]
  555. let mut sequence_no;
  556. #[cfg(feature = "medium-ieee802154")]
  557. loop {
  558. sequence_no = (rand.rand_u32() & 0xff) as u8;
  559. if sequence_no != 0 {
  560. break;
  561. }
  562. }
  563. #[cfg(feature = "proto-sixlowpan")]
  564. let mut tag;
  565. #[cfg(feature = "proto-sixlowpan")]
  566. loop {
  567. tag = rand.rand_u16();
  568. if tag != 0 {
  569. break;
  570. }
  571. }
  572. #[cfg(feature = "proto-ipv4")]
  573. let mut ipv4_id;
  574. #[cfg(feature = "proto-ipv4")]
  575. loop {
  576. ipv4_id = rand.rand_u16();
  577. if ipv4_id != 0 {
  578. break;
  579. }
  580. }
  581. Interface {
  582. fragments: FragmentsBuffer {
  583. #[cfg(feature = "proto-ipv4-fragmentation")]
  584. ipv4_fragments: self.ipv4_fragments,
  585. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  586. sixlowpan_fragments: self.sixlowpan_fragments,
  587. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  588. sixlowpan_fragments_cache_timeout: self.sixlowpan_reassembly_buffer_timeout,
  589. #[cfg(not(any(
  590. feature = "proto-ipv4-fragmentation",
  591. feature = "proto-sixlowpan-fragmentation"
  592. )))]
  593. _lifetime: core::marker::PhantomData,
  594. },
  595. out_packets: OutPackets {
  596. #[cfg(feature = "proto-ipv4-fragmentation")]
  597. ipv4_out_packet: Ipv4OutPacket::new(self.ipv4_out_buffer),
  598. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  599. sixlowpan_out_packet: SixlowpanOutPacket::new(self.sixlowpan_out_buffer),
  600. #[cfg(not(feature = "proto-sixlowpan-fragmentation"))]
  601. _lifetime: core::marker::PhantomData,
  602. },
  603. inner: InterfaceInner {
  604. now: Instant::from_secs(0),
  605. caps,
  606. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  607. hardware_addr,
  608. ip_addrs: self.ip_addrs,
  609. #[cfg(feature = "proto-ipv4")]
  610. any_ip: self.any_ip,
  611. routes: self.routes,
  612. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  613. neighbor_cache,
  614. #[cfg(feature = "proto-igmp")]
  615. ipv4_multicast_groups: self.ipv4_multicast_groups,
  616. #[cfg(feature = "proto-igmp")]
  617. igmp_report_state: IgmpReportState::Inactive,
  618. #[cfg(feature = "medium-ieee802154")]
  619. sequence_no,
  620. #[cfg(feature = "medium-ieee802154")]
  621. pan_id: self.pan_id,
  622. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  623. tag,
  624. #[cfg(feature = "proto-ipv4-fragmentation")]
  625. ipv4_id,
  626. #[cfg(feature = "proto-sixlowpan")]
  627. sixlowpan_address_context: &[],
  628. rand,
  629. },
  630. }
  631. }
  632. }
  633. #[derive(Debug, PartialEq)]
  634. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  635. #[cfg(feature = "medium-ethernet")]
  636. enum EthernetPacket<'a> {
  637. #[cfg(feature = "proto-ipv4")]
  638. Arp(ArpRepr),
  639. Ip(IpPacket<'a>),
  640. }
  641. #[derive(Debug, PartialEq)]
  642. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  643. pub(crate) enum IpPacket<'a> {
  644. #[cfg(feature = "proto-ipv4")]
  645. Icmpv4((Ipv4Repr, Icmpv4Repr<'a>)),
  646. #[cfg(feature = "proto-igmp")]
  647. Igmp((Ipv4Repr, IgmpRepr)),
  648. #[cfg(feature = "proto-ipv6")]
  649. Icmpv6((Ipv6Repr, Icmpv6Repr<'a>)),
  650. #[cfg(feature = "socket-raw")]
  651. Raw((IpRepr, &'a [u8])),
  652. #[cfg(any(feature = "socket-udp", feature = "socket-dns"))]
  653. Udp((IpRepr, UdpRepr, &'a [u8])),
  654. #[cfg(feature = "socket-tcp")]
  655. Tcp((IpRepr, TcpRepr<'a>)),
  656. #[cfg(feature = "socket-dhcpv4")]
  657. Dhcpv4((Ipv4Repr, UdpRepr, DhcpRepr<'a>)),
  658. }
  659. impl<'a> IpPacket<'a> {
  660. pub(crate) fn ip_repr(&self) -> IpRepr {
  661. match self {
  662. #[cfg(feature = "proto-ipv4")]
  663. IpPacket::Icmpv4((ipv4_repr, _)) => IpRepr::Ipv4(*ipv4_repr),
  664. #[cfg(feature = "proto-igmp")]
  665. IpPacket::Igmp((ipv4_repr, _)) => IpRepr::Ipv4(*ipv4_repr),
  666. #[cfg(feature = "proto-ipv6")]
  667. IpPacket::Icmpv6((ipv6_repr, _)) => IpRepr::Ipv6(*ipv6_repr),
  668. #[cfg(feature = "socket-raw")]
  669. IpPacket::Raw((ip_repr, _)) => ip_repr.clone(),
  670. #[cfg(any(feature = "socket-udp", feature = "socket-dns"))]
  671. IpPacket::Udp((ip_repr, _, _)) => ip_repr.clone(),
  672. #[cfg(feature = "socket-tcp")]
  673. IpPacket::Tcp((ip_repr, _)) => ip_repr.clone(),
  674. #[cfg(feature = "socket-dhcpv4")]
  675. IpPacket::Dhcpv4((ipv4_repr, _, _)) => IpRepr::Ipv4(*ipv4_repr),
  676. }
  677. }
  678. pub(crate) fn emit_payload(
  679. &self,
  680. _ip_repr: &IpRepr,
  681. payload: &mut [u8],
  682. caps: &DeviceCapabilities,
  683. ) {
  684. match self {
  685. #[cfg(feature = "proto-ipv4")]
  686. IpPacket::Icmpv4((_, icmpv4_repr)) => {
  687. icmpv4_repr.emit(&mut Icmpv4Packet::new_unchecked(payload), &caps.checksum)
  688. }
  689. #[cfg(feature = "proto-igmp")]
  690. IpPacket::Igmp((_, igmp_repr)) => {
  691. igmp_repr.emit(&mut IgmpPacket::new_unchecked(payload))
  692. }
  693. #[cfg(feature = "proto-ipv6")]
  694. IpPacket::Icmpv6((_, icmpv6_repr)) => icmpv6_repr.emit(
  695. &_ip_repr.src_addr(),
  696. &_ip_repr.dst_addr(),
  697. &mut Icmpv6Packet::new_unchecked(payload),
  698. &caps.checksum,
  699. ),
  700. #[cfg(feature = "socket-raw")]
  701. IpPacket::Raw((_, raw_packet)) => payload.copy_from_slice(raw_packet),
  702. #[cfg(any(feature = "socket-udp", feature = "socket-dns"))]
  703. IpPacket::Udp((_, udp_repr, inner_payload)) => udp_repr.emit(
  704. &mut UdpPacket::new_unchecked(payload),
  705. &_ip_repr.src_addr(),
  706. &_ip_repr.dst_addr(),
  707. inner_payload.len(),
  708. |buf| buf.copy_from_slice(inner_payload),
  709. &caps.checksum,
  710. ),
  711. #[cfg(feature = "socket-tcp")]
  712. IpPacket::Tcp((_, mut tcp_repr)) => {
  713. // This is a terrible hack to make TCP performance more acceptable on systems
  714. // where the TCP buffers are significantly larger than network buffers,
  715. // e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
  716. // together with four 1500 B Ethernet receive buffers. If left untreated,
  717. // this would result in our peer pushing our window and sever packet loss.
  718. //
  719. // I'm really not happy about this "solution" but I don't know what else to do.
  720. if let Some(max_burst_size) = caps.max_burst_size {
  721. let mut max_segment_size = caps.max_transmission_unit;
  722. max_segment_size -= _ip_repr.header_len();
  723. max_segment_size -= tcp_repr.header_len();
  724. let max_window_size = max_burst_size * max_segment_size;
  725. if tcp_repr.window_len as usize > max_window_size {
  726. tcp_repr.window_len = max_window_size as u16;
  727. }
  728. }
  729. tcp_repr.emit(
  730. &mut TcpPacket::new_unchecked(payload),
  731. &_ip_repr.src_addr(),
  732. &_ip_repr.dst_addr(),
  733. &caps.checksum,
  734. );
  735. }
  736. #[cfg(feature = "socket-dhcpv4")]
  737. IpPacket::Dhcpv4((_, udp_repr, dhcp_repr)) => udp_repr.emit(
  738. &mut UdpPacket::new_unchecked(payload),
  739. &_ip_repr.src_addr(),
  740. &_ip_repr.dst_addr(),
  741. dhcp_repr.buffer_len(),
  742. |buf| dhcp_repr.emit(&mut DhcpPacket::new_unchecked(buf)).unwrap(),
  743. &caps.checksum,
  744. ),
  745. }
  746. }
  747. }
  748. #[cfg(any(feature = "proto-ipv4", feature = "proto-ipv6"))]
  749. fn icmp_reply_payload_len(len: usize, mtu: usize, header_len: usize) -> usize {
  750. // Send back as much of the original payload as will fit within
  751. // the minimum MTU required by IPv4. See RFC 1812 § 4.3.2.3 for
  752. // more details.
  753. //
  754. // Since the entire network layer packet must fit within the minimum
  755. // MTU supported, the payload must not exceed the following:
  756. //
  757. // <min mtu> - IP Header Size * 2 - ICMPv4 DstUnreachable hdr size
  758. cmp::min(len, mtu - header_len * 2 - 8)
  759. }
  760. #[cfg(feature = "proto-igmp")]
  761. enum IgmpReportState {
  762. Inactive,
  763. ToGeneralQuery {
  764. version: IgmpVersion,
  765. timeout: Instant,
  766. interval: Duration,
  767. next_index: usize,
  768. },
  769. ToSpecificQuery {
  770. version: IgmpVersion,
  771. timeout: Instant,
  772. group: Ipv4Address,
  773. },
  774. }
  775. impl<'a> Interface<'a> {
  776. /// Get the socket context.
  777. ///
  778. /// The context is needed for some socket methods.
  779. pub fn context(&mut self) -> &mut InterfaceInner<'a> {
  780. &mut self.inner
  781. }
  782. /// Get the HardwareAddress address of the interface.
  783. ///
  784. /// # Panics
  785. /// This function panics if the medium is not Ethernet or Ieee802154.
  786. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  787. pub fn hardware_addr(&self) -> HardwareAddress {
  788. #[cfg(all(feature = "medium-ethernet", not(feature = "medium-ieee802154")))]
  789. assert!(self.inner.caps.medium == Medium::Ethernet);
  790. #[cfg(all(feature = "medium-ieee802154", not(feature = "medium-ethernet")))]
  791. assert!(self.inner.caps.medium == Medium::Ieee802154);
  792. #[cfg(all(feature = "medium-ieee802154", feature = "medium-ethernet"))]
  793. assert!(
  794. self.inner.caps.medium == Medium::Ethernet
  795. || self.inner.caps.medium == Medium::Ieee802154
  796. );
  797. self.inner.hardware_addr.unwrap()
  798. }
  799. /// Set the HardwareAddress address of the interface.
  800. ///
  801. /// # Panics
  802. /// This function panics if the address is not unicast, and if the medium is not Ethernet or
  803. /// Ieee802154.
  804. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  805. pub fn set_hardware_addr(&mut self, addr: HardwareAddress) {
  806. #[cfg(all(feature = "medium-ethernet", not(feature = "medium-ieee802154")))]
  807. assert!(self.inner.caps.medium == Medium::Ethernet);
  808. #[cfg(all(feature = "medium-ieee802154", not(feature = "medium-ethernet")))]
  809. assert!(self.inner.caps.medium == Medium::Ieee802154);
  810. #[cfg(all(feature = "medium-ieee802154", feature = "medium-ethernet"))]
  811. assert!(
  812. self.inner.caps.medium == Medium::Ethernet
  813. || self.inner.caps.medium == Medium::Ieee802154
  814. );
  815. InterfaceInner::check_hardware_addr(&addr);
  816. self.inner.hardware_addr = Some(addr);
  817. }
  818. /// Add an address to a list of subscribed multicast IP addresses.
  819. ///
  820. /// Returns `Ok(announce_sent)` if the address was added successfully, where `annouce_sent`
  821. /// indicates whether an initial immediate announcement has been sent.
  822. pub fn join_multicast_group<D, T: Into<IpAddress>>(
  823. &mut self,
  824. device: &mut D,
  825. addr: T,
  826. timestamp: Instant,
  827. ) -> Result<bool>
  828. where
  829. D: Device + ?Sized,
  830. {
  831. self.inner.now = timestamp;
  832. match addr.into() {
  833. #[cfg(feature = "proto-igmp")]
  834. IpAddress::Ipv4(addr) => {
  835. let is_not_new = self
  836. .inner
  837. .ipv4_multicast_groups
  838. .insert(addr, ())
  839. .map_err(|_| Error::Exhausted)?
  840. .is_some();
  841. if is_not_new {
  842. Ok(false)
  843. } else if let Some(pkt) = self.inner.igmp_report_packet(IgmpVersion::Version2, addr)
  844. {
  845. // Send initial membership report
  846. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  847. self.inner.dispatch_ip(tx_token, pkt, None)?;
  848. Ok(true)
  849. } else {
  850. Ok(false)
  851. }
  852. }
  853. // Multicast is not yet implemented for other address families
  854. #[allow(unreachable_patterns)]
  855. _ => Err(Error::Unaddressable),
  856. }
  857. }
  858. /// Remove an address from the subscribed multicast IP addresses.
  859. ///
  860. /// Returns `Ok(leave_sent)` if the address was removed successfully, where `leave_sent`
  861. /// indicates whether an immediate leave packet has been sent.
  862. pub fn leave_multicast_group<D, T: Into<IpAddress>>(
  863. &mut self,
  864. device: &mut D,
  865. addr: T,
  866. timestamp: Instant,
  867. ) -> Result<bool>
  868. where
  869. D: Device + ?Sized,
  870. {
  871. self.inner.now = timestamp;
  872. match addr.into() {
  873. #[cfg(feature = "proto-igmp")]
  874. IpAddress::Ipv4(addr) => {
  875. let was_not_present = self.inner.ipv4_multicast_groups.remove(&addr).is_none();
  876. if was_not_present {
  877. Ok(false)
  878. } else if let Some(pkt) = self.inner.igmp_leave_packet(addr) {
  879. // Send group leave packet
  880. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  881. self.inner.dispatch_ip(tx_token, pkt, None)?;
  882. Ok(true)
  883. } else {
  884. Ok(false)
  885. }
  886. }
  887. // Multicast is not yet implemented for other address families
  888. #[allow(unreachable_patterns)]
  889. _ => Err(Error::Unaddressable),
  890. }
  891. }
  892. /// Check whether the interface listens to given destination multicast IP address.
  893. pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
  894. self.inner.has_multicast_group(addr)
  895. }
  896. /// Get the IP addresses of the interface.
  897. pub fn ip_addrs(&self) -> &[IpCidr] {
  898. self.inner.ip_addrs.as_ref()
  899. }
  900. /// Get the first IPv4 address if present.
  901. #[cfg(feature = "proto-ipv4")]
  902. pub fn ipv4_addr(&self) -> Option<Ipv4Address> {
  903. self.ip_addrs()
  904. .iter()
  905. .find_map(|cidr| match cidr.address() {
  906. IpAddress::Ipv4(addr) => Some(addr),
  907. #[allow(unreachable_patterns)]
  908. _ => None,
  909. })
  910. }
  911. /// Update the IP addresses of the interface.
  912. ///
  913. /// # Panics
  914. /// This function panics if any of the addresses are not unicast.
  915. pub fn update_ip_addrs<F: FnOnce(&mut ManagedSlice<'a, IpCidr>)>(&mut self, f: F) {
  916. f(&mut self.inner.ip_addrs);
  917. InterfaceInner::flush_cache(&mut self.inner);
  918. InterfaceInner::check_ip_addrs(&self.inner.ip_addrs)
  919. }
  920. /// Check whether the interface has the given IP address assigned.
  921. pub fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  922. self.inner.has_ip_addr(addr)
  923. }
  924. /// Get the first IPv4 address of the interface.
  925. #[cfg(feature = "proto-ipv4")]
  926. pub fn ipv4_address(&self) -> Option<Ipv4Address> {
  927. self.inner.ipv4_address()
  928. }
  929. pub fn routes(&self) -> &Routes<'a> {
  930. &self.inner.routes
  931. }
  932. pub fn routes_mut(&mut self) -> &mut Routes<'a> {
  933. &mut self.inner.routes
  934. }
  935. /// Transmit packets queued in the given sockets, and receive packets queued
  936. /// in the device.
  937. ///
  938. /// This function returns a boolean value indicating whether any packets were
  939. /// processed or emitted, and thus, whether the readiness of any socket might
  940. /// have changed.
  941. ///
  942. /// # Errors
  943. /// This method will routinely return errors in response to normal network
  944. /// activity as well as certain boundary conditions such as buffer exhaustion.
  945. /// These errors are provided as an aid for troubleshooting, and are meant
  946. /// to be logged and ignored.
  947. ///
  948. /// As a special case, `Err(Error::Unrecognized)` is returned in response to
  949. /// packets containing any unsupported protocol, option, or form, which is
  950. /// a very common occurrence and on a production system it should not even
  951. /// be logged.
  952. pub fn poll<D>(
  953. &mut self,
  954. timestamp: Instant,
  955. device: &mut D,
  956. sockets: &mut SocketSet<'_>,
  957. ) -> Result<bool>
  958. where
  959. D: Device + ?Sized,
  960. {
  961. self.inner.now = timestamp;
  962. #[cfg(feature = "proto-ipv4-fragmentation")]
  963. self.fragments
  964. .ipv4_fragments
  965. .remove_when(|frag| Ok(timestamp >= frag.expires_at()?))?;
  966. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  967. self.fragments
  968. .sixlowpan_fragments
  969. .remove_when(|frag| Ok(timestamp >= frag.expires_at()?))?;
  970. #[cfg(feature = "proto-ipv4-fragmentation")]
  971. match self.ipv4_egress(device) {
  972. Ok(true) => return Ok(true),
  973. Err(e) => {
  974. net_debug!("failed to transmit: {}", e);
  975. return Err(e);
  976. }
  977. _ => (),
  978. }
  979. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  980. match self.sixlowpan_egress(device) {
  981. Ok(true) => return Ok(true),
  982. Err(e) => {
  983. net_debug!("failed to transmit: {}", e);
  984. return Err(e);
  985. }
  986. _ => (),
  987. }
  988. let mut readiness_may_have_changed = false;
  989. loop {
  990. let processed_any = self.socket_ingress(device, sockets);
  991. let emitted_any = self.socket_egress(device, sockets);
  992. #[cfg(feature = "proto-igmp")]
  993. self.igmp_egress(device)?;
  994. if processed_any || emitted_any {
  995. readiness_may_have_changed = true;
  996. } else {
  997. break;
  998. }
  999. }
  1000. Ok(readiness_may_have_changed)
  1001. }
  1002. /// Return a _soft deadline_ for calling [poll] the next time.
  1003. /// The [Instant] returned is the time at which you should call [poll] next.
  1004. /// It is harmless (but wastes energy) to call it before the [Instant], and
  1005. /// potentially harmful (impacting quality of service) to call it after the
  1006. /// [Instant]
  1007. ///
  1008. /// [poll]: #method.poll
  1009. /// [Instant]: struct.Instant.html
  1010. pub fn poll_at(&mut self, timestamp: Instant, sockets: &SocketSet<'_>) -> Option<Instant> {
  1011. self.inner.now = timestamp;
  1012. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  1013. if !self.out_packets.all_transmitted() {
  1014. return Some(Instant::from_millis(0));
  1015. }
  1016. let inner = &mut self.inner;
  1017. sockets
  1018. .items()
  1019. .filter_map(move |item| {
  1020. let socket_poll_at = item.socket.poll_at(inner);
  1021. match item
  1022. .meta
  1023. .poll_at(socket_poll_at, |ip_addr| inner.has_neighbor(&ip_addr))
  1024. {
  1025. PollAt::Ingress => None,
  1026. PollAt::Time(instant) => Some(instant),
  1027. PollAt::Now => Some(Instant::from_millis(0)),
  1028. }
  1029. })
  1030. .min()
  1031. }
  1032. /// Return an _advisory wait time_ for calling [poll] the next time.
  1033. /// The [Duration] returned is the time left to wait before calling [poll] next.
  1034. /// It is harmless (but wastes energy) to call it before the [Duration] has passed,
  1035. /// and potentially harmful (impacting quality of service) to call it after the
  1036. /// [Duration] has passed.
  1037. ///
  1038. /// [poll]: #method.poll
  1039. /// [Duration]: struct.Duration.html
  1040. pub fn poll_delay(&mut self, timestamp: Instant, sockets: &SocketSet<'_>) -> Option<Duration> {
  1041. match self.poll_at(timestamp, sockets) {
  1042. Some(poll_at) if timestamp < poll_at => Some(poll_at - timestamp),
  1043. Some(_) => Some(Duration::from_millis(0)),
  1044. _ => None,
  1045. }
  1046. }
  1047. fn socket_ingress<D>(&mut self, device: &mut D, sockets: &mut SocketSet<'_>) -> bool
  1048. where
  1049. D: Device + ?Sized,
  1050. {
  1051. let mut processed_any = false;
  1052. let Self {
  1053. inner,
  1054. fragments: ref mut _fragments,
  1055. out_packets: _out_packets,
  1056. } = self;
  1057. while let Some((rx_token, tx_token)) = device.receive() {
  1058. let res = rx_token.consume(inner.now, |frame| {
  1059. match inner.caps.medium {
  1060. #[cfg(feature = "medium-ethernet")]
  1061. Medium::Ethernet => {
  1062. if let Some(packet) = inner.process_ethernet(sockets, &frame, _fragments) {
  1063. if let Err(err) = inner.dispatch(tx_token, packet, Some(_out_packets)) {
  1064. net_debug!("Failed to send response: {}", err);
  1065. }
  1066. }
  1067. }
  1068. #[cfg(feature = "medium-ip")]
  1069. Medium::Ip => {
  1070. if let Some(packet) = inner.process_ip(sockets, &frame, _fragments) {
  1071. if let Err(err) =
  1072. inner.dispatch_ip(tx_token, packet, Some(_out_packets))
  1073. {
  1074. net_debug!("Failed to send response: {}", err);
  1075. }
  1076. }
  1077. }
  1078. #[cfg(feature = "medium-ieee802154")]
  1079. Medium::Ieee802154 => {
  1080. if let Some(packet) = inner.process_ieee802154(sockets, &frame, _fragments)
  1081. {
  1082. if let Err(err) =
  1083. inner.dispatch_ip(tx_token, packet, Some(_out_packets))
  1084. {
  1085. net_debug!("Failed to send response: {}", err);
  1086. }
  1087. }
  1088. }
  1089. }
  1090. processed_any = true;
  1091. Ok(())
  1092. });
  1093. if let Err(err) = res {
  1094. net_debug!("Failed to consume RX token: {}", err);
  1095. }
  1096. }
  1097. processed_any
  1098. }
  1099. fn socket_egress<D>(&mut self, device: &mut D, sockets: &mut SocketSet<'_>) -> bool
  1100. where
  1101. D: Device + ?Sized,
  1102. {
  1103. let Self {
  1104. inner,
  1105. out_packets: _out_packets,
  1106. ..
  1107. } = self;
  1108. let _caps = device.capabilities();
  1109. let mut emitted_any = false;
  1110. for item in sockets.items_mut() {
  1111. if !item
  1112. .meta
  1113. .egress_permitted(inner.now, |ip_addr| inner.has_neighbor(&ip_addr))
  1114. {
  1115. continue;
  1116. }
  1117. let mut neighbor_addr = None;
  1118. let mut respond = |inner: &mut InterfaceInner, response: IpPacket| {
  1119. neighbor_addr = Some(response.ip_repr().dst_addr());
  1120. let t = device.transmit().ok_or_else(|| {
  1121. net_debug!("failed to transmit IP: {}", Error::Exhausted);
  1122. Error::Exhausted
  1123. })?;
  1124. #[cfg(any(
  1125. feature = "proto-ipv4-fragmentation",
  1126. feature = "proto-sixlowpan-fragmentation"
  1127. ))]
  1128. inner.dispatch_ip(t, response, Some(_out_packets))?;
  1129. #[cfg(not(any(
  1130. feature = "proto-ipv4-fragmentation",
  1131. feature = "proto-sixlowpan-fragmentation"
  1132. )))]
  1133. inner.dispatch_ip(t, response, None)?;
  1134. emitted_any = true;
  1135. Ok(())
  1136. };
  1137. let result = match &mut item.socket {
  1138. #[cfg(feature = "socket-raw")]
  1139. Socket::Raw(socket) => socket.dispatch(inner, |inner, response| {
  1140. respond(inner, IpPacket::Raw(response))
  1141. }),
  1142. #[cfg(feature = "socket-icmp")]
  1143. Socket::Icmp(socket) => socket.dispatch(inner, |inner, response| match response {
  1144. #[cfg(feature = "proto-ipv4")]
  1145. (IpRepr::Ipv4(ipv4_repr), IcmpRepr::Ipv4(icmpv4_repr)) => {
  1146. respond(inner, IpPacket::Icmpv4((ipv4_repr, icmpv4_repr)))
  1147. }
  1148. #[cfg(feature = "proto-ipv6")]
  1149. (IpRepr::Ipv6(ipv6_repr), IcmpRepr::Ipv6(icmpv6_repr)) => {
  1150. respond(inner, IpPacket::Icmpv6((ipv6_repr, icmpv6_repr)))
  1151. }
  1152. #[allow(unreachable_patterns)]
  1153. _ => unreachable!(),
  1154. }),
  1155. #[cfg(feature = "socket-udp")]
  1156. Socket::Udp(socket) => socket.dispatch(inner, |inner, response| {
  1157. respond(inner, IpPacket::Udp(response))
  1158. }),
  1159. #[cfg(feature = "socket-tcp")]
  1160. Socket::Tcp(socket) => socket.dispatch(inner, |inner, response| {
  1161. respond(inner, IpPacket::Tcp(response))
  1162. }),
  1163. #[cfg(feature = "socket-dhcpv4")]
  1164. Socket::Dhcpv4(socket) => socket.dispatch(inner, |inner, response| {
  1165. respond(inner, IpPacket::Dhcpv4(response))
  1166. }),
  1167. #[cfg(feature = "socket-dns")]
  1168. Socket::Dns(ref mut socket) => socket.dispatch(inner, |inner, response| {
  1169. respond(inner, IpPacket::Udp(response))
  1170. }),
  1171. };
  1172. match result {
  1173. Err(Error::Exhausted) => break, // Device buffer full.
  1174. Err(Error::Unaddressable) => {
  1175. // `NeighborCache` already takes care of rate limiting the neighbor discovery
  1176. // requests from the socket. However, without an additional rate limiting
  1177. // mechanism, we would spin on every socket that has yet to discover its
  1178. // neighbor.
  1179. item.meta.neighbor_missing(
  1180. inner.now,
  1181. neighbor_addr.expect("non-IP response packet"),
  1182. );
  1183. break;
  1184. }
  1185. Err(err) => {
  1186. net_debug!(
  1187. "{}: cannot dispatch egress packet: {}",
  1188. item.meta.handle,
  1189. err
  1190. );
  1191. }
  1192. Ok(()) => {}
  1193. }
  1194. }
  1195. emitted_any
  1196. }
  1197. /// Depending on `igmp_report_state` and the therein contained
  1198. /// timeouts, send IGMP membership reports.
  1199. #[cfg(feature = "proto-igmp")]
  1200. fn igmp_egress<D>(&mut self, device: &mut D) -> Result<bool>
  1201. where
  1202. D: Device + ?Sized,
  1203. {
  1204. match self.inner.igmp_report_state {
  1205. IgmpReportState::ToSpecificQuery {
  1206. version,
  1207. timeout,
  1208. group,
  1209. } if self.inner.now >= timeout => {
  1210. if let Some(pkt) = self.inner.igmp_report_packet(version, group) {
  1211. // Send initial membership report
  1212. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  1213. self.inner.dispatch_ip(tx_token, pkt, None)?;
  1214. }
  1215. self.inner.igmp_report_state = IgmpReportState::Inactive;
  1216. Ok(true)
  1217. }
  1218. IgmpReportState::ToGeneralQuery {
  1219. version,
  1220. timeout,
  1221. interval,
  1222. next_index,
  1223. } if self.inner.now >= timeout => {
  1224. let addr = self
  1225. .inner
  1226. .ipv4_multicast_groups
  1227. .iter()
  1228. .nth(next_index)
  1229. .map(|(addr, ())| *addr);
  1230. match addr {
  1231. Some(addr) => {
  1232. if let Some(pkt) = self.inner.igmp_report_packet(version, addr) {
  1233. // Send initial membership report
  1234. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  1235. self.inner.dispatch_ip(tx_token, pkt, None)?;
  1236. }
  1237. let next_timeout = (timeout + interval).max(self.inner.now);
  1238. self.inner.igmp_report_state = IgmpReportState::ToGeneralQuery {
  1239. version,
  1240. timeout: next_timeout,
  1241. interval,
  1242. next_index: next_index + 1,
  1243. };
  1244. Ok(true)
  1245. }
  1246. None => {
  1247. self.inner.igmp_report_state = IgmpReportState::Inactive;
  1248. Ok(false)
  1249. }
  1250. }
  1251. }
  1252. _ => Ok(false),
  1253. }
  1254. }
  1255. /// Process fragments that still need to be sent for IPv4 packets.
  1256. ///
  1257. /// This function returns a boolean value indicating whether any packets were
  1258. /// processed or emitted, and thus, whether the readiness of any socket might
  1259. /// have changed.
  1260. #[cfg(feature = "proto-ipv4-fragmentation")]
  1261. fn ipv4_egress<D>(&mut self, device: &mut D) -> Result<bool>
  1262. where
  1263. D: Device + ?Sized,
  1264. {
  1265. // Reset the buffer when we transmitted everything.
  1266. if self.out_packets.ipv4_out_packet.finished() {
  1267. self.out_packets.ipv4_out_packet.reset();
  1268. }
  1269. if self.out_packets.ipv4_out_packet.is_empty() {
  1270. return Ok(false);
  1271. }
  1272. let Ipv4OutPacket {
  1273. packet_len,
  1274. sent_bytes,
  1275. ..
  1276. } = &self.out_packets.ipv4_out_packet;
  1277. if *packet_len > *sent_bytes {
  1278. match device.transmit() {
  1279. Some(tx_token) => self
  1280. .inner
  1281. .dispatch_ipv4_out_packet(tx_token, &mut self.out_packets.ipv4_out_packet),
  1282. None => Err(Error::Exhausted),
  1283. }
  1284. .map(|_| true)
  1285. } else {
  1286. Ok(false)
  1287. }
  1288. }
  1289. /// Process fragments that still need to be sent for 6LoWPAN packets.
  1290. ///
  1291. /// This function returns a boolean value indicating whether any packets were
  1292. /// processed or emitted, and thus, whether the readiness of any socket might
  1293. /// have changed.
  1294. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  1295. fn sixlowpan_egress<D>(&mut self, device: &mut D) -> Result<bool>
  1296. where
  1297. D: Device + ?Sized,
  1298. {
  1299. // Reset the buffer when we transmitted everything.
  1300. if self.out_packets.sixlowpan_out_packet.finished() {
  1301. self.out_packets.sixlowpan_out_packet.reset();
  1302. }
  1303. if self.out_packets.sixlowpan_out_packet.is_empty() {
  1304. return Ok(false);
  1305. }
  1306. let SixlowpanOutPacket {
  1307. packet_len,
  1308. sent_bytes,
  1309. ..
  1310. } = &self.out_packets.sixlowpan_out_packet;
  1311. if *packet_len > *sent_bytes {
  1312. match device.transmit() {
  1313. Some(tx_token) => self.inner.dispatch_ieee802154_out_packet(
  1314. tx_token,
  1315. &mut self.out_packets.sixlowpan_out_packet,
  1316. ),
  1317. None => Err(Error::Exhausted),
  1318. }
  1319. .map(|_| true)
  1320. } else {
  1321. Ok(false)
  1322. }
  1323. }
  1324. }
  1325. impl<'a> InterfaceInner<'a> {
  1326. #[allow(unused)] // unused depending on which sockets are enabled
  1327. pub(crate) fn now(&self) -> Instant {
  1328. self.now
  1329. }
  1330. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  1331. #[allow(unused)] // unused depending on which sockets are enabled
  1332. pub(crate) fn hardware_addr(&self) -> Option<HardwareAddress> {
  1333. self.hardware_addr
  1334. }
  1335. #[allow(unused)] // unused depending on which sockets are enabled
  1336. pub(crate) fn checksum_caps(&self) -> ChecksumCapabilities {
  1337. self.caps.checksum.clone()
  1338. }
  1339. #[allow(unused)] // unused depending on which sockets are enabled
  1340. pub(crate) fn ip_mtu(&self) -> usize {
  1341. self.caps.ip_mtu()
  1342. }
  1343. #[allow(unused)] // unused depending on which sockets are enabled, and in tests
  1344. pub(crate) fn rand(&mut self) -> &mut Rand {
  1345. &mut self.rand
  1346. }
  1347. #[allow(unused)] // unused depending on which sockets are enabled
  1348. pub(crate) fn get_source_address(&mut self, dst_addr: IpAddress) -> Option<IpAddress> {
  1349. let v = dst_addr.version();
  1350. for cidr in self.ip_addrs.iter() {
  1351. let addr = cidr.address();
  1352. if addr.version() == v {
  1353. return Some(addr);
  1354. }
  1355. }
  1356. None
  1357. }
  1358. #[cfg(feature = "proto-ipv4")]
  1359. #[allow(unused)]
  1360. pub(crate) fn get_source_address_ipv4(
  1361. &mut self,
  1362. _dst_addr: Ipv4Address,
  1363. ) -> Option<Ipv4Address> {
  1364. for cidr in self.ip_addrs.iter() {
  1365. #[allow(irrefutable_let_patterns)] // if only ipv4 is enabled
  1366. if let IpCidr::Ipv4(cidr) = cidr {
  1367. return Some(cidr.address());
  1368. }
  1369. }
  1370. None
  1371. }
  1372. #[cfg(feature = "proto-ipv6")]
  1373. #[allow(unused)]
  1374. pub(crate) fn get_source_address_ipv6(
  1375. &mut self,
  1376. _dst_addr: Ipv6Address,
  1377. ) -> Option<Ipv6Address> {
  1378. for cidr in self.ip_addrs.iter() {
  1379. #[allow(irrefutable_let_patterns)] // if only ipv6 is enabled
  1380. if let IpCidr::Ipv6(cidr) = cidr {
  1381. return Some(cidr.address());
  1382. }
  1383. }
  1384. None
  1385. }
  1386. #[cfg(test)]
  1387. pub(crate) fn mock() -> Self {
  1388. Self {
  1389. caps: DeviceCapabilities {
  1390. #[cfg(feature = "medium-ethernet")]
  1391. medium: crate::phy::Medium::Ethernet,
  1392. #[cfg(all(not(feature = "medium-ethernet"), feature = "medium-ip"))]
  1393. medium: crate::phy::Medium::Ip,
  1394. #[cfg(all(not(feature = "medium-ethernet"), feature = "medium-ieee802154"))]
  1395. medium: crate::phy::Medium::Ieee802154,
  1396. checksum: crate::phy::ChecksumCapabilities {
  1397. #[cfg(feature = "proto-ipv4")]
  1398. icmpv4: crate::phy::Checksum::Both,
  1399. #[cfg(feature = "proto-ipv6")]
  1400. icmpv6: crate::phy::Checksum::Both,
  1401. ipv4: crate::phy::Checksum::Both,
  1402. tcp: crate::phy::Checksum::Both,
  1403. udp: crate::phy::Checksum::Both,
  1404. },
  1405. max_burst_size: None,
  1406. #[cfg(feature = "medium-ethernet")]
  1407. max_transmission_unit: 1514,
  1408. #[cfg(not(feature = "medium-ethernet"))]
  1409. max_transmission_unit: 1500,
  1410. },
  1411. now: Instant::from_millis_const(0),
  1412. ip_addrs: ManagedSlice::Owned(vec![
  1413. #[cfg(feature = "proto-ipv4")]
  1414. IpCidr::Ipv4(Ipv4Cidr::new(Ipv4Address::new(192, 168, 1, 1), 24)),
  1415. #[cfg(feature = "proto-ipv6")]
  1416. IpCidr::Ipv6(Ipv6Cidr::new(
  1417. Ipv6Address([0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
  1418. 64,
  1419. )),
  1420. ]),
  1421. rand: Rand::new(1234),
  1422. routes: Routes::new(&mut [][..]),
  1423. #[cfg(feature = "proto-ipv4")]
  1424. any_ip: false,
  1425. #[cfg(feature = "medium-ieee802154")]
  1426. pan_id: Some(crate::wire::Ieee802154Pan(0xabcd)),
  1427. #[cfg(feature = "medium-ieee802154")]
  1428. sequence_no: 1,
  1429. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  1430. tag: 1,
  1431. #[cfg(feature = "proto-sixlowpan")]
  1432. sixlowpan_address_context: &[],
  1433. #[cfg(feature = "proto-ipv4-fragmentation")]
  1434. ipv4_id: 1,
  1435. #[cfg(feature = "medium-ethernet")]
  1436. hardware_addr: Some(crate::wire::HardwareAddress::Ethernet(
  1437. crate::wire::EthernetAddress([0x02, 0x02, 0x02, 0x02, 0x02, 0x02]),
  1438. )),
  1439. #[cfg(all(not(feature = "medium-ethernet"), feature = "medium-ieee802154"))]
  1440. hardware_addr: Some(crate::wire::HardwareAddress::Ieee802154(
  1441. crate::wire::Ieee802154Address::Extended([
  1442. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x2, 0x2,
  1443. ]),
  1444. )),
  1445. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  1446. neighbor_cache: None,
  1447. #[cfg(feature = "proto-igmp")]
  1448. igmp_report_state: IgmpReportState::Inactive,
  1449. #[cfg(feature = "proto-igmp")]
  1450. ipv4_multicast_groups: ManagedMap::Borrowed(&mut []),
  1451. }
  1452. }
  1453. #[cfg(test)]
  1454. #[allow(unused)] // unused depending on which sockets are enabled
  1455. pub(crate) fn set_now(&mut self, now: Instant) {
  1456. self.now = now
  1457. }
  1458. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  1459. fn check_hardware_addr(addr: &HardwareAddress) {
  1460. if !addr.is_unicast() {
  1461. panic!("Ethernet address {} is not unicast", addr)
  1462. }
  1463. }
  1464. fn check_ip_addrs(addrs: &[IpCidr]) {
  1465. for cidr in addrs {
  1466. if !cidr.address().is_unicast() && !cidr.address().is_unspecified() {
  1467. panic!("IP address {} is not unicast", cidr.address())
  1468. }
  1469. }
  1470. }
  1471. #[cfg(feature = "medium-ieee802154")]
  1472. fn get_sequence_number(&mut self) -> u8 {
  1473. let no = self.sequence_no;
  1474. self.sequence_no = self.sequence_no.wrapping_add(1);
  1475. no
  1476. }
  1477. #[cfg(feature = "proto-ipv4-fragmentation")]
  1478. fn get_ipv4_ident(&mut self) -> u16 {
  1479. let ipv4_id = self.ipv4_id;
  1480. self.ipv4_id = self.ipv4_id.wrapping_add(1);
  1481. ipv4_id
  1482. }
  1483. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  1484. fn get_sixlowpan_fragment_tag(&mut self) -> u16 {
  1485. let tag = self.tag;
  1486. self.tag = self.tag.wrapping_add(1);
  1487. tag
  1488. }
  1489. /// Determine if the given `Ipv6Address` is the solicited node
  1490. /// multicast address for a IPv6 addresses assigned to the interface.
  1491. /// See [RFC 4291 § 2.7.1] for more details.
  1492. ///
  1493. /// [RFC 4291 § 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1
  1494. #[cfg(feature = "proto-ipv6")]
  1495. pub fn has_solicited_node(&self, addr: Ipv6Address) -> bool {
  1496. self.ip_addrs.iter().any(|cidr| {
  1497. match *cidr {
  1498. IpCidr::Ipv6(cidr) if cidr.address() != Ipv6Address::LOOPBACK => {
  1499. // Take the lower order 24 bits of the IPv6 address and
  1500. // append those bits to FF02:0:0:0:0:1:FF00::/104.
  1501. addr.as_bytes()[14..] == cidr.address().as_bytes()[14..]
  1502. }
  1503. _ => false,
  1504. }
  1505. })
  1506. }
  1507. /// Check whether the interface has the given IP address assigned.
  1508. fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  1509. let addr = addr.into();
  1510. self.ip_addrs.iter().any(|probe| probe.address() == addr)
  1511. }
  1512. /// Get the first IPv4 address of the interface.
  1513. #[cfg(feature = "proto-ipv4")]
  1514. pub fn ipv4_address(&self) -> Option<Ipv4Address> {
  1515. self.ip_addrs.iter().find_map(|addr| match *addr {
  1516. IpCidr::Ipv4(cidr) => Some(cidr.address()),
  1517. #[cfg(feature = "proto-ipv6")]
  1518. IpCidr::Ipv6(_) => None,
  1519. })
  1520. }
  1521. /// Check whether the interface listens to given destination multicast IP address.
  1522. ///
  1523. /// If built without feature `proto-igmp` this function will
  1524. /// always return `false`.
  1525. pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
  1526. match addr.into() {
  1527. #[cfg(feature = "proto-igmp")]
  1528. IpAddress::Ipv4(key) => {
  1529. key == Ipv4Address::MULTICAST_ALL_SYSTEMS
  1530. || self.ipv4_multicast_groups.get(&key).is_some()
  1531. }
  1532. #[allow(unreachable_patterns)]
  1533. _ => false,
  1534. }
  1535. }
  1536. #[cfg(feature = "medium-ip")]
  1537. fn process_ip<'frame, T: AsRef<[u8]>>(
  1538. &mut self,
  1539. sockets: &mut SocketSet,
  1540. ip_payload: &'frame T,
  1541. _fragments: &'frame mut FragmentsBuffer<'a>,
  1542. ) -> Option<IpPacket<'frame>> {
  1543. match IpVersion::of_packet(ip_payload.as_ref()) {
  1544. #[cfg(feature = "proto-ipv4")]
  1545. Ok(IpVersion::Ipv4) => {
  1546. let ipv4_packet = check!(Ipv4Packet::new_checked(ip_payload));
  1547. #[cfg(feature = "proto-ipv4-fragmentation")]
  1548. {
  1549. self.process_ipv4(sockets, &ipv4_packet, Some(&mut _fragments.ipv4_fragments))
  1550. }
  1551. #[cfg(not(feature = "proto-ipv4-fragmentation"))]
  1552. {
  1553. self.process_ipv4(sockets, &ipv4_packet, None)
  1554. }
  1555. }
  1556. #[cfg(feature = "proto-ipv6")]
  1557. Ok(IpVersion::Ipv6) => {
  1558. let ipv6_packet = check!(Ipv6Packet::new_checked(ip_payload));
  1559. self.process_ipv6(sockets, &ipv6_packet)
  1560. }
  1561. // Drop all other traffic.
  1562. _ => None,
  1563. }
  1564. }
  1565. #[cfg(feature = "socket-raw")]
  1566. fn raw_socket_filter<'frame>(
  1567. &mut self,
  1568. sockets: &mut SocketSet,
  1569. ip_repr: &IpRepr,
  1570. ip_payload: &'frame [u8],
  1571. ) -> bool {
  1572. let mut handled_by_raw_socket = false;
  1573. // Pass every IP packet to all raw sockets we have registered.
  1574. for raw_socket in sockets
  1575. .items_mut()
  1576. .filter_map(|i| raw::Socket::downcast_mut(&mut i.socket))
  1577. {
  1578. if raw_socket.accepts(ip_repr) {
  1579. raw_socket.process(self, ip_repr, ip_payload);
  1580. handled_by_raw_socket = true;
  1581. }
  1582. }
  1583. handled_by_raw_socket
  1584. }
  1585. /// Checks if an incoming packet has a broadcast address for the interfaces
  1586. /// associated ipv4 addresses.
  1587. #[cfg(feature = "proto-ipv4")]
  1588. fn is_subnet_broadcast(&self, address: Ipv4Address) -> bool {
  1589. self.ip_addrs
  1590. .iter()
  1591. .filter_map(|own_cidr| match own_cidr {
  1592. IpCidr::Ipv4(own_ip) => Some(own_ip.broadcast()?),
  1593. #[cfg(feature = "proto-ipv6")]
  1594. IpCidr::Ipv6(_) => None,
  1595. })
  1596. .any(|broadcast_address| address == broadcast_address)
  1597. }
  1598. /// Checks if an ipv4 address is broadcast, taking into account subnet broadcast addresses
  1599. #[cfg(feature = "proto-ipv4")]
  1600. fn is_broadcast_v4(&self, address: Ipv4Address) -> bool {
  1601. address.is_broadcast() || self.is_subnet_broadcast(address)
  1602. }
  1603. /// Checks if an ipv4 address is unicast, taking into account subnet broadcast addresses
  1604. #[cfg(feature = "proto-ipv4")]
  1605. fn is_unicast_v4(&self, address: Ipv4Address) -> bool {
  1606. address.is_unicast() && !self.is_subnet_broadcast(address)
  1607. }
  1608. #[cfg(any(feature = "socket-udp", feature = "socket-dns"))]
  1609. fn process_udp<'frame>(
  1610. &mut self,
  1611. sockets: &mut SocketSet,
  1612. ip_repr: IpRepr,
  1613. udp_repr: UdpRepr,
  1614. handled_by_raw_socket: bool,
  1615. udp_payload: &'frame [u8],
  1616. ip_payload: &'frame [u8],
  1617. ) -> Option<IpPacket<'frame>> {
  1618. #[cfg(feature = "socket-udp")]
  1619. for udp_socket in sockets
  1620. .items_mut()
  1621. .filter_map(|i| udp::Socket::downcast_mut(&mut i.socket))
  1622. {
  1623. if udp_socket.accepts(self, &ip_repr, &udp_repr) {
  1624. udp_socket.process(self, &ip_repr, &udp_repr, udp_payload);
  1625. return None;
  1626. }
  1627. }
  1628. #[cfg(feature = "socket-dns")]
  1629. for dns_socket in sockets
  1630. .items_mut()
  1631. .filter_map(|i| dns::Socket::downcast_mut(&mut i.socket))
  1632. {
  1633. if dns_socket.accepts(&ip_repr, &udp_repr) {
  1634. dns_socket.process(self, &ip_repr, &udp_repr, udp_payload);
  1635. return None;
  1636. }
  1637. }
  1638. // The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  1639. match ip_repr {
  1640. #[cfg(feature = "proto-ipv4")]
  1641. IpRepr::Ipv4(_) if handled_by_raw_socket => None,
  1642. #[cfg(feature = "proto-ipv6")]
  1643. IpRepr::Ipv6(_) if handled_by_raw_socket => None,
  1644. #[cfg(feature = "proto-ipv4")]
  1645. IpRepr::Ipv4(ipv4_repr) => {
  1646. let payload_len =
  1647. icmp_reply_payload_len(ip_payload.len(), IPV4_MIN_MTU, ipv4_repr.buffer_len());
  1648. let icmpv4_reply_repr = Icmpv4Repr::DstUnreachable {
  1649. reason: Icmpv4DstUnreachable::PortUnreachable,
  1650. header: ipv4_repr,
  1651. data: &ip_payload[0..payload_len],
  1652. };
  1653. self.icmpv4_reply(ipv4_repr, icmpv4_reply_repr)
  1654. }
  1655. #[cfg(feature = "proto-ipv6")]
  1656. IpRepr::Ipv6(ipv6_repr) => {
  1657. let payload_len =
  1658. icmp_reply_payload_len(ip_payload.len(), IPV6_MIN_MTU, ipv6_repr.buffer_len());
  1659. let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable {
  1660. reason: Icmpv6DstUnreachable::PortUnreachable,
  1661. header: ipv6_repr,
  1662. data: &ip_payload[0..payload_len],
  1663. };
  1664. self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr)
  1665. }
  1666. }
  1667. }
  1668. #[cfg(feature = "socket-tcp")]
  1669. pub(crate) fn process_tcp<'frame>(
  1670. &mut self,
  1671. sockets: &mut SocketSet,
  1672. ip_repr: IpRepr,
  1673. ip_payload: &'frame [u8],
  1674. ) -> Option<IpPacket<'frame>> {
  1675. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  1676. let tcp_packet = check!(TcpPacket::new_checked(ip_payload));
  1677. let tcp_repr = check!(TcpRepr::parse(
  1678. &tcp_packet,
  1679. &src_addr,
  1680. &dst_addr,
  1681. &self.caps.checksum
  1682. ));
  1683. for tcp_socket in sockets
  1684. .items_mut()
  1685. .filter_map(|i| tcp::Socket::downcast_mut(&mut i.socket))
  1686. {
  1687. if tcp_socket.accepts(self, &ip_repr, &tcp_repr) {
  1688. return tcp_socket
  1689. .process(self, &ip_repr, &tcp_repr)
  1690. .map(IpPacket::Tcp);
  1691. }
  1692. }
  1693. if tcp_repr.control == TcpControl::Rst {
  1694. // Never reply to a TCP RST packet with another TCP RST packet.
  1695. None
  1696. } else {
  1697. // The packet wasn't handled by a socket, send a TCP RST packet.
  1698. Some(IpPacket::Tcp(tcp::Socket::rst_reply(&ip_repr, &tcp_repr)))
  1699. }
  1700. }
  1701. #[cfg(feature = "medium-ethernet")]
  1702. fn dispatch<Tx>(
  1703. &mut self,
  1704. tx_token: Tx,
  1705. packet: EthernetPacket,
  1706. _out_packet: Option<&mut OutPackets<'_>>,
  1707. ) -> Result<()>
  1708. where
  1709. Tx: TxToken,
  1710. {
  1711. match packet {
  1712. #[cfg(feature = "proto-ipv4")]
  1713. EthernetPacket::Arp(arp_repr) => {
  1714. let dst_hardware_addr = match arp_repr {
  1715. ArpRepr::EthernetIpv4 {
  1716. target_hardware_addr,
  1717. ..
  1718. } => target_hardware_addr,
  1719. };
  1720. self.dispatch_ethernet(tx_token, arp_repr.buffer_len(), |mut frame| {
  1721. frame.set_dst_addr(dst_hardware_addr);
  1722. frame.set_ethertype(EthernetProtocol::Arp);
  1723. let mut packet = ArpPacket::new_unchecked(frame.payload_mut());
  1724. arp_repr.emit(&mut packet);
  1725. })
  1726. }
  1727. EthernetPacket::Ip(packet) => self.dispatch_ip(tx_token, packet, _out_packet),
  1728. }
  1729. }
  1730. fn in_same_network(&self, addr: &IpAddress) -> bool {
  1731. self.ip_addrs.iter().any(|cidr| cidr.contains_addr(addr))
  1732. }
  1733. fn route(&self, addr: &IpAddress, timestamp: Instant) -> Result<IpAddress> {
  1734. // Send directly.
  1735. if self.in_same_network(addr) || addr.is_broadcast() {
  1736. return Ok(*addr);
  1737. }
  1738. // Route via a router.
  1739. match self.routes.lookup(addr, timestamp) {
  1740. Some(router_addr) => Ok(router_addr),
  1741. None => Err(Error::Unaddressable),
  1742. }
  1743. }
  1744. fn has_neighbor(&self, addr: &IpAddress) -> bool {
  1745. match self.route(addr, self.now) {
  1746. Ok(_routed_addr) => match self.caps.medium {
  1747. #[cfg(feature = "medium-ethernet")]
  1748. Medium::Ethernet => self
  1749. .neighbor_cache
  1750. .as_ref()
  1751. .unwrap()
  1752. .lookup(&_routed_addr, self.now)
  1753. .found(),
  1754. #[cfg(feature = "medium-ieee802154")]
  1755. Medium::Ieee802154 => self
  1756. .neighbor_cache
  1757. .as_ref()
  1758. .unwrap()
  1759. .lookup(&_routed_addr, self.now)
  1760. .found(),
  1761. #[cfg(feature = "medium-ip")]
  1762. Medium::Ip => true,
  1763. },
  1764. Err(_) => false,
  1765. }
  1766. }
  1767. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  1768. fn lookup_hardware_addr<Tx>(
  1769. &mut self,
  1770. tx_token: Tx,
  1771. src_addr: &IpAddress,
  1772. dst_addr: &IpAddress,
  1773. ) -> Result<(HardwareAddress, Tx)>
  1774. where
  1775. Tx: TxToken,
  1776. {
  1777. if dst_addr.is_broadcast() {
  1778. let hardware_addr = match self.caps.medium {
  1779. #[cfg(feature = "medium-ethernet")]
  1780. Medium::Ethernet => HardwareAddress::Ethernet(EthernetAddress::BROADCAST),
  1781. #[cfg(feature = "medium-ieee802154")]
  1782. Medium::Ieee802154 => HardwareAddress::Ieee802154(Ieee802154Address::BROADCAST),
  1783. #[cfg(feature = "medium-ip")]
  1784. Medium::Ip => unreachable!(),
  1785. };
  1786. return Ok((hardware_addr, tx_token));
  1787. }
  1788. if dst_addr.is_multicast() {
  1789. let b = dst_addr.as_bytes();
  1790. let hardware_addr = match *dst_addr {
  1791. #[cfg(feature = "proto-ipv4")]
  1792. IpAddress::Ipv4(_addr) => {
  1793. HardwareAddress::Ethernet(EthernetAddress::from_bytes(&[
  1794. 0x01,
  1795. 0x00,
  1796. 0x5e,
  1797. b[1] & 0x7F,
  1798. b[2],
  1799. b[3],
  1800. ]))
  1801. }
  1802. #[cfg(feature = "proto-ipv6")]
  1803. IpAddress::Ipv6(_addr) => match self.caps.medium {
  1804. #[cfg(feature = "medium-ethernet")]
  1805. Medium::Ethernet => HardwareAddress::Ethernet(EthernetAddress::from_bytes(&[
  1806. 0x33, 0x33, b[12], b[13], b[14], b[15],
  1807. ])),
  1808. #[cfg(feature = "medium-ieee802154")]
  1809. Medium::Ieee802154 => {
  1810. // Not sure if this is correct
  1811. HardwareAddress::Ieee802154(Ieee802154Address::BROADCAST)
  1812. }
  1813. #[cfg(feature = "medium-ip")]
  1814. Medium::Ip => unreachable!(),
  1815. },
  1816. };
  1817. return Ok((hardware_addr, tx_token));
  1818. }
  1819. let dst_addr = self.route(dst_addr, self.now)?;
  1820. match self
  1821. .neighbor_cache
  1822. .as_mut()
  1823. .unwrap()
  1824. .lookup(&dst_addr, self.now)
  1825. {
  1826. NeighborAnswer::Found(hardware_addr) => return Ok((hardware_addr, tx_token)),
  1827. NeighborAnswer::RateLimited => return Err(Error::Unaddressable),
  1828. _ => (), // XXX
  1829. }
  1830. match (src_addr, dst_addr) {
  1831. #[cfg(feature = "proto-ipv4")]
  1832. (&IpAddress::Ipv4(src_addr), IpAddress::Ipv4(dst_addr)) => {
  1833. net_debug!(
  1834. "address {} not in neighbor cache, sending ARP request",
  1835. dst_addr
  1836. );
  1837. let src_hardware_addr =
  1838. if let Some(HardwareAddress::Ethernet(addr)) = self.hardware_addr {
  1839. addr
  1840. } else {
  1841. return Err(Error::Malformed);
  1842. };
  1843. let arp_repr = ArpRepr::EthernetIpv4 {
  1844. operation: ArpOperation::Request,
  1845. source_hardware_addr: src_hardware_addr,
  1846. source_protocol_addr: src_addr,
  1847. target_hardware_addr: EthernetAddress::BROADCAST,
  1848. target_protocol_addr: dst_addr,
  1849. };
  1850. self.dispatch_ethernet(tx_token, arp_repr.buffer_len(), |mut frame| {
  1851. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1852. frame.set_ethertype(EthernetProtocol::Arp);
  1853. arp_repr.emit(&mut ArpPacket::new_unchecked(frame.payload_mut()))
  1854. })?;
  1855. }
  1856. #[cfg(feature = "proto-ipv6")]
  1857. (&IpAddress::Ipv6(src_addr), IpAddress::Ipv6(dst_addr)) => {
  1858. net_debug!(
  1859. "address {} not in neighbor cache, sending Neighbor Solicitation",
  1860. dst_addr
  1861. );
  1862. let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit {
  1863. target_addr: dst_addr,
  1864. lladdr: Some(self.hardware_addr.unwrap().into()),
  1865. });
  1866. let packet = IpPacket::Icmpv6((
  1867. Ipv6Repr {
  1868. src_addr,
  1869. dst_addr: dst_addr.solicited_node(),
  1870. next_header: IpProtocol::Icmpv6,
  1871. payload_len: solicit.buffer_len(),
  1872. hop_limit: 0xff,
  1873. },
  1874. solicit,
  1875. ));
  1876. self.dispatch_ip(tx_token, packet, None)?;
  1877. }
  1878. #[allow(unreachable_patterns)]
  1879. _ => (),
  1880. }
  1881. // The request got dispatched, limit the rate on the cache.
  1882. self.neighbor_cache.as_mut().unwrap().limit_rate(self.now);
  1883. Err(Error::Unaddressable)
  1884. }
  1885. fn flush_cache(&mut self) {
  1886. #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
  1887. if let Some(cache) = self.neighbor_cache.as_mut() {
  1888. cache.flush()
  1889. }
  1890. }
  1891. fn dispatch_ip<Tx: TxToken>(
  1892. &mut self,
  1893. tx_token: Tx,
  1894. packet: IpPacket,
  1895. _out_packet: Option<&mut OutPackets<'_>>,
  1896. ) -> Result<()> {
  1897. let mut ip_repr = packet.ip_repr();
  1898. assert!(!ip_repr.dst_addr().is_unspecified());
  1899. // Dispatch IEEE802.15.4:
  1900. #[cfg(feature = "medium-ieee802154")]
  1901. if matches!(self.caps.medium, Medium::Ieee802154) {
  1902. let (dst_hardware_addr, tx_token) = match self.lookup_hardware_addr(
  1903. tx_token,
  1904. &ip_repr.src_addr(),
  1905. &ip_repr.dst_addr(),
  1906. )? {
  1907. (HardwareAddress::Ieee802154(addr), tx_token) => (addr, tx_token),
  1908. _ => unreachable!(),
  1909. };
  1910. return self.dispatch_ieee802154(dst_hardware_addr, tx_token, packet, _out_packet);
  1911. }
  1912. // Dispatch IP/Ethernet:
  1913. let caps = self.caps.clone();
  1914. #[cfg(feature = "proto-ipv4-fragmentation")]
  1915. let ipv4_id = self.get_ipv4_ident();
  1916. // First we calculate the total length that we will have to emit.
  1917. let mut total_len = ip_repr.buffer_len();
  1918. // Add the size of the Ethernet header if the medium is Ethernet.
  1919. #[cfg(feature = "medium-ethernet")]
  1920. if matches!(self.caps.medium, Medium::Ethernet) {
  1921. total_len = EthernetFrame::<&[u8]>::buffer_len(total_len);
  1922. }
  1923. // If the medium is Ethernet, then we need to retrieve the destination hardware address.
  1924. #[cfg(feature = "medium-ethernet")]
  1925. let (dst_hardware_addr, tx_token) = match self.caps.medium {
  1926. Medium::Ethernet => {
  1927. match self.lookup_hardware_addr(
  1928. tx_token,
  1929. &ip_repr.src_addr(),
  1930. &ip_repr.dst_addr(),
  1931. )? {
  1932. (HardwareAddress::Ethernet(addr), tx_token) => (addr, tx_token),
  1933. #[cfg(feature = "medium-ieee802154")]
  1934. (HardwareAddress::Ieee802154(_), _) => unreachable!(),
  1935. }
  1936. }
  1937. _ => (EthernetAddress([0; 6]), tx_token),
  1938. };
  1939. // Emit function for the Ethernet header.
  1940. #[cfg(feature = "medium-ethernet")]
  1941. let emit_ethernet = |repr: &IpRepr, tx_buffer: &mut [u8]| {
  1942. let mut frame = EthernetFrame::new_unchecked(tx_buffer);
  1943. let src_addr = if let Some(HardwareAddress::Ethernet(addr)) = self.hardware_addr {
  1944. addr
  1945. } else {
  1946. return Err(Error::Malformed);
  1947. };
  1948. frame.set_src_addr(src_addr);
  1949. frame.set_dst_addr(dst_hardware_addr);
  1950. match repr.version() {
  1951. #[cfg(feature = "proto-ipv4")]
  1952. IpVersion::Ipv4 => frame.set_ethertype(EthernetProtocol::Ipv4),
  1953. #[cfg(feature = "proto-ipv6")]
  1954. IpVersion::Ipv6 => frame.set_ethertype(EthernetProtocol::Ipv6),
  1955. }
  1956. Ok(())
  1957. };
  1958. // Emit function for the IP header and payload.
  1959. let emit_ip = |repr: &IpRepr, mut tx_buffer: &mut [u8]| {
  1960. repr.emit(&mut tx_buffer, &self.caps.checksum);
  1961. let payload = &mut tx_buffer[repr.header_len()..];
  1962. packet.emit_payload(repr, payload, &caps);
  1963. };
  1964. let total_ip_len = ip_repr.buffer_len();
  1965. match ip_repr {
  1966. #[cfg(feature = "proto-ipv4")]
  1967. IpRepr::Ipv4(ref mut repr) => {
  1968. // If we have an IPv4 packet, then we need to check if we need to fragment it.
  1969. if total_ip_len > self.caps.max_transmission_unit {
  1970. #[cfg(feature = "proto-ipv4-fragmentation")]
  1971. {
  1972. net_debug!("start fragmentation");
  1973. let Ipv4OutPacket {
  1974. buffer,
  1975. packet_len,
  1976. sent_bytes,
  1977. repr: out_packet_repr,
  1978. frag_offset,
  1979. ident,
  1980. #[cfg(feature = "medium-ethernet")]
  1981. dst_hardware_addr: dst_address,
  1982. } = &mut _out_packet.unwrap().ipv4_out_packet;
  1983. // Calculate how much we will send now (including the Ethernet header).
  1984. let tx_len = self.caps.max_transmission_unit;
  1985. let ip_header_len = repr.buffer_len();
  1986. let first_frag_ip_len = self.caps.ip_mtu();
  1987. if buffer.len() < first_frag_ip_len {
  1988. net_debug!(
  1989. "Fragmentation buffer is too small, at least {} needed",
  1990. first_frag_ip_len
  1991. );
  1992. return Err(Error::Exhausted);
  1993. }
  1994. #[cfg(feature = "medium-ethernet")]
  1995. {
  1996. *dst_address = dst_hardware_addr;
  1997. }
  1998. // Save the total packet len (without the Ethernet header, but with the first
  1999. // IP header).
  2000. *packet_len = total_ip_len;
  2001. // Save the IP header for other fragments.
  2002. *out_packet_repr = *repr;
  2003. // Save how much bytes we will send now.
  2004. *sent_bytes = first_frag_ip_len;
  2005. // Modify the IP header
  2006. repr.payload_len = first_frag_ip_len - repr.buffer_len();
  2007. // Emit the IP header to the buffer.
  2008. emit_ip(&ip_repr, buffer);
  2009. let mut ipv4_packet = Ipv4Packet::new_unchecked(&mut buffer[..]);
  2010. *ident = ipv4_id;
  2011. ipv4_packet.set_ident(ipv4_id);
  2012. ipv4_packet.set_more_frags(true);
  2013. ipv4_packet.set_dont_frag(false);
  2014. ipv4_packet.set_frag_offset(0);
  2015. if caps.checksum.ipv4.tx() {
  2016. ipv4_packet.fill_checksum();
  2017. }
  2018. // Transmit the first packet.
  2019. tx_token.consume(self.now, tx_len, |mut tx_buffer| {
  2020. #[cfg(feature = "medium-ethernet")]
  2021. if matches!(self.caps.medium, Medium::Ethernet) {
  2022. emit_ethernet(&ip_repr, tx_buffer)?;
  2023. tx_buffer = &mut tx_buffer[EthernetFrame::<&[u8]>::header_len()..];
  2024. }
  2025. // Change the offset for the next packet.
  2026. *frag_offset = (first_frag_ip_len - ip_header_len) as u16;
  2027. // Copy the IP header and the payload.
  2028. tx_buffer[..first_frag_ip_len]
  2029. .copy_from_slice(&buffer[..first_frag_ip_len]);
  2030. Ok(())
  2031. })
  2032. }
  2033. #[cfg(not(feature = "proto-ipv4-fragmentation"))]
  2034. {
  2035. net_debug!("Enable the `proto-ipv4-fragmentation` feature for fragmentation support.");
  2036. Ok(())
  2037. }
  2038. } else {
  2039. // No fragmentation is required.
  2040. tx_token.consume(self.now, total_len, |mut tx_buffer| {
  2041. #[cfg(feature = "medium-ethernet")]
  2042. if matches!(self.caps.medium, Medium::Ethernet) {
  2043. emit_ethernet(&ip_repr, tx_buffer)?;
  2044. tx_buffer = &mut tx_buffer[EthernetFrame::<&[u8]>::header_len()..];
  2045. }
  2046. emit_ip(&ip_repr, tx_buffer);
  2047. Ok(())
  2048. })
  2049. }
  2050. }
  2051. // We don't support IPv6 fragmentation yet.
  2052. #[cfg(feature = "proto-ipv6")]
  2053. IpRepr::Ipv6(_) => tx_token.consume(self.now, total_len, |mut tx_buffer| {
  2054. #[cfg(feature = "medium-ethernet")]
  2055. if matches!(self.caps.medium, Medium::Ethernet) {
  2056. emit_ethernet(&ip_repr, tx_buffer)?;
  2057. tx_buffer = &mut tx_buffer[EthernetFrame::<&[u8]>::header_len()..];
  2058. }
  2059. emit_ip(&ip_repr, tx_buffer);
  2060. Ok(())
  2061. }),
  2062. }
  2063. }
  2064. }