dhcpc.c 46 KB

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