dhcpv4.rs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. // See https://tools.ietf.org/html/rfc2131 for the DHCP specification.
  2. use byteorder::{ByteOrder, NetworkEndian};
  3. use crate::{Error, Result};
  4. use crate::wire::{EthernetAddress, Ipv4Address};
  5. use crate::wire::arp::Hardware;
  6. const DHCP_MAGIC_NUMBER: u32 = 0x63825363;
  7. pub const MAX_DNS_SERVERS: usize = 3;
  8. enum_with_unknown! {
  9. /// The possible opcodes of a DHCP packet.
  10. pub enum OpCode(u8) {
  11. Request = 1,
  12. Reply = 2,
  13. }
  14. }
  15. enum_with_unknown! {
  16. /// The possible message types of a DHCP packet.
  17. pub enum MessageType(u8) {
  18. Discover = 1,
  19. Offer = 2,
  20. Request = 3,
  21. Decline = 4,
  22. Ack = 5,
  23. Nak = 6,
  24. Release = 7,
  25. Inform = 8,
  26. }
  27. }
  28. impl MessageType {
  29. fn opcode(&self) -> OpCode {
  30. match *self {
  31. MessageType::Discover | MessageType::Inform | MessageType::Request |
  32. MessageType::Decline | MessageType::Release => OpCode::Request,
  33. MessageType::Offer | MessageType::Ack | MessageType::Nak => OpCode::Reply,
  34. MessageType::Unknown(_) => OpCode::Unknown(0),
  35. }
  36. }
  37. }
  38. /// A representation of a single DHCP option.
  39. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  40. pub enum DhcpOption<'a> {
  41. EndOfList,
  42. Pad,
  43. MessageType(MessageType),
  44. RequestedIp(Ipv4Address),
  45. ClientIdentifier(EthernetAddress),
  46. ServerIdentifier(Ipv4Address),
  47. IpLeaseTime(u32),
  48. Router(Ipv4Address),
  49. SubnetMask(Ipv4Address),
  50. MaximumDhcpMessageSize(u16),
  51. Other { kind: u8, data: &'a [u8] }
  52. }
  53. impl<'a> DhcpOption<'a> {
  54. pub fn parse(buffer: &'a [u8]) -> Result<(&'a [u8], DhcpOption<'a>)> {
  55. // See https://tools.ietf.org/html/rfc2132 for all possible DHCP options.
  56. let (skip_len, option);
  57. match *buffer.get(0).ok_or(Error::Truncated)? {
  58. field::OPT_END => {
  59. skip_len = 1;
  60. option = DhcpOption::EndOfList;
  61. }
  62. field::OPT_PAD => {
  63. skip_len = 1;
  64. option = DhcpOption::Pad;
  65. }
  66. kind => {
  67. let length = *buffer.get(1).ok_or(Error::Truncated)? as usize;
  68. skip_len = length + 2;
  69. let data = buffer.get(2..skip_len).ok_or(Error::Truncated)?;
  70. match (kind, length) {
  71. (field::OPT_END, _) |
  72. (field::OPT_PAD, _) =>
  73. unreachable!(),
  74. (field::OPT_DHCP_MESSAGE_TYPE, 1) => {
  75. option = DhcpOption::MessageType(MessageType::from(data[0]));
  76. },
  77. (field::OPT_REQUESTED_IP, 4) => {
  78. option = DhcpOption::RequestedIp(Ipv4Address::from_bytes(data));
  79. }
  80. (field::OPT_CLIENT_ID, 7) => {
  81. let hardware_type = Hardware::from(u16::from(data[0]));
  82. if hardware_type != Hardware::Ethernet {
  83. return Err(Error::Unrecognized);
  84. }
  85. option = DhcpOption::ClientIdentifier(EthernetAddress::from_bytes(&data[1..]));
  86. }
  87. (field::OPT_SERVER_IDENTIFIER, 4) => {
  88. option = DhcpOption::ServerIdentifier(Ipv4Address::from_bytes(data));
  89. }
  90. (field::OPT_ROUTER, 4) => {
  91. option = DhcpOption::Router(Ipv4Address::from_bytes(data));
  92. }
  93. (field::OPT_SUBNET_MASK, 4) => {
  94. option = DhcpOption::SubnetMask(Ipv4Address::from_bytes(data));
  95. }
  96. (field::OPT_MAX_DHCP_MESSAGE_SIZE, 2) => {
  97. option = DhcpOption::MaximumDhcpMessageSize(u16::from_be_bytes([data[0], data[1]]));
  98. }
  99. (field::OPT_IP_LEASE_TIME, 4) => {
  100. option = DhcpOption::IpLeaseTime(u32::from_be_bytes([data[0], data[1], data[2], data[3]]))
  101. }
  102. (_, _) => {
  103. option = DhcpOption::Other { kind: kind, data: data };
  104. }
  105. }
  106. }
  107. }
  108. Ok((&buffer[skip_len..], option))
  109. }
  110. pub fn buffer_len(&self) -> usize {
  111. match self {
  112. &DhcpOption::EndOfList => 1,
  113. &DhcpOption::Pad => 1,
  114. &DhcpOption::MessageType(_) => 3,
  115. &DhcpOption::ClientIdentifier(eth_addr) => {
  116. 3 + eth_addr.as_bytes().len()
  117. }
  118. &DhcpOption::RequestedIp(ip) |
  119. &DhcpOption::ServerIdentifier(ip) |
  120. &DhcpOption::Router(ip) |
  121. &DhcpOption::SubnetMask(ip) => {
  122. 2 + ip.as_bytes().len()
  123. },
  124. &DhcpOption::MaximumDhcpMessageSize(_) => {
  125. 4
  126. }
  127. &DhcpOption::IpLeaseTime(_) => 6,
  128. &DhcpOption::Other { data, .. } => 2 + data.len()
  129. }
  130. }
  131. pub fn emit<'b>(&self, buffer: &'b mut [u8]) -> &'b mut [u8] {
  132. let skip_length;
  133. match *self {
  134. DhcpOption::EndOfList => {
  135. skip_length = 1;
  136. buffer[0] = field::OPT_END;
  137. }
  138. DhcpOption::Pad => {
  139. skip_length = 1;
  140. buffer[0] = field::OPT_PAD;
  141. }
  142. _ => {
  143. skip_length = self.buffer_len();
  144. buffer[1] = (skip_length - 2) as u8;
  145. match *self {
  146. DhcpOption::EndOfList | DhcpOption::Pad => unreachable!(),
  147. DhcpOption::MessageType(value) => {
  148. buffer[0] = field::OPT_DHCP_MESSAGE_TYPE;
  149. buffer[2] = value.into();
  150. }
  151. DhcpOption::ClientIdentifier(eth_addr) => {
  152. buffer[0] = field::OPT_CLIENT_ID;
  153. buffer[2] = u16::from(Hardware::Ethernet) as u8;
  154. buffer[3..9].copy_from_slice(eth_addr.as_bytes());
  155. }
  156. DhcpOption::RequestedIp(ip) => {
  157. buffer[0] = field::OPT_REQUESTED_IP;
  158. buffer[2..6].copy_from_slice(ip.as_bytes());
  159. }
  160. DhcpOption::ServerIdentifier(ip) => {
  161. buffer[0] = field::OPT_SERVER_IDENTIFIER;
  162. buffer[2..6].copy_from_slice(ip.as_bytes());
  163. }
  164. DhcpOption::Router(ip) => {
  165. buffer[0] = field::OPT_ROUTER;
  166. buffer[2..6].copy_from_slice(ip.as_bytes());
  167. }
  168. DhcpOption::SubnetMask(mask) => {
  169. buffer[0] = field::OPT_SUBNET_MASK;
  170. buffer[2..6].copy_from_slice(mask.as_bytes());
  171. }
  172. DhcpOption::MaximumDhcpMessageSize(size) => {
  173. buffer[0] = field::OPT_MAX_DHCP_MESSAGE_SIZE;
  174. buffer[2..4].copy_from_slice(&size.to_be_bytes()[..]);
  175. }
  176. DhcpOption::IpLeaseTime(lease_time) => {
  177. buffer[0] = field::OPT_IP_LEASE_TIME;
  178. buffer[2..6].copy_from_slice(&lease_time.to_be_bytes()[..]);
  179. }
  180. DhcpOption::Other { kind, data: provided } => {
  181. buffer[0] = kind;
  182. buffer[2..skip_length].copy_from_slice(provided);
  183. }
  184. }
  185. }
  186. }
  187. &mut buffer[skip_length..]
  188. }
  189. }
  190. /// A read/write wrapper around a Dynamic Host Configuration Protocol packet buffer.
  191. #[derive(Debug, PartialEq)]
  192. pub struct Packet<T: AsRef<[u8]>> {
  193. buffer: T
  194. }
  195. pub(crate) mod field {
  196. #![allow(non_snake_case)]
  197. #![allow(unused)]
  198. use crate::wire::field::*;
  199. pub const OP: usize = 0;
  200. pub const HTYPE: usize = 1;
  201. pub const HLEN: usize = 2;
  202. pub const HOPS: usize = 3;
  203. pub const XID: Field = 4..8;
  204. pub const SECS: Field = 8..10;
  205. pub const FLAGS: Field = 10..12;
  206. pub const CIADDR: Field = 12..16;
  207. pub const YIADDR: Field = 16..20;
  208. pub const SIADDR: Field = 20..24;
  209. pub const GIADDR: Field = 24..28;
  210. pub const CHADDR: Field = 28..34;
  211. pub const SNAME: Field = 34..108;
  212. pub const FILE: Field = 108..236;
  213. pub const MAGIC_NUMBER: Field = 236..240;
  214. pub const OPTIONS: Rest = 240..;
  215. // Vendor Extensions
  216. pub const OPT_END: u8 = 255;
  217. pub const OPT_PAD: u8 = 0;
  218. pub const OPT_SUBNET_MASK: u8 = 1;
  219. pub const OPT_TIME_OFFSET: u8 = 2;
  220. pub const OPT_ROUTER: u8 = 3;
  221. pub const OPT_TIME_SERVER: u8 = 4;
  222. pub const OPT_NAME_SERVER: u8 = 5;
  223. pub const OPT_DOMAIN_NAME_SERVER: u8 = 6;
  224. pub const OPT_LOG_SERVER: u8 = 7;
  225. pub const OPT_COOKIE_SERVER: u8 = 8;
  226. pub const OPT_LPR_SERVER: u8 = 9;
  227. pub const OPT_IMPRESS_SERVER: u8 = 10;
  228. pub const OPT_RESOURCE_LOCATION_SERVER: u8 = 11;
  229. pub const OPT_HOST_NAME: u8 = 12;
  230. pub const OPT_BOOT_FILE_SIZE: u8 = 13;
  231. pub const OPT_MERIT_DUMP: u8 = 14;
  232. pub const OPT_DOMAIN_NAME: u8 = 15;
  233. pub const OPT_SWAP_SERVER: u8 = 16;
  234. pub const OPT_ROOT_PATH: u8 = 17;
  235. pub const OPT_EXTENSIONS_PATH: u8 = 18;
  236. // IP Layer Parameters per Host
  237. pub const OPT_IP_FORWARDING: u8 = 19;
  238. pub const OPT_NON_LOCAL_SOURCE_ROUTING: u8 = 20;
  239. pub const OPT_POLICY_FILTER: u8 = 21;
  240. pub const OPT_MAX_DATAGRAM_REASSEMBLY_SIZE: u8 = 22;
  241. pub const OPT_DEFAULT_TTL: u8 = 23;
  242. pub const OPT_PATH_MTU_AGING_TIMEOUT: u8 = 24;
  243. pub const OPT_PATH_MTU_PLATEU_TABLE: u8 = 25;
  244. // IP Layer Parameters per Interface
  245. pub const OPT_INTERFACE_MTU: u8 = 26;
  246. pub const OPT_ALL_SUBNETS_ARE_LOCAL: u8 = 27;
  247. pub const OPT_BROADCAST_ADDRESS: u8 = 28;
  248. pub const OPT_PERFORM_MASK_DISCOVERY: u8 = 29;
  249. pub const OPT_MASK_SUPPLIER: u8 = 30;
  250. pub const OPT_PERFORM_ROUTER_DISCOVERY: u8 = 31;
  251. pub const OPT_ROUTER_SOLICITATION_ADDRESS: u8 = 32;
  252. pub const OPT_STATIC_ROUTE: u8 = 33;
  253. // Link Layer Parameters per Interface
  254. pub const OPT_TRAILER_ENCAPSULATION: u8 = 34;
  255. pub const OPT_ARP_CACHE_TIMEOUT: u8 = 35;
  256. pub const OPT_ETHERNET_ENCAPSULATION: u8 = 36;
  257. // TCP Parameters
  258. pub const OPT_TCP_DEFAULT_TTL: u8 = 37;
  259. pub const OPT_TCP_KEEPALIVE_INTERVAL: u8 = 38;
  260. pub const OPT_TCP_KEEPALIVE_GARBAGE: u8 = 39;
  261. // Application and Service Parameters
  262. pub const OPT_NIS_DOMAIN: u8 = 40;
  263. pub const OPT_NIS_SERVERS: u8 = 41;
  264. pub const OPT_NTP_SERVERS: u8 = 42;
  265. pub const OPT_VENDOR_SPECIFIC_INFO: u8 = 43;
  266. pub const OPT_NETBIOS_NAME_SERVER: u8 = 44;
  267. pub const OPT_NETBIOS_DISTRIBUTION_SERVER: u8 = 45;
  268. pub const OPT_NETBIOS_NODE_TYPE: u8 = 46;
  269. pub const OPT_NETBIOS_SCOPE: u8 = 47;
  270. pub const OPT_X_WINDOW_FONT_SERVER: u8 = 48;
  271. pub const OPT_X_WINDOW_DISPLAY_MANAGER: u8 = 49;
  272. pub const OPT_NIS_PLUS_DOMAIN: u8 = 64;
  273. pub const OPT_NIS_PLUS_SERVERS: u8 = 65;
  274. pub const OPT_MOBILE_IP_HOME_AGENT: u8 = 68;
  275. pub const OPT_SMTP_SERVER: u8 = 69;
  276. pub const OPT_POP3_SERVER: u8 = 70;
  277. pub const OPT_NNTP_SERVER: u8 = 71;
  278. pub const OPT_WWW_SERVER: u8 = 72;
  279. pub const OPT_FINGER_SERVER: u8 = 73;
  280. pub const OPT_IRC_SERVER: u8 = 74;
  281. pub const OPT_STREETTALK_SERVER: u8 = 75;
  282. pub const OPT_STDA_SERVER: u8 = 76;
  283. // DHCP Extensions
  284. pub const OPT_REQUESTED_IP: u8 = 50;
  285. pub const OPT_IP_LEASE_TIME: u8 = 51;
  286. pub const OPT_OPTION_OVERLOAD: u8 = 52;
  287. pub const OPT_TFTP_SERVER_NAME: u8 = 66;
  288. pub const OPT_BOOTFILE_NAME: u8 = 67;
  289. pub const OPT_DHCP_MESSAGE_TYPE: u8 = 53;
  290. pub const OPT_SERVER_IDENTIFIER: u8 = 54;
  291. pub const OPT_PARAMETER_REQUEST_LIST: u8 = 55;
  292. pub const OPT_MESSAGE: u8 = 56;
  293. pub const OPT_MAX_DHCP_MESSAGE_SIZE: u8 = 57;
  294. pub const OPT_RENEWAL_TIME_VALUE: u8 = 58;
  295. pub const OPT_REBINDING_TIME_VALUE: u8 = 59;
  296. pub const OPT_VENDOR_CLASS_ID: u8 = 60;
  297. pub const OPT_CLIENT_ID: u8 = 61;
  298. }
  299. impl<T: AsRef<[u8]>> Packet<T> {
  300. /// Imbue a raw octet buffer with DHCP packet structure.
  301. pub fn new_unchecked(buffer: T) -> Packet<T> {
  302. Packet { buffer }
  303. }
  304. /// Shorthand for a combination of [new_unchecked] and [check_len].
  305. ///
  306. /// [new_unchecked]: #method.new_unchecked
  307. /// [check_len]: #method.check_len
  308. pub fn new_checked(buffer: T) -> Result<Packet<T>> {
  309. let packet = Self::new_unchecked(buffer);
  310. packet.check_len()?;
  311. Ok(packet)
  312. }
  313. /// Ensure that no accessor method will panic if called.
  314. /// Returns `Err(Error::Truncated)` if the buffer is too short.
  315. ///
  316. /// [set_header_len]: #method.set_header_len
  317. pub fn check_len(&self) -> Result<()> {
  318. let len = self.buffer.as_ref().len();
  319. if len < field::MAGIC_NUMBER.end {
  320. Err(Error::Truncated)
  321. } else {
  322. Ok(())
  323. }
  324. }
  325. /// Consume the packet, returning the underlying buffer.
  326. pub fn into_inner(self) -> T {
  327. self.buffer
  328. }
  329. /// Returns the operation code of this packet.
  330. pub fn opcode(&self) -> OpCode {
  331. let data = self.buffer.as_ref();
  332. OpCode::from(data[field::OP])
  333. }
  334. /// Returns the hardware protocol type (e.g. ethernet).
  335. pub fn hardware_type(&self) -> Hardware {
  336. let data = self.buffer.as_ref();
  337. Hardware::from(u16::from(data[field::HTYPE]))
  338. }
  339. /// Returns the length of a hardware address in bytes (e.g. 6 for ethernet).
  340. pub fn hardware_len(&self) -> u8 {
  341. self.buffer.as_ref()[field::HLEN]
  342. }
  343. /// Returns the transaction ID.
  344. ///
  345. /// The transaction ID (called `xid` in the specification) is a random number used to
  346. /// associate messages and responses between client and server. The number is chosen by
  347. /// the client.
  348. pub fn transaction_id(&self) -> u32 {
  349. let field = &self.buffer.as_ref()[field::XID];
  350. NetworkEndian::read_u32(field)
  351. }
  352. /// Returns the hardware address of the client (called `chaddr` in the specification).
  353. ///
  354. /// Only ethernet is supported by `smoltcp`, so this functions returns
  355. /// an `EthernetAddress`.
  356. pub fn client_hardware_address(&self) -> EthernetAddress {
  357. let field = &self.buffer.as_ref()[field::CHADDR];
  358. EthernetAddress::from_bytes(field)
  359. }
  360. /// Returns the value of the `hops` field.
  361. ///
  362. /// The `hops` field is set to zero by clients and optionally used by relay agents.
  363. pub fn hops(&self) -> u8 {
  364. self.buffer.as_ref()[field::HOPS]
  365. }
  366. /// Returns the value of the `secs` field.
  367. ///
  368. /// The secs field is filled by clients and describes the number of seconds elapsed
  369. /// since client began process.
  370. pub fn secs(&self) -> u16 {
  371. let field = &self.buffer.as_ref()[field::SECS];
  372. NetworkEndian::read_u16(field)
  373. }
  374. /// Returns the value of the `magic cookie` field in the DHCP options.
  375. ///
  376. /// This field should be always be `0x63825363`.
  377. pub fn magic_number(&self) -> u32 {
  378. let field = &self.buffer.as_ref()[field::MAGIC_NUMBER];
  379. NetworkEndian::read_u32(field)
  380. }
  381. /// Returns the Ipv4 address of the client, zero if not set.
  382. ///
  383. /// This corresponds to the `ciaddr` field in the DHCP specification. According to it,
  384. /// this field is “only filled in if client is in `BOUND`, `RENEW` or `REBINDING` state
  385. /// and can respond to ARP requests”.
  386. pub fn client_ip(&self) -> Ipv4Address {
  387. let field = &self.buffer.as_ref()[field::CIADDR];
  388. Ipv4Address::from_bytes(field)
  389. }
  390. /// Returns the value of the `yiaddr` field, zero if not set.
  391. pub fn your_ip(&self) -> Ipv4Address {
  392. let field = &self.buffer.as_ref()[field::YIADDR];
  393. Ipv4Address::from_bytes(field)
  394. }
  395. /// Returns the value of the `siaddr` field, zero if not set.
  396. pub fn server_ip(&self) -> Ipv4Address {
  397. let field = &self.buffer.as_ref()[field::SIADDR];
  398. Ipv4Address::from_bytes(field)
  399. }
  400. /// Returns the value of the `giaddr` field, zero if not set.
  401. pub fn relay_agent_ip(&self) -> Ipv4Address {
  402. let field = &self.buffer.as_ref()[field::GIADDR];
  403. Ipv4Address::from_bytes(field)
  404. }
  405. /// Returns true if the broadcast flag is set.
  406. pub fn broadcast_flag(&self) -> bool {
  407. let field = &self.buffer.as_ref()[field::FLAGS];
  408. NetworkEndian::read_u16(field) & 0b1 == 0b1
  409. }
  410. }
  411. impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> {
  412. /// Return a pointer to the options.
  413. #[inline]
  414. pub fn options(&self) -> Result<&'a [u8]> {
  415. let data = self.buffer.as_ref();
  416. data.get(field::OPTIONS).ok_or(Error::Malformed)
  417. }
  418. }
  419. impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
  420. /// Sets the optional `sname` (“server name”) and `file` (“boot file name”) fields to zero.
  421. ///
  422. /// The fields are not commonly used, so we set their value always to zero. **This method
  423. /// must be called when creating a packet, otherwise the emitted values for these fields
  424. /// are undefined!**
  425. pub fn set_sname_and_boot_file_to_zero(&mut self) {
  426. let data = self.buffer.as_mut();
  427. for byte in &mut data[field::SNAME] {
  428. *byte = 0;
  429. }
  430. for byte in &mut data[field::FILE] {
  431. *byte = 0;
  432. }
  433. }
  434. /// Sets the `OpCode` for the packet.
  435. pub fn set_opcode(&mut self, value: OpCode) {
  436. let data = self.buffer.as_mut();
  437. data[field::OP] = value.into();
  438. }
  439. /// Sets the hardware address type (only ethernet is supported).
  440. pub fn set_hardware_type(&mut self, value: Hardware) {
  441. let data = self.buffer.as_mut();
  442. let number: u16 = value.into();
  443. assert!(number <= u16::from(u8::max_value())); // TODO: Replace with TryFrom when it's stable
  444. data[field::HTYPE] = number as u8;
  445. }
  446. /// Sets the hardware address length.
  447. ///
  448. /// Only ethernet is supported, so this field should be set to the value `6`.
  449. pub fn set_hardware_len(&mut self, value: u8) {
  450. self.buffer.as_mut()[field::HLEN] = value;
  451. }
  452. /// Sets the transaction ID.
  453. ///
  454. /// The transaction ID (called `xid` in the specification) is a random number used to
  455. /// associate messages and responses between client and server. The number is chosen by
  456. /// the client.
  457. pub fn set_transaction_id(&mut self, value: u32) {
  458. let field = &mut self.buffer.as_mut()[field::XID];
  459. NetworkEndian::write_u32(field, value)
  460. }
  461. /// Sets the ethernet address of the client.
  462. ///
  463. /// Sets the `chaddr` field.
  464. pub fn set_client_hardware_address(&mut self, value: EthernetAddress) {
  465. let field = &mut self.buffer.as_mut()[field::CHADDR];
  466. field.copy_from_slice(value.as_bytes());
  467. }
  468. /// Sets the hops field.
  469. ///
  470. /// The `hops` field is set to zero by clients and optionally used by relay agents.
  471. pub fn set_hops(&mut self, value: u8) {
  472. self.buffer.as_mut()[field::HOPS] = value;
  473. }
  474. /// Sets the `secs` field.
  475. ///
  476. /// The secs field is filled by clients and describes the number of seconds elapsed
  477. /// since client began process.
  478. pub fn set_secs(&mut self, value: u16) {
  479. let field = &mut self.buffer.as_mut()[field::SECS];
  480. NetworkEndian::write_u16(field, value);
  481. }
  482. /// Sets the value of the `magic cookie` field in the DHCP options.
  483. ///
  484. /// This field should be always be `0x63825363`.
  485. pub fn set_magic_number(&mut self, value: u32) {
  486. let field = &mut self.buffer.as_mut()[field::MAGIC_NUMBER];
  487. NetworkEndian::write_u32(field, value);
  488. }
  489. /// Sets the Ipv4 address of the client.
  490. ///
  491. /// This corresponds to the `ciaddr` field in the DHCP specification. According to it,
  492. /// this field is “only filled in if client is in `BOUND`, `RENEW` or `REBINDING` state
  493. /// and can respond to ARP requests”.
  494. pub fn set_client_ip(&mut self, value: Ipv4Address) {
  495. let field = &mut self.buffer.as_mut()[field::CIADDR];
  496. field.copy_from_slice(value.as_bytes());
  497. }
  498. /// Sets the value of the `yiaddr` field.
  499. pub fn set_your_ip(&mut self, value: Ipv4Address) {
  500. let field = &mut self.buffer.as_mut()[field::YIADDR];
  501. field.copy_from_slice(value.as_bytes());
  502. }
  503. /// Sets the value of the `siaddr` field.
  504. pub fn set_server_ip(&mut self, value: Ipv4Address) {
  505. let field = &mut self.buffer.as_mut()[field::SIADDR];
  506. field.copy_from_slice(value.as_bytes());
  507. }
  508. /// Sets the value of the `giaddr` field.
  509. pub fn set_relay_agent_ip(&mut self, value: Ipv4Address) {
  510. let field = &mut self.buffer.as_mut()[field::GIADDR];
  511. field.copy_from_slice(value.as_bytes());
  512. }
  513. /// Sets the broadcast flag to the specified value.
  514. pub fn set_broadcast_flag(&mut self, value: bool) {
  515. let field = &mut self.buffer.as_mut()[field::FLAGS];
  516. NetworkEndian::write_u16(field, if value { 1 } else { 0 });
  517. }
  518. }
  519. impl<'a, T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> Packet<&'a mut T> {
  520. /// Return a pointer to the options.
  521. #[inline]
  522. pub fn options_mut(&mut self) -> Result<&mut [u8]> {
  523. let data = self.buffer.as_mut();
  524. data.get_mut(field::OPTIONS).ok_or(Error::Truncated)
  525. }
  526. }
  527. /// A high-level representation of a Dynamic Host Configuration Protocol packet.
  528. ///
  529. /// DHCP messages have the following layout (see [RFC 2131](https://tools.ietf.org/html/rfc2131)
  530. /// for details):
  531. ///
  532. /// ```no_rust
  533. /// 0 1 2 3
  534. /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  535. /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  536. /// | message_type | htype (N/A) | hlen (N/A) | hops |
  537. /// +---------------+---------------+---------------+---------------+
  538. /// | transaction_id |
  539. /// +-------------------------------+-------------------------------+
  540. /// | secs | flags |
  541. /// +-------------------------------+-------------------------------+
  542. /// | client_ip |
  543. /// +---------------------------------------------------------------+
  544. /// | your_ip |
  545. /// +---------------------------------------------------------------+
  546. /// | server_ip |
  547. /// +---------------------------------------------------------------+
  548. /// | relay_agent_ip |
  549. /// +---------------------------------------------------------------+
  550. /// | |
  551. /// | client_hardware_address |
  552. /// | |
  553. /// | |
  554. /// +---------------------------------------------------------------+
  555. /// | |
  556. /// | sname (N/A) |
  557. /// +---------------------------------------------------------------+
  558. /// | |
  559. /// | file (N/A) |
  560. /// +---------------------------------------------------------------+
  561. /// | |
  562. /// | options |
  563. /// +---------------------------------------------------------------+
  564. /// ```
  565. ///
  566. /// It is assumed that the access layer is Ethernet, so `htype` (the field representing the
  567. /// hardware address type) is always set to `1`, and `hlen` (which represents the hardware address
  568. /// length) is set to `6`.
  569. ///
  570. /// The `options` field has a variable length.
  571. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  572. pub struct Repr<'a> {
  573. /// This field is also known as `op` in the RFC. It indicates the type of DHCP message this
  574. /// packet represents.
  575. pub message_type: MessageType,
  576. /// This field is also known as `xid` in the RFC. It is a random number chosen by the client,
  577. /// used by the client and server to associate messages and responses between a client and a
  578. /// server.
  579. pub transaction_id: u32,
  580. /// This field is also known as `chaddr` in the RFC and for networks where the access layer is
  581. /// ethernet, it is the client MAC address.
  582. pub client_hardware_address: EthernetAddress,
  583. /// This field is also known as `ciaddr` in the RFC. It is only filled in if client is in
  584. /// BOUND, RENEW or REBINDING state and can respond to ARP requests.
  585. pub client_ip: Ipv4Address,
  586. /// This field is also known as `yiaddr` in the RFC.
  587. pub your_ip: Ipv4Address,
  588. /// This field is also known as `siaddr` in the RFC. It may be set by the server in DHCPOFFER
  589. /// and DHCPACK messages, and represent the address of the next server to use in bootstrap.
  590. pub server_ip: Ipv4Address,
  591. /// Default gateway
  592. pub router: Option<Ipv4Address>,
  593. /// This field comes from a corresponding DhcpOption.
  594. pub subnet_mask: Option<Ipv4Address>,
  595. /// This field is also known as `giaddr` in the RFC. In order to allow DHCP clients on subnets
  596. /// not directly served by DHCP servers to communicate with DHCP servers, DHCP relay agents can
  597. /// be installed on these subnets. The DHCP client broadcasts on the local link; the relay
  598. /// agent receives the broadcast and transmits it to one or more DHCP servers using unicast.
  599. /// The relay agent stores its own IP address in the `relay_agent_ip` field of the DHCP packet.
  600. /// The DHCP server uses the `relay_agent_ip` to determine the subnet on which the relay agent
  601. /// received the broadcast, and allocates an IP address on that subnet. When the DHCP server
  602. /// replies to the client, it sends the reply to the `relay_agent_ip` address, again using
  603. /// unicast. The relay agent then retransmits the response on the local network
  604. pub relay_agent_ip: Ipv4Address,
  605. /// Broadcast flags. It can be set in DHCPDISCOVER, DHCPINFORM and DHCPREQUEST message if the
  606. /// client requires the response to be broadcasted.
  607. pub broadcast: bool,
  608. /// The "requested IP address" option. It can be used by clients in DHCPREQUEST or DHCPDISCOVER
  609. /// messages, or by servers in DHCPDECLINE messages.
  610. pub requested_ip: Option<Ipv4Address>,
  611. /// The "client identifier" option.
  612. ///
  613. /// The 'client identifier' is an opaque key, not to be interpreted by the server; for example,
  614. /// the 'client identifier' may contain a hardware address, identical to the contents of the
  615. /// 'chaddr' field, or it may contain another type of identifier, such as a DNS name. The
  616. /// 'client identifier' chosen by a DHCP client MUST be unique to that client within the subnet
  617. /// to which the client is attached. If the client uses a 'client identifier' in one message,
  618. /// it MUST use that same identifier in all subsequent messages, to ensure that all servers
  619. /// correctly identify the client.
  620. pub client_identifier: Option<EthernetAddress>,
  621. /// The "server identifier" option. It is used both to identify a DHCP server
  622. /// in a DHCP message and as a destination address from clients to servers.
  623. pub server_identifier: Option<Ipv4Address>,
  624. /// The parameter request list informs the server about which configuration parameters
  625. /// the client is interested in.
  626. pub parameter_request_list: Option<&'a [u8]>,
  627. /// DNS servers
  628. pub dns_servers: Option<[Option<Ipv4Address>; MAX_DNS_SERVERS]>,
  629. /// The maximum size dhcp packet the interface can receive
  630. pub max_size: Option<u16>,
  631. /// The DHCP IP lease duration, specified in seconds.
  632. pub lease_duration: Option<u32>
  633. }
  634. impl<'a> Repr<'a> {
  635. /// Return the length of a packet that will be emitted from this high-level representation.
  636. pub fn buffer_len(&self) -> usize {
  637. let mut len = field::OPTIONS.start;
  638. // message type and end-of-options options
  639. len += 3 + 1;
  640. if self.requested_ip.is_some() { len += 6; }
  641. if self.client_identifier.is_some() { len += 9; }
  642. if self.server_identifier.is_some() { len += 6; }
  643. if self.max_size.is_some() { len += 4; }
  644. if self.router.is_some() { len += 6; }
  645. if self.subnet_mask.is_some() { len += 6; }
  646. if self.lease_duration.is_some() { len += 6; }
  647. if let Some(dns_servers) = self.dns_servers {
  648. len += 2;
  649. len += dns_servers.iter().flatten().count() * core::mem::size_of::<u32>();
  650. }
  651. if let Some(list) = self.parameter_request_list { len += list.len() + 2; }
  652. len
  653. }
  654. /// Parse a DHCP packet and return a high-level representation.
  655. pub fn parse<T>(packet: &Packet<&'a T>) -> Result<Self>
  656. where T: AsRef<[u8]> + ?Sized {
  657. let transaction_id = packet.transaction_id();
  658. let client_hardware_address = packet.client_hardware_address();
  659. let client_ip = packet.client_ip();
  660. let your_ip = packet.your_ip();
  661. let server_ip = packet.server_ip();
  662. let relay_agent_ip = packet.relay_agent_ip();
  663. // only ethernet is supported right now
  664. match packet.hardware_type() {
  665. Hardware::Ethernet => {
  666. if packet.hardware_len() != 6 {
  667. return Err(Error::Malformed);
  668. }
  669. }
  670. Hardware::Unknown(_) => return Err(Error::Unrecognized), // unimplemented
  671. }
  672. if packet.magic_number() != DHCP_MAGIC_NUMBER {
  673. return Err(Error::Malformed);
  674. }
  675. let mut message_type = Err(Error::Malformed);
  676. let mut requested_ip = None;
  677. let mut client_identifier = None;
  678. let mut server_identifier = None;
  679. let mut router = None;
  680. let mut subnet_mask = None;
  681. let mut parameter_request_list = None;
  682. let mut dns_servers = None;
  683. let mut max_size = None;
  684. let mut lease_duration = None;
  685. let mut options = packet.options()?;
  686. while !options.is_empty() {
  687. let (next_options, option) = DhcpOption::parse(options)?;
  688. match option {
  689. DhcpOption::EndOfList => break,
  690. DhcpOption::Pad => {},
  691. DhcpOption::MessageType(value) => {
  692. if value.opcode() == packet.opcode() {
  693. message_type = Ok(value);
  694. }
  695. },
  696. DhcpOption::RequestedIp(ip) => {
  697. requested_ip = Some(ip);
  698. }
  699. DhcpOption::ClientIdentifier(eth_addr) => {
  700. client_identifier = Some(eth_addr);
  701. }
  702. DhcpOption::ServerIdentifier(ip) => {
  703. server_identifier = Some(ip);
  704. }
  705. DhcpOption::Router(ip) => {
  706. router = Some(ip);
  707. }
  708. DhcpOption::SubnetMask(mask) => {
  709. subnet_mask = Some(mask);
  710. },
  711. DhcpOption::MaximumDhcpMessageSize(size) => {
  712. max_size = Some(size);
  713. }
  714. DhcpOption::IpLeaseTime(duration) => {
  715. lease_duration = Some(duration);
  716. }
  717. DhcpOption::Other {kind: field::OPT_PARAMETER_REQUEST_LIST, data} => {
  718. parameter_request_list = Some(data);
  719. }
  720. DhcpOption::Other {kind: field::OPT_DOMAIN_NAME_SERVER, data} => {
  721. let mut servers = [None; MAX_DNS_SERVERS];
  722. for (server, chunk) in servers.iter_mut().zip(data.chunks(4)) {
  723. *server = Some(Ipv4Address::from_bytes(chunk));
  724. }
  725. dns_servers = Some(servers);
  726. }
  727. DhcpOption::Other {..} => {}
  728. }
  729. options = next_options;
  730. }
  731. let broadcast = packet.broadcast_flag();
  732. Ok(Repr {
  733. transaction_id, client_hardware_address, client_ip, your_ip, server_ip, relay_agent_ip,
  734. broadcast, requested_ip, server_identifier, router,
  735. subnet_mask, client_identifier, parameter_request_list, dns_servers, max_size,
  736. lease_duration,
  737. message_type: message_type?,
  738. })
  739. }
  740. /// Emit a high-level representation into a Dynamic Host
  741. /// Configuration Protocol packet.
  742. pub fn emit<T>(&self, packet: &mut Packet<&mut T>) -> Result<()>
  743. where T: AsRef<[u8]> + AsMut<[u8]> + ?Sized {
  744. packet.set_sname_and_boot_file_to_zero();
  745. packet.set_opcode(self.message_type.opcode());
  746. packet.set_hardware_type(Hardware::Ethernet);
  747. packet.set_hardware_len(6);
  748. packet.set_transaction_id(self.transaction_id);
  749. packet.set_client_hardware_address(self.client_hardware_address);
  750. packet.set_hops(0);
  751. packet.set_secs(0); // TODO
  752. packet.set_magic_number(0x63825363);
  753. packet.set_client_ip(self.client_ip);
  754. packet.set_your_ip(self.your_ip);
  755. packet.set_server_ip(self.server_ip);
  756. packet.set_relay_agent_ip(self.relay_agent_ip);
  757. packet.set_broadcast_flag(self.broadcast);
  758. {
  759. let mut options = packet.options_mut()?;
  760. let tmp = options; options = DhcpOption::MessageType(self.message_type).emit(tmp);
  761. if let Some(eth_addr) = self.client_identifier {
  762. let tmp = options; options = DhcpOption::ClientIdentifier(eth_addr).emit(tmp);
  763. }
  764. if let Some(ip) = self.server_identifier {
  765. let tmp = options; options = DhcpOption::ServerIdentifier(ip).emit(tmp);
  766. }
  767. if let Some(ip) = self.router {
  768. let tmp = options; options = DhcpOption::Router(ip).emit(tmp);
  769. }
  770. if let Some(ip) = self.subnet_mask {
  771. let tmp = options; options = DhcpOption::SubnetMask(ip).emit(tmp);
  772. }
  773. if let Some(ip) = self.requested_ip {
  774. let tmp = options; options = DhcpOption::RequestedIp(ip).emit(tmp);
  775. }
  776. if let Some(size) = self.max_size {
  777. let tmp = options; options = DhcpOption::MaximumDhcpMessageSize(size).emit(tmp);
  778. }
  779. if let Some(duration) = self.lease_duration {
  780. let tmp = options; options = DhcpOption::IpLeaseTime(duration).emit(tmp);
  781. }
  782. if let Some(dns_servers) = self.dns_servers {
  783. const IP_SIZE: usize = core::mem::size_of::<u32>();
  784. let mut servers = [0; MAX_DNS_SERVERS * IP_SIZE];
  785. let data_len = dns_servers.iter().flatten()
  786. .enumerate()
  787. .map(|(i, ip)| {
  788. servers[(i * IP_SIZE)..((i + 1) * IP_SIZE)]
  789. .copy_from_slice(ip.as_bytes());
  790. ()
  791. }).count() * IP_SIZE;
  792. let option = DhcpOption::Other{ kind: field::OPT_DOMAIN_NAME_SERVER, data: &servers[..data_len] };
  793. let tmp = options; options = option.emit(tmp);
  794. }
  795. if let Some(list) = self.parameter_request_list {
  796. let option = DhcpOption::Other{ kind: field::OPT_PARAMETER_REQUEST_LIST, data: list };
  797. let tmp = options; options = option.emit(tmp);
  798. }
  799. DhcpOption::EndOfList.emit(options);
  800. }
  801. Ok(())
  802. }
  803. }
  804. #[cfg(test)]
  805. mod test {
  806. use crate::wire::Ipv4Address;
  807. use super::*;
  808. const MAGIC_COOKIE: u32 = 0x63825363;
  809. static DISCOVER_BYTES: &[u8] = &[
  810. 0x01, 0x01, 0x06, 0x00, 0x00, 0x00, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  811. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x82, 0x01,
  812. 0xfc, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  813. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  814. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  815. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  816. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  817. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  818. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  819. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  820. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  821. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  822. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  823. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  824. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63,
  825. 0x35, 0x01, 0x01, 0x3d, 0x07, 0x01, 0x00, 0x0b, 0x82, 0x01, 0xfc, 0x42, 0x32, 0x04, 0x00, 0x00,
  826. 0x00, 0x00, 0x39, 0x2, 0x5, 0xdc, 0x37, 0x04, 0x01, 0x03, 0x06, 0x2a, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  827. ];
  828. static ACK_DNS_SERVER_BYTES: &[u8] = &[
  829. 0x02, 0x01, 0x06, 0x00, 0xcc, 0x34, 0x75, 0xab, 0x00, 0x00, 0x80, 0x00, 0x0a, 0xff, 0x06, 0x91,
  830. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0xff, 0x06, 0xfe, 0x34, 0x17, 0xeb, 0xc9,
  831. 0xaa, 0x2f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  832. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  833. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  834. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  835. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  836. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  837. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  838. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  839. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  840. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  841. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  842. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  843. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63,
  844. 0x35, 0x01, 0x05, 0x36, 0x04, 0xa3, 0x01, 0x4a, 0x16, 0x01, 0x04, 0xff, 0xff, 0xff, 0x00, 0x2b,
  845. 0x05, 0xdc, 0x03, 0x4e, 0x41, 0x50, 0x0f, 0x15, 0x6e, 0x61, 0x74, 0x2e, 0x70, 0x68, 0x79, 0x73,
  846. 0x69, 0x63, 0x73, 0x2e, 0x6f, 0x78, 0x2e, 0x61, 0x63, 0x2e, 0x75, 0x6b, 0x00, 0x03, 0x04, 0x0a,
  847. 0xff, 0x06, 0xfe, 0x06, 0x10, 0xa3, 0x01, 0x4a, 0x06, 0xa3, 0x01, 0x4a, 0x07, 0xa3, 0x01, 0x4a,
  848. 0x03, 0xa3, 0x01, 0x4a, 0x04, 0x2c, 0x10, 0xa3, 0x01, 0x4a, 0x03, 0xa3, 0x01, 0x4a, 0x04, 0xa3,
  849. 0x01, 0x4a, 0x06, 0xa3, 0x01, 0x4a, 0x07, 0x2e, 0x01, 0x08, 0xff
  850. ];
  851. static ACK_LEASE_TIME_BYTES: &[u8] = &[
  852. 0x02, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  853. 0x0a, 0x22, 0x10, 0x0b, 0x0a, 0x22, 0x10, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x04, 0x91, 0x62, 0xd2,
  854. 0xa8, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  855. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  856. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  857. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  858. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  859. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  860. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  861. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  862. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  863. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  864. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  865. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  866. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63,
  867. 0x35, 0x01, 0x05, 0x36, 0x04, 0x0a, 0x22, 0x10, 0x0a, 0x33, 0x04, 0x00, 0x00, 0x02, 0x56, 0x01,
  868. 0x04, 0xff, 0xff, 0xff, 0x00, 0x03, 0x04, 0x0a, 0x22, 0x10, 0x0a, 0xff, 0x00, 0x00, 0x00, 0x00,
  869. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  870. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  871. ];
  872. const IP_NULL: Ipv4Address = Ipv4Address([0, 0, 0, 0]);
  873. const CLIENT_MAC: EthernetAddress = EthernetAddress([0x0, 0x0b, 0x82, 0x01, 0xfc, 0x42]);
  874. const DHCP_SIZE: u16 = 1500;
  875. #[test]
  876. fn test_deconstruct_discover() {
  877. let packet = Packet::new_unchecked(DISCOVER_BYTES);
  878. assert_eq!(packet.magic_number(), MAGIC_COOKIE);
  879. assert_eq!(packet.opcode(), OpCode::Request);
  880. assert_eq!(packet.hardware_type(), Hardware::Ethernet);
  881. assert_eq!(packet.hardware_len(), 6);
  882. assert_eq!(packet.hops(), 0);
  883. assert_eq!(packet.transaction_id(), 0x3d1d);
  884. assert_eq!(packet.secs(), 0);
  885. assert_eq!(packet.client_ip(), IP_NULL);
  886. assert_eq!(packet.your_ip(), IP_NULL);
  887. assert_eq!(packet.server_ip(), IP_NULL);
  888. assert_eq!(packet.relay_agent_ip(), IP_NULL);
  889. assert_eq!(packet.client_hardware_address(), CLIENT_MAC);
  890. let options = packet.options().unwrap();
  891. assert_eq!(options.len(), 3 + 9 + 6 + 4 + 6 + 1 + 7);
  892. let (options, message_type) = DhcpOption::parse(options).unwrap();
  893. assert_eq!(message_type, DhcpOption::MessageType(MessageType::Discover));
  894. assert_eq!(options.len(), 9 + 6 + 4 + 6 + 1 + 7);
  895. let (options, client_id) = DhcpOption::parse(options).unwrap();
  896. assert_eq!(client_id, DhcpOption::ClientIdentifier(CLIENT_MAC));
  897. assert_eq!(options.len(), 6 + 4 + 6 + 1 + 7);
  898. let (options, client_id) = DhcpOption::parse(options).unwrap();
  899. assert_eq!(client_id, DhcpOption::RequestedIp(IP_NULL));
  900. assert_eq!(options.len(), 4 + 6 + 1 + 7);
  901. let (options, msg_size) = DhcpOption::parse(options).unwrap();
  902. assert_eq!(msg_size, DhcpOption::MaximumDhcpMessageSize(DHCP_SIZE));
  903. assert_eq!(options.len(), 6 + 1 + 7);
  904. let (options, client_id) = DhcpOption::parse(options).unwrap();
  905. assert_eq!(client_id, DhcpOption::Other {
  906. kind: field::OPT_PARAMETER_REQUEST_LIST, data: &[1, 3, 6, 42]
  907. });
  908. assert_eq!(options.len(), 1 + 7);
  909. let (options, client_id) = DhcpOption::parse(options).unwrap();
  910. assert_eq!(client_id, DhcpOption::EndOfList);
  911. assert_eq!(options.len(), 7); // padding
  912. }
  913. #[test]
  914. fn test_construct_discover() {
  915. let mut bytes = vec![0xa5; 276];
  916. let mut packet = Packet::new_unchecked(&mut bytes);
  917. packet.set_magic_number(MAGIC_COOKIE);
  918. packet.set_sname_and_boot_file_to_zero();
  919. packet.set_opcode(OpCode::Request);
  920. packet.set_hardware_type(Hardware::Ethernet);
  921. packet.set_hardware_len(6);
  922. packet.set_hops(0);
  923. packet.set_transaction_id(0x3d1d);
  924. packet.set_secs(0);
  925. packet.set_broadcast_flag(false);
  926. packet.set_client_ip(IP_NULL);
  927. packet.set_your_ip(IP_NULL);
  928. packet.set_server_ip(IP_NULL);
  929. packet.set_relay_agent_ip(IP_NULL);
  930. packet.set_client_hardware_address(CLIENT_MAC);
  931. {
  932. let mut options = packet.options_mut().unwrap();
  933. let tmp = options; options = DhcpOption::MessageType(MessageType::Discover).emit(tmp);
  934. let tmp = options; options = DhcpOption::ClientIdentifier(CLIENT_MAC).emit(tmp);
  935. let tmp = options; options = DhcpOption::RequestedIp(IP_NULL).emit(tmp);
  936. let tmp = options; options = DhcpOption::MaximumDhcpMessageSize(DHCP_SIZE).emit(tmp);
  937. let option = DhcpOption::Other {
  938. kind: field::OPT_PARAMETER_REQUEST_LIST, data: &[1, 3, 6, 42],
  939. };
  940. let tmp = options; options = option.emit(tmp);
  941. DhcpOption::EndOfList.emit(options);
  942. }
  943. let packet = &mut packet.into_inner()[..];
  944. for byte in &mut packet[269..276] {
  945. *byte = 0; // padding bytes
  946. }
  947. assert_eq!(packet, DISCOVER_BYTES);
  948. }
  949. fn offer_repr() -> Repr<'static> {
  950. Repr {
  951. message_type: MessageType::Offer,
  952. transaction_id: 0x3d1d,
  953. client_hardware_address: CLIENT_MAC,
  954. client_ip: IP_NULL,
  955. your_ip: IP_NULL,
  956. server_ip: IP_NULL,
  957. router: Some(IP_NULL),
  958. subnet_mask: Some(IP_NULL),
  959. relay_agent_ip: IP_NULL,
  960. broadcast: false,
  961. requested_ip: None,
  962. client_identifier: Some(CLIENT_MAC),
  963. server_identifier: None,
  964. parameter_request_list: None,
  965. dns_servers: None,
  966. max_size: None,
  967. lease_duration: Some(0xffff_ffff), // Infinite lease
  968. }
  969. }
  970. fn discover_repr() -> Repr<'static> {
  971. Repr {
  972. message_type: MessageType::Discover,
  973. transaction_id: 0x3d1d,
  974. client_hardware_address: CLIENT_MAC,
  975. client_ip: IP_NULL,
  976. your_ip: IP_NULL,
  977. server_ip: IP_NULL,
  978. router: None,
  979. subnet_mask: None,
  980. relay_agent_ip: IP_NULL,
  981. broadcast: false,
  982. max_size: Some(DHCP_SIZE),
  983. lease_duration: None,
  984. requested_ip: Some(IP_NULL),
  985. client_identifier: Some(CLIENT_MAC),
  986. server_identifier: None,
  987. parameter_request_list: Some(&[1, 3, 6, 42]),
  988. dns_servers: None,
  989. }
  990. }
  991. #[test]
  992. fn test_parse_discover() {
  993. let packet = Packet::new_unchecked(DISCOVER_BYTES);
  994. let repr = Repr::parse(&packet).unwrap();
  995. assert_eq!(repr, discover_repr());
  996. }
  997. #[test]
  998. fn test_emit_discover() {
  999. let repr = discover_repr();
  1000. let mut bytes = vec![0xa5; repr.buffer_len()];
  1001. let mut packet = Packet::new_unchecked(&mut bytes);
  1002. repr.emit(&mut packet).unwrap();
  1003. let packet = &packet.into_inner()[..];
  1004. let packet_len = packet.len();
  1005. assert_eq!(packet, &DISCOVER_BYTES[..packet_len]);
  1006. for byte in &DISCOVER_BYTES[packet_len..] {
  1007. assert_eq!(*byte, 0); // padding bytes
  1008. }
  1009. }
  1010. #[test]
  1011. fn test_emit_offer() {
  1012. let repr = offer_repr();
  1013. let mut bytes = vec![0xa5; repr.buffer_len()];
  1014. let mut packet = Packet::new_unchecked(&mut bytes);
  1015. repr.emit(&mut packet).unwrap();
  1016. }
  1017. #[test]
  1018. fn test_emit_offer_dns() {
  1019. let repr = {
  1020. let mut repr = offer_repr();
  1021. repr.dns_servers = Some([
  1022. Some(Ipv4Address([163, 1, 74, 6])),
  1023. Some(Ipv4Address([163, 1, 74, 7])),
  1024. Some(Ipv4Address([163, 1, 74, 3]))]);
  1025. repr
  1026. };
  1027. let mut bytes = vec![0xa5; repr.buffer_len()];
  1028. let mut packet = Packet::new_unchecked(&mut bytes);
  1029. repr.emit(&mut packet).unwrap();
  1030. let packet = Packet::new_unchecked(&bytes);
  1031. let repr_parsed = Repr::parse(&packet).unwrap();
  1032. assert_eq!(repr_parsed.dns_servers, Some([
  1033. Some(Ipv4Address([163, 1, 74, 6])),
  1034. Some(Ipv4Address([163, 1, 74, 7])),
  1035. Some(Ipv4Address([163, 1, 74, 3]))]));
  1036. }
  1037. #[test]
  1038. fn test_emit_dhcp_option() {
  1039. static DATA: &[u8] = &[1, 3, 6];
  1040. let mut bytes = vec![0xa5; 5];
  1041. let dhcp_option = DhcpOption::Other {
  1042. kind: field::OPT_PARAMETER_REQUEST_LIST,
  1043. data: DATA,
  1044. };
  1045. {
  1046. let rest = dhcp_option.emit(&mut bytes);
  1047. assert_eq!(rest.len(), 0);
  1048. }
  1049. assert_eq!(&bytes[0..2], &[field::OPT_PARAMETER_REQUEST_LIST, DATA.len() as u8]);
  1050. assert_eq!(&bytes[2..], DATA);
  1051. }
  1052. #[test]
  1053. fn test_parse_ack_dns_servers() {
  1054. let packet = Packet::new_unchecked(ACK_DNS_SERVER_BYTES);
  1055. let repr = Repr::parse(&packet).unwrap();
  1056. // The packet described by ACK_BYTES advertises 4 DNS servers
  1057. // Here we ensure that we correctly parse the first 3 into our fixed
  1058. // length-3 array (see issue #305)
  1059. assert_eq!(repr.dns_servers, Some([
  1060. Some(Ipv4Address([163, 1, 74, 6])),
  1061. Some(Ipv4Address([163, 1, 74, 7])),
  1062. Some(Ipv4Address([163, 1, 74, 3]))]));
  1063. }
  1064. #[test]
  1065. fn test_parse_ack_lease_duration() {
  1066. let packet = Packet::new_unchecked(ACK_LEASE_TIME_BYTES);
  1067. let repr = Repr::parse(&packet).unwrap();
  1068. // Verify that the lease time in the ACK is properly parsed. The packet contains a lease
  1069. // duration of 598s.
  1070. assert_eq!(repr.lease_duration, Some(598));
  1071. }
  1072. }