dhcpc.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * udhcp client
  4. *
  5. * Russ Dill <Russ.Dill@asu.edu> July 2001
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include <syslog.h>
  22. /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
  23. #define WANT_PIDFILE 1
  24. #include "common.h"
  25. #include "dhcpd.h"
  26. #include "dhcpc.h"
  27. #include <asm/types.h>
  28. #if (defined(__GLIBC__) && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1) || defined(_NEWLIB_VERSION)
  29. # include <netpacket/packet.h>
  30. # include <net/ethernet.h>
  31. #else
  32. # include <linux/if_packet.h>
  33. # include <linux/if_ether.h>
  34. #endif
  35. #include <linux/filter.h>
  36. /* struct client_config_t client_config is in bb_common_bufsiz1 */
  37. /*** Script execution code ***/
  38. /* get a rough idea of how long an option will be (rounding up...) */
  39. static const uint8_t len_of_option_as_string[] = {
  40. [OPTION_IP ] = sizeof("255.255.255.255 "),
  41. [OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
  42. [OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
  43. [OPTION_STRING ] = 1,
  44. #if ENABLE_FEATURE_UDHCP_RFC3397
  45. [OPTION_DNS_STRING ] = 1, /* unused */
  46. /* Hmmm, this severely overestimates size if SIP_SERVERS option
  47. * is in domain name form: N-byte option in binary form
  48. * mallocs ~16*N bytes. But it is freed almost at once.
  49. */
  50. [OPTION_SIP_SERVERS ] = sizeof("255.255.255.255 "),
  51. #endif
  52. // [OPTION_BOOLEAN ] = sizeof("yes "),
  53. [OPTION_U8 ] = sizeof("255 "),
  54. [OPTION_U16 ] = sizeof("65535 "),
  55. // [OPTION_S16 ] = sizeof("-32768 "),
  56. [OPTION_U32 ] = sizeof("4294967295 "),
  57. [OPTION_S32 ] = sizeof("-2147483684 "),
  58. };
  59. /* note: ip is a pointer to an IP in network order, possibly misaliged */
  60. static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
  61. {
  62. return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
  63. }
  64. /* really simple implementation, just count the bits */
  65. static int mton(uint32_t mask)
  66. {
  67. int i = 0;
  68. mask = ntohl(mask); /* 111110000-like bit pattern */
  69. while (mask) {
  70. i++;
  71. mask <<= 1;
  72. }
  73. return i;
  74. }
  75. /* Create "opt_name=opt_value" string */
  76. static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name)
  77. {
  78. unsigned upper_length;
  79. int len, type, optlen;
  80. char *dest, *ret;
  81. /* option points to OPT_DATA, need to go back and get OPT_LEN */
  82. len = option[OPT_LEN - OPT_DATA];
  83. type = optflag->flags & OPTION_TYPE_MASK;
  84. optlen = dhcp_option_lengths[type];
  85. upper_length = len_of_option_as_string[type] * ((unsigned)len / (unsigned)optlen);
  86. dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
  87. dest += sprintf(ret, "%s=", opt_name);
  88. while (len >= optlen) {
  89. switch (type) {
  90. case OPTION_IP_PAIR:
  91. dest += sprint_nip(dest, "", option);
  92. *dest++ = '/';
  93. option += 4;
  94. optlen = 4;
  95. case OPTION_IP:
  96. dest += sprint_nip(dest, "", option);
  97. // TODO: it can be a list only if (optflag->flags & OPTION_LIST).
  98. // Should we bail out/warn if we see multi-ip option which is
  99. // not allowed to be such? For example, DHCP_BROADCAST...
  100. break;
  101. // case OPTION_BOOLEAN:
  102. // dest += sprintf(dest, *option ? "yes" : "no");
  103. // break;
  104. case OPTION_U8:
  105. dest += sprintf(dest, "%u", *option);
  106. break;
  107. // case OPTION_S16:
  108. case OPTION_U16: {
  109. uint16_t val_u16;
  110. move_from_unaligned16(val_u16, option);
  111. dest += sprintf(dest, "%u", ntohs(val_u16));
  112. break;
  113. }
  114. case OPTION_S32:
  115. case OPTION_U32: {
  116. uint32_t val_u32;
  117. move_from_unaligned32(val_u32, option);
  118. dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32));
  119. break;
  120. }
  121. case OPTION_STRING:
  122. memcpy(dest, option, len);
  123. dest[len] = '\0';
  124. return ret; /* Short circuit this case */
  125. case OPTION_STATIC_ROUTES: {
  126. /* Option binary format:
  127. * mask [one byte, 0..32]
  128. * ip [big endian, 0..4 bytes depending on mask]
  129. * router [big endian, 4 bytes]
  130. * may be repeated
  131. *
  132. * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2"
  133. */
  134. const char *pfx = "";
  135. while (len >= 1 + 4) { /* mask + 0-byte ip + router */
  136. uint32_t nip;
  137. uint8_t *p;
  138. unsigned mask;
  139. int bytes;
  140. mask = *option++;
  141. if (mask > 32)
  142. break;
  143. len--;
  144. nip = 0;
  145. p = (void*) &nip;
  146. bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */
  147. while (--bytes >= 0) {
  148. *p++ = *option++;
  149. len--;
  150. }
  151. if (len < 4)
  152. break;
  153. /* print ip/mask */
  154. dest += sprint_nip(dest, pfx, (void*) &nip);
  155. pfx = " ";
  156. dest += sprintf(dest, "/%u ", mask);
  157. /* print router */
  158. dest += sprint_nip(dest, "", option);
  159. option += 4;
  160. len -= 4;
  161. }
  162. return ret;
  163. }
  164. #if ENABLE_FEATURE_UDHCP_RFC3397
  165. case OPTION_DNS_STRING:
  166. /* unpack option into dest; use ret for prefix (i.e., "optname=") */
  167. dest = dname_dec(option, len, ret);
  168. if (dest) {
  169. free(ret);
  170. return dest;
  171. }
  172. /* error. return "optname=" string */
  173. return ret;
  174. case OPTION_SIP_SERVERS:
  175. /* Option binary format:
  176. * type: byte
  177. * type=0: domain names, dns-compressed
  178. * type=1: IP addrs
  179. */
  180. option++;
  181. len--;
  182. if (option[-1] == 0) {
  183. dest = dname_dec(option, len, ret);
  184. if (dest) {
  185. free(ret);
  186. return dest;
  187. }
  188. } else
  189. if (option[-1] == 1) {
  190. const char *pfx = "";
  191. while (1) {
  192. len -= 4;
  193. if (len < 0)
  194. break;
  195. dest += sprint_nip(dest, pfx, option);
  196. pfx = " ";
  197. option += 4;
  198. }
  199. }
  200. return ret;
  201. #endif
  202. } /* switch */
  203. option += optlen;
  204. len -= optlen;
  205. if (len <= 0)
  206. break;
  207. *dest++ = ' ';
  208. *dest = '\0';
  209. }
  210. return ret;
  211. }
  212. /* put all the parameters into the environment */
  213. static char **fill_envp(struct dhcp_packet *packet)
  214. {
  215. int num_options = 0;
  216. int i;
  217. char **envp, **curr;
  218. const char *opt_name;
  219. uint8_t *temp;
  220. uint8_t over = 0;
  221. if (packet) {
  222. for (i = 0; dhcp_optflags[i].code; i++) {
  223. if (udhcp_get_option(packet, dhcp_optflags[i].code)) {
  224. num_options++;
  225. if (dhcp_optflags[i].code == DHCP_SUBNET)
  226. num_options++; /* for mton */
  227. }
  228. }
  229. if (packet->siaddr_nip)
  230. num_options++;
  231. temp = udhcp_get_option(packet, DHCP_OPTION_OVERLOAD);
  232. if (temp)
  233. over = *temp;
  234. if (!(over & FILE_FIELD) && packet->file[0])
  235. num_options++;
  236. if (!(over & SNAME_FIELD) && packet->sname[0])
  237. num_options++;
  238. }
  239. curr = envp = xzalloc(sizeof(char *) * (num_options + 3));
  240. *curr = xasprintf("interface=%s", client_config.interface);
  241. putenv(*curr++);
  242. if (packet == NULL)
  243. return envp;
  244. *curr = xmalloc(sizeof("ip=255.255.255.255"));
  245. sprint_nip(*curr, "ip=", (uint8_t *) &packet->yiaddr);
  246. putenv(*curr++);
  247. opt_name = dhcp_option_strings;
  248. i = 0;
  249. while (*opt_name) {
  250. temp = udhcp_get_option(packet, dhcp_optflags[i].code);
  251. if (!temp)
  252. goto next;
  253. *curr = xmalloc_optname_optval(temp, &dhcp_optflags[i], opt_name);
  254. putenv(*curr++);
  255. /* Fill in a subnet bits option for things like /24 */
  256. if (dhcp_optflags[i].code == DHCP_SUBNET) {
  257. uint32_t subnet;
  258. move_from_unaligned32(subnet, temp);
  259. *curr = xasprintf("mask=%d", mton(subnet));
  260. putenv(*curr++);
  261. }
  262. next:
  263. opt_name += strlen(opt_name) + 1;
  264. i++;
  265. }
  266. if (packet->siaddr_nip) {
  267. *curr = xmalloc(sizeof("siaddr=255.255.255.255"));
  268. sprint_nip(*curr, "siaddr=", (uint8_t *) &packet->siaddr_nip);
  269. putenv(*curr++);
  270. }
  271. if (!(over & FILE_FIELD) && packet->file[0]) {
  272. /* watch out for invalid packets */
  273. *curr = xasprintf("boot_file=%."DHCP_PKT_FILE_LEN_STR"s", packet->file);
  274. putenv(*curr++);
  275. }
  276. if (!(over & SNAME_FIELD) && packet->sname[0]) {
  277. /* watch out for invalid packets */
  278. *curr = xasprintf("sname=%."DHCP_PKT_SNAME_LEN_STR"s", packet->sname);
  279. putenv(*curr++);
  280. }
  281. return envp;
  282. }
  283. /* Call a script with a par file and env vars */
  284. static void udhcp_run_script(struct dhcp_packet *packet, const char *name)
  285. {
  286. char **envp, **curr;
  287. char *argv[3];
  288. if (client_config.script == NULL)
  289. return;
  290. envp = fill_envp(packet);
  291. /* call script */
  292. log1("Executing %s %s", client_config.script, name);
  293. argv[0] = (char*) client_config.script;
  294. argv[1] = (char*) name;
  295. argv[2] = NULL;
  296. spawn_and_wait(argv);
  297. for (curr = envp; *curr; curr++) {
  298. log2(" %s", *curr);
  299. bb_unsetenv(*curr);
  300. free(*curr);
  301. }
  302. free(envp);
  303. }
  304. /*** Sending/receiving packets ***/
  305. static ALWAYS_INLINE uint32_t random_xid(void)
  306. {
  307. return rand();
  308. }
  309. /* Initialize the packet with the proper defaults */
  310. static void init_packet(struct dhcp_packet *packet, char type)
  311. {
  312. udhcp_init_header(packet, type);
  313. memcpy(packet->chaddr, client_config.client_mac, 6);
  314. if (client_config.clientid)
  315. udhcp_add_binary_option(packet, client_config.clientid);
  316. if (client_config.hostname)
  317. udhcp_add_binary_option(packet, client_config.hostname);
  318. if (client_config.fqdn)
  319. udhcp_add_binary_option(packet, client_config.fqdn);
  320. if (type != DHCPDECLINE
  321. && type != DHCPRELEASE
  322. && client_config.vendorclass
  323. ) {
  324. udhcp_add_binary_option(packet, client_config.vendorclass);
  325. }
  326. }
  327. static void add_client_options(struct dhcp_packet *packet)
  328. {
  329. /* Add a "param req" option with the list of options we'd like to have
  330. * from stubborn DHCP servers. Pull the data from the struct in common.c.
  331. * No bounds checking because it goes towards the head of the packet. */
  332. uint8_t c;
  333. int end = udhcp_end_option(packet->options);
  334. int i, len = 0;
  335. for (i = 0; (c = dhcp_optflags[i].code) != 0; i++) {
  336. if (( (dhcp_optflags[i].flags & OPTION_REQ)
  337. && !client_config.no_default_options
  338. )
  339. || (client_config.opt_mask[c >> 3] & (1 << (c & 7)))
  340. ) {
  341. packet->options[end + OPT_DATA + len] = c;
  342. len++;
  343. }
  344. }
  345. if (len) {
  346. packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
  347. packet->options[end + OPT_LEN] = len;
  348. packet->options[end + OPT_DATA + len] = DHCP_END;
  349. }
  350. /* Add -x options if any */
  351. {
  352. struct option_set *curr = client_config.options;
  353. while (curr) {
  354. udhcp_add_binary_option(packet, curr->data);
  355. curr = curr->next;
  356. }
  357. // if (client_config.sname)
  358. // strncpy((char*)packet->sname, client_config.sname, sizeof(packet->sname) - 1);
  359. // if (client_config.boot_file)
  360. // strncpy((char*)packet->file, client_config.boot_file, sizeof(packet->file) - 1);
  361. }
  362. }
  363. /* RFC 2131
  364. * 4.4.4 Use of broadcast and unicast
  365. *
  366. * The DHCP client broadcasts DHCPDISCOVER, DHCPREQUEST and DHCPINFORM
  367. * messages, unless the client knows the address of a DHCP server.
  368. * The client unicasts DHCPRELEASE messages to the server. Because
  369. * the client is declining the use of the IP address supplied by the server,
  370. * the client broadcasts DHCPDECLINE messages.
  371. *
  372. * When the DHCP client knows the address of a DHCP server, in either
  373. * INIT or REBOOTING state, the client may use that address
  374. * in the DHCPDISCOVER or DHCPREQUEST rather than the IP broadcast address.
  375. * The client may also use unicast to send DHCPINFORM messages
  376. * to a known DHCP server. If the client receives no response to DHCP
  377. * messages sent to the IP address of a known DHCP server, the DHCP
  378. * client reverts to using the IP broadcast address.
  379. */
  380. static int raw_bcast_from_client_config_ifindex(struct dhcp_packet *packet)
  381. {
  382. return udhcp_send_raw_packet(packet,
  383. /*src*/ INADDR_ANY, CLIENT_PORT,
  384. /*dst*/ INADDR_BROADCAST, SERVER_PORT, MAC_BCAST_ADDR,
  385. client_config.ifindex);
  386. }
  387. /* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
  388. static int send_discover(uint32_t xid, uint32_t requested)
  389. {
  390. struct dhcp_packet packet;
  391. init_packet(&packet, DHCPDISCOVER);
  392. packet.xid = xid;
  393. if (requested)
  394. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  395. /* Explicitly saying that we want RFC-compliant packets helps
  396. * some buggy DHCP servers to NOT send bigger packets */
  397. udhcp_add_simple_option(&packet, DHCP_MAX_SIZE, htons(576));
  398. add_client_options(&packet);
  399. bb_info_msg("Sending discover...");
  400. return raw_bcast_from_client_config_ifindex(&packet);
  401. }
  402. /* Broadcast a DHCP request message */
  403. /* RFC 2131 3.1 paragraph 3:
  404. * "The client _broadcasts_ a DHCPREQUEST message..."
  405. */
  406. static int send_select(uint32_t xid, uint32_t server, uint32_t requested)
  407. {
  408. struct dhcp_packet packet;
  409. struct in_addr addr;
  410. init_packet(&packet, DHCPREQUEST);
  411. packet.xid = xid;
  412. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  413. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  414. add_client_options(&packet);
  415. addr.s_addr = requested;
  416. bb_info_msg("Sending select for %s...", inet_ntoa(addr));
  417. return raw_bcast_from_client_config_ifindex(&packet);
  418. }
  419. /* Unicast or broadcast a DHCP renew message */
  420. static int send_renew(uint32_t xid, uint32_t server, uint32_t ciaddr)
  421. {
  422. struct dhcp_packet packet;
  423. init_packet(&packet, DHCPREQUEST);
  424. packet.xid = xid;
  425. packet.ciaddr = ciaddr;
  426. add_client_options(&packet);
  427. bb_info_msg("Sending renew...");
  428. if (server)
  429. return udhcp_send_kernel_packet(&packet,
  430. ciaddr, CLIENT_PORT,
  431. server, SERVER_PORT);
  432. return raw_bcast_from_client_config_ifindex(&packet);
  433. }
  434. #if ENABLE_FEATURE_UDHCPC_ARPING
  435. /* Broadcast a DHCP decline message */
  436. static int send_decline(uint32_t xid, uint32_t server, uint32_t requested)
  437. {
  438. struct dhcp_packet packet;
  439. init_packet(&packet, DHCPDECLINE);
  440. packet.xid = xid;
  441. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  442. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  443. bb_info_msg("Sending decline...");
  444. return raw_bcast_from_client_config_ifindex(&packet);
  445. }
  446. #endif
  447. /* Unicast a DHCP release message */
  448. static int send_release(uint32_t server, uint32_t ciaddr)
  449. {
  450. struct dhcp_packet packet;
  451. init_packet(&packet, DHCPRELEASE);
  452. packet.xid = random_xid();
  453. packet.ciaddr = ciaddr;
  454. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  455. bb_info_msg("Sending release...");
  456. return udhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
  457. }
  458. /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
  459. static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
  460. {
  461. int bytes;
  462. struct ip_udp_dhcp_packet packet;
  463. uint16_t check;
  464. memset(&packet, 0, sizeof(packet));
  465. bytes = safe_read(fd, &packet, sizeof(packet));
  466. if (bytes < 0) {
  467. log1("Packet read error, ignoring");
  468. /* NB: possible down interface, etc. Caller should pause. */
  469. return bytes; /* returns -1 */
  470. }
  471. if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp))) {
  472. log1("Packet is too short, ignoring");
  473. return -2;
  474. }
  475. if (bytes < ntohs(packet.ip.tot_len)) {
  476. /* packet is bigger than sizeof(packet), we did partial read */
  477. log1("Oversized packet, ignoring");
  478. return -2;
  479. }
  480. /* ignore any extra garbage bytes */
  481. bytes = ntohs(packet.ip.tot_len);
  482. /* make sure its the right packet for us, and that it passes sanity checks */
  483. if (packet.ip.protocol != IPPROTO_UDP || packet.ip.version != IPVERSION
  484. || packet.ip.ihl != (sizeof(packet.ip) >> 2)
  485. || packet.udp.dest != htons(CLIENT_PORT)
  486. /* || bytes > (int) sizeof(packet) - can't happen */
  487. || ntohs(packet.udp.len) != (uint16_t)(bytes - sizeof(packet.ip))
  488. ) {
  489. log1("Unrelated/bogus packet, ignoring");
  490. return -2;
  491. }
  492. /* verify IP checksum */
  493. check = packet.ip.check;
  494. packet.ip.check = 0;
  495. if (check != udhcp_checksum(&packet.ip, sizeof(packet.ip))) {
  496. log1("Bad IP header checksum, ignoring");
  497. return -2;
  498. }
  499. /* verify UDP checksum. IP header has to be modified for this */
  500. memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
  501. /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
  502. packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
  503. check = packet.udp.check;
  504. packet.udp.check = 0;
  505. if (check && check != udhcp_checksum(&packet, bytes)) {
  506. log1("Packet with bad UDP checksum received, ignoring");
  507. return -2;
  508. }
  509. memcpy(dhcp_pkt, &packet.data, bytes - (sizeof(packet.ip) + sizeof(packet.udp)));
  510. if (dhcp_pkt->cookie != htonl(DHCP_MAGIC)) {
  511. bb_info_msg("Packet with bad magic, ignoring");
  512. return -2;
  513. }
  514. log1("Got valid DHCP packet");
  515. udhcp_dump_packet(dhcp_pkt);
  516. return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
  517. }
  518. /*** Main ***/
  519. static int sockfd = -1;
  520. #define LISTEN_NONE 0
  521. #define LISTEN_KERNEL 1
  522. #define LISTEN_RAW 2
  523. static smallint listen_mode;
  524. /* initial state: (re)start DHCP negotiation */
  525. #define INIT_SELECTING 0
  526. /* discover was sent, DHCPOFFER reply received */
  527. #define REQUESTING 1
  528. /* select/renew was sent, DHCPACK reply received */
  529. #define BOUND 2
  530. /* half of lease passed, want to renew it by sending unicast renew requests */
  531. #define RENEWING 3
  532. /* renew requests were not answered, lease is almost over, send broadcast renew */
  533. #define REBINDING 4
  534. /* manually requested renew (SIGUSR1) */
  535. #define RENEW_REQUESTED 5
  536. /* release, possibly manually requested (SIGUSR2) */
  537. #define RELEASED 6
  538. static smallint state;
  539. static int udhcp_raw_socket(int ifindex)
  540. {
  541. int fd;
  542. struct sockaddr_ll sock;
  543. /*
  544. * Comment:
  545. *
  546. * I've selected not to see LL header, so BPF doesn't see it, too.
  547. * The filter may also pass non-IP and non-ARP packets, but we do
  548. * a more complete check when receiving the message in userspace.
  549. *
  550. * and filter shamelessly stolen from:
  551. *
  552. * http://www.flamewarmaster.de/software/dhcpclient/
  553. *
  554. * There are a few other interesting ideas on that page (look under
  555. * "Motivation"). Use of netlink events is most interesting. Think
  556. * of various network servers listening for events and reconfiguring.
  557. * That would obsolete sending HUP signals and/or make use of restarts.
  558. *
  559. * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
  560. * License: GPL v2.
  561. *
  562. * TODO: make conditional?
  563. */
  564. #define SERVER_AND_CLIENT_PORTS ((67 << 16) + 68)
  565. static const struct sock_filter filter_instr[] = {
  566. /* check for udp */
  567. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
  568. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 2, 0), /* L5, L1, is UDP? */
  569. /* ugly check for arp on ethernet-like and IPv4 */
  570. BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), /* L1: */
  571. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x08000604, 3, 4), /* L3, L4 */
  572. /* skip IP header */
  573. BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* L5: */
  574. /* check udp source and destination ports */
  575. BPF_STMT(BPF_LD|BPF_W|BPF_IND, 0),
  576. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, SERVER_AND_CLIENT_PORTS, 0, 1), /* L3, L4 */
  577. /* returns */
  578. BPF_STMT(BPF_RET|BPF_K, 0x0fffffff ), /* L3: pass */
  579. BPF_STMT(BPF_RET|BPF_K, 0), /* L4: reject */
  580. };
  581. static const struct sock_fprog filter_prog = {
  582. .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
  583. /* casting const away: */
  584. .filter = (struct sock_filter *) filter_instr,
  585. };
  586. log1("Opening raw socket on ifindex %d", ifindex); //log2?
  587. fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
  588. log1("Got raw socket fd %d", fd); //log2?
  589. if (SERVER_PORT == 67 && CLIENT_PORT == 68) {
  590. /* Use only if standard ports are in use */
  591. /* Ignoring error (kernel may lack support for this) */
  592. if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
  593. sizeof(filter_prog)) >= 0)
  594. log1("Attached filter to raw socket fd %d", fd); // log?
  595. }
  596. sock.sll_family = AF_PACKET;
  597. sock.sll_protocol = htons(ETH_P_IP);
  598. sock.sll_ifindex = ifindex;
  599. xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
  600. log1("Created raw socket");
  601. return fd;
  602. }
  603. static void change_listen_mode(int new_mode)
  604. {
  605. log1("Entering listen mode: %s",
  606. new_mode != LISTEN_NONE
  607. ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
  608. : "none"
  609. );
  610. listen_mode = new_mode;
  611. if (sockfd >= 0) {
  612. close(sockfd);
  613. sockfd = -1;
  614. }
  615. if (new_mode == LISTEN_KERNEL)
  616. sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
  617. else if (new_mode != LISTEN_NONE)
  618. sockfd = udhcp_raw_socket(client_config.ifindex);
  619. /* else LISTEN_NONE: sockfd stays closed */
  620. }
  621. static void perform_renew(void)
  622. {
  623. bb_info_msg("Performing a DHCP renew");
  624. switch (state) {
  625. case BOUND:
  626. change_listen_mode(LISTEN_KERNEL);
  627. case RENEWING:
  628. case REBINDING:
  629. state = RENEW_REQUESTED;
  630. break;
  631. case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
  632. udhcp_run_script(NULL, "deconfig");
  633. case REQUESTING:
  634. case RELEASED:
  635. change_listen_mode(LISTEN_RAW);
  636. state = INIT_SELECTING;
  637. break;
  638. case INIT_SELECTING:
  639. break;
  640. }
  641. }
  642. static void perform_release(uint32_t requested_ip, uint32_t server_addr)
  643. {
  644. char buffer[sizeof("255.255.255.255")];
  645. struct in_addr temp_addr;
  646. /* send release packet */
  647. if (state == BOUND || state == RENEWING || state == REBINDING) {
  648. temp_addr.s_addr = server_addr;
  649. strcpy(buffer, inet_ntoa(temp_addr));
  650. temp_addr.s_addr = requested_ip;
  651. bb_info_msg("Unicasting a release of %s to %s",
  652. inet_ntoa(temp_addr), buffer);
  653. send_release(server_addr, requested_ip); /* unicast */
  654. udhcp_run_script(NULL, "deconfig");
  655. }
  656. bb_info_msg("Entering released state");
  657. change_listen_mode(LISTEN_NONE);
  658. state = RELEASED;
  659. }
  660. static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
  661. {
  662. uint8_t *storage;
  663. int len = strnlen(str, 255);
  664. storage = xzalloc(len + extra + OPT_DATA);
  665. storage[OPT_CODE] = code;
  666. storage[OPT_LEN] = len + extra;
  667. memcpy(storage + extra + OPT_DATA, str, len);
  668. return storage;
  669. }
  670. #if BB_MMU
  671. static void client_background(void)
  672. {
  673. bb_daemonize(0);
  674. logmode &= ~LOGMODE_STDIO;
  675. /* rewrite pidfile, as our pid is different now */
  676. write_pidfile(client_config.pidfile);
  677. }
  678. #endif
  679. int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  680. int udhcpc_main(int argc UNUSED_PARAM, char **argv)
  681. {
  682. uint8_t *temp, *message;
  683. const char *str_c, *str_V, *str_h, *str_F, *str_r;
  684. IF_FEATURE_UDHCP_PORT(char *str_P;)
  685. llist_t *list_O = NULL;
  686. llist_t *list_x = NULL;
  687. int tryagain_timeout = 20;
  688. int discover_timeout = 3;
  689. int discover_retries = 3;
  690. uint32_t server_addr = server_addr; /* for compiler */
  691. uint32_t requested_ip = 0;
  692. uint32_t xid = 0;
  693. uint32_t lease_seconds = 0; /* can be given as 32-bit quantity */
  694. int packet_num;
  695. int timeout; /* must be signed */
  696. unsigned already_waited_sec;
  697. unsigned opt;
  698. int max_fd;
  699. int retval;
  700. struct timeval tv;
  701. struct dhcp_packet packet;
  702. fd_set rfds;
  703. #if ENABLE_LONG_OPTS
  704. static const char udhcpc_longopts[] ALIGN1 =
  705. "clientid\0" Required_argument "c"
  706. "clientid-none\0" No_argument "C"
  707. "vendorclass\0" Required_argument "V"
  708. "hostname\0" Required_argument "H"
  709. "fqdn\0" Required_argument "F"
  710. "interface\0" Required_argument "i"
  711. "now\0" No_argument "n"
  712. "pidfile\0" Required_argument "p"
  713. "quit\0" No_argument "q"
  714. "release\0" No_argument "R"
  715. "request\0" Required_argument "r"
  716. "script\0" Required_argument "s"
  717. "timeout\0" Required_argument "T"
  718. "version\0" No_argument "v"
  719. "retries\0" Required_argument "t"
  720. "tryagain\0" Required_argument "A"
  721. "syslog\0" No_argument "S"
  722. "request-option\0" Required_argument "O"
  723. "no-default-options\0" No_argument "o"
  724. "foreground\0" No_argument "f"
  725. "background\0" No_argument "b"
  726. IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
  727. IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
  728. ;
  729. #endif
  730. enum {
  731. OPT_c = 1 << 0,
  732. OPT_C = 1 << 1,
  733. OPT_V = 1 << 2,
  734. OPT_H = 1 << 3,
  735. OPT_h = 1 << 4,
  736. OPT_F = 1 << 5,
  737. OPT_i = 1 << 6,
  738. OPT_n = 1 << 7,
  739. OPT_p = 1 << 8,
  740. OPT_q = 1 << 9,
  741. OPT_R = 1 << 10,
  742. OPT_r = 1 << 11,
  743. OPT_s = 1 << 12,
  744. OPT_T = 1 << 13,
  745. OPT_t = 1 << 14,
  746. OPT_S = 1 << 15,
  747. OPT_A = 1 << 16,
  748. OPT_O = 1 << 17,
  749. OPT_o = 1 << 18,
  750. OPT_x = 1 << 19,
  751. OPT_f = 1 << 20,
  752. /* The rest has variable bit positions, need to be clever */
  753. OPTBIT_f = 20,
  754. USE_FOR_MMU( OPTBIT_b,)
  755. IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
  756. IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
  757. USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
  758. IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
  759. IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
  760. };
  761. /* Default options. */
  762. IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
  763. IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
  764. client_config.interface = "eth0";
  765. client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  766. str_V = "udhcp "BB_VER;
  767. /* Parse command line */
  768. /* Cc: mutually exclusive; O,x: list; -T,-t,-A take numeric param */
  769. opt_complementary = "c--C:C--c:O::x::T+:t+:A+"
  770. #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  771. ":vv"
  772. #endif
  773. ;
  774. IF_LONG_OPTS(applet_long_options = udhcpc_longopts;)
  775. opt = getopt32(argv, "c:CV:H:h:F:i:np:qRr:s:T:t:SA:O:ox:f"
  776. USE_FOR_MMU("b")
  777. IF_FEATURE_UDHCPC_ARPING("a")
  778. IF_FEATURE_UDHCP_PORT("P:")
  779. "v"
  780. , &str_c, &str_V, &str_h, &str_h, &str_F
  781. , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
  782. , &client_config.script /* s */
  783. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  784. , &list_O
  785. , &list_x
  786. IF_FEATURE_UDHCP_PORT(, &str_P)
  787. #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  788. , &dhcp_verbose
  789. #endif
  790. );
  791. if (opt & (OPT_h|OPT_H))
  792. client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
  793. if (opt & OPT_F) {
  794. /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
  795. client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
  796. /* Flag bits: 0000NEOS
  797. * S: 1 = Client requests server to update A RR in DNS as well as PTR
  798. * O: 1 = Server indicates to client that DNS has been updated regardless
  799. * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
  800. * not "host.domain.com". Format 0 is obsolete.
  801. * N: 1 = Client requests server to not update DNS (S must be 0 then)
  802. * Two [0] bytes which follow are deprecated and must be 0.
  803. */
  804. client_config.fqdn[OPT_DATA + 0] = 0x1;
  805. /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
  806. /*client_config.fqdn[OPT_DATA + 2] = 0; */
  807. }
  808. if (opt & OPT_r)
  809. requested_ip = inet_addr(str_r);
  810. #if ENABLE_FEATURE_UDHCP_PORT
  811. if (opt & OPT_P) {
  812. CLIENT_PORT = xatou16(str_P);
  813. SERVER_PORT = CLIENT_PORT - 1;
  814. }
  815. #endif
  816. if (opt & OPT_o)
  817. client_config.no_default_options = 1;
  818. while (list_O) {
  819. char *optstr = llist_pop(&list_O);
  820. unsigned n = udhcp_option_idx(optstr);
  821. n = dhcp_optflags[n].code;
  822. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  823. }
  824. while (list_x) {
  825. char *optstr = llist_pop(&list_x);
  826. char *colon = strchr(optstr, ':');
  827. if (colon)
  828. *colon = ' ';
  829. /* now it looks similar to udhcpd's config file line:
  830. * "optname optval", using the common routine: */
  831. udhcp_str2optset(optstr, &client_config.options);
  832. }
  833. if (udhcp_read_interface(client_config.interface,
  834. &client_config.ifindex,
  835. NULL,
  836. client_config.client_mac)
  837. ) {
  838. return 1;
  839. }
  840. if (opt & OPT_c) {
  841. client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, str_c, 0);
  842. } else if (!(opt & OPT_C)) {
  843. /* not set and not suppressed, set the default client ID */
  844. client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
  845. client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
  846. memcpy(client_config.clientid + OPT_DATA+1, client_config.client_mac, 6);
  847. }
  848. if (str_V[0] != '\0')
  849. client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
  850. #if !BB_MMU
  851. /* on NOMMU reexec (i.e., background) early */
  852. if (!(opt & OPT_f)) {
  853. bb_daemonize_or_rexec(0 /* flags */, argv);
  854. logmode = LOGMODE_NONE;
  855. }
  856. #endif
  857. if (opt & OPT_S) {
  858. openlog(applet_name, LOG_PID, LOG_DAEMON);
  859. logmode |= LOGMODE_SYSLOG;
  860. }
  861. /* Make sure fd 0,1,2 are open */
  862. bb_sanitize_stdio();
  863. /* Equivalent of doing a fflush after every \n */
  864. setlinebuf(stdout);
  865. /* Create pidfile */
  866. write_pidfile(client_config.pidfile);
  867. /* Goes to stdout (unless NOMMU) and possibly syslog */
  868. bb_info_msg("%s (v"BB_VER") started", applet_name);
  869. /* Set up the signal pipe */
  870. udhcp_sp_setup();
  871. /* We want random_xid to be random... */
  872. srand(monotonic_us());
  873. state = INIT_SELECTING;
  874. udhcp_run_script(NULL, "deconfig");
  875. change_listen_mode(LISTEN_RAW);
  876. packet_num = 0;
  877. timeout = 0;
  878. already_waited_sec = 0;
  879. /* Main event loop. select() waits on signal pipe and possibly
  880. * on sockfd.
  881. * "continue" statements in code below jump to the top of the loop.
  882. */
  883. for (;;) {
  884. /* silence "uninitialized!" warning */
  885. unsigned timestamp_before_wait = timestamp_before_wait;
  886. //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
  887. /* Was opening raw or udp socket here
  888. * if (listen_mode != LISTEN_NONE && sockfd < 0),
  889. * but on fast network renew responses return faster
  890. * than we open sockets. Thus this code is moved
  891. * to change_listen_mode(). Thus we open listen socket
  892. * BEFORE we send renew request (see "case BOUND:"). */
  893. max_fd = udhcp_sp_fd_set(&rfds, sockfd);
  894. tv.tv_sec = timeout - already_waited_sec;
  895. tv.tv_usec = 0;
  896. retval = 0;
  897. /* If we already timed out, fall through with retval = 0, else... */
  898. if ((int)tv.tv_sec > 0) {
  899. timestamp_before_wait = (unsigned)monotonic_sec();
  900. log1("Waiting on select...");
  901. retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
  902. if (retval < 0) {
  903. /* EINTR? A signal was caught, don't panic */
  904. if (errno == EINTR) {
  905. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  906. continue;
  907. }
  908. /* Else: an error occured, panic! */
  909. bb_perror_msg_and_die("select");
  910. }
  911. }
  912. /* If timeout dropped to zero, time to become active:
  913. * resend discover/renew/whatever
  914. */
  915. if (retval == 0) {
  916. /* We will restart the wait in any case */
  917. already_waited_sec = 0;
  918. switch (state) {
  919. case INIT_SELECTING:
  920. if (packet_num < discover_retries) {
  921. if (packet_num == 0)
  922. xid = random_xid();
  923. /* broadcast */
  924. send_discover(xid, requested_ip);
  925. timeout = discover_timeout;
  926. packet_num++;
  927. continue;
  928. }
  929. leasefail:
  930. udhcp_run_script(NULL, "leasefail");
  931. #if BB_MMU /* -b is not supported on NOMMU */
  932. if (opt & OPT_b) { /* background if no lease */
  933. bb_info_msg("No lease, forking to background");
  934. client_background();
  935. /* do not background again! */
  936. opt = ((opt & ~OPT_b) | OPT_f);
  937. } else
  938. #endif
  939. if (opt & OPT_n) { /* abort if no lease */
  940. bb_info_msg("No lease, failing");
  941. retval = 1;
  942. goto ret;
  943. }
  944. /* wait before trying again */
  945. timeout = tryagain_timeout;
  946. packet_num = 0;
  947. continue;
  948. case REQUESTING:
  949. if (packet_num < discover_retries) {
  950. /* send broadcast select packet */
  951. send_select(xid, server_addr, requested_ip);
  952. timeout = discover_timeout;
  953. packet_num++;
  954. continue;
  955. }
  956. /* Timed out, go back to init state.
  957. * "discover...select...discover..." loops
  958. * were seen in the wild. Treat them similarly
  959. * to "no response to discover" case */
  960. change_listen_mode(LISTEN_RAW);
  961. state = INIT_SELECTING;
  962. goto leasefail;
  963. case BOUND:
  964. /* 1/2 lease passed, enter renewing state */
  965. state = RENEWING;
  966. change_listen_mode(LISTEN_KERNEL);
  967. log1("Entering renew state");
  968. /* fall right through */
  969. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  970. case_RENEW_REQUESTED:
  971. case RENEWING:
  972. if (timeout > 60) {
  973. /* send an unicast renew request */
  974. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  975. * a new UDP socket for sending inside send_renew.
  976. * I hazard to guess existing listening socket
  977. * is somehow conflicting with it, but why is it
  978. * not deterministic then?! Strange.
  979. * Anyway, it does recover by eventually failing through
  980. * into INIT_SELECTING state.
  981. */
  982. send_renew(xid, server_addr, requested_ip);
  983. timeout >>= 1;
  984. continue;
  985. }
  986. /* Timed out, enter rebinding state */
  987. log1("Entering rebinding state");
  988. state = REBINDING;
  989. /* fall right through */
  990. case REBINDING:
  991. /* Switch to bcast receive */
  992. change_listen_mode(LISTEN_RAW);
  993. /* Lease is *really* about to run out,
  994. * try to find DHCP server using broadcast */
  995. if (timeout > 0) {
  996. /* send a broadcast renew request */
  997. send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
  998. timeout >>= 1;
  999. continue;
  1000. }
  1001. /* Timed out, enter init state */
  1002. bb_info_msg("Lease lost, entering init state");
  1003. udhcp_run_script(NULL, "deconfig");
  1004. state = INIT_SELECTING;
  1005. /*timeout = 0; - already is */
  1006. packet_num = 0;
  1007. continue;
  1008. /* case RELEASED: */
  1009. }
  1010. /* yah, I know, *you* say it would never happen */
  1011. timeout = INT_MAX;
  1012. continue; /* back to main loop */
  1013. } /* if select timed out */
  1014. /* select() didn't timeout, something happened */
  1015. /* Is it a signal? */
  1016. /* note: udhcp_sp_read checks FD_ISSET before reading */
  1017. switch (udhcp_sp_read(&rfds)) {
  1018. case SIGUSR1:
  1019. perform_renew();
  1020. if (state == RENEW_REQUESTED)
  1021. goto case_RENEW_REQUESTED;
  1022. /* Start things over */
  1023. packet_num = 0;
  1024. /* Kill any timeouts, user wants this to hurry along */
  1025. timeout = 0;
  1026. continue;
  1027. case SIGUSR2:
  1028. perform_release(requested_ip, server_addr);
  1029. timeout = INT_MAX;
  1030. continue;
  1031. case SIGTERM:
  1032. bb_info_msg("Received SIGTERM");
  1033. if (opt & OPT_R) /* release on quit */
  1034. perform_release(requested_ip, server_addr);
  1035. goto ret0;
  1036. }
  1037. /* Is it a packet? */
  1038. if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
  1039. continue; /* no */
  1040. {
  1041. int len;
  1042. /* A packet is ready, read it */
  1043. if (listen_mode == LISTEN_KERNEL)
  1044. len = udhcp_recv_kernel_packet(&packet, sockfd);
  1045. else
  1046. len = udhcp_recv_raw_packet(&packet, sockfd);
  1047. if (len == -1) {
  1048. /* Error is severe, reopen socket */
  1049. bb_info_msg("Read error: %s, reopening socket", strerror(errno));
  1050. sleep(discover_timeout); /* 3 seconds by default */
  1051. change_listen_mode(listen_mode); /* just close and reopen */
  1052. }
  1053. /* If this packet will turn out to be unrelated/bogus,
  1054. * we will go back and wait for next one.
  1055. * Be sure timeout is properly decreased. */
  1056. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1057. if (len < 0)
  1058. continue;
  1059. }
  1060. if (packet.xid != xid) {
  1061. log1("xid %x (our is %x), ignoring packet",
  1062. (unsigned)packet.xid, (unsigned)xid);
  1063. continue;
  1064. }
  1065. /* Ignore packets that aren't for us */
  1066. if (packet.hlen != 6
  1067. || memcmp(packet.chaddr, client_config.client_mac, 6)
  1068. ) {
  1069. //FIXME: need to also check that last 10 bytes are zero
  1070. log1("chaddr does not match, ignoring packet"); // log2?
  1071. continue;
  1072. }
  1073. message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
  1074. if (message == NULL) {
  1075. bb_error_msg("no message type option, ignoring packet");
  1076. continue;
  1077. }
  1078. switch (state) {
  1079. case INIT_SELECTING:
  1080. /* Must be a DHCPOFFER to one of our xid's */
  1081. if (*message == DHCPOFFER) {
  1082. /* TODO: why we don't just fetch server's IP from IP header? */
  1083. temp = udhcp_get_option(&packet, DHCP_SERVER_ID);
  1084. if (!temp) {
  1085. bb_error_msg("no server ID in message");
  1086. continue;
  1087. /* still selecting - this server looks bad */
  1088. }
  1089. /* it IS unaligned sometimes, don't "optimize" */
  1090. move_from_unaligned32(server_addr, temp);
  1091. xid = packet.xid;
  1092. requested_ip = packet.yiaddr;
  1093. /* enter requesting state */
  1094. state = REQUESTING;
  1095. timeout = 0;
  1096. packet_num = 0;
  1097. already_waited_sec = 0;
  1098. }
  1099. continue;
  1100. case REQUESTING:
  1101. case RENEWING:
  1102. case RENEW_REQUESTED:
  1103. case REBINDING:
  1104. if (*message == DHCPACK) {
  1105. temp = udhcp_get_option(&packet, DHCP_LEASE_TIME);
  1106. if (!temp) {
  1107. bb_error_msg("no lease time with ACK, using 1 hour lease");
  1108. lease_seconds = 60 * 60;
  1109. } else {
  1110. /* it IS unaligned sometimes, don't "optimize" */
  1111. move_from_unaligned32(lease_seconds, temp);
  1112. lease_seconds = ntohl(lease_seconds);
  1113. lease_seconds &= 0x0fffffff; /* paranoia: must not be prone to overflows */
  1114. if (lease_seconds < 10) /* and not too small */
  1115. lease_seconds = 10;
  1116. }
  1117. #if ENABLE_FEATURE_UDHCPC_ARPING
  1118. if (opt & OPT_a) {
  1119. /* RFC 2131 3.1 paragraph 5:
  1120. * "The client receives the DHCPACK message with configuration
  1121. * parameters. The client SHOULD perform a final check on the
  1122. * parameters (e.g., ARP for allocated network address), and notes
  1123. * the duration of the lease specified in the DHCPACK message. At this
  1124. * point, the client is configured. If the client detects that the
  1125. * address is already in use (e.g., through the use of ARP),
  1126. * the client MUST send a DHCPDECLINE message to the server and restarts
  1127. * the configuration process..." */
  1128. if (!arpping(packet.yiaddr,
  1129. NULL,
  1130. (uint32_t) 0,
  1131. client_config.client_mac,
  1132. client_config.interface)
  1133. ) {
  1134. bb_info_msg("Offered address is in use "
  1135. "(got ARP reply), declining");
  1136. send_decline(xid, server_addr, packet.yiaddr);
  1137. if (state != REQUESTING)
  1138. udhcp_run_script(NULL, "deconfig");
  1139. change_listen_mode(LISTEN_RAW);
  1140. state = INIT_SELECTING;
  1141. requested_ip = 0;
  1142. timeout = tryagain_timeout;
  1143. packet_num = 0;
  1144. already_waited_sec = 0;
  1145. continue; /* back to main loop */
  1146. }
  1147. }
  1148. #endif
  1149. /* enter bound state */
  1150. timeout = lease_seconds / 2;
  1151. {
  1152. struct in_addr temp_addr;
  1153. temp_addr.s_addr = packet.yiaddr;
  1154. bb_info_msg("Lease of %s obtained, lease time %u",
  1155. inet_ntoa(temp_addr), (unsigned)lease_seconds);
  1156. }
  1157. requested_ip = packet.yiaddr;
  1158. udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
  1159. state = BOUND;
  1160. change_listen_mode(LISTEN_NONE);
  1161. if (opt & OPT_q) { /* quit after lease */
  1162. if (opt & OPT_R) /* release on quit */
  1163. perform_release(requested_ip, server_addr);
  1164. goto ret0;
  1165. }
  1166. /* future renew failures should not exit (JM) */
  1167. opt &= ~OPT_n;
  1168. #if BB_MMU /* NOMMU case backgrounded earlier */
  1169. if (!(opt & OPT_f)) {
  1170. client_background();
  1171. /* do not background again! */
  1172. opt = ((opt & ~OPT_b) | OPT_f);
  1173. }
  1174. #endif
  1175. already_waited_sec = 0;
  1176. continue; /* back to main loop */
  1177. }
  1178. if (*message == DHCPNAK) {
  1179. /* return to init state */
  1180. bb_info_msg("Received DHCP NAK");
  1181. udhcp_run_script(&packet, "nak");
  1182. if (state != REQUESTING)
  1183. udhcp_run_script(NULL, "deconfig");
  1184. change_listen_mode(LISTEN_RAW);
  1185. sleep(3); /* avoid excessive network traffic */
  1186. state = INIT_SELECTING;
  1187. requested_ip = 0;
  1188. timeout = 0;
  1189. packet_num = 0;
  1190. already_waited_sec = 0;
  1191. }
  1192. continue;
  1193. /* case BOUND: - ignore all packets */
  1194. /* case RELEASED: - ignore all packets */
  1195. }
  1196. /* back to main loop */
  1197. } /* for (;;) - main loop ends */
  1198. ret0:
  1199. retval = 0;
  1200. ret:
  1201. /*if (client_config.pidfile) - remove_pidfile has its own check */
  1202. remove_pidfile(client_config.pidfile);
  1203. return retval;
  1204. }