ethernet.rs 20 KB

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