ethernet.rs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  1. // Heads up! Before working on this file you should read the parts
  2. // of RFC 1122 that discuss Ethernet, ARP and IP.
  3. #[cfg(feature = "proto-ipv4")]
  4. use core::cmp;
  5. use managed::ManagedSlice;
  6. use {Error, Result};
  7. use phy::{Device, DeviceCapabilities, RxToken, TxToken};
  8. use wire::pretty_print::PrettyPrinter;
  9. use wire::{EthernetAddress, EthernetProtocol, EthernetFrame};
  10. use wire::{IpAddress, IpProtocol, IpRepr, IpCidr};
  11. #[cfg(feature = "proto-ipv6")]
  12. use wire::{Ipv6Packet, Ipv6Repr};
  13. #[cfg(feature = "proto-ipv4")]
  14. use wire::{Ipv4Address, Ipv4Packet, Ipv4Repr};
  15. #[cfg(feature = "proto-ipv4")]
  16. use wire::{ArpPacket, ArpRepr, ArpOperation};
  17. #[cfg(feature = "proto-ipv4")]
  18. use wire::{Icmpv4Packet, Icmpv4Repr, Icmpv4DstUnreachable};
  19. #[cfg(feature = "socket-udp")]
  20. use wire::{UdpPacket, UdpRepr};
  21. #[cfg(all(feature = "proto-ipv4", feature = "socket-udp"))]
  22. use wire::IPV4_MIN_MTU;
  23. #[cfg(feature = "socket-tcp")]
  24. use wire::{TcpPacket, TcpRepr, TcpControl};
  25. use socket::{Socket, SocketSet, AnySocket};
  26. #[cfg(feature = "socket-raw")]
  27. use socket::RawSocket;
  28. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  29. use socket::IcmpSocket;
  30. #[cfg(feature = "socket-udp")]
  31. use socket::UdpSocket;
  32. #[cfg(feature = "socket-tcp")]
  33. use socket::TcpSocket;
  34. use super::{NeighborCache, NeighborAnswer};
  35. /// An Ethernet network interface.
  36. ///
  37. /// The network interface logically owns a number of other data structures; to avoid
  38. /// a dependency on heap allocation, it instead owns a `BorrowMut<[T]>`, which can be
  39. /// a `&mut [T]`, or `Vec<T>` if a heap is available.
  40. pub struct Interface<'b, 'c, DeviceT: for<'d> Device<'d>> {
  41. device: DeviceT,
  42. inner: InterfaceInner<'b, 'c>,
  43. }
  44. /// The device independent part of an Ethernet network interface.
  45. ///
  46. /// Separating the device from the data required for prorcessing and dispatching makes
  47. /// it possible to borrow them independently. For example, the tx and rx tokens borrow
  48. /// the `device` mutably until they're used, which makes it impossible to call other
  49. /// methods on the `Interface` in this time (since its `device` field is borrowed
  50. /// exclusively). However, it is still possible to call methods on its `inner` field.
  51. struct InterfaceInner<'b, 'c> {
  52. neighbor_cache: NeighborCache<'b>,
  53. ethernet_addr: EthernetAddress,
  54. ip_addrs: ManagedSlice<'c, IpCidr>,
  55. #[cfg(feature = "proto-ipv4")]
  56. ipv4_gateway: Option<Ipv4Address>,
  57. device_capabilities: DeviceCapabilities,
  58. }
  59. /// A builder structure used for creating a Ethernet network
  60. /// interface.
  61. pub struct InterfaceBuilder <'b, 'c, DeviceT: for<'d> Device<'d>> {
  62. device: DeviceT,
  63. ethernet_addr: Option<EthernetAddress>,
  64. neighbor_cache: Option<NeighborCache<'b>>,
  65. ip_addrs: ManagedSlice<'c, IpCidr>,
  66. #[cfg(feature = "proto-ipv4")]
  67. ipv4_gateway: Option<Ipv4Address>,
  68. }
  69. impl<'b, 'c, DeviceT> InterfaceBuilder<'b, 'c, DeviceT>
  70. where DeviceT: for<'d> Device<'d> {
  71. /// Create a builder used for creating a network interface using the
  72. /// given device and address.
  73. ///
  74. /// # Examples
  75. ///
  76. /// ```
  77. /// # use std::collections::BTreeMap;
  78. /// use smoltcp::iface::{EthernetInterfaceBuilder, NeighborCache};
  79. /// # use smoltcp::phy::Loopback;
  80. /// use smoltcp::wire::{EthernetAddress, IpCidr, IpAddress};
  81. ///
  82. /// let device = // ...
  83. /// # Loopback::new();
  84. /// let hw_addr = // ...
  85. /// # EthernetAddress::default();
  86. /// let neighbor_cache = // ...
  87. /// # NeighborCache::new(BTreeMap::new());
  88. /// let ip_addrs = // ...
  89. /// # [];
  90. /// let iface = EthernetInterfaceBuilder::new(device)
  91. /// .ethernet_addr(hw_addr)
  92. /// .neighbor_cache(neighbor_cache)
  93. /// .ip_addrs(ip_addrs)
  94. /// .finalize();
  95. /// ```
  96. pub fn new(device: DeviceT) -> InterfaceBuilder<'b, 'c, DeviceT> {
  97. InterfaceBuilder {
  98. device: device,
  99. ethernet_addr: None,
  100. neighbor_cache: None,
  101. ip_addrs: ManagedSlice::Borrowed(&mut []),
  102. #[cfg(feature = "proto-ipv4")]
  103. ipv4_gateway: None
  104. }
  105. }
  106. /// Set the Ethernet address the interface will use. See also
  107. /// [ethernet_addr].
  108. ///
  109. /// # Panics
  110. /// This function panics if the address is not unicast.
  111. ///
  112. /// [ethernet_addr]: struct.EthernetInterface.html#method.ethernet_addr
  113. pub fn ethernet_addr(mut self, addr: EthernetAddress) -> InterfaceBuilder<'b, 'c, DeviceT> {
  114. InterfaceInner::check_ethernet_addr(&addr);
  115. self.ethernet_addr = Some(addr);
  116. self
  117. }
  118. /// Set the IP addresses the interface will use. See also
  119. /// [ip_addrs].
  120. ///
  121. /// # Panics
  122. /// This function panics if any of the addresses is not unicast.
  123. ///
  124. /// [ip_addrs]: struct.EthernetInterface.html#method.ip_addrs
  125. pub fn ip_addrs<T>(mut self, ip_addrs: T) -> InterfaceBuilder<'b, 'c, DeviceT>
  126. where T: Into<ManagedSlice<'c, IpCidr>>
  127. {
  128. let ip_addrs = ip_addrs.into();
  129. InterfaceInner::check_ip_addrs(&ip_addrs);
  130. self.ip_addrs = ip_addrs;
  131. self
  132. }
  133. /// Set the IPv4 gateway the interface will use. See also
  134. /// [ipv4_gateway].
  135. ///
  136. /// # Panics
  137. /// This function panics if the given address is not unicast.
  138. ///
  139. /// [ipv4_gateway]: struct.EthernetInterface.html#method.ipv4_gateway
  140. #[cfg(feature = "proto-ipv4")]
  141. pub fn ipv4_gateway<T>(mut self, gateway: T) -> InterfaceBuilder<'b, 'c, DeviceT>
  142. where T: Into<Ipv4Address>
  143. {
  144. let addr = gateway.into();
  145. InterfaceInner::check_gateway_addr(&addr);
  146. self.ipv4_gateway = Some(addr);
  147. self
  148. }
  149. /// Set the Neighbor Cache the interface will use.
  150. pub fn neighbor_cache(mut self, neighbor_cache: NeighborCache<'b>) ->
  151. InterfaceBuilder<'b, 'c, DeviceT> {
  152. self.neighbor_cache = Some(neighbor_cache);
  153. self
  154. }
  155. /// Create a network interface using the previously provided configuration.
  156. ///
  157. /// # Panics
  158. /// If a required option is not provided, this function will panic. Required
  159. /// options are:
  160. ///
  161. /// - [ethernet_addr]
  162. /// - [neighbor_cache]
  163. ///
  164. /// [ethernet_addr]: #method.ethernet_addr
  165. /// [neighbor_cache]: #method.neighbor_cache
  166. pub fn finalize(self) -> Interface<'b, 'c, DeviceT> {
  167. match (self.ethernet_addr, self.neighbor_cache) {
  168. (Some(ethernet_addr), Some(neighbor_cache)) => {
  169. let device_capabilities = self.device.capabilities();
  170. Interface {
  171. device: self.device,
  172. inner: InterfaceInner {
  173. ethernet_addr, device_capabilities, neighbor_cache,
  174. ip_addrs: self.ip_addrs,
  175. #[cfg(feature = "proto-ipv4")]
  176. ipv4_gateway: self.ipv4_gateway,
  177. }
  178. }
  179. },
  180. _ => panic!("a required option was not set"),
  181. }
  182. }
  183. }
  184. #[derive(Debug, PartialEq)]
  185. enum Packet<'a> {
  186. None,
  187. #[cfg(feature = "proto-ipv4")]
  188. Arp(ArpRepr),
  189. #[cfg(feature = "proto-ipv4")]
  190. Icmpv4((Ipv4Repr, Icmpv4Repr<'a>)),
  191. #[cfg(feature = "socket-raw")]
  192. Raw((IpRepr, &'a [u8])),
  193. #[cfg(feature = "socket-udp")]
  194. Udp((IpRepr, UdpRepr<'a>)),
  195. #[cfg(feature = "socket-tcp")]
  196. Tcp((IpRepr, TcpRepr<'a>))
  197. }
  198. impl<'a> Packet<'a> {
  199. fn neighbor_addr(&self) -> Option<IpAddress> {
  200. match self {
  201. &Packet::None => None,
  202. #[cfg(feature = "proto-ipv4")]
  203. &Packet::Arp(_) => None,
  204. #[cfg(feature = "proto-ipv4")]
  205. &Packet::Icmpv4((ref ipv4_repr, _)) => Some(ipv4_repr.dst_addr.into()),
  206. #[cfg(feature = "socket-raw")]
  207. &Packet::Raw((ref ip_repr, _)) => Some(ip_repr.dst_addr()),
  208. #[cfg(feature = "socket-udp")]
  209. &Packet::Udp((ref ip_repr, _)) => Some(ip_repr.dst_addr()),
  210. #[cfg(feature = "socket-tcp")]
  211. &Packet::Tcp((ref ip_repr, _)) => Some(ip_repr.dst_addr())
  212. }
  213. }
  214. }
  215. impl<'b, 'c, DeviceT> Interface<'b, 'c, DeviceT>
  216. where DeviceT: for<'d> Device<'d> {
  217. /// Get the Ethernet address of the interface.
  218. pub fn ethernet_addr(&self) -> EthernetAddress {
  219. self.inner.ethernet_addr
  220. }
  221. /// Set the Ethernet address of the interface.
  222. ///
  223. /// # Panics
  224. /// This function panics if the address is not unicast.
  225. pub fn set_ethernet_addr(&mut self, addr: EthernetAddress) {
  226. self.inner.ethernet_addr = addr;
  227. InterfaceInner::check_ethernet_addr(&self.inner.ethernet_addr);
  228. }
  229. /// Get the IP addresses of the interface.
  230. pub fn ip_addrs(&self) -> &[IpCidr] {
  231. self.inner.ip_addrs.as_ref()
  232. }
  233. /// Update the IP addresses of the interface.
  234. ///
  235. /// # Panics
  236. /// This function panics if any of the addresses is not unicast.
  237. pub fn update_ip_addrs<F: FnOnce(&mut ManagedSlice<'c, IpCidr>)>(&mut self, f: F) {
  238. f(&mut self.inner.ip_addrs);
  239. InterfaceInner::check_ip_addrs(&self.inner.ip_addrs)
  240. }
  241. /// Check whether the interface has the given IP address assigned.
  242. pub fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  243. self.inner.has_ip_addr(addr)
  244. }
  245. /// Get the IPv4 gateway of the interface.
  246. #[cfg(feature = "proto-ipv4")]
  247. pub fn ipv4_gateway(&self) -> Option<Ipv4Address> {
  248. self.inner.ipv4_gateway
  249. }
  250. /// Set the IPv4 gateway of the interface.
  251. ///
  252. /// # Panics
  253. /// This function panics if the given address is not unicast.
  254. #[cfg(feature = "proto-ipv4")]
  255. pub fn set_ipv4_gateway<GatewayAddrT>(&mut self, gateway: GatewayAddrT)
  256. where GatewayAddrT: Into<Option<Ipv4Address>> {
  257. self.inner.ipv4_gateway = gateway.into();
  258. self.inner.ipv4_gateway.map(|addr| InterfaceInner::check_gateway_addr(&addr));
  259. }
  260. /// Transmit packets queued in the given sockets, and receive packets queued
  261. /// in the device.
  262. ///
  263. /// The timestamp must be a number of milliseconds, monotonically increasing
  264. /// since an arbitrary moment in time, such as system startup.
  265. ///
  266. /// This function returns a boolean value indicating whether any packets were
  267. /// processed or emitted, and thus, whether the readiness of any socket might
  268. /// have changed.
  269. ///
  270. /// # Errors
  271. /// This method will routinely return errors in response to normal network
  272. /// activity as well as certain boundary conditions such as buffer exhaustion.
  273. /// These errors are provided as an aid for troubleshooting, and are meant
  274. /// to be logged and ignored.
  275. ///
  276. /// As a special case, `Err(Error::Unrecognized)` is returned in response to
  277. /// packets containing any unsupported protocol, option, or form, which is
  278. /// a very common occurrence and on a production system it should not even
  279. /// be logged.
  280. pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<bool> {
  281. let mut readiness_may_have_changed = false;
  282. loop {
  283. let processed_any = self.socket_ingress(sockets, timestamp)?;
  284. let emitted_any = self.socket_egress(sockets, timestamp)?;
  285. if processed_any || emitted_any {
  286. readiness_may_have_changed = true;
  287. } else {
  288. break
  289. }
  290. }
  291. Ok(readiness_may_have_changed)
  292. }
  293. /// Return a _soft deadline_ for calling [poll] the next time.
  294. /// That is, if `iface.poll_at(&sockets, 1000)` returns `Ok(Some(2000))`,
  295. /// you should call call [poll] in 1000 ms; it is harmless (but wastes energy)
  296. /// to call it 500 ms later, and potentially harmful (impacting quality of service)
  297. /// to call it 1500 ms later.
  298. ///
  299. /// The timestamp argument is the same as for [poll].
  300. ///
  301. /// [poll]: #method.poll
  302. pub fn poll_at(&self, sockets: &SocketSet, timestamp: u64) -> Option<u64> {
  303. sockets.iter().filter_map(|socket| {
  304. let socket_poll_at = socket.poll_at();
  305. socket.meta().poll_at(socket_poll_at, |ip_addr|
  306. self.inner.has_neighbor(&ip_addr, timestamp))
  307. }).min()
  308. }
  309. /// Return an _advisory wait time_ for calling [poll] the next time.
  310. /// That is, if `iface.poll_at(&sockets, 1000)` returns `Ok(Some(1000))`,
  311. /// you should call call [poll] in 1000 ms; it is harmless (but wastes energy)
  312. /// to call it 500 ms later, and potentially harmful (impacting quality of service)
  313. /// to call it 1500 ms later.
  314. ///
  315. /// This is a shortcut for `poll_at(..., timestamp).map(|at| at.saturating_sub(timestamp))`.
  316. ///
  317. /// The timestamp argument is the same as for [poll].
  318. ///
  319. /// [poll]: #method.poll
  320. pub fn poll_delay(&self, sockets: &SocketSet, timestamp: u64) -> Option<u64> {
  321. self.poll_at(sockets, timestamp).map(|at| at.saturating_sub(timestamp))
  322. }
  323. fn socket_ingress(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<bool> {
  324. let mut processed_any = false;
  325. loop {
  326. let &mut Self { ref mut device, ref mut inner } = self;
  327. let (rx_token, tx_token) = match device.receive() {
  328. None => break,
  329. Some(tokens) => tokens,
  330. };
  331. rx_token.consume(timestamp, |frame| {
  332. inner.process_ethernet(sockets, timestamp, &frame).map_err(|err| {
  333. net_debug!("cannot process ingress packet: {}", err);
  334. net_debug!("packet dump follows:\n{}",
  335. PrettyPrinter::<EthernetFrame<&[u8]>>::new("", &frame));
  336. err
  337. }).and_then(|response| {
  338. processed_any = true;
  339. inner.dispatch(tx_token, timestamp, response).map_err(|err| {
  340. net_debug!("cannot dispatch response packet: {}", err);
  341. err
  342. })
  343. })
  344. })?;
  345. }
  346. Ok(processed_any)
  347. }
  348. fn socket_egress(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<bool> {
  349. let mut caps = self.device.capabilities();
  350. caps.max_transmission_unit -= EthernetFrame::<&[u8]>::header_len();
  351. let mut emitted_any = false;
  352. for mut socket in sockets.iter_mut() {
  353. if !socket.meta_mut().egress_permitted(|ip_addr|
  354. self.inner.has_neighbor(&ip_addr, timestamp)) {
  355. continue
  356. }
  357. let mut neighbor_addr = None;
  358. let mut device_result = Ok(());
  359. let &mut Self { ref mut device, ref mut inner } = self;
  360. macro_rules! respond {
  361. ($response:expr) => ({
  362. let response = $response;
  363. neighbor_addr = response.neighbor_addr();
  364. let tx_token = device.transmit().ok_or(Error::Exhausted)?;
  365. device_result = inner.dispatch(tx_token, timestamp, response);
  366. device_result
  367. })
  368. }
  369. let socket_result =
  370. match *socket {
  371. #[cfg(feature = "socket-raw")]
  372. Socket::Raw(ref mut socket) =>
  373. socket.dispatch(&caps.checksum, |response|
  374. respond!(Packet::Raw(response))),
  375. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  376. Socket::Icmp(ref mut socket) =>
  377. socket.dispatch(&caps, |response| {
  378. match response {
  379. #[cfg(feature = "proto-ipv4")]
  380. (IpRepr::Ipv4(ipv4_repr), icmpv4_repr) =>
  381. respond!(Packet::Icmpv4((ipv4_repr, icmpv4_repr))),
  382. _ => Err(Error::Unaddressable)
  383. }
  384. }),
  385. #[cfg(feature = "socket-udp")]
  386. Socket::Udp(ref mut socket) =>
  387. socket.dispatch(|response|
  388. respond!(Packet::Udp(response))),
  389. #[cfg(feature = "socket-tcp")]
  390. Socket::Tcp(ref mut socket) =>
  391. socket.dispatch(timestamp, &caps, |response|
  392. respond!(Packet::Tcp(response))),
  393. Socket::__Nonexhaustive(_) => unreachable!()
  394. };
  395. match (device_result, socket_result) {
  396. (Err(Error::Exhausted), _) => break, // nowhere to transmit
  397. (Ok(()), Err(Error::Exhausted)) => (), // nothing to transmit
  398. (Err(Error::Unaddressable), _) => {
  399. // `NeighborCache` already takes care of rate limiting the neighbor discovery
  400. // requests from the socket. However, without an additional rate limiting
  401. // mechanism, we would spin on every socket that has yet to discover its
  402. // neighboor.
  403. socket.meta_mut().neighbor_missing(timestamp,
  404. neighbor_addr.expect("non-IP response packet"));
  405. break
  406. }
  407. (Err(err), _) | (_, Err(err)) => {
  408. net_debug!("{}: cannot dispatch egress packet: {}",
  409. socket.meta().handle, err);
  410. return Err(err)
  411. }
  412. (Ok(()), Ok(())) => emitted_any = true
  413. }
  414. }
  415. Ok(emitted_any)
  416. }
  417. }
  418. impl<'b, 'c> InterfaceInner<'b, 'c> {
  419. fn check_ethernet_addr(addr: &EthernetAddress) {
  420. if addr.is_multicast() {
  421. panic!("Ethernet address {} is not unicast", addr)
  422. }
  423. }
  424. fn check_ip_addrs(addrs: &[IpCidr]) {
  425. for cidr in addrs {
  426. if !cidr.address().is_unicast() {
  427. panic!("IP address {} is not unicast", cidr.address())
  428. }
  429. }
  430. }
  431. #[cfg(feature = "proto-ipv4")]
  432. fn check_gateway_addr(addr: &Ipv4Address) {
  433. if !addr.is_unicast() {
  434. panic!("gateway IP address {} is not unicast", addr);
  435. }
  436. }
  437. /// Check whether the interface has the given IP address assigned.
  438. fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  439. let addr = addr.into();
  440. self.ip_addrs.iter().any(|probe| probe.address() == addr)
  441. }
  442. fn process_ethernet<'frame, T: AsRef<[u8]>>
  443. (&mut self, sockets: &mut SocketSet, timestamp: u64, frame: &'frame T) ->
  444. Result<Packet<'frame>>
  445. {
  446. let eth_frame = EthernetFrame::new_checked(frame)?;
  447. // Ignore any packets not directed to our hardware address.
  448. if !eth_frame.dst_addr().is_broadcast() &&
  449. eth_frame.dst_addr() != self.ethernet_addr {
  450. return Ok(Packet::None)
  451. }
  452. match eth_frame.ethertype() {
  453. #[cfg(feature = "proto-ipv4")]
  454. EthernetProtocol::Arp =>
  455. self.process_arp(timestamp, &eth_frame),
  456. #[cfg(feature = "proto-ipv4")]
  457. EthernetProtocol::Ipv4 =>
  458. self.process_ipv4(sockets, timestamp, &eth_frame),
  459. #[cfg(feature = "proto-ipv6")]
  460. EthernetProtocol::Ipv6 =>
  461. self.process_ipv6(sockets, timestamp, &eth_frame),
  462. // Drop all other traffic.
  463. _ => Err(Error::Unrecognized),
  464. }
  465. }
  466. #[cfg(feature = "proto-ipv4")]
  467. fn process_arp<'frame, T: AsRef<[u8]>>
  468. (&mut self, timestamp: u64, eth_frame: &EthernetFrame<&'frame T>) ->
  469. Result<Packet<'frame>>
  470. {
  471. let arp_packet = ArpPacket::new_checked(eth_frame.payload())?;
  472. let arp_repr = ArpRepr::parse(&arp_packet)?;
  473. match arp_repr {
  474. // Respond to ARP requests aimed at us, and fill the ARP cache from all ARP
  475. // requests and replies, to minimize the chance that we have to perform
  476. // an explicit ARP request.
  477. ArpRepr::EthernetIpv4 {
  478. operation, source_hardware_addr, source_protocol_addr, target_protocol_addr, ..
  479. } => {
  480. if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() {
  481. self.neighbor_cache.fill(source_protocol_addr.into(),
  482. source_hardware_addr,
  483. timestamp);
  484. } else {
  485. // Discard packets with non-unicast source addresses.
  486. net_debug!("non-unicast source address");
  487. return Err(Error::Malformed)
  488. }
  489. if operation == ArpOperation::Request && self.has_ip_addr(target_protocol_addr) {
  490. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  491. operation: ArpOperation::Reply,
  492. source_hardware_addr: self.ethernet_addr,
  493. source_protocol_addr: target_protocol_addr,
  494. target_hardware_addr: source_hardware_addr,
  495. target_protocol_addr: source_protocol_addr
  496. }))
  497. } else {
  498. Ok(Packet::None)
  499. }
  500. }
  501. _ => Err(Error::Unrecognized)
  502. }
  503. }
  504. #[cfg(all(any(feature = "proto-ipv4", feature = "proto-ipv6"), feature = "socket-raw"))]
  505. fn raw_socket_filter<'frame>(&mut self, sockets: &mut SocketSet, ip_repr: &IpRepr,
  506. ip_payload: &'frame [u8]) -> bool {
  507. let checksum_caps = self.device_capabilities.checksum.clone();
  508. let mut handled_by_raw_socket = false;
  509. // Pass every IP packet to all raw sockets we have registered.
  510. for mut raw_socket in sockets.iter_mut().filter_map(RawSocket::downcast) {
  511. if !raw_socket.accepts(&ip_repr) { continue }
  512. match raw_socket.process(&ip_repr, ip_payload, &checksum_caps) {
  513. // The packet is valid and handled by socket.
  514. Ok(()) => handled_by_raw_socket = true,
  515. // The socket buffer is full.
  516. Err(Error::Exhausted) => (),
  517. // Raw sockets don't validate the packets in any way.
  518. Err(_) => unreachable!(),
  519. }
  520. }
  521. handled_by_raw_socket
  522. }
  523. #[cfg(feature = "proto-ipv6")]
  524. fn process_ipv6<'frame, T: AsRef<[u8]>>
  525. (&mut self, sockets: &mut SocketSet, timestamp: u64,
  526. eth_frame: &EthernetFrame<&'frame T>) ->
  527. Result<Packet<'frame>>
  528. {
  529. let ipv6_packet = Ipv6Packet::new_checked(eth_frame.payload())?;
  530. let ipv6_repr = Ipv6Repr::parse(&ipv6_packet)?;
  531. if !ipv6_repr.src_addr.is_unicast() {
  532. // Discard packets with non-unicast source addresses.
  533. net_debug!("non-unicast source address");
  534. return Err(Error::Malformed)
  535. }
  536. if eth_frame.src_addr().is_unicast() {
  537. // Fill the neighbor cache from IP header of unicast frames.
  538. let ip_addr = IpAddress::Ipv6(ipv6_repr.src_addr);
  539. if self.in_same_network(&ip_addr) {
  540. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  541. }
  542. }
  543. let ip_repr = IpRepr::Ipv6(ipv6_repr);
  544. let ip_payload = ipv6_packet.payload();
  545. #[cfg(feature = "socket-raw")]
  546. let handled_by_raw_socket = self.raw_socket_filter(sockets, &ip_repr, ip_payload);
  547. match ipv6_repr.next_header {
  548. #[cfg(feature = "socket-udp")]
  549. IpProtocol::Udp =>
  550. self.process_udp(sockets, ip_repr, ip_payload),
  551. #[cfg(feature = "socket-tcp")]
  552. IpProtocol::Tcp =>
  553. self.process_tcp(sockets, timestamp, ip_repr, ip_payload),
  554. #[cfg(feature = "socket-raw")]
  555. _ if handled_by_raw_socket =>
  556. Ok(Packet::None),
  557. // TODO: send error responses when appropriate.
  558. _ => Ok(Packet::None)
  559. }
  560. }
  561. #[cfg(feature = "proto-ipv4")]
  562. fn process_ipv4<'frame, T: AsRef<[u8]>>
  563. (&mut self, sockets: &mut SocketSet, timestamp: u64,
  564. eth_frame: &EthernetFrame<&'frame T>) ->
  565. Result<Packet<'frame>>
  566. {
  567. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
  568. let checksum_caps = self.device_capabilities.checksum.clone();
  569. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &checksum_caps)?;
  570. if !ipv4_repr.src_addr.is_unicast() {
  571. // Discard packets with non-unicast source addresses.
  572. net_debug!("non-unicast source address");
  573. return Err(Error::Malformed)
  574. }
  575. if eth_frame.src_addr().is_unicast() {
  576. // Fill the neighbor cache from IP header of unicast frames.
  577. let ip_addr = IpAddress::Ipv4(ipv4_repr.src_addr);
  578. if self.in_same_network(&ip_addr) {
  579. self.neighbor_cache.fill(ip_addr, eth_frame.src_addr(), timestamp);
  580. }
  581. }
  582. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  583. let ip_payload = ipv4_packet.payload();
  584. #[cfg(feature = "socket-raw")]
  585. let handled_by_raw_socket = self.raw_socket_filter(sockets, &ip_repr, ip_payload);
  586. if !ipv4_repr.dst_addr.is_broadcast() && !self.has_ip_addr(ipv4_repr.dst_addr) {
  587. // Ignore IP packets not directed at us.
  588. return Ok(Packet::None)
  589. }
  590. match ipv4_repr.protocol {
  591. IpProtocol::Icmp =>
  592. self.process_icmpv4(sockets, ip_repr, ip_payload),
  593. #[cfg(feature = "socket-udp")]
  594. IpProtocol::Udp =>
  595. self.process_udp(sockets, ip_repr, ip_payload),
  596. #[cfg(feature = "socket-tcp")]
  597. IpProtocol::Tcp =>
  598. self.process_tcp(sockets, timestamp, ip_repr, ip_payload),
  599. #[cfg(feature = "socket-raw")]
  600. _ if handled_by_raw_socket =>
  601. Ok(Packet::None),
  602. _ => {
  603. // Send back as much of the original payload as we can
  604. let payload_len = cmp::min(
  605. ip_payload.len(), self.device_capabilities.max_transmission_unit);
  606. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  607. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  608. header: ipv4_repr,
  609. data: &ip_payload[0..payload_len]
  610. };
  611. Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr))
  612. }
  613. }
  614. }
  615. #[cfg(feature = "proto-ipv4")]
  616. fn process_icmpv4<'frame>(&self, _sockets: &mut SocketSet, ip_repr: IpRepr,
  617. ip_payload: &'frame [u8]) -> Result<Packet<'frame>>
  618. {
  619. let icmp_packet = Icmpv4Packet::new_checked(ip_payload)?;
  620. let checksum_caps = self.device_capabilities.checksum.clone();
  621. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &checksum_caps)?;
  622. #[cfg(feature = "socket-icmp")]
  623. let mut handled_by_icmp_socket = false;
  624. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  625. for mut icmp_socket in _sockets.iter_mut().filter_map(IcmpSocket::downcast) {
  626. if !icmp_socket.accepts(&ip_repr, &icmp_repr, &checksum_caps) { continue }
  627. match icmp_socket.process(&ip_repr, &icmp_repr, &checksum_caps) {
  628. // The packet is valid and handled by socket.
  629. Ok(()) => handled_by_icmp_socket = true,
  630. // The socket buffer is full.
  631. Err(Error::Exhausted) => (),
  632. // ICMP sockets don't validate the packets in any way.
  633. Err(_) => unreachable!(),
  634. }
  635. }
  636. match icmp_repr {
  637. // Respond to echo requests.
  638. Icmpv4Repr::EchoRequest { ident, seq_no, data } => {
  639. let icmp_reply_repr = Icmpv4Repr::EchoReply {
  640. ident: ident,
  641. seq_no: seq_no,
  642. data: data
  643. };
  644. match ip_repr {
  645. IpRepr::Ipv4(ipv4_repr) => Ok(self.icmpv4_reply(ipv4_repr, icmp_reply_repr)),
  646. _ => Err(Error::Unrecognized),
  647. }
  648. }
  649. // Ignore any echo replies.
  650. Icmpv4Repr::EchoReply { .. } => Ok(Packet::None),
  651. // Don't report an error if a packet with unknown type
  652. // has been handled by an ICMP socket
  653. #[cfg(feature = "socket-icmp")]
  654. _ if handled_by_icmp_socket => Ok(Packet::None),
  655. // FIXME: do something correct here?
  656. _ => Err(Error::Unrecognized),
  657. }
  658. }
  659. #[cfg(feature = "proto-ipv4")]
  660. fn icmpv4_reply<'frame, 'icmp: 'frame>
  661. (&self, ipv4_repr: Ipv4Repr, icmp_repr: Icmpv4Repr<'icmp>) ->
  662. Packet<'frame>
  663. {
  664. if ipv4_repr.dst_addr.is_unicast() {
  665. let ipv4_reply_repr = Ipv4Repr {
  666. src_addr: ipv4_repr.dst_addr,
  667. dst_addr: ipv4_repr.src_addr,
  668. protocol: IpProtocol::Icmp,
  669. payload_len: icmp_repr.buffer_len(),
  670. hop_limit: 64
  671. };
  672. Packet::Icmpv4((ipv4_reply_repr, icmp_repr))
  673. } else {
  674. // Do not send any ICMP replies to a broadcast destination address.
  675. Packet::None
  676. }
  677. }
  678. #[cfg(feature = "socket-udp")]
  679. fn process_udp<'frame>(&self, sockets: &mut SocketSet,
  680. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  681. Result<Packet<'frame>>
  682. {
  683. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  684. let udp_packet = UdpPacket::new_checked(ip_payload)?;
  685. let checksum_caps = self.device_capabilities.checksum.clone();
  686. let udp_repr = UdpRepr::parse(&udp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  687. for mut udp_socket in sockets.iter_mut().filter_map(UdpSocket::downcast) {
  688. if !udp_socket.accepts(&ip_repr, &udp_repr) { continue }
  689. match udp_socket.process(&ip_repr, &udp_repr) {
  690. // The packet is valid and handled by socket.
  691. Ok(()) => return Ok(Packet::None),
  692. // The packet is malformed, or the socket buffer is full.
  693. Err(e) => return Err(e)
  694. }
  695. }
  696. // The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  697. match ip_repr {
  698. #[cfg(feature = "proto-ipv4")]
  699. IpRepr::Ipv4(ipv4_repr) => {
  700. // Send back as much of the original payload as will fit within
  701. // the minimum MTU required by IPv4. See RFC 1812 § 4.3.2.3 for
  702. // more details.
  703. //
  704. // Since the entire network layer packet must fit within 576
  705. // bytes, the payload must not exceed the following:
  706. //
  707. // 576 - New IP hdr size - Old IP hdr size - ICMPv4 DstUnreachable hdr size
  708. //
  709. // We do no support IP options, so this becomes 576 - 20 - 20 - 8.
  710. const DST_UNREACHABLE_HDR_SIZE: usize = 48;
  711. let payload_len = cmp::min(ip_payload.len(), IPV4_MIN_MTU - DST_UNREACHABLE_HDR_SIZE);
  712. let icmpv4_reply_repr = Icmpv4Repr::DstUnreachable {
  713. reason: Icmpv4DstUnreachable::PortUnreachable,
  714. header: ipv4_repr,
  715. data: &ip_payload[0..payload_len]
  716. };
  717. Ok(self.icmpv4_reply(ipv4_repr, icmpv4_reply_repr))
  718. },
  719. #[cfg(feature = "proto-ipv6")]
  720. IpRepr::Ipv6(_) => Err(Error::Unaddressable),
  721. IpRepr::Unspecified { .. } |
  722. IpRepr::__Nonexhaustive => Err(Error::Unaddressable),
  723. }
  724. }
  725. #[cfg(feature = "socket-tcp")]
  726. fn process_tcp<'frame>(&self, sockets: &mut SocketSet, timestamp: u64,
  727. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  728. Result<Packet<'frame>>
  729. {
  730. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  731. let tcp_packet = TcpPacket::new_checked(ip_payload)?;
  732. let checksum_caps = self.device_capabilities.checksum.clone();
  733. let tcp_repr = TcpRepr::parse(&tcp_packet, &src_addr, &dst_addr, &checksum_caps)?;
  734. for mut tcp_socket in sockets.iter_mut().filter_map(TcpSocket::downcast) {
  735. if !tcp_socket.accepts(&ip_repr, &tcp_repr) { continue }
  736. match tcp_socket.process(timestamp, &ip_repr, &tcp_repr) {
  737. // The packet is valid and handled by socket.
  738. Ok(reply) => return Ok(reply.map_or(Packet::None, Packet::Tcp)),
  739. // The packet is malformed, or doesn't match the socket state,
  740. // or the socket buffer is full.
  741. Err(e) => return Err(e)
  742. }
  743. }
  744. if tcp_repr.control == TcpControl::Rst {
  745. // Never reply to a TCP RST packet with another TCP RST packet.
  746. Ok(Packet::None)
  747. } else {
  748. // The packet wasn't handled by a socket, send a TCP RST packet.
  749. Ok(Packet::Tcp(TcpSocket::rst_reply(&ip_repr, &tcp_repr)))
  750. }
  751. }
  752. fn dispatch<Tx>(&mut self, tx_token: Tx, timestamp: u64,
  753. packet: Packet) -> Result<()>
  754. where Tx: TxToken
  755. {
  756. let checksum_caps = self.device_capabilities.checksum.clone();
  757. match packet {
  758. #[cfg(feature = "proto-ipv4")]
  759. Packet::Arp(arp_repr) => {
  760. let dst_hardware_addr =
  761. match arp_repr {
  762. ArpRepr::EthernetIpv4 { target_hardware_addr, .. } => target_hardware_addr,
  763. _ => unreachable!()
  764. };
  765. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  766. frame.set_dst_addr(dst_hardware_addr);
  767. frame.set_ethertype(EthernetProtocol::Arp);
  768. let mut packet = ArpPacket::new(frame.payload_mut());
  769. arp_repr.emit(&mut packet);
  770. })
  771. },
  772. #[cfg(feature = "proto-ipv4")]
  773. Packet::Icmpv4((ipv4_repr, icmpv4_repr)) => {
  774. self.dispatch_ip(tx_token, timestamp, IpRepr::Ipv4(ipv4_repr),
  775. |_ip_repr, payload| {
  776. icmpv4_repr.emit(&mut Icmpv4Packet::new(payload), &checksum_caps);
  777. })
  778. }
  779. #[cfg(feature = "socket-raw")]
  780. Packet::Raw((ip_repr, raw_packet)) => {
  781. self.dispatch_ip(tx_token, timestamp, ip_repr, |_ip_repr, payload| {
  782. payload.copy_from_slice(raw_packet);
  783. })
  784. }
  785. #[cfg(feature = "socket-udp")]
  786. Packet::Udp((ip_repr, udp_repr)) => {
  787. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  788. udp_repr.emit(&mut UdpPacket::new(payload),
  789. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  790. &checksum_caps);
  791. })
  792. }
  793. #[cfg(feature = "socket-tcp")]
  794. Packet::Tcp((ip_repr, mut tcp_repr)) => {
  795. let caps = self.device_capabilities.clone();
  796. self.dispatch_ip(tx_token, timestamp, ip_repr, |ip_repr, payload| {
  797. // This is a terrible hack to make TCP performance more acceptable on systems
  798. // where the TCP buffers are significantly larger than network buffers,
  799. // e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
  800. // together with four 1500 B Ethernet receive buffers. If left untreated,
  801. // this would result in our peer pushing our window and sever packet loss.
  802. //
  803. // I'm really not happy about this "solution" but I don't know what else to do.
  804. if let Some(max_burst_size) = caps.max_burst_size {
  805. let mut max_segment_size = caps.max_transmission_unit;
  806. max_segment_size -= EthernetFrame::<&[u8]>::header_len();
  807. max_segment_size -= ip_repr.buffer_len();
  808. max_segment_size -= tcp_repr.header_len();
  809. let max_window_size = max_burst_size * max_segment_size;
  810. if tcp_repr.window_len as usize > max_window_size {
  811. tcp_repr.window_len = max_window_size as u16;
  812. }
  813. }
  814. tcp_repr.emit(&mut TcpPacket::new(payload),
  815. &ip_repr.src_addr(), &ip_repr.dst_addr(),
  816. &checksum_caps);
  817. })
  818. }
  819. Packet::None => Ok(())
  820. }
  821. }
  822. fn dispatch_ethernet<Tx, F>(&mut self, tx_token: Tx, timestamp: u64,
  823. buffer_len: usize, f: F) -> Result<()>
  824. where Tx: TxToken, F: FnOnce(EthernetFrame<&mut [u8]>)
  825. {
  826. let tx_len = EthernetFrame::<&[u8]>::buffer_len(buffer_len);
  827. tx_token.consume(timestamp, tx_len, |tx_buffer| {
  828. debug_assert!(tx_buffer.as_ref().len() == tx_len);
  829. let mut frame = EthernetFrame::new(tx_buffer.as_mut());
  830. frame.set_src_addr(self.ethernet_addr);
  831. f(frame);
  832. Ok(())
  833. })
  834. }
  835. fn in_same_network(&self, addr: &IpAddress) -> bool {
  836. self.ip_addrs
  837. .iter()
  838. .find(|cidr| cidr.contains_addr(addr))
  839. .is_some()
  840. }
  841. fn route(&self, addr: &IpAddress) -> Result<IpAddress> {
  842. // Send directly.
  843. if self.in_same_network(addr) || addr.is_broadcast() {
  844. return Ok(addr.clone())
  845. }
  846. // Route via a gateway.
  847. match addr {
  848. #[cfg(feature = "proto-ipv4")]
  849. &IpAddress::Ipv4(_) => match self.ipv4_gateway {
  850. Some(gateway) => Ok(gateway.into()),
  851. None => Err(Error::Unaddressable),
  852. }
  853. _ => Err(Error::Unaddressable)
  854. }
  855. }
  856. fn has_neighbor<'a>(&self, addr: &'a IpAddress, timestamp: u64) -> bool {
  857. match self.route(addr) {
  858. Ok(routed_addr) => {
  859. self.neighbor_cache
  860. .lookup_pure(&routed_addr, timestamp)
  861. .is_some()
  862. }
  863. Err(_) => false
  864. }
  865. }
  866. fn lookup_hardware_addr<Tx>(&mut self, tx_token: Tx, timestamp: u64,
  867. src_addr: &IpAddress, dst_addr: &IpAddress) ->
  868. Result<(EthernetAddress, Tx)>
  869. where Tx: TxToken
  870. {
  871. let dst_addr = self.route(dst_addr)?;
  872. match self.neighbor_cache.lookup(&dst_addr, timestamp) {
  873. NeighborAnswer::Found(hardware_addr) =>
  874. return Ok((hardware_addr, tx_token)),
  875. NeighborAnswer::RateLimited =>
  876. return Err(Error::Unaddressable),
  877. NeighborAnswer::NotFound => (),
  878. }
  879. match (src_addr, dst_addr) {
  880. #[cfg(feature = "proto-ipv4")]
  881. (&IpAddress::Ipv4(src_addr), IpAddress::Ipv4(dst_addr)) => {
  882. net_debug!("address {} not in neighbor cache, sending ARP request",
  883. dst_addr);
  884. let arp_repr = ArpRepr::EthernetIpv4 {
  885. operation: ArpOperation::Request,
  886. source_hardware_addr: self.ethernet_addr,
  887. source_protocol_addr: src_addr,
  888. target_hardware_addr: EthernetAddress::BROADCAST,
  889. target_protocol_addr: dst_addr,
  890. };
  891. self.dispatch_ethernet(tx_token, timestamp, arp_repr.buffer_len(), |mut frame| {
  892. frame.set_dst_addr(EthernetAddress::BROADCAST);
  893. frame.set_ethertype(EthernetProtocol::Arp);
  894. arp_repr.emit(&mut ArpPacket::new(frame.payload_mut()))
  895. })?;
  896. Err(Error::Unaddressable)
  897. }
  898. _ => Err(Error::Unaddressable)
  899. }
  900. }
  901. fn dispatch_ip<Tx, F>(&mut self, tx_token: Tx, timestamp: u64,
  902. ip_repr: IpRepr, f: F) -> Result<()>
  903. where Tx: TxToken, F: FnOnce(IpRepr, &mut [u8])
  904. {
  905. let ip_repr = ip_repr.lower(&self.ip_addrs)?;
  906. let checksum_caps = self.device_capabilities.checksum.clone();
  907. let (dst_hardware_addr, tx_token) =
  908. self.lookup_hardware_addr(tx_token, timestamp,
  909. &ip_repr.src_addr(), &ip_repr.dst_addr())?;
  910. self.dispatch_ethernet(tx_token, timestamp, ip_repr.total_len(), |mut frame| {
  911. frame.set_dst_addr(dst_hardware_addr);
  912. match ip_repr {
  913. #[cfg(feature = "proto-ipv4")]
  914. IpRepr::Ipv4(_) => frame.set_ethertype(EthernetProtocol::Ipv4),
  915. #[cfg(feature = "proto-ipv6")]
  916. IpRepr::Ipv6(_) => frame.set_ethertype(EthernetProtocol::Ipv6),
  917. _ => return
  918. }
  919. ip_repr.emit(frame.payload_mut(), &checksum_caps);
  920. let payload = &mut frame.payload_mut()[ip_repr.buffer_len()..];
  921. f(ip_repr, payload)
  922. })
  923. }
  924. }
  925. #[cfg(test)]
  926. mod test {
  927. use std::collections::BTreeMap;
  928. use {Result, Error};
  929. use super::InterfaceBuilder;
  930. use iface::{NeighborCache, EthernetInterface};
  931. use phy::{self, Loopback, ChecksumCapabilities};
  932. use socket::SocketSet;
  933. #[cfg(feature = "proto-ipv4")]
  934. use wire::{ArpOperation, ArpPacket, ArpRepr};
  935. use wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
  936. use wire::{IpAddress, IpCidr, IpProtocol, IpRepr};
  937. #[cfg(feature = "proto-ipv4")]
  938. use wire::{Ipv4Address, Ipv4Repr};
  939. #[cfg(feature = "proto-ipv4")]
  940. use wire::{Icmpv4Repr, Icmpv4DstUnreachable};
  941. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  942. use wire::{UdpPacket, UdpRepr};
  943. #[cfg(feature = "proto-ipv6")]
  944. use wire::{Ipv6Address, Ipv6Repr};
  945. use super::Packet;
  946. fn create_loopback<'a, 'b>() -> (EthernetInterface<'static, 'b, Loopback>,
  947. SocketSet<'static, 'a, 'b>) {
  948. // Create a basic device
  949. let device = Loopback::new();
  950. let ip_addrs = [
  951. #[cfg(feature = "proto-ipv4")]
  952. IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8),
  953. #[cfg(feature = "proto-ipv6")]
  954. IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 128)
  955. ];
  956. let iface = InterfaceBuilder::new(device)
  957. .ethernet_addr(EthernetAddress::default())
  958. .neighbor_cache(NeighborCache::new(BTreeMap::new()))
  959. .ip_addrs(ip_addrs)
  960. .finalize();
  961. (iface, SocketSet::new(vec![]))
  962. }
  963. #[derive(Debug, PartialEq)]
  964. struct MockTxToken;
  965. impl phy::TxToken for MockTxToken {
  966. fn consume<R, F>(self, _: u64, _: usize, _: F) -> Result<R>
  967. where F: FnOnce(&mut [u8]) -> Result<R> {
  968. Err(Error::__Nonexhaustive)
  969. }
  970. }
  971. #[test]
  972. #[should_panic(expected = "a required option was not set")]
  973. fn test_builder_initialization_panic() {
  974. InterfaceBuilder::new(Loopback::new()).finalize();
  975. }
  976. #[test]
  977. #[cfg(feature = "proto-ipv4")]
  978. fn test_no_icmp_to_broadcast() {
  979. let (mut iface, mut socket_set) = create_loopback();
  980. let mut eth_bytes = vec![0u8; 34];
  981. // Unknown Ipv4 Protocol
  982. //
  983. // Because the destination is the broadcast address
  984. // this should not trigger and Destination Unreachable
  985. // response. See RFC 1122 § 3.2.2.
  986. let repr = IpRepr::Ipv4(Ipv4Repr {
  987. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  988. dst_addr: Ipv4Address::BROADCAST,
  989. protocol: IpProtocol::Unknown(0x0c),
  990. payload_len: 0,
  991. hop_limit: 0x40
  992. });
  993. let frame = {
  994. let mut frame = EthernetFrame::new(&mut eth_bytes);
  995. frame.set_dst_addr(EthernetAddress::BROADCAST);
  996. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  997. frame.set_ethertype(EthernetProtocol::Ipv4);
  998. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  999. EthernetFrame::new(&*frame.into_inner())
  1000. };
  1001. // Ensure that the unknown protocol frame does not trigger an
  1002. // ICMP error response when the destination address is a
  1003. // broadcast address
  1004. assert_eq!(iface.inner.process_ipv4(&mut socket_set, 0, &frame),
  1005. Ok(Packet::None));
  1006. }
  1007. #[test]
  1008. #[cfg(feature = "proto-ipv4")]
  1009. fn test_icmp_error_no_payload() {
  1010. static NO_BYTES: [u8; 0] = [];
  1011. let (mut iface, mut socket_set) = create_loopback();
  1012. let mut eth_bytes = vec![0u8; 34];
  1013. // Unknown Ipv4 Protocol with no payload
  1014. let repr = IpRepr::Ipv4(Ipv4Repr {
  1015. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1016. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1017. protocol: IpProtocol::Unknown(0x0c),
  1018. payload_len: 0,
  1019. hop_limit: 0x40
  1020. });
  1021. // emit the above repr to a frame
  1022. let frame = {
  1023. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1024. frame.set_dst_addr(EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  1025. frame.set_src_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1026. frame.set_ethertype(EthernetProtocol::Ipv4);
  1027. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1028. EthernetFrame::new(&*frame.into_inner())
  1029. };
  1030. // The expected Destination Unreachable response due to the
  1031. // unknown protocol
  1032. let icmp_repr = Icmpv4Repr::DstUnreachable {
  1033. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  1034. header: Ipv4Repr {
  1035. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1036. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1037. protocol: IpProtocol::Unknown(12),
  1038. payload_len: 0,
  1039. hop_limit: 64
  1040. },
  1041. data: &NO_BYTES
  1042. };
  1043. let expected_repr = Packet::Icmpv4((
  1044. Ipv4Repr {
  1045. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1046. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1047. protocol: IpProtocol::Icmp,
  1048. payload_len: icmp_repr.buffer_len(),
  1049. hop_limit: 64
  1050. },
  1051. icmp_repr
  1052. ));
  1053. // Ensure that the unknown protocol triggers an error response.
  1054. // And we correctly handle no payload.
  1055. assert_eq!(iface.inner.process_ipv4(&mut socket_set, 0, &frame),
  1056. Ok(expected_repr));
  1057. }
  1058. #[test]
  1059. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1060. fn test_icmp_error_port_unreachable() {
  1061. static UDP_PAYLOAD: [u8; 12] = [
  1062. 0x48, 0x65, 0x6c, 0x6c,
  1063. 0x6f, 0x2c, 0x20, 0x57,
  1064. 0x6f, 0x6c, 0x64, 0x21
  1065. ];
  1066. let (iface, mut socket_set) = create_loopback();
  1067. let mut udp_bytes_unicast = vec![0u8; 20];
  1068. let mut udp_bytes_broadcast = vec![0u8; 20];
  1069. let mut packet_unicast = UdpPacket::new(&mut udp_bytes_unicast);
  1070. let mut packet_broadcast = UdpPacket::new(&mut udp_bytes_broadcast);
  1071. let udp_repr = UdpRepr {
  1072. src_port: 67,
  1073. dst_port: 68,
  1074. payload: &UDP_PAYLOAD
  1075. };
  1076. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1077. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1078. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1079. protocol: IpProtocol::Udp,
  1080. payload_len: udp_repr.buffer_len(),
  1081. hop_limit: 64
  1082. });
  1083. // Emit the representations to a packet
  1084. udp_repr.emit(&mut packet_unicast, &ip_repr.src_addr(),
  1085. &ip_repr.dst_addr(), &ChecksumCapabilities::default());
  1086. let data = packet_unicast.into_inner();
  1087. // The expected Destination Unreachable ICMPv4 error response due
  1088. // to no sockets listening on the destination port.
  1089. let icmp_repr = Icmpv4Repr::DstUnreachable {
  1090. reason: Icmpv4DstUnreachable::PortUnreachable,
  1091. header: Ipv4Repr {
  1092. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1093. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1094. protocol: IpProtocol::Udp,
  1095. payload_len: udp_repr.buffer_len(),
  1096. hop_limit: 64
  1097. },
  1098. data: &data
  1099. };
  1100. let expected_repr = Packet::Icmpv4((
  1101. Ipv4Repr {
  1102. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x01]),
  1103. dst_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1104. protocol: IpProtocol::Icmp,
  1105. payload_len: icmp_repr.buffer_len(),
  1106. hop_limit: 64
  1107. },
  1108. icmp_repr
  1109. ));
  1110. // Ensure that the unknown protocol triggers an error response.
  1111. // And we correctly handle no payload.
  1112. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, data),
  1113. Ok(expected_repr));
  1114. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1115. src_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x02]),
  1116. dst_addr: Ipv4Address::BROADCAST,
  1117. protocol: IpProtocol::Udp,
  1118. payload_len: udp_repr.buffer_len(),
  1119. hop_limit: 64
  1120. });
  1121. // Emit the representations to a packet
  1122. udp_repr.emit(&mut packet_broadcast, &ip_repr.src_addr(),
  1123. &IpAddress::Ipv4(Ipv4Address::BROADCAST),
  1124. &ChecksumCapabilities::default());
  1125. // Ensure that the port unreachable error does not trigger an
  1126. // ICMP error response when the destination address is a
  1127. // broadcast address and no socket is bound to the port.
  1128. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr,
  1129. packet_broadcast.into_inner()), Ok(Packet::None));
  1130. }
  1131. #[test]
  1132. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1133. fn test_handle_udp_broadcast() {
  1134. use socket::{UdpPacketBuffer, UdpSocket, UdpSocketBuffer};
  1135. use wire::IpEndpoint;
  1136. static UDP_PAYLOAD: [u8; 5] = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
  1137. let (iface, mut socket_set) = create_loopback();
  1138. let rx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 15])]);
  1139. let tx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 15])]);
  1140. let udp_socket = UdpSocket::new(rx_buffer, tx_buffer);
  1141. let mut udp_bytes = vec![0u8; 13];
  1142. let mut packet = UdpPacket::new(&mut udp_bytes);
  1143. let socket_handle = socket_set.add(udp_socket);
  1144. let src_ip = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1145. let udp_repr = UdpRepr {
  1146. src_port: 67,
  1147. dst_port: 68,
  1148. payload: &UDP_PAYLOAD
  1149. };
  1150. let ip_repr = IpRepr::Ipv4(Ipv4Repr {
  1151. src_addr: src_ip,
  1152. dst_addr: Ipv4Address::BROADCAST,
  1153. protocol: IpProtocol::Udp,
  1154. payload_len: udp_repr.buffer_len(),
  1155. hop_limit: 0x40
  1156. });
  1157. {
  1158. // Bind the socket to port 68
  1159. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1160. assert_eq!(socket.bind(68), Ok(()));
  1161. assert!(!socket.can_recv());
  1162. assert!(socket.can_send());
  1163. }
  1164. udp_repr.emit(&mut packet, &ip_repr.src_addr(), &ip_repr.dst_addr(),
  1165. &ChecksumCapabilities::default());
  1166. // Packet should be handled by bound UDP socket
  1167. assert_eq!(iface.inner.process_udp(&mut socket_set, ip_repr, packet.into_inner()),
  1168. Ok(Packet::None));
  1169. {
  1170. // Make sure the payload to the UDP packet processed by process_udp is
  1171. // appended to the bound sockets rx_buffer
  1172. let mut socket = socket_set.get::<UdpSocket>(socket_handle);
  1173. assert!(socket.can_recv());
  1174. assert_eq!(socket.recv(), Ok((&UDP_PAYLOAD[..], IpEndpoint::new(src_ip.into(), 67))));
  1175. }
  1176. }
  1177. #[test]
  1178. #[cfg(all(feature = "socket-udp", feature = "proto-ipv4"))]
  1179. fn test_icmpv4_reply_size() {
  1180. use wire::IPV4_MIN_MTU;
  1181. let (iface, mut socket_set) = create_loopback();
  1182. let src_addr = Ipv4Address([192, 168, 1, 1]);
  1183. let dst_addr = Ipv4Address([192, 168, 1, 2]);
  1184. // UDP packet that if not tructated will cause a icmp port unreachable reply
  1185. // to exeed 576 bytes in length.
  1186. let udp_repr = UdpRepr {
  1187. src_port: 67,
  1188. dst_port: 68,
  1189. payload: &[0x2a; 524]
  1190. };
  1191. let mut bytes = vec![0xff; udp_repr.buffer_len()];
  1192. let mut packet = UdpPacket::new(&mut bytes[..]);
  1193. udp_repr.emit(&mut packet, &src_addr.into(), &dst_addr.into(), &ChecksumCapabilities::default());
  1194. let ipv4_repr = Ipv4Repr {
  1195. src_addr: src_addr,
  1196. dst_addr: dst_addr,
  1197. protocol: IpProtocol::Udp,
  1198. hop_limit: 64,
  1199. payload_len: udp_repr.buffer_len()
  1200. };
  1201. let payload = packet.into_inner();
  1202. // Expected packets
  1203. let expected_icmpv4_repr = Icmpv4Repr::DstUnreachable {
  1204. reason: Icmpv4DstUnreachable::PortUnreachable,
  1205. header: ipv4_repr,
  1206. // We only include 520 bytes of the original payload
  1207. // in the expected packets payload. We must only send
  1208. // ICMPv4 replies that do not exceed 576 bytes in length.
  1209. //
  1210. // 528 + 2 * sizeof(IPv4 Header) + sizeof(DstUnreachable Header) = 576
  1211. data: &payload[..528]
  1212. };
  1213. let expected_ipv4_repr = Ipv4Repr {
  1214. src_addr: dst_addr,
  1215. dst_addr: src_addr,
  1216. protocol: IpProtocol::Icmp,
  1217. hop_limit: 64,
  1218. payload_len: expected_icmpv4_repr.buffer_len()
  1219. };
  1220. // The expected packet does not exceed the IPV4_MIN_MTU
  1221. assert_eq!(expected_ipv4_repr.buffer_len() + expected_icmpv4_repr.buffer_len(),
  1222. IPV4_MIN_MTU);
  1223. // The expected packet and the generated packet are equal
  1224. assert_eq!(iface.inner.process_udp(&mut socket_set, ipv4_repr.into(), payload),
  1225. Ok(Packet::Icmpv4((expected_ipv4_repr, expected_icmpv4_repr))));
  1226. }
  1227. #[test]
  1228. #[cfg(feature = "proto-ipv4")]
  1229. fn test_handle_valid_arp_request() {
  1230. let (mut iface, mut socket_set) = create_loopback();
  1231. let mut eth_bytes = vec![0u8; 42];
  1232. let local_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x01]);
  1233. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1234. let local_hw_addr = EthernetAddress([0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
  1235. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  1236. let repr = ArpRepr::EthernetIpv4 {
  1237. operation: ArpOperation::Request,
  1238. source_hardware_addr: remote_hw_addr,
  1239. source_protocol_addr: remote_ip_addr,
  1240. target_hardware_addr: EthernetAddress::default(),
  1241. target_protocol_addr: local_ip_addr,
  1242. };
  1243. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1244. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1245. frame.set_src_addr(remote_hw_addr);
  1246. frame.set_ethertype(EthernetProtocol::Arp);
  1247. {
  1248. let mut packet = ArpPacket::new(frame.payload_mut());
  1249. repr.emit(&mut packet);
  1250. }
  1251. // Ensure an ARP Request for us triggers an ARP Reply
  1252. assert_eq!(iface.inner.process_ethernet(&mut socket_set, 0, frame.into_inner()),
  1253. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  1254. operation: ArpOperation::Reply,
  1255. source_hardware_addr: local_hw_addr,
  1256. source_protocol_addr: local_ip_addr,
  1257. target_hardware_addr: remote_hw_addr,
  1258. target_protocol_addr: remote_ip_addr
  1259. })));
  1260. // Ensure the address of the requestor was entered in the cache
  1261. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, 0,
  1262. &IpAddress::Ipv4(local_ip_addr), &IpAddress::Ipv4(remote_ip_addr)),
  1263. Ok((remote_hw_addr, MockTxToken)));
  1264. }
  1265. #[test]
  1266. #[cfg(feature = "proto-ipv4")]
  1267. fn test_handle_other_arp_request() {
  1268. let (mut iface, mut socket_set) = create_loopback();
  1269. let mut eth_bytes = vec![0u8; 42];
  1270. let remote_ip_addr = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
  1271. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]);
  1272. let repr = ArpRepr::EthernetIpv4 {
  1273. operation: ArpOperation::Request,
  1274. source_hardware_addr: remote_hw_addr,
  1275. source_protocol_addr: remote_ip_addr,
  1276. target_hardware_addr: EthernetAddress::default(),
  1277. target_protocol_addr: Ipv4Address([0x7f, 0x00, 0x00, 0x03]),
  1278. };
  1279. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1280. frame.set_dst_addr(EthernetAddress::BROADCAST);
  1281. frame.set_src_addr(remote_hw_addr);
  1282. frame.set_ethertype(EthernetProtocol::Arp);
  1283. {
  1284. let mut packet = ArpPacket::new(frame.payload_mut());
  1285. repr.emit(&mut packet);
  1286. }
  1287. // Ensure an ARP Request for someone else does not trigger an ARP Reply
  1288. assert_eq!(iface.inner.process_ethernet(&mut socket_set, 0, frame.into_inner()),
  1289. Ok(Packet::None));
  1290. // Ensure the address of the requestor was entered in the cache
  1291. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, 0,
  1292. &IpAddress::Ipv4(Ipv4Address([0x7f, 0x00, 0x00, 0x01])),
  1293. &IpAddress::Ipv4(remote_ip_addr)),
  1294. Ok((remote_hw_addr, MockTxToken)));
  1295. }
  1296. #[test]
  1297. #[cfg(all(feature = "socket-icmp", feature = "proto-ipv4"))]
  1298. fn test_icmpv4_socket() {
  1299. use socket::{IcmpPacketBuffer, IcmpSocket, IcmpSocketBuffer, IcmpEndpoint};
  1300. use wire::Icmpv4Packet;
  1301. let (iface, mut socket_set) = create_loopback();
  1302. let rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketBuffer::new(vec![0; 24])]);
  1303. let tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketBuffer::new(vec![0; 24])]);
  1304. let icmpv4_socket = IcmpSocket::new(rx_buffer, tx_buffer);
  1305. let socket_handle = socket_set.add(icmpv4_socket);
  1306. let ident = 0x1234;
  1307. let seq_no = 0x5432;
  1308. let echo_data = &[0xff; 16];
  1309. {
  1310. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  1311. // Bind to the ID 0x1234
  1312. assert_eq!(socket.bind(IcmpEndpoint::Ident(ident)), Ok(()));
  1313. }
  1314. // Ensure the ident we bound to and the ident of the packet are the same.
  1315. let mut bytes = [0xff; 24];
  1316. let mut packet = Icmpv4Packet::new(&mut bytes);
  1317. let echo_repr = Icmpv4Repr::EchoRequest{ ident, seq_no, data: echo_data };
  1318. echo_repr.emit(&mut packet, &ChecksumCapabilities::default());
  1319. let icmp_data = &packet.into_inner()[..];
  1320. let ipv4_repr = Ipv4Repr {
  1321. src_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x02),
  1322. dst_addr: Ipv4Address::new(0x7f, 0x00, 0x00, 0x01),
  1323. protocol: IpProtocol::Icmp,
  1324. payload_len: 24,
  1325. hop_limit: 64
  1326. };
  1327. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  1328. // Open a socket and ensure the packet is handled due to the listening
  1329. // socket.
  1330. {
  1331. assert!(!socket_set.get::<IcmpSocket>(socket_handle).can_recv());
  1332. }
  1333. // Confirm we still get EchoReply from `smoltcp` even with the ICMP socket listening
  1334. let echo_reply = Icmpv4Repr::EchoReply{ ident, seq_no, data: echo_data };
  1335. let ipv4_reply = Ipv4Repr {
  1336. src_addr: ipv4_repr.dst_addr,
  1337. dst_addr: ipv4_repr.src_addr,
  1338. ..ipv4_repr
  1339. };
  1340. assert_eq!(iface.inner.process_icmpv4(&mut socket_set, ip_repr, icmp_data),
  1341. Ok(Packet::Icmpv4((ipv4_reply, echo_reply))));
  1342. {
  1343. let mut socket = socket_set.get::<IcmpSocket>(socket_handle);
  1344. assert!(socket.can_recv());
  1345. assert_eq!(socket.recv(),
  1346. Ok((&icmp_data[..],
  1347. IpAddress::Ipv4(Ipv4Address::new(0x7f, 0x00, 0x00, 0x02)))));
  1348. }
  1349. }
  1350. #[test]
  1351. #[cfg(feature = "proto-ipv6")]
  1352. fn test_raw_socket() {
  1353. let (mut iface, mut socket_set) = create_loopback();
  1354. let remote_ip_addr = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
  1355. let remote_hw_addr = EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x01]);
  1356. let mut eth_bytes = vec![0; 54];
  1357. let repr = IpRepr::Ipv6(Ipv6Repr {
  1358. src_addr: remote_ip_addr,
  1359. dst_addr: Ipv6Address::LOOPBACK,
  1360. next_header: IpProtocol::Unknown(0x0c),
  1361. payload_len: 0,
  1362. hop_limit: 0x40
  1363. });
  1364. let frame = {
  1365. let mut frame = EthernetFrame::new(&mut eth_bytes);
  1366. frame.set_dst_addr(EthernetAddress([0x52, 0x54, 0x00, 0x00, 0x00, 0x00]));
  1367. frame.set_src_addr(remote_hw_addr);
  1368. frame.set_ethertype(EthernetProtocol::Ipv6);
  1369. repr.emit(frame.payload_mut(), &ChecksumCapabilities::default());
  1370. EthernetFrame::new(&*frame.into_inner())
  1371. };
  1372. assert_eq!(iface.inner.process_ipv6(&mut socket_set, 0, &frame),
  1373. Ok(Packet::None));
  1374. // Ensure the address of the requestor was entered in the cache
  1375. assert_eq!(iface.inner.lookup_hardware_addr(MockTxToken, 0,
  1376. &IpAddress::Ipv6(Ipv6Address::LOOPBACK),
  1377. &IpAddress::Ipv6(remote_ip_addr)),
  1378. Ok((remote_hw_addr, MockTxToken)));
  1379. }
  1380. }