ethernet.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. use managed::{Managed, ManagedSlice};
  2. use Error;
  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::{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 Response<'a> {
  24. Nop,
  25. Arp(ArpRepr),
  26. Icmpv4(Ipv4Repr, Icmpv4Repr<'a>),
  27. Tcpv4(Ipv4Repr, TcpRepr<'a>)
  28. }
  29. impl<'a, 'b, 'c, DeviceT: Device + 'a> Interface<'a, 'b, 'c, DeviceT> {
  30. /// Create a network interface using the provided network device.
  31. ///
  32. /// # Panics
  33. /// See the restrictions on [set_hardware_addr](#method.set_hardware_addr)
  34. /// and [set_protocol_addrs](#method.set_protocol_addrs) functions.
  35. pub fn new<DeviceMT, ArpCacheMT, ProtocolAddrsMT>
  36. (device: DeviceMT, arp_cache: ArpCacheMT,
  37. hardware_addr: EthernetAddress, protocol_addrs: ProtocolAddrsMT) ->
  38. Interface<'a, 'b, 'c, DeviceT>
  39. where DeviceMT: Into<Managed<'a, DeviceT>>,
  40. ArpCacheMT: Into<Managed<'b, ArpCache>>,
  41. ProtocolAddrsMT: Into<ManagedSlice<'c, IpAddress>>, {
  42. let device = device.into();
  43. let arp_cache = arp_cache.into();
  44. let protocol_addrs = protocol_addrs.into();
  45. Self::check_hardware_addr(&hardware_addr);
  46. Self::check_protocol_addrs(&protocol_addrs);
  47. Interface {
  48. device: device,
  49. arp_cache: arp_cache,
  50. hardware_addr: hardware_addr,
  51. protocol_addrs: protocol_addrs,
  52. }
  53. }
  54. fn check_hardware_addr(addr: &EthernetAddress) {
  55. if addr.is_multicast() {
  56. panic!("hardware address {} is not unicast", addr)
  57. }
  58. }
  59. /// Get the hardware address of the interface.
  60. pub fn hardware_addr(&self) -> EthernetAddress {
  61. self.hardware_addr
  62. }
  63. /// Set the hardware address of the interface.
  64. ///
  65. /// # Panics
  66. /// This function panics if the address is not unicast.
  67. pub fn set_hardware_addr(&mut self, addr: EthernetAddress) {
  68. self.hardware_addr = addr;
  69. Self::check_hardware_addr(&self.hardware_addr);
  70. }
  71. fn check_protocol_addrs(addrs: &[IpAddress]) {
  72. for addr in addrs {
  73. if !addr.is_unicast() {
  74. panic!("protocol address {} is not unicast", addr)
  75. }
  76. }
  77. }
  78. /// Get the protocol addresses of the interface.
  79. pub fn protocol_addrs(&self) -> &[IpAddress] {
  80. self.protocol_addrs.as_ref()
  81. }
  82. /// Update the protocol addresses of the interface.
  83. ///
  84. /// # Panics
  85. /// This function panics if any of the addresses is not unicast.
  86. pub fn update_protocol_addrs<F: FnOnce(&mut ManagedSlice<'c, IpAddress>)>(&mut self, f: F) {
  87. f(&mut self.protocol_addrs);
  88. Self::check_protocol_addrs(&self.protocol_addrs)
  89. }
  90. /// Check whether the interface has the given protocol address assigned.
  91. pub fn has_protocol_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
  92. let addr = addr.into();
  93. self.protocol_addrs.iter().any(|&probe| probe == addr)
  94. }
  95. /// Receive and process a packet, if available, and then transmit a packet, if necessary,
  96. /// handling the given set of sockets.
  97. ///
  98. /// The timestamp is a monotonically increasing number of milliseconds.
  99. pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<(), Error> {
  100. // First, transmit any outgoing packets.
  101. loop {
  102. if self.emit(sockets, timestamp)? { break }
  103. }
  104. // Now, receive any incoming packets.
  105. let rx_buffer = self.device.receive()?;
  106. let eth_frame = EthernetFrame::new_checked(&rx_buffer)?;
  107. // Ignore any packets not directed to our hardware address.
  108. if !eth_frame.dst_addr().is_broadcast() &&
  109. eth_frame.dst_addr() != self.hardware_addr {
  110. return Ok(())
  111. }
  112. let response = match eth_frame.ethertype() {
  113. EthernetProtocol::Arp =>
  114. self.process_arp(&eth_frame)?,
  115. EthernetProtocol::Ipv4 =>
  116. self.process_ipv4(sockets, timestamp, &eth_frame)?,
  117. // Drop all other traffic.
  118. _ => return Err(Error::Unrecognized),
  119. };
  120. self.send_response(response)
  121. }
  122. // Snoop all ARP traffic, and respond to ARP packets directed at us.
  123. fn process_arp<'frame, T: AsRef<[u8]>>
  124. (&mut self, eth_frame: &EthernetFrame<&'frame T>) ->
  125. Result<Response<'frame>, Error> {
  126. let arp_packet = ArpPacket::new_checked(eth_frame.payload())?;
  127. let arp_repr = ArpRepr::parse(&arp_packet)?;
  128. match arp_repr {
  129. // Respond to ARP requests aimed at us, and fill the ARP cache
  130. // from all ARP requests, including gratuitous.
  131. ArpRepr::EthernetIpv4 {
  132. operation: ArpOperation::Request,
  133. source_hardware_addr, source_protocol_addr,
  134. target_protocol_addr, ..
  135. } => {
  136. if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() {
  137. self.arp_cache.fill(&source_protocol_addr.into(),
  138. &source_hardware_addr);
  139. }
  140. if self.has_protocol_addr(target_protocol_addr) {
  141. Ok(Response::Arp(ArpRepr::EthernetIpv4 {
  142. operation: ArpOperation::Reply,
  143. source_hardware_addr: self.hardware_addr,
  144. source_protocol_addr: target_protocol_addr,
  145. target_hardware_addr: source_hardware_addr,
  146. target_protocol_addr: source_protocol_addr
  147. }))
  148. } else {
  149. Ok(Response::Nop)
  150. }
  151. }
  152. // Fill the ARP cache from gratuitous ARP replies.
  153. ArpRepr::EthernetIpv4 {
  154. operation: ArpOperation::Reply,
  155. source_hardware_addr, source_protocol_addr, ..
  156. } => {
  157. if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() {
  158. self.arp_cache.fill(&source_protocol_addr.into(),
  159. &source_hardware_addr);
  160. }
  161. Ok(Response::Nop)
  162. }
  163. _ => Err(Error::Unrecognized)
  164. }
  165. }
  166. fn process_ipv4<'frame, T: AsRef<[u8]>>
  167. (&mut self, sockets: &mut SocketSet, timestamp: u64,
  168. eth_frame: &EthernetFrame<&'frame T>) ->
  169. Result<Response<'frame>, Error> {
  170. let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
  171. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet)?;
  172. if ipv4_repr.src_addr.is_unicast() && eth_frame.src_addr().is_unicast() {
  173. // Fill the ARP cache from IP header of unicast frames.
  174. self.arp_cache.fill(&IpAddress::Ipv4(ipv4_repr.src_addr),
  175. &eth_frame.src_addr());
  176. }
  177. // Pass every IP packet to all raw sockets we have registered.
  178. let mut handled_by_raw_socket = false;
  179. for raw_socket in sockets.iter_mut().filter_map(
  180. <Socket as AsSocket<RawSocket>>::try_as_socket) {
  181. match raw_socket.process(timestamp, &IpRepr::Ipv4(ipv4_repr),
  182. ipv4_packet.payload()) {
  183. Ok(()) => handled_by_raw_socket = true,
  184. Err(Error::Rejected) => (),
  185. _ => unreachable!(),
  186. }
  187. }
  188. if !self.has_protocol_addr(ipv4_repr.dst_addr) {
  189. // Ignore IP packets not directed at us.
  190. return Ok(Response::Nop)
  191. }
  192. match ipv4_repr.protocol {
  193. IpProtocol::Icmp =>
  194. Self::process_icmpv4(ipv4_repr, ipv4_packet.payload()),
  195. IpProtocol::Tcp =>
  196. Self::process_tcpv4(sockets, timestamp, ipv4_repr, ipv4_packet.payload()),
  197. IpProtocol::Udp =>
  198. Self::process_udpv4(sockets, timestamp, ipv4_repr, ipv4_packet.payload()),
  199. _ => {
  200. if handled_by_raw_socket {
  201. Ok(Response::Nop)
  202. } else {
  203. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  204. reason: Icmpv4DstUnreachable::PortUnreachable,
  205. header: ipv4_repr,
  206. data: &ipv4_packet.payload()[0..8]
  207. };
  208. let ipv4_reply_repr = Ipv4Repr {
  209. src_addr: ipv4_repr.dst_addr,
  210. dst_addr: ipv4_repr.src_addr,
  211. protocol: IpProtocol::Icmp,
  212. payload_len: icmp_reply_repr.buffer_len()
  213. };
  214. Ok(Response::Icmpv4(ipv4_reply_repr, icmp_reply_repr))
  215. }
  216. }
  217. }
  218. }
  219. fn process_icmpv4<'frame>(ipv4_repr: Ipv4Repr, ip_payload: &'frame [u8]) ->
  220. Result<Response<'frame>, Error> {
  221. let icmp_packet = Icmpv4Packet::new_checked(ip_payload)?;
  222. let icmp_repr = Icmpv4Repr::parse(&icmp_packet)?;
  223. match icmp_repr {
  224. // Respond to echo requests.
  225. Icmpv4Repr::EchoRequest {
  226. ident, seq_no, data
  227. } => {
  228. let icmp_reply_repr = Icmpv4Repr::EchoReply {
  229. ident: ident,
  230. seq_no: seq_no,
  231. data: data
  232. };
  233. let ipv4_reply_repr = Ipv4Repr {
  234. src_addr: ipv4_repr.dst_addr,
  235. dst_addr: ipv4_repr.src_addr,
  236. protocol: IpProtocol::Icmp,
  237. payload_len: icmp_reply_repr.buffer_len()
  238. };
  239. Ok(Response::Icmpv4(ipv4_reply_repr, icmp_reply_repr))
  240. }
  241. // Ignore any echo replies.
  242. Icmpv4Repr::EchoReply { .. } => Ok(Response::Nop),
  243. // FIXME: do something correct here?
  244. _ => Err(Error::Unrecognized),
  245. }
  246. }
  247. fn process_tcpv4<'frame>(sockets: &mut SocketSet, timestamp: u64,
  248. ipv4_repr: Ipv4Repr, ip_payload: &'frame [u8]) ->
  249. Result<Response<'frame>, Error> {
  250. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  251. for tcp_socket in sockets.iter_mut().filter_map(
  252. <Socket as AsSocket<TcpSocket>>::try_as_socket) {
  253. match tcp_socket.process(timestamp, &ip_repr, ip_payload) {
  254. // The packet was valid and handled by socket.
  255. Ok(()) => return Ok(Response::Nop),
  256. // The packet wasn't addressed to the socket.
  257. // Send RST only if no other socket accepts the packet.
  258. Err(Error::Rejected) => continue,
  259. // The packet was addressed to the socket but is malformed.
  260. Err(Error::Malformed) => break,
  261. Err(e) => return Err(e)
  262. }
  263. }
  264. // The packet wasn't handled by a socket, send a TCP RST packet.
  265. let tcp_packet = TcpPacket::new_checked(ip_payload)?;
  266. if tcp_packet.rst() {
  267. // Don't reply to a TCP RST packet with another TCP RST packet.
  268. return Ok(Response::Nop)
  269. }
  270. let tcp_reply_repr = TcpRepr {
  271. src_port: tcp_packet.dst_port(),
  272. dst_port: tcp_packet.src_port(),
  273. control: TcpControl::Rst,
  274. push: false,
  275. seq_number: tcp_packet.ack_number(),
  276. ack_number: Some(tcp_packet.seq_number() +
  277. tcp_packet.segment_len()),
  278. window_len: 0,
  279. max_seg_size: None,
  280. payload: &[]
  281. };
  282. let ipv4_reply_repr = Ipv4Repr {
  283. src_addr: ipv4_repr.dst_addr,
  284. dst_addr: ipv4_repr.src_addr,
  285. protocol: IpProtocol::Tcp,
  286. payload_len: tcp_reply_repr.buffer_len()
  287. };
  288. Ok(Response::Tcpv4(ipv4_reply_repr, tcp_reply_repr))
  289. }
  290. fn process_udpv4<'frame>(sockets: &mut SocketSet, timestamp: u64,
  291. ipv4_repr: Ipv4Repr, ip_payload: &'frame [u8]) ->
  292. Result<Response<'frame>, Error> {
  293. let ip_repr = IpRepr::Ipv4(ipv4_repr);
  294. for udp_socket in sockets.iter_mut().filter_map(
  295. <Socket as AsSocket<UdpSocket>>::try_as_socket) {
  296. match udp_socket.process(timestamp, &ip_repr, ip_payload) {
  297. // The packet was valid and handled by socket.
  298. Ok(()) => return Ok(Response::Nop),
  299. // The packet wasn't addressed to the socket.
  300. Err(Error::Rejected) => continue,
  301. // The packet was addressed to the socket but is malformed.
  302. Err(Error::Malformed) => break,
  303. Err(e) => return Err(e)
  304. }
  305. }
  306. //The packet wasn't handled by a socket, send an ICMP port unreachable packet.
  307. let icmp_reply_repr = Icmpv4Repr::DstUnreachable {
  308. reason: Icmpv4DstUnreachable::PortUnreachable,
  309. header: ipv4_repr,
  310. data: &ip_payload[0..8]
  311. };
  312. let ipv4_reply_repr = Ipv4Repr {
  313. src_addr: ipv4_repr.dst_addr,
  314. dst_addr: ipv4_repr.src_addr,
  315. protocol: IpProtocol::Icmp,
  316. payload_len: icmp_reply_repr.buffer_len()
  317. };
  318. Ok(Response::Icmpv4(ipv4_reply_repr, icmp_reply_repr))
  319. }
  320. fn send_response(&mut self, response: Response) -> Result<(), Error> {
  321. macro_rules! ip_response {
  322. ($tx_buffer:ident, $frame:ident, $ip_repr:ident) => ({
  323. let dst_hardware_addr =
  324. match self.arp_cache.lookup(&$ip_repr.dst_addr.into()) {
  325. None => return Err(Error::Unaddressable),
  326. Some(hardware_addr) => hardware_addr
  327. };
  328. let frame_len = EthernetFrame::<&[u8]>::buffer_len($ip_repr.buffer_len() +
  329. $ip_repr.payload_len);
  330. $tx_buffer = self.device.transmit(frame_len)?;
  331. $frame = EthernetFrame::new_checked(&mut $tx_buffer)
  332. .expect("transmit frame too small");
  333. $frame.set_src_addr(self.hardware_addr);
  334. $frame.set_dst_addr(dst_hardware_addr);
  335. $frame.set_ethertype(EthernetProtocol::Ipv4);
  336. let mut ip_packet = Ipv4Packet::new($frame.payload_mut());
  337. $ip_repr.emit(&mut ip_packet);
  338. ip_packet
  339. })
  340. }
  341. match response {
  342. Response::Arp(repr) => {
  343. let tx_len = EthernetFrame::<&[u8]>::buffer_len(repr.buffer_len());
  344. let mut tx_buffer = self.device.transmit(tx_len)?;
  345. let mut frame = EthernetFrame::new_checked(&mut tx_buffer)
  346. .expect("transmit frame too small");
  347. frame.set_src_addr(self.hardware_addr);
  348. frame.set_dst_addr(match repr {
  349. ArpRepr::EthernetIpv4 { target_hardware_addr, .. } => target_hardware_addr,
  350. _ => unreachable!()
  351. });
  352. frame.set_ethertype(EthernetProtocol::Arp);
  353. let mut packet = ArpPacket::new(frame.payload_mut());
  354. repr.emit(&mut packet);
  355. Ok(())
  356. },
  357. Response::Icmpv4(ip_repr, icmp_repr) => {
  358. let mut tx_buffer;
  359. let mut frame;
  360. let mut ip_packet = ip_response!(tx_buffer, frame, ip_repr);
  361. let mut icmp_packet = Icmpv4Packet::new(ip_packet.payload_mut());
  362. icmp_repr.emit(&mut icmp_packet);
  363. Ok(())
  364. }
  365. Response::Tcpv4(ip_repr, tcp_repr) => {
  366. let mut tx_buffer;
  367. let mut frame;
  368. let mut ip_packet = ip_response!(tx_buffer, frame, ip_repr);
  369. let mut tcp_packet = TcpPacket::new(ip_packet.payload_mut());
  370. tcp_repr.emit(&mut tcp_packet,
  371. &IpAddress::Ipv4(ip_repr.src_addr),
  372. &IpAddress::Ipv4(ip_repr.dst_addr));
  373. Ok(())
  374. }
  375. Response::Nop => {
  376. Ok(())
  377. }
  378. }
  379. }
  380. fn emit(&mut self, sockets: &mut SocketSet, timestamp: u64) -> Result<bool, Error> {
  381. // Borrow checker is being overly careful around closures, so we have
  382. // to hack around that.
  383. let src_hardware_addr = self.hardware_addr;
  384. let src_protocol_addrs = self.protocol_addrs.as_ref();
  385. let arp_cache = &mut self.arp_cache;
  386. let device = &mut self.device;
  387. let mut limits = device.limits();
  388. limits.max_transmission_unit -= EthernetFrame::<&[u8]>::header_len();
  389. let mut nothing_to_transmit = true;
  390. for socket in sockets.iter_mut() {
  391. let result = socket.dispatch(timestamp, &limits, &mut |repr, payload| {
  392. let repr = repr.lower(src_protocol_addrs)?;
  393. match arp_cache.lookup(&repr.dst_addr()) {
  394. Some(dst_hardware_addr) => {
  395. let tx_len = EthernetFrame::<&[u8]>::buffer_len(repr.buffer_len() +
  396. payload.buffer_len());
  397. let mut tx_buffer = device.transmit(tx_len)?;
  398. let mut frame = EthernetFrame::new_checked(&mut tx_buffer)
  399. .expect("transmit frame too small");
  400. frame.set_src_addr(src_hardware_addr);
  401. frame.set_dst_addr(dst_hardware_addr);
  402. frame.set_ethertype(EthernetProtocol::Ipv4);
  403. repr.emit(frame.payload_mut());
  404. let mut ip_packet = Ipv4Packet::new(frame.payload_mut());
  405. payload.emit(&repr, ip_packet.payload_mut());
  406. }
  407. None => {
  408. let (src_addr, dst_addr) =
  409. match (repr.src_addr(), repr.dst_addr()) {
  410. (IpAddress::Ipv4(src_addr), IpAddress::Ipv4(dst_addr)) =>
  411. (src_addr, dst_addr),
  412. // We've lowered all addresses to a concrete form.
  413. _ => unreachable!()
  414. };
  415. let payload = ArpRepr::EthernetIpv4 {
  416. operation: ArpOperation::Request,
  417. source_hardware_addr: src_hardware_addr,
  418. source_protocol_addr: src_addr,
  419. target_hardware_addr: EthernetAddress::default(),
  420. target_protocol_addr: dst_addr,
  421. };
  422. let tx_len = EthernetFrame::<&[u8]>::buffer_len(payload.buffer_len());
  423. let mut tx_buffer = device.transmit(tx_len)?;
  424. let mut frame = EthernetFrame::new_checked(&mut tx_buffer)
  425. .expect("transmit frame too small");
  426. frame.set_src_addr(src_hardware_addr);
  427. frame.set_dst_addr(EthernetAddress([0xff; 6]));
  428. frame.set_ethertype(EthernetProtocol::Arp);
  429. let mut arp_packet = ArpPacket::new(frame.payload_mut());
  430. payload.emit(&mut arp_packet);
  431. }
  432. }
  433. Ok(())
  434. });
  435. match result {
  436. Ok(()) => {
  437. nothing_to_transmit = false;
  438. break
  439. }
  440. Err(Error::Exhausted) => continue,
  441. Err(e) => return Err(e)
  442. }
  443. }
  444. Ok(nothing_to_transmit)
  445. }
  446. }