ethernet.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. use managed::{Managed, ManagedSlice};
  2. use {Error, Result};
  3. use phy::Device;
  4. use wire::{EthernetAddress, EthernetProtocol, EthernetFrame};
  5. use wire::{ArpPacket, ArpRepr, ArpOperation};
  6. use wire::{Ipv4Packet, Ipv4Repr};
  7. use wire::{Icmpv4Packet, Icmpv4Repr, Icmpv4DstUnreachable};
  8. use wire::{IpAddress, IpProtocol, IpRepr};
  9. use wire::{UdpPacket, UdpRepr, TcpPacket, TcpRepr, TcpControl};
  10. use socket::{Socket, SocketSet, RawSocket, TcpSocket, UdpSocket, AsSocket};
  11. use super::ArpCache;
  12. /// An Ethernet network interface.
  13. ///
  14. /// The network interface logically owns a number of other data structures; to avoid
  15. /// a dependency on heap allocation, it instead owns a `BorrowMut<[T]>`, which can be
  16. /// a `&mut [T]`, or `Vec<T>` if a heap is available.
  17. pub struct Interface<'a, 'b, 'c, DeviceT: Device + 'a> {
  18. device: Managed<'a, DeviceT>,
  19. arp_cache: Managed<'b, ArpCache>,
  20. hardware_addr: EthernetAddress,
  21. protocol_addrs: ManagedSlice<'c, IpAddress>,
  22. }
  23. enum Packet<'a> {
  24. None,
  25. Arp(ArpRepr),
  26. Icmpv4(Ipv4Repr, Icmpv4Repr<'a>),
  27. Raw((IpRepr, &'a [u8])),
  28. Udp((IpRepr, UdpRepr<'a>)),
  29. Tcp((IpRepr, TcpRepr<'a>))
  30. }
  31. impl<'a, 'b, 'c, DeviceT: Device + 'a> Interface<'a, 'b, 'c, DeviceT> {
  32. /// Create a network interface using the provided network device.
  33. ///
  34. /// # Panics
  35. /// See the restrictions on [set_hardware_addr](#method.set_hardware_addr)
  36. /// and [set_protocol_addrs](#method.set_protocol_addrs) functions.
  37. pub fn new<DeviceMT, ArpCacheMT, ProtocolAddrsMT>
  38. (device: DeviceMT, arp_cache: ArpCacheMT,
  39. hardware_addr: EthernetAddress, protocol_addrs: ProtocolAddrsMT) ->
  40. Interface<'a, 'b, 'c, DeviceT>
  41. where DeviceMT: Into<Managed<'a, DeviceT>>,
  42. ArpCacheMT: Into<Managed<'b, ArpCache>>,
  43. ProtocolAddrsMT: Into<ManagedSlice<'c, IpAddress>>, {
  44. let device = device.into();
  45. let arp_cache = arp_cache.into();
  46. let protocol_addrs = protocol_addrs.into();
  47. Self::check_hardware_addr(&hardware_addr);
  48. Self::check_protocol_addrs(&protocol_addrs);
  49. Interface {
  50. device: device,
  51. arp_cache: arp_cache,
  52. hardware_addr: hardware_addr,
  53. protocol_addrs: protocol_addrs,
  54. }
  55. }
  56. fn check_hardware_addr(addr: &EthernetAddress) {
  57. if addr.is_multicast() {
  58. panic!("hardware address {} is not unicast", addr)
  59. }
  60. }
  61. /// Get the hardware address of the interface.
  62. pub fn hardware_addr(&self) -> EthernetAddress {
  63. self.hardware_addr
  64. }
  65. /// Set the hardware address of the interface.
  66. ///
  67. /// # Panics
  68. /// This function panics if the address is not unicast.
  69. pub fn set_hardware_addr(&mut self, addr: EthernetAddress) {
  70. self.hardware_addr = addr;
  71. Self::check_hardware_addr(&self.hardware_addr);
  72. }
  73. fn check_protocol_addrs(addrs: &[IpAddress]) {
  74. for addr in addrs {
  75. if !addr.is_unicast() {
  76. panic!("protocol address {} is not unicast", addr)
  77. }
  78. }
  79. }
  80. /// Get the protocol addresses of the interface.
  81. pub fn protocol_addrs(&self) -> &[IpAddress] {
  82. self.protocol_addrs.as_ref()
  83. }
  84. /// Update the protocol addresses of the interface.
  85. ///
  86. /// # Panics
  87. /// This function panics if any of the addresses is not unicast.
  88. pub fn update_protocol_addrs<F: FnOnce(&mut ManagedSlice<'c, IpAddress>)>(&mut self, f: F) {
  89. f(&mut self.protocol_addrs);
  90. Self::check_protocol_addrs(&self.protocol_addrs)
  91. }
  92. /// Check whether the interface has the given protocol address assigned.
  93. pub fn has_protocol_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  94. let addr = addr.into();
  95. self.protocol_addrs.iter().any(|&probe| probe == addr)
  96. }
  97. /// Transmit packets queued in the given sockets, and receive packets queued
  98. /// in the device.
  99. ///
  100. /// The timestamp must be a number of milliseconds, monotonically increasing
  101. /// since an arbitrary moment in time, such as system startup.
  102. ///
  103. /// This function returns a _soft deadline_ for calling it the next time.
  104. /// That is, if `iface.poll(&mut sockets, 1000)` returns `Ok(Some(2000))`,
  105. /// it harmless (but wastes energy) to call it 500 ms later, and potentially
  106. /// harmful (impacting quality of service) to call it 1500 ms later.
  107. pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<Option<u64>> {
  108. self.socket_egress(sockets, timestamp)?;
  109. if self.socket_ingress(sockets, timestamp)? {
  110. Ok(Some(0))
  111. } else {
  112. Ok(sockets.iter().filter_map(|socket| socket.poll_at()).min())
  113. }
  114. }
  115. fn socket_ingress(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<bool> {
  116. let mut processed_any = false;
  117. loop {
  118. let frame =
  119. match self.device.receive(timestamp) {
  120. Ok(frame) => frame,
  121. Err(Error::Exhausted) => break, // nothing to receive
  122. Err(err) => return Err(err)
  123. };
  124. let response =
  125. match self.process_ethernet(sockets, timestamp, &frame) {
  126. Ok(response) => response,
  127. Err(err) => {
  128. net_debug!("cannot process ingress packet: {}", err);
  129. return Err(err)
  130. }
  131. };
  132. processed_any = true;
  133. match self.dispatch(timestamp, response) {
  134. Ok(()) => (),
  135. Err(err) => {
  136. net_debug!("cannot dispatch response packet: {}", err);
  137. return Err(err)
  138. }
  139. }
  140. }
  141. Ok(processed_any)
  142. }
  143. fn socket_egress(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<()> {
  144. let mut limits = self.device.limits();
  145. limits.max_transmission_unit -= EthernetFrame::<&[u8]>::header_len();
  146. for socket in sockets.iter_mut() {
  147. let mut device_result = Ok(());
  148. let socket_result =
  149. match socket {
  150. &mut Socket::Raw(ref mut socket) =>
  151. socket.dispatch(|response| {
  152. device_result = self.dispatch(timestamp, Packet::Raw(response));
  153. device_result
  154. }),
  155. &mut Socket::Udp(ref mut socket) =>
  156. socket.dispatch(|response| {
  157. device_result = self.dispatch(timestamp, Packet::Udp(response));
  158. device_result
  159. }),
  160. &mut Socket::Tcp(ref mut socket) =>
  161. socket.dispatch(timestamp, &limits, |response| {
  162. device_result = self.dispatch(timestamp, Packet::Tcp(response));
  163. device_result
  164. }),
  165. &mut Socket::__Nonexhaustive => unreachable!()
  166. };
  167. match (device_result, socket_result) {
  168. (Err(Error::Exhausted), Ok(())) => break, // nowhere to transmit
  169. (Ok(()), Err(Error::Exhausted)) => (), // nothing to transmit
  170. (Err(err), _) | (_, Err(err)) => {
  171. net_debug!("cannot dispatch egress packet: {}", err);
  172. return Err(err)
  173. }
  174. (Ok(()), Ok(())) => ()
  175. }
  176. }
  177. Ok(())
  178. }
  179. fn process_ethernet<'frame, T: AsRef<[u8]>>
  180. (&mut self, sockets: &mut SocketSet, timestamp: u64,
  181. frame: &'frame T) ->
  182. Result<Packet<'frame>> {
  183. let eth_frame = EthernetFrame::new_checked(frame)?;
  184. // Ignore any packets not directed to our hardware address.
  185. if !eth_frame.dst_addr().is_broadcast() &&
  186. eth_frame.dst_addr() != self.hardware_addr {
  187. return Ok(Packet::None)
  188. }
  189. match eth_frame.ethertype() {
  190. EthernetProtocol::Arp =>
  191. self.process_arp(&eth_frame),
  192. EthernetProtocol::Ipv4 =>
  193. self.process_ipv4(sockets, timestamp, &eth_frame),
  194. // Drop all other traffic.
  195. _ => Err(Error::Unrecognized),
  196. }
  197. }
  198. fn process_arp<'frame, T: AsRef<[u8]>>
  199. (&mut self, eth_frame: &EthernetFrame<&'frame T>) ->
  200. Result<Packet<'frame>> {
  201. let arp_packet = ArpPacket::new_checked(eth_frame.payload())?;
  202. let arp_repr = ArpRepr::parse(&arp_packet)?;
  203. match arp_repr {
  204. // Respond to ARP requests aimed at us, and fill the ARP cache from all ARP
  205. // requests and replies, to minimize the chance that we have to perform
  206. // an explicit ARP request.
  207. ArpRepr::EthernetIpv4 {
  208. operation, source_hardware_addr, source_protocol_addr, target_protocol_addr, ..
  209. } => {
  210. if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() {
  211. self.arp_cache.fill(&source_protocol_addr.into(),
  212. &source_hardware_addr);
  213. } else {
  214. // Discard packets with non-unicast source addresses.
  215. net_debug!("non-unicast source in {}", arp_repr);
  216. return Err(Error::Malformed)
  217. }
  218. if operation == ArpOperation::Request &&
  219. self.has_protocol_addr(target_protocol_addr) {
  220. Ok(Packet::Arp(ArpRepr::EthernetIpv4 {
  221. operation: ArpOperation::Reply,
  222. source_hardware_addr: self.hardware_addr,
  223. source_protocol_addr: target_protocol_addr,
  224. target_hardware_addr: source_hardware_addr,
  225. target_protocol_addr: source_protocol_addr
  226. }))
  227. } else {
  228. Ok(Packet::None)
  229. }
  230. }
  231. _ => Err(Error::Unrecognized)
  232. }
  233. }
  234. fn process_ipv4<'frame, T: AsRef<[u8]>>
  235. (&mut self, sockets: &mut SocketSet, timestamp: u64,
  236. eth_frame: &EthernetFrame<&'frame T>) ->
  237. Result<Packet<'frame>> {
  238. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
  239. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet)?;
  240. if !ipv4_repr.src_addr.is_unicast() {
  241. // Discard packets with non-unicast source addresses.
  242. net_debug!("non-unicast source in {}", ipv4_repr);
  243. return Err(Error::Malformed)
  244. }
  245. if eth_frame.src_addr().is_unicast() {
  246. // Fill the ARP cache from IP header of unicast frames.
  247. self.arp_cache.fill(&IpAddress::Ipv4(ipv4_repr.src_addr),
  248. &eth_frame.src_addr());
  249. }
  250. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  251. let ip_payload = ipv4_packet.payload();
  252. // Pass every IP packet to all raw sockets we have registered.
  253. let mut handled_by_raw_socket = false;
  254. for raw_socket in sockets.iter_mut().filter_map(
  255. <Socket as AsSocket<RawSocket>>::try_as_socket) {
  256. match raw_socket.process(&ip_repr, ip_payload) {
  257. // The packet is valid and handled by socket.
  258. Ok(()) => handled_by_raw_socket = true,
  259. // The packet isn't addressed to the socket, or cannot be accepted by it.
  260. Err(Error::Rejected) | Err(Error::Exhausted) => (),
  261. // Raw sockets either accept or reject packets, not parse them.
  262. _ => unreachable!(),
  263. }
  264. }
  265. if !self.has_protocol_addr(ipv4_repr.dst_addr) {
  266. // Ignore IP packets not directed at us.
  267. return Ok(Packet::None)
  268. }
  269. match ipv4_repr.protocol {
  270. IpProtocol::Icmp =>
  271. Self::process_icmpv4(ipv4_repr, ip_payload),
  272. IpProtocol::Udp =>
  273. Self::process_udp(sockets, ip_repr, ip_payload),
  274. IpProtocol::Tcp =>
  275. Self::process_tcp(sockets, timestamp, ip_repr, ip_payload),
  276. _ if handled_by_raw_socket =>
  277. Ok(Packet::None),
  278. _ => {
  279. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  280. reason: Icmpv4DstUnreachable::ProtoUnreachable,
  281. header: ipv4_repr,
  282. data: &ip_payload[0..8]
  283. };
  284. let ipv4_reply_repr = Ipv4Repr {
  285. src_addr: ipv4_repr.dst_addr,
  286. dst_addr: ipv4_repr.src_addr,
  287. protocol: IpProtocol::Icmp,
  288. payload_len: icmp_reply_repr.buffer_len()
  289. };
  290. Ok(Packet::Icmpv4(ipv4_reply_repr, icmp_reply_repr))
  291. }
  292. }
  293. }
  294. fn process_icmpv4<'frame>(ipv4_repr: Ipv4Repr, ip_payload: &'frame [u8]) ->
  295. Result<Packet<'frame>> {
  296. let icmp_packet = Icmpv4Packet::new_checked(ip_payload)?;
  297. let icmp_repr = Icmpv4Repr::parse(&icmp_packet)?;
  298. match icmp_repr {
  299. // Respond to echo requests.
  300. Icmpv4Repr::EchoRequest { ident, seq_no, data } => {
  301. let icmp_reply_repr = Icmpv4Repr::EchoReply {
  302. ident: ident,
  303. seq_no: seq_no,
  304. data: data
  305. };
  306. let ipv4_reply_repr = Ipv4Repr {
  307. src_addr: ipv4_repr.dst_addr,
  308. dst_addr: ipv4_repr.src_addr,
  309. protocol: IpProtocol::Icmp,
  310. payload_len: icmp_reply_repr.buffer_len()
  311. };
  312. Ok(Packet::Icmpv4(ipv4_reply_repr, icmp_reply_repr))
  313. }
  314. // Ignore any echo replies.
  315. Icmpv4Repr::EchoReply { .. } => Ok(Packet::None),
  316. // FIXME: do something correct here?
  317. _ => Err(Error::Unrecognized),
  318. }
  319. }
  320. fn process_udp<'frame>(sockets: &mut SocketSet,
  321. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  322. Result<Packet<'frame>> {
  323. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  324. let udp_packet = UdpPacket::new_checked(ip_payload)?;
  325. let udp_repr = UdpRepr::parse(&udp_packet, &src_addr, &dst_addr)?;
  326. for udp_socket in sockets.iter_mut().filter_map(
  327. <Socket as AsSocket<UdpSocket>>::try_as_socket) {
  328. match udp_socket.process(&ip_repr, &udp_repr) {
  329. // The packet is valid and handled by socket.
  330. Ok(()) => return Ok(Packet::None),
  331. // The packet isn't addressed to the socket.
  332. Err(Error::Rejected) => continue,
  333. // The packet is malformed, or addressed to the socket but cannot be accepted.
  334. Err(e) => return Err(e)
  335. }
  336. }
  337. // The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  338. match ip_repr {
  339. IpRepr::Ipv4(ipv4_repr) => {
  340. let icmpv4_reply_repr = Icmpv4Repr::DstUnreachable {
  341. reason: Icmpv4DstUnreachable::PortUnreachable,
  342. header: ipv4_repr,
  343. data: &ip_payload[0..8]
  344. };
  345. let ipv4_reply_repr = Ipv4Repr {
  346. src_addr: ipv4_repr.dst_addr,
  347. dst_addr: ipv4_repr.src_addr,
  348. protocol: IpProtocol::Icmp,
  349. payload_len: icmpv4_reply_repr.buffer_len()
  350. };
  351. Ok(Packet::Icmpv4(ipv4_reply_repr, icmpv4_reply_repr))
  352. },
  353. IpRepr::Unspecified { .. } |
  354. IpRepr::__Nonexhaustive =>
  355. unreachable!()
  356. }
  357. }
  358. fn process_tcp<'frame>(sockets: &mut SocketSet, timestamp: u64,
  359. ip_repr: IpRepr, ip_payload: &'frame [u8]) ->
  360. Result<Packet<'frame>> {
  361. let (src_addr, dst_addr) = (ip_repr.src_addr(), ip_repr.dst_addr());
  362. let tcp_packet = TcpPacket::new_checked(ip_payload)?;
  363. let tcp_repr = TcpRepr::parse(&tcp_packet, &src_addr, &dst_addr)?;
  364. for tcp_socket in sockets.iter_mut().filter_map(
  365. <Socket as AsSocket<TcpSocket>>::try_as_socket) {
  366. match tcp_socket.process(timestamp, &ip_repr, &tcp_repr) {
  367. // The packet is valid and handled by socket.
  368. Ok(reply) => return Ok(reply.map_or(Packet::None, Packet::Tcp)),
  369. // The packet isn't addressed to the socket.
  370. // Send RST only if no other socket accepts the packet.
  371. Err(Error::Rejected) => continue,
  372. // The packet is malformed, or addressed to the socket but cannot be accepted.
  373. Err(e) => return Err(e)
  374. }
  375. }
  376. if tcp_repr.control == TcpControl::Rst {
  377. // Never reply to a TCP RST packet with another TCP RST packet.
  378. Ok(Packet::None)
  379. } else {
  380. // The packet wasn't handled by a socket, send a TCP RST packet.
  381. Ok(Packet::Tcp(TcpSocket::rst_reply(&ip_repr, &tcp_repr)))
  382. }
  383. }
  384. fn dispatch(&mut self, timestamp: u64, packet: Packet) -> Result<()> {
  385. match packet {
  386. Packet::Arp(arp_repr) => {
  387. let dst_hardware_addr =
  388. match arp_repr {
  389. ArpRepr::EthernetIpv4 { target_hardware_addr, .. } => target_hardware_addr,
  390. _ => unreachable!()
  391. };
  392. self.dispatch_ethernet(timestamp, arp_repr.buffer_len(), |mut frame| {
  393. frame.set_dst_addr(dst_hardware_addr);
  394. frame.set_ethertype(EthernetProtocol::Arp);
  395. let mut packet = ArpPacket::new(frame.payload_mut());
  396. arp_repr.emit(&mut packet);
  397. })
  398. },
  399. Packet::Icmpv4(ipv4_repr, icmpv4_repr) => {
  400. self.dispatch_ip(timestamp, IpRepr::Ipv4(ipv4_repr), |_ip_repr, payload| {
  401. icmpv4_repr.emit(&mut Icmpv4Packet::new(payload));
  402. })
  403. }
  404. Packet::Raw((ip_repr, raw_packet)) => {
  405. self.dispatch_ip(timestamp, ip_repr, |_ip_repr, payload| {
  406. payload.copy_from_slice(raw_packet);
  407. })
  408. }
  409. Packet::Udp((ip_repr, udp_repr)) => {
  410. self.dispatch_ip(timestamp, ip_repr, |ip_repr, payload| {
  411. udp_repr.emit(&mut UdpPacket::new(payload),
  412. &ip_repr.src_addr(), &ip_repr.dst_addr());
  413. })
  414. }
  415. Packet::Tcp((ip_repr, mut tcp_repr)) => {
  416. let limits = self.device.limits();
  417. self.dispatch_ip(timestamp, ip_repr, |ip_repr, payload| {
  418. // This is a terrible hack to make TCP performance more acceptable on systems
  419. // where the TCP buffers are significantly larger than network buffers,
  420. // e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
  421. // together with four 1500 B Ethernet receive buffers. If left untreated,
  422. // this would result in our peer pushing our window and sever packet loss.
  423. //
  424. // I'm really not happy about this "solution" but I don't know what else to do.
  425. if let Some(max_burst_size) = limits.max_burst_size {
  426. let mut max_segment_size = limits.max_transmission_unit;
  427. max_segment_size -= EthernetFrame::<&[u8]>::header_len();
  428. max_segment_size -= ip_repr.buffer_len();
  429. max_segment_size -= tcp_repr.header_len();
  430. let max_window_size = max_burst_size * max_segment_size;
  431. if tcp_repr.window_len as usize > max_window_size {
  432. tcp_repr.window_len = max_window_size as u16;
  433. }
  434. }
  435. tcp_repr.emit(&mut TcpPacket::new(payload),
  436. &ip_repr.src_addr(), &ip_repr.dst_addr());
  437. })
  438. }
  439. Packet::None => Ok(())
  440. }
  441. }
  442. fn dispatch_ethernet<F>(&mut self, timestamp: u64, buffer_len: usize, f: F) -> Result<()>
  443. where F: FnOnce(EthernetFrame<&mut [u8]>) {
  444. let tx_len = EthernetFrame::<&[u8]>::buffer_len(buffer_len);
  445. let mut tx_buffer = self.device.transmit(timestamp, tx_len)?;
  446. debug_assert!(tx_buffer.as_ref().len() == tx_len);
  447. let mut frame = EthernetFrame::new(tx_buffer.as_mut());
  448. frame.set_src_addr(self.hardware_addr);
  449. f(frame);
  450. Ok(())
  451. }
  452. fn lookup_hardware_addr(&mut self, timestamp: u64,
  453. src_addr: &IpAddress, dst_addr: &IpAddress) ->
  454. Result<EthernetAddress> {
  455. if let Some(hardware_addr) = self.arp_cache.lookup(dst_addr) {
  456. return Ok(hardware_addr)
  457. }
  458. if dst_addr.is_broadcast() {
  459. return Ok(EthernetAddress([0xff; 6]))
  460. }
  461. match (src_addr, dst_addr) {
  462. (&IpAddress::Ipv4(src_addr), &IpAddress::Ipv4(dst_addr)) => {
  463. net_debug!("address {} not in ARP cache, sending request",
  464. dst_addr);
  465. let arp_repr = ArpRepr::EthernetIpv4 {
  466. operation: ArpOperation::Request,
  467. source_hardware_addr: self.hardware_addr,
  468. source_protocol_addr: src_addr,
  469. target_hardware_addr: EthernetAddress([0xff; 6]),
  470. target_protocol_addr: dst_addr,
  471. };
  472. self.dispatch_ethernet(timestamp, arp_repr.buffer_len(), |mut frame| {
  473. frame.set_dst_addr(EthernetAddress([0xff; 6]));
  474. frame.set_ethertype(EthernetProtocol::Arp);
  475. arp_repr.emit(&mut ArpPacket::new(frame.payload_mut()))
  476. })?;
  477. Err(Error::Unaddressable)
  478. }
  479. _ => unreachable!()
  480. }
  481. }
  482. fn dispatch_ip<F>(&mut self, timestamp: u64, ip_repr: IpRepr, f: F) -> Result<()>
  483. where F: FnOnce(IpRepr, &mut [u8]) {
  484. let ip_repr = ip_repr.lower(&self.protocol_addrs)?;
  485. let dst_hardware_addr =
  486. self.lookup_hardware_addr(timestamp, &ip_repr.src_addr(), &ip_repr.dst_addr())?;
  487. self.dispatch_ethernet(timestamp, ip_repr.total_len(), |mut frame| {
  488. frame.set_dst_addr(dst_hardware_addr);
  489. match ip_repr {
  490. IpRepr::Ipv4(_) => frame.set_ethertype(EthernetProtocol::Ipv4),
  491. _ => unreachable!()
  492. }
  493. ip_repr.emit(frame.payload_mut());
  494. let payload = &mut frame.payload_mut()[ip_repr.buffer_len()..];
  495. f(ip_repr, payload)
  496. })
  497. }
  498. }