source: MondoRescue/branches/3.3/mindi-busybox/networking/udhcp/dhcpc.c@ 3626

Last change on this file since 3626 was 3626, checked in by Bruno Cornec, 7 years ago

Adds fixes for rhel4 to busybox 1.25

File size: 57.3 KB
Line 
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
28#include <netinet/if_ether.h>
29// BCO for RHEL4
30#include <linux/types.h>
31// BCO
32#include <linux/filter.h>
33#include <linux/if_packet.h>
34
35#ifndef PACKET_AUXDATA
36# define PACKET_AUXDATA 8
37struct tpacket_auxdata {
38 uint32_t tp_status;
39 uint32_t tp_len;
40 uint32_t tp_snaplen;
41 uint16_t tp_mac;
42 uint16_t tp_net;
43 uint16_t tp_vlan_tci;
44 uint16_t tp_padding;
45};
46#endif
47
48
49/* "struct client_config_t client_config" is in bb_common_bufsiz1 */
50
51
52#if ENABLE_LONG_OPTS
53static const char udhcpc_longopts[] ALIGN1 =
54 "clientid-none\0" No_argument "C"
55 "vendorclass\0" Required_argument "V"
56 "hostname\0" Required_argument "H"
57 "fqdn\0" Required_argument "F"
58 "interface\0" Required_argument "i"
59 "now\0" No_argument "n"
60 "pidfile\0" Required_argument "p"
61 "quit\0" No_argument "q"
62 "release\0" No_argument "R"
63 "request\0" Required_argument "r"
64 "script\0" Required_argument "s"
65 "timeout\0" Required_argument "T"
66 "retries\0" Required_argument "t"
67 "tryagain\0" Required_argument "A"
68 "syslog\0" No_argument "S"
69 "request-option\0" Required_argument "O"
70 "no-default-options\0" No_argument "o"
71 "foreground\0" No_argument "f"
72 "background\0" No_argument "b"
73 "broadcast\0" No_argument "B"
74 IF_FEATURE_UDHCPC_ARPING("arping\0" Optional_argument "a")
75 IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
76 ;
77#endif
78/* Must match getopt32 option string order */
79enum {
80 OPT_C = 1 << 0,
81 OPT_V = 1 << 1,
82 OPT_H = 1 << 2,
83 OPT_h = 1 << 3,
84 OPT_F = 1 << 4,
85 OPT_i = 1 << 5,
86 OPT_n = 1 << 6,
87 OPT_p = 1 << 7,
88 OPT_q = 1 << 8,
89 OPT_R = 1 << 9,
90 OPT_r = 1 << 10,
91 OPT_s = 1 << 11,
92 OPT_T = 1 << 12,
93 OPT_t = 1 << 13,
94 OPT_S = 1 << 14,
95 OPT_A = 1 << 15,
96 OPT_O = 1 << 16,
97 OPT_o = 1 << 17,
98 OPT_x = 1 << 18,
99 OPT_f = 1 << 19,
100 OPT_B = 1 << 20,
101/* The rest has variable bit positions, need to be clever */
102 OPTBIT_B = 20,
103 USE_FOR_MMU( OPTBIT_b,)
104 IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
105 IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
106 USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
107 IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
108 IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
109};
110
111
112/*** Script execution code ***/
113
114/* get a rough idea of how long an option will be (rounding up...) */
115static const uint8_t len_of_option_as_string[] ALIGN1 = {
116 [OPTION_IP ] = sizeof("255.255.255.255 "),
117 [OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
118 [OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
119 [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
120 [OPTION_STRING ] = 1,
121 [OPTION_STRING_HOST ] = 1,
122#if ENABLE_FEATURE_UDHCP_RFC3397
123 [OPTION_DNS_STRING ] = 1, /* unused */
124 /* Hmmm, this severely overestimates size if SIP_SERVERS option
125 * is in domain name form: N-byte option in binary form
126 * mallocs ~16*N bytes. But it is freed almost at once.
127 */
128 [OPTION_SIP_SERVERS ] = sizeof("255.255.255.255 "),
129#endif
130// [OPTION_BOOLEAN ] = sizeof("yes "),
131 [OPTION_U8 ] = sizeof("255 "),
132 [OPTION_U16 ] = sizeof("65535 "),
133// [OPTION_S16 ] = sizeof("-32768 "),
134 [OPTION_U32 ] = sizeof("4294967295 "),
135 [OPTION_S32 ] = sizeof("-2147483684 "),
136};
137
138/* note: ip is a pointer to an IP in network order, possibly misaliged */
139static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
140{
141 return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
142}
143
144/* really simple implementation, just count the bits */
145static int mton(uint32_t mask)
146{
147 int i = 0;
148 mask = ntohl(mask); /* 111110000-like bit pattern */
149 while (mask) {
150 i++;
151 mask <<= 1;
152 }
153 return i;
154}
155
156#if ENABLE_FEATURE_UDHCPC_SANITIZEOPT
157/* Check if a given label represents a valid DNS label
158 * Return pointer to the first character after the label upon success,
159 * NULL otherwise.
160 * See RFC1035, 2.3.1
161 */
162/* We don't need to be particularly anal. For example, allowing _, hyphen
163 * at the end, or leading and trailing dots would be ok, since it
164 * can't be used for attacks. (Leading hyphen can be, if someone uses
165 * cmd "$hostname"
166 * in the script: then hostname may be treated as an option)
167 */
168static const char *valid_domain_label(const char *label)
169{
170 unsigned char ch;
171 unsigned pos = 0;
172
173 for (;;) {
174 ch = *label;
175 if ((ch|0x20) < 'a' || (ch|0x20) > 'z') {
176 if (ch < '0' || ch > '9') {
177 if (ch == '\0' || ch == '.')
178 return label;
179 /* DNS allows only '-', but we are more permissive */
180 if (ch != '-' && ch != '_')
181 return NULL;
182 }
183 }
184 label++;
185 pos++;
186 //Do we want this?
187 //if (pos > 63) /* NS_MAXLABEL; labels must be 63 chars or less */
188 // return NULL;
189 }
190}
191
192/* Check if a given name represents a valid DNS name */
193/* See RFC1035, 2.3.1 */
194static int good_hostname(const char *name)
195{
196 //const char *start = name;
197
198 for (;;) {
199 name = valid_domain_label(name);
200 if (!name)
201 return 0;
202 if (!name[0])
203 return 1;
204 //Do we want this?
205 //return ((name - start) < 1025); /* NS_MAXDNAME */
206 name++;
207 if (*name == '\0')
208 return 1; // We allow trailing dot too
209 }
210}
211#else
212# define good_hostname(name) 1
213#endif
214
215/* Create "opt_name=opt_value" string */
216static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name)
217{
218 unsigned upper_length;
219 int len, type, optlen;
220 char *dest, *ret;
221
222 /* option points to OPT_DATA, need to go back to get OPT_LEN */
223 len = option[-OPT_DATA + OPT_LEN];
224
225 type = optflag->flags & OPTION_TYPE_MASK;
226 optlen = dhcp_option_lengths[type];
227 upper_length = len_of_option_as_string[type]
228 * ((unsigned)(len + optlen) / (unsigned)optlen);
229
230 dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
231 dest += sprintf(ret, "%s=", opt_name);
232
233 while (len >= optlen) {
234 switch (type) {
235 case OPTION_IP:
236 case OPTION_IP_PAIR:
237 dest += sprint_nip(dest, "", option);
238 if (type == OPTION_IP)
239 break;
240 dest += sprint_nip(dest, "/", option + 4);
241 break;
242// case OPTION_BOOLEAN:
243// dest += sprintf(dest, *option ? "yes" : "no");
244// break;
245 case OPTION_U8:
246 dest += sprintf(dest, "%u", *option);
247 break;
248// case OPTION_S16:
249 case OPTION_U16: {
250 uint16_t val_u16;
251 move_from_unaligned16(val_u16, option);
252 dest += sprintf(dest, "%u", ntohs(val_u16));
253 break;
254 }
255 case OPTION_S32:
256 case OPTION_U32: {
257 uint32_t val_u32;
258 move_from_unaligned32(val_u32, option);
259 dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32));
260 break;
261 }
262 /* Note: options which use 'return' instead of 'break'
263 * (for example, OPTION_STRING) skip the code which handles
264 * the case of list of options.
265 */
266 case OPTION_STRING:
267 case OPTION_STRING_HOST:
268 memcpy(dest, option, len);
269 dest[len] = '\0';
270 if (type == OPTION_STRING_HOST && !good_hostname(dest))
271 safe_strncpy(dest, "bad", len);
272 return ret;
273 case OPTION_STATIC_ROUTES: {
274 /* Option binary format:
275 * mask [one byte, 0..32]
276 * ip [big endian, 0..4 bytes depending on mask]
277 * router [big endian, 4 bytes]
278 * may be repeated
279 *
280 * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2"
281 */
282 const char *pfx = "";
283
284 while (len >= 1 + 4) { /* mask + 0-byte ip + router */
285 uint32_t nip;
286 uint8_t *p;
287 unsigned mask;
288 int bytes;
289
290 mask = *option++;
291 if (mask > 32)
292 break;
293 len--;
294
295 nip = 0;
296 p = (void*) &nip;
297 bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */
298 while (--bytes >= 0) {
299 *p++ = *option++;
300 len--;
301 }
302 if (len < 4)
303 break;
304
305 /* print ip/mask */
306 dest += sprint_nip(dest, pfx, (void*) &nip);
307 pfx = " ";
308 dest += sprintf(dest, "/%u ", mask);
309 /* print router */
310 dest += sprint_nip(dest, "", option);
311 option += 4;
312 len -= 4;
313 }
314
315 return ret;
316 }
317 case OPTION_6RD:
318 /* Option binary format (see RFC 5969):
319 * 0 1 2 3
320 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
321 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
322 * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen |
323 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
324 * | 6rdPrefix |
325 * ... (16 octets) ...
326 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
327 * ... 6rdBRIPv4Address(es) ...
328 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
329 * We convert it to a string
330 * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..."
331 *
332 * Sanity check: ensure that our length is at least 22 bytes, that
333 * IPv4MaskLen <= 32,
334 * 6rdPrefixLen <= 128,
335 * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128
336 * (2nd condition need no check - it follows from 1st and 3rd).
337 * Else, return envvar with empty value ("optname=")
338 */
339 if (len >= (1 + 1 + 16 + 4)
340 && option[0] <= 32
341 && (option[1] + 32 - option[0]) <= 128
342 ) {
343 /* IPv4MaskLen */
344 dest += sprintf(dest, "%u ", *option++);
345 /* 6rdPrefixLen */
346 dest += sprintf(dest, "%u ", *option++);
347 /* 6rdPrefix */
348 dest += sprint_nip6(dest, /* "", */ option);
349 option += 16;
350 len -= 1 + 1 + 16 + 4;
351 /* "+ 4" above corresponds to the length of IPv4 addr
352 * we consume in the loop below */
353 while (1) {
354 /* 6rdBRIPv4Address(es) */
355 dest += sprint_nip(dest, " ", option);
356 option += 4;
357 len -= 4; /* do we have yet another 4+ bytes? */
358 if (len < 0)
359 break; /* no */
360 }
361 }
362
363 return ret;
364#if ENABLE_FEATURE_UDHCP_RFC3397
365 case OPTION_DNS_STRING:
366 /* unpack option into dest; use ret for prefix (i.e., "optname=") */
367 dest = dname_dec(option, len, ret);
368 if (dest) {
369 free(ret);
370 return dest;
371 }
372 /* error. return "optname=" string */
373 return ret;
374 case OPTION_SIP_SERVERS:
375 /* Option binary format:
376 * type: byte
377 * type=0: domain names, dns-compressed
378 * type=1: IP addrs
379 */
380 option++;
381 len--;
382 if (option[-1] == 0) {
383 dest = dname_dec(option, len, ret);
384 if (dest) {
385 free(ret);
386 return dest;
387 }
388 } else
389 if (option[-1] == 1) {
390 const char *pfx = "";
391 while (1) {
392 len -= 4;
393 if (len < 0)
394 break;
395 dest += sprint_nip(dest, pfx, option);
396 pfx = " ";
397 option += 4;
398 }
399 }
400 return ret;
401#endif
402 } /* switch */
403
404 /* If we are here, try to format any remaining data
405 * in the option as another, similarly-formatted option
406 */
407 option += optlen;
408 len -= optlen;
409// TODO: it can be a list only if (optflag->flags & OPTION_LIST).
410// Should we bail out/warn if we see multi-ip option which is
411// not allowed to be such (for example, DHCP_BROADCAST)? -
412 if (len < optlen /* || !(optflag->flags & OPTION_LIST) */)
413 break;
414 *dest++ = ' ';
415 *dest = '\0';
416 } /* while */
417
418 return ret;
419}
420
421/* put all the parameters into the environment */
422static char **fill_envp(struct dhcp_packet *packet)
423{
424 int envc;
425 int i;
426 char **envp, **curr;
427 const char *opt_name;
428 uint8_t *temp;
429 uint8_t overload = 0;
430
431#define BITMAP unsigned
432#define BBITS (sizeof(BITMAP) * 8)
433#define BMASK(i) (1 << (i & (sizeof(BITMAP) * 8 - 1)))
434#define FOUND_OPTS(i) (found_opts[(unsigned)i / BBITS])
435 BITMAP found_opts[256 / BBITS];
436
437 memset(found_opts, 0, sizeof(found_opts));
438
439 /* We need 6 elements for:
440 * "interface=IFACE"
441 * "ip=N.N.N.N" from packet->yiaddr
442 * "siaddr=IP" from packet->siaddr_nip (unless 0)
443 * "boot_file=FILE" from packet->file (unless overloaded)
444 * "sname=SERVER_HOSTNAME" from packet->sname (unless overloaded)
445 * terminating NULL
446 */
447 envc = 6;
448 /* +1 element for each option, +2 for subnet option: */
449 if (packet) {
450 /* note: do not search for "pad" (0) and "end" (255) options */
451//TODO: change logic to scan packet _once_
452 for (i = 1; i < 255; i++) {
453 temp = udhcp_get_option(packet, i);
454 if (temp) {
455 if (i == DHCP_OPTION_OVERLOAD)
456 overload = *temp;
457 else if (i == DHCP_SUBNET)
458 envc++; /* for $mask */
459 envc++;
460 /*if (i != DHCP_MESSAGE_TYPE)*/
461 FOUND_OPTS(i) |= BMASK(i);
462 }
463 }
464 }
465 curr = envp = xzalloc(sizeof(envp[0]) * envc);
466
467 *curr = xasprintf("interface=%s", client_config.interface);
468 putenv(*curr++);
469
470 if (!packet)
471 return envp;
472
473 /* Export BOOTP fields. Fields we don't (yet?) export:
474 * uint8_t op; // always BOOTREPLY
475 * uint8_t htype; // hardware address type. 1 = 10mb ethernet
476 * uint8_t hlen; // hardware address length
477 * uint8_t hops; // used by relay agents only
478 * uint32_t xid;
479 * uint16_t secs; // elapsed since client began acquisition/renewal
480 * uint16_t flags; // only one flag so far: bcast. Never set by server
481 * uint32_t ciaddr; // client IP (usually == yiaddr. can it be different
482 * // if during renew server wants to give us differn IP?)
483 * uint32_t gateway_nip; // relay agent IP address
484 * uint8_t chaddr[16]; // link-layer client hardware address (MAC)
485 * TODO: export gateway_nip as $giaddr?
486 */
487 /* Most important one: yiaddr as $ip */
488 *curr = xmalloc(sizeof("ip=255.255.255.255"));
489 sprint_nip(*curr, "ip=", (uint8_t *) &packet->yiaddr);
490 putenv(*curr++);
491 if (packet->siaddr_nip) {
492 /* IP address of next server to use in bootstrap */
493 *curr = xmalloc(sizeof("siaddr=255.255.255.255"));
494 sprint_nip(*curr, "siaddr=", (uint8_t *) &packet->siaddr_nip);
495 putenv(*curr++);
496 }
497 if (!(overload & FILE_FIELD) && packet->file[0]) {
498 /* watch out for invalid packets */
499 *curr = xasprintf("boot_file=%."DHCP_PKT_FILE_LEN_STR"s", packet->file);
500 putenv(*curr++);
501 }
502 if (!(overload & SNAME_FIELD) && packet->sname[0]) {
503 /* watch out for invalid packets */
504 *curr = xasprintf("sname=%."DHCP_PKT_SNAME_LEN_STR"s", packet->sname);
505 putenv(*curr++);
506 }
507
508 /* Export known DHCP options */
509 opt_name = dhcp_option_strings;
510 i = 0;
511 while (*opt_name) {
512 uint8_t code = dhcp_optflags[i].code;
513 BITMAP *found_ptr = &FOUND_OPTS(code);
514 BITMAP found_mask = BMASK(code);
515 if (!(*found_ptr & found_mask))
516 goto next;
517 *found_ptr &= ~found_mask; /* leave only unknown options */
518 temp = udhcp_get_option(packet, code);
519 *curr = xmalloc_optname_optval(temp, &dhcp_optflags[i], opt_name);
520 putenv(*curr++);
521 if (code == DHCP_SUBNET) {
522 /* Subnet option: make things like "$ip/$mask" possible */
523 uint32_t subnet;
524 move_from_unaligned32(subnet, temp);
525 *curr = xasprintf("mask=%u", mton(subnet));
526 putenv(*curr++);
527 }
528 next:
529 opt_name += strlen(opt_name) + 1;
530 i++;
531 }
532 /* Export unknown options */
533 for (i = 0; i < 256;) {
534 BITMAP bitmap = FOUND_OPTS(i);
535 if (!bitmap) {
536 i += BBITS;
537 continue;
538 }
539 if (bitmap & BMASK(i)) {
540 unsigned len, ofs;
541
542 temp = udhcp_get_option(packet, i);
543 /* udhcp_get_option returns ptr to data portion,
544 * need to go back to get len
545 */
546 len = temp[-OPT_DATA + OPT_LEN];
547 *curr = xmalloc(sizeof("optNNN=") + 1 + len*2);
548 ofs = sprintf(*curr, "opt%u=", i);
549 *bin2hex(*curr + ofs, (void*) temp, len) = '\0';
550 putenv(*curr++);
551 }
552 i++;
553 }
554
555 return envp;
556}
557
558/* Call a script with a par file and env vars */
559static void udhcp_run_script(struct dhcp_packet *packet, const char *name)
560{
561 char **envp, **curr;
562 char *argv[3];
563
564 envp = fill_envp(packet);
565
566 /* call script */
567 log1("executing %s %s", client_config.script, name);
568 argv[0] = (char*) client_config.script;
569 argv[1] = (char*) name;
570 argv[2] = NULL;
571 spawn_and_wait(argv);
572
573 for (curr = envp; *curr; curr++) {
574 log2(" %s", *curr);
575 bb_unsetenv_and_free(*curr);
576 }
577 free(envp);
578}
579
580
581/*** Sending/receiving packets ***/
582
583static ALWAYS_INLINE uint32_t random_xid(void)
584{
585 return rand();
586}
587
588/* Initialize the packet with the proper defaults */
589static void init_packet(struct dhcp_packet *packet, char type)
590{
591 uint16_t secs;
592
593 /* Fill in: op, htype, hlen, cookie fields; message type option: */
594 udhcp_init_header(packet, type);
595
596 packet->xid = random_xid();
597
598 client_config.last_secs = monotonic_sec();
599 if (client_config.first_secs == 0)
600 client_config.first_secs = client_config.last_secs;
601 secs = client_config.last_secs - client_config.first_secs;
602 packet->secs = htons(secs);
603
604 memcpy(packet->chaddr, client_config.client_mac, 6);
605 if (client_config.clientid)
606 udhcp_add_binary_option(packet, client_config.clientid);
607}
608
609static void add_client_options(struct dhcp_packet *packet)
610{
611 int i, end, len;
612
613 udhcp_add_simple_option(packet, DHCP_MAX_SIZE, htons(IP_UDP_DHCP_SIZE));
614
615 /* Add a "param req" option with the list of options we'd like to have
616 * from stubborn DHCP servers. Pull the data from the struct in common.c.
617 * No bounds checking because it goes towards the head of the packet. */
618 end = udhcp_end_option(packet->options);
619 len = 0;
620 for (i = 1; i < DHCP_END; i++) {
621 if (client_config.opt_mask[i >> 3] & (1 << (i & 7))) {
622 packet->options[end + OPT_DATA + len] = i;
623 len++;
624 }
625 }
626 if (len) {
627 packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
628 packet->options[end + OPT_LEN] = len;
629 packet->options[end + OPT_DATA + len] = DHCP_END;
630 }
631
632 if (client_config.vendorclass)
633 udhcp_add_binary_option(packet, client_config.vendorclass);
634 if (client_config.hostname)
635 udhcp_add_binary_option(packet, client_config.hostname);
636 if (client_config.fqdn)
637 udhcp_add_binary_option(packet, client_config.fqdn);
638
639 /* Request broadcast replies if we have no IP addr */
640 if ((option_mask32 & OPT_B) && packet->ciaddr == 0)
641 packet->flags |= htons(BROADCAST_FLAG);
642
643 /* Add -x options if any */
644 {
645 struct option_set *curr = client_config.options;
646 while (curr) {
647 udhcp_add_binary_option(packet, curr->data);
648 curr = curr->next;
649 }
650// if (client_config.sname)
651// strncpy((char*)packet->sname, client_config.sname, sizeof(packet->sname) - 1);
652// if (client_config.boot_file)
653// strncpy((char*)packet->file, client_config.boot_file, sizeof(packet->file) - 1);
654 }
655
656 // This will be needed if we remove -V VENDOR_STR in favor of
657 // -x vendor:VENDOR_STR
658 //if (!udhcp_find_option(packet.options, DHCP_VENDOR))
659 // /* not set, set the default vendor ID */
660 // ...add (DHCP_VENDOR, "udhcp "BB_VER) opt...
661}
662
663/* RFC 2131
664 * 4.4.4 Use of broadcast and unicast
665 *
666 * The DHCP client broadcasts DHCPDISCOVER, DHCPREQUEST and DHCPINFORM
667 * messages, unless the client knows the address of a DHCP server.
668 * The client unicasts DHCPRELEASE messages to the server. Because
669 * the client is declining the use of the IP address supplied by the server,
670 * the client broadcasts DHCPDECLINE messages.
671 *
672 * When the DHCP client knows the address of a DHCP server, in either
673 * INIT or REBOOTING state, the client may use that address
674 * in the DHCPDISCOVER or DHCPREQUEST rather than the IP broadcast address.
675 * The client may also use unicast to send DHCPINFORM messages
676 * to a known DHCP server. If the client receives no response to DHCP
677 * messages sent to the IP address of a known DHCP server, the DHCP
678 * client reverts to using the IP broadcast address.
679 */
680
681static int raw_bcast_from_client_config_ifindex(struct dhcp_packet *packet, uint32_t src_nip)
682{
683 return udhcp_send_raw_packet(packet,
684 /*src*/ src_nip, CLIENT_PORT,
685 /*dst*/ INADDR_BROADCAST, SERVER_PORT, MAC_BCAST_ADDR,
686 client_config.ifindex);
687}
688
689static int bcast_or_ucast(struct dhcp_packet *packet, uint32_t ciaddr, uint32_t server)
690{
691 if (server)
692 return udhcp_send_kernel_packet(packet,
693 ciaddr, CLIENT_PORT,
694 server, SERVER_PORT);
695 return raw_bcast_from_client_config_ifindex(packet, ciaddr);
696}
697
698/* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
699/* NOINLINE: limit stack usage in caller */
700static NOINLINE int send_discover(uint32_t xid, uint32_t requested)
701{
702 struct dhcp_packet packet;
703
704 /* Fill in: op, htype, hlen, cookie, chaddr fields,
705 * random xid field (we override it below),
706 * client-id option (unless -C), message type option:
707 */
708 init_packet(&packet, DHCPDISCOVER);
709
710 packet.xid = xid;
711 if (requested)
712 udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
713
714 /* Add options: maxsize,
715 * optionally: hostname, fqdn, vendorclass,
716 * "param req" option according to -O, options specified with -x
717 */
718 add_client_options(&packet);
719
720 bb_error_msg("sending %s", "discover");
721 return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
722}
723
724/* Broadcast a DHCP request message */
725/* RFC 2131 3.1 paragraph 3:
726 * "The client _broadcasts_ a DHCPREQUEST message..."
727 */
728/* NOINLINE: limit stack usage in caller */
729static NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requested)
730{
731 struct dhcp_packet packet;
732 struct in_addr addr;
733
734/*
735 * RFC 2131 4.3.2 DHCPREQUEST message
736 * ...
737 * If the DHCPREQUEST message contains a 'server identifier'
738 * option, the message is in response to a DHCPOFFER message.
739 * Otherwise, the message is a request to verify or extend an
740 * existing lease. If the client uses a 'client identifier'
741 * in a DHCPREQUEST message, it MUST use that same 'client identifier'
742 * in all subsequent messages. If the client included a list
743 * of requested parameters in a DHCPDISCOVER message, it MUST
744 * include that list in all subsequent messages.
745 */
746 /* Fill in: op, htype, hlen, cookie, chaddr fields,
747 * random xid field (we override it below),
748 * client-id option (unless -C), message type option:
749 */
750 init_packet(&packet, DHCPREQUEST);
751
752 packet.xid = xid;
753 udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
754
755 udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
756
757 /* Add options: maxsize,
758 * optionally: hostname, fqdn, vendorclass,
759 * "param req" option according to -O, and options specified with -x
760 */
761 add_client_options(&packet);
762
763 addr.s_addr = requested;
764 bb_error_msg("sending select for %s", inet_ntoa(addr));
765 return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
766}
767
768/* Unicast or broadcast a DHCP renew message */
769/* NOINLINE: limit stack usage in caller */
770static NOINLINE int send_renew(uint32_t xid, uint32_t server, uint32_t ciaddr)
771{
772 struct dhcp_packet packet;
773
774/*
775 * RFC 2131 4.3.2 DHCPREQUEST message
776 * ...
777 * DHCPREQUEST generated during RENEWING state:
778 *
779 * 'server identifier' MUST NOT be filled in, 'requested IP address'
780 * option MUST NOT be filled in, 'ciaddr' MUST be filled in with
781 * client's IP address. In this situation, the client is completely
782 * configured, and is trying to extend its lease. This message will
783 * be unicast, so no relay agents will be involved in its
784 * transmission. Because 'giaddr' is therefore not filled in, the
785 * DHCP server will trust the value in 'ciaddr', and use it when
786 * replying to the client.
787 */
788 /* Fill in: op, htype, hlen, cookie, chaddr fields,
789 * random xid field (we override it below),
790 * client-id option (unless -C), message type option:
791 */
792 init_packet(&packet, DHCPREQUEST);
793
794 packet.xid = xid;
795 packet.ciaddr = ciaddr;
796
797 /* Add options: maxsize,
798 * optionally: hostname, fqdn, vendorclass,
799 * "param req" option according to -O, and options specified with -x
800 */
801 add_client_options(&packet);
802
803 bb_error_msg("sending %s", "renew");
804 return bcast_or_ucast(&packet, ciaddr, server);
805}
806
807#if ENABLE_FEATURE_UDHCPC_ARPING
808/* Broadcast a DHCP decline message */
809/* NOINLINE: limit stack usage in caller */
810static NOINLINE int send_decline(/*uint32_t xid,*/ uint32_t server, uint32_t requested)
811{
812 struct dhcp_packet packet;
813
814 /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
815 * client-id option (unless -C), message type option:
816 */
817 init_packet(&packet, DHCPDECLINE);
818
819#if 0
820 /* RFC 2131 says DHCPDECLINE's xid is randomly selected by client,
821 * but in case the server is buggy and wants DHCPDECLINE's xid
822 * to match the xid which started entire handshake,
823 * we use the same xid we used in initial DHCPDISCOVER:
824 */
825 packet.xid = xid;
826#endif
827 /* DHCPDECLINE uses "requested ip", not ciaddr, to store offered IP */
828 udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
829
830 udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
831
832 bb_error_msg("sending %s", "decline");
833 return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
834}
835#endif
836
837/* Unicast a DHCP release message */
838static int send_release(uint32_t server, uint32_t ciaddr)
839{
840 struct dhcp_packet packet;
841
842 /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
843 * client-id option (unless -C), message type option:
844 */
845 init_packet(&packet, DHCPRELEASE);
846
847 /* DHCPRELEASE uses ciaddr, not "requested ip", to store IP being released */
848 packet.ciaddr = ciaddr;
849
850 udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
851
852 bb_error_msg("sending %s", "release");
853 /* Note: normally we unicast here since "server" is not zero.
854 * However, there _are_ people who run "address-less" DHCP servers,
855 * and reportedly ISC dhcp client and Windows allow that.
856 */
857 return bcast_or_ucast(&packet, ciaddr, server);
858}
859
860/* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
861/* NOINLINE: limit stack usage in caller */
862static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
863{
864 int bytes;
865 struct ip_udp_dhcp_packet packet;
866 uint16_t check;
867 unsigned char cmsgbuf[CMSG_LEN(sizeof(struct tpacket_auxdata))];
868 struct iovec iov;
869 struct msghdr msg;
870 struct cmsghdr *cmsg;
871
872 /* used to use just safe_read(fd, &packet, sizeof(packet))
873 * but we need to check for TP_STATUS_CSUMNOTREADY :(
874 */
875 iov.iov_base = &packet;
876 iov.iov_len = sizeof(packet);
877 memset(&msg, 0, sizeof(msg));
878 msg.msg_iov = &iov;
879 msg.msg_iovlen = 1;
880 msg.msg_control = cmsgbuf;
881 msg.msg_controllen = sizeof(cmsgbuf);
882 for (;;) {
883 bytes = recvmsg(fd, &msg, 0);
884 if (bytes < 0) {
885 if (errno == EINTR)
886 continue;
887 log1("packet read error, ignoring");
888 /* NB: possible down interface, etc. Caller should pause. */
889 return bytes; /* returns -1 */
890 }
891 break;
892 }
893
894 if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp))) {
895 log1("packet is too short, ignoring");
896 return -2;
897 }
898
899 if (bytes < ntohs(packet.ip.tot_len)) {
900 /* packet is bigger than sizeof(packet), we did partial read */
901 log1("oversized packet, ignoring");
902 return -2;
903 }
904
905 /* ignore any extra garbage bytes */
906 bytes = ntohs(packet.ip.tot_len);
907
908 /* make sure its the right packet for us, and that it passes sanity checks */
909 if (packet.ip.protocol != IPPROTO_UDP
910 || packet.ip.version != IPVERSION
911 || packet.ip.ihl != (sizeof(packet.ip) >> 2)
912 || packet.udp.dest != htons(CLIENT_PORT)
913 /* || bytes > (int) sizeof(packet) - can't happen */
914 || ntohs(packet.udp.len) != (uint16_t)(bytes - sizeof(packet.ip))
915 ) {
916 log1("unrelated/bogus packet, ignoring");
917 return -2;
918 }
919
920 /* verify IP checksum */
921 check = packet.ip.check;
922 packet.ip.check = 0;
923 if (check != inet_cksum((uint16_t *)&packet.ip, sizeof(packet.ip))) {
924 log1("bad IP header checksum, ignoring");
925 return -2;
926 }
927
928 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
929 if (cmsg->cmsg_level == SOL_PACKET
930 && cmsg->cmsg_type == PACKET_AUXDATA
931 ) {
932 /* some VMs don't checksum UDP and TCP data
933 * they send to the same physical machine,
934 * here we detect this case:
935 */
936 struct tpacket_auxdata *aux = (void *)CMSG_DATA(cmsg);
937 if (aux->tp_status & TP_STATUS_CSUMNOTREADY)
938 goto skip_udp_sum_check;
939 }
940 }
941
942 /* verify UDP checksum. IP header has to be modified for this */
943 memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
944 /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
945 packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
946 check = packet.udp.check;
947 packet.udp.check = 0;
948 if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
949 log1("packet with bad UDP checksum received, ignoring");
950 return -2;
951 }
952 skip_udp_sum_check:
953
954 if (packet.data.cookie != htonl(DHCP_MAGIC)) {
955 bb_error_msg("packet with bad magic, ignoring");
956 return -2;
957 }
958
959 log1("received %s", "a packet");
960 udhcp_dump_packet(&packet.data);
961
962 bytes -= sizeof(packet.ip) + sizeof(packet.udp);
963 memcpy(dhcp_pkt, &packet.data, bytes);
964 return bytes;
965}
966
967
968/*** Main ***/
969
970static int sockfd = -1;
971
972#define LISTEN_NONE 0
973#define LISTEN_KERNEL 1
974#define LISTEN_RAW 2
975static smallint listen_mode;
976
977/* initial state: (re)start DHCP negotiation */
978#define INIT_SELECTING 0
979/* discover was sent, DHCPOFFER reply received */
980#define REQUESTING 1
981/* select/renew was sent, DHCPACK reply received */
982#define BOUND 2
983/* half of lease passed, want to renew it by sending unicast renew requests */
984#define RENEWING 3
985/* renew requests were not answered, lease is almost over, send broadcast renew */
986#define REBINDING 4
987/* manually requested renew (SIGUSR1) */
988#define RENEW_REQUESTED 5
989/* release, possibly manually requested (SIGUSR2) */
990#define RELEASED 6
991static smallint state;
992
993static int udhcp_raw_socket(int ifindex)
994{
995 int fd;
996 struct sockaddr_ll sock;
997
998 log1("opening raw socket on ifindex %d", ifindex); //log2?
999
1000 fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
1001 /* ^^^^^
1002 * SOCK_DGRAM: remove link-layer headers on input (SOCK_RAW keeps them)
1003 * ETH_P_IP: want to receive only packets with IPv4 eth type
1004 */
1005 log1("got raw socket fd"); //log2?
1006
1007 sock.sll_family = AF_PACKET;
1008 sock.sll_protocol = htons(ETH_P_IP);
1009 sock.sll_ifindex = ifindex;
1010 xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
1011
1012#if 0 /* Several users reported breakage when BPF filter is used */
1013 if (CLIENT_PORT == 68) {
1014 /* Use only if standard port is in use */
1015 /*
1016 * I've selected not to see LL header, so BPF doesn't see it, too.
1017 * The filter may also pass non-IP and non-ARP packets, but we do
1018 * a more complete check when receiving the message in userspace.
1019 *
1020 * and filter shamelessly stolen from:
1021 *
1022 * http://www.flamewarmaster.de/software/dhcpclient/
1023 *
1024 * There are a few other interesting ideas on that page (look under
1025 * "Motivation"). Use of netlink events is most interesting. Think
1026 * of various network servers listening for events and reconfiguring.
1027 * That would obsolete sending HUP signals and/or make use of restarts.
1028 *
1029 * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
1030 * License: GPL v2.
1031 */
1032 static const struct sock_filter filter_instr[] = {
1033 /* load 9th byte (protocol) */
1034 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
1035 /* jump to L1 if it is IPPROTO_UDP, else to L4 */
1036 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
1037 /* L1: load halfword from offset 6 (flags and frag offset) */
1038 BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
1039 /* jump to L4 if any bits in frag offset field are set, else to L2 */
1040 BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
1041 /* L2: skip IP header (load index reg with header len) */
1042 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
1043 /* load udp destination port from halfword[header_len + 2] */
1044 BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
1045 /* jump to L3 if udp dport is CLIENT_PORT, else to L4 */
1046 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
1047 /* L3: accept packet ("accept 0x7fffffff bytes") */
1048 /* Accepting 0xffffffff works too but kernel 2.6.19 is buggy */
1049 BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
1050 /* L4: discard packet ("accept zero bytes") */
1051 BPF_STMT(BPF_RET|BPF_K, 0),
1052 };
1053 static const struct sock_fprog filter_prog = {
1054 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
1055 /* casting const away: */
1056 .filter = (struct sock_filter *) filter_instr,
1057 };
1058 /* Ignoring error (kernel may lack support for this) */
1059 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
1060 sizeof(filter_prog)) >= 0)
1061 log1("attached filter to raw socket fd"); // log?
1062 }
1063#endif
1064
1065 if (setsockopt_1(fd, SOL_PACKET, PACKET_AUXDATA) != 0) {
1066 if (errno != ENOPROTOOPT)
1067 log1("can't set PACKET_AUXDATA on raw socket");
1068 }
1069
1070 log1("created raw socket");
1071
1072 return fd;
1073}
1074
1075static void change_listen_mode(int new_mode)
1076{
1077 log1("entering listen mode: %s",
1078 new_mode != LISTEN_NONE
1079 ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
1080 : "none"
1081 );
1082
1083 listen_mode = new_mode;
1084 if (sockfd >= 0) {
1085 close(sockfd);
1086 sockfd = -1;
1087 }
1088 if (new_mode == LISTEN_KERNEL)
1089 sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
1090 else if (new_mode != LISTEN_NONE)
1091 sockfd = udhcp_raw_socket(client_config.ifindex);
1092 /* else LISTEN_NONE: sockfd stays closed */
1093}
1094
1095/* Called only on SIGUSR1 */
1096static void perform_renew(void)
1097{
1098 bb_error_msg("performing DHCP renew");
1099 switch (state) {
1100 case BOUND:
1101 change_listen_mode(LISTEN_KERNEL);
1102 case RENEWING:
1103 case REBINDING:
1104 state = RENEW_REQUESTED;
1105 break;
1106 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
1107 udhcp_run_script(NULL, "deconfig");
1108 case REQUESTING:
1109 case RELEASED:
1110 change_listen_mode(LISTEN_RAW);
1111 state = INIT_SELECTING;
1112 break;
1113 case INIT_SELECTING:
1114 break;
1115 }
1116}
1117
1118static void perform_release(uint32_t server_addr, uint32_t requested_ip)
1119{
1120 char buffer[sizeof("255.255.255.255")];
1121 struct in_addr temp_addr;
1122
1123 /* send release packet */
1124 if (state == BOUND || state == RENEWING || state == REBINDING) {
1125 temp_addr.s_addr = server_addr;
1126 strcpy(buffer, inet_ntoa(temp_addr));
1127 temp_addr.s_addr = requested_ip;
1128 bb_error_msg("unicasting a release of %s to %s",
1129 inet_ntoa(temp_addr), buffer);
1130 send_release(server_addr, requested_ip); /* unicast */
1131 udhcp_run_script(NULL, "deconfig");
1132 }
1133 bb_error_msg("entering released state");
1134
1135 change_listen_mode(LISTEN_NONE);
1136 state = RELEASED;
1137}
1138
1139static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
1140{
1141 uint8_t *storage;
1142 int len = strnlen(str, 255);
1143 storage = xzalloc(len + extra + OPT_DATA);
1144 storage[OPT_CODE] = code;
1145 storage[OPT_LEN] = len + extra;
1146 memcpy(storage + extra + OPT_DATA, str, len);
1147 return storage;
1148}
1149
1150#if BB_MMU
1151static void client_background(void)
1152{
1153 bb_daemonize(0);
1154 logmode &= ~LOGMODE_STDIO;
1155 /* rewrite pidfile, as our pid is different now */
1156 write_pidfile(client_config.pidfile);
1157}
1158#endif
1159
1160//usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
1161//usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
1162//usage:#else
1163//usage:# define IF_UDHCP_VERBOSE(...)
1164//usage:#endif
1165//usage:#define udhcpc_trivial_usage
1166//usage: "[-fbq"IF_UDHCP_VERBOSE("v")"RB]"IF_FEATURE_UDHCPC_ARPING(" [-a[MSEC]]")" [-t N] [-T SEC] [-A SEC/-n]\n"
1167//usage: " [-i IFACE]"IF_FEATURE_UDHCP_PORT(" [-P PORT]")" [-s PROG] [-p PIDFILE]\n"
1168//usage: " [-oC] [-r IP] [-V VENDOR] [-F NAME] [-x OPT:VAL]... [-O OPT]..."
1169//usage:#define udhcpc_full_usage "\n"
1170//usage: IF_LONG_OPTS(
1171//usage: "\n -i,--interface IFACE Interface to use (default eth0)"
1172//usage: IF_FEATURE_UDHCP_PORT(
1173//usage: "\n -P,--client-port PORT Use PORT (default 68)"
1174//usage: )
1175//usage: "\n -s,--script PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
1176//usage: "\n -p,--pidfile FILE Create pidfile"
1177//usage: "\n -B,--broadcast Request broadcast replies"
1178//usage: "\n -t,--retries N Send up to N discover packets (default 3)"
1179//usage: "\n -T,--timeout SEC Pause between packets (default 3)"
1180//usage: "\n -A,--tryagain SEC Wait if lease is not obtained (default 20)"
1181//usage: "\n -n,--now Exit if lease is not obtained"
1182//usage: "\n -q,--quit Exit after obtaining lease"
1183//usage: "\n -R,--release Release IP on exit"
1184//usage: "\n -f,--foreground Run in foreground"
1185//usage: USE_FOR_MMU(
1186//usage: "\n -b,--background Background if lease is not obtained"
1187//usage: )
1188//usage: "\n -S,--syslog Log to syslog too"
1189//usage: IF_FEATURE_UDHCPC_ARPING(
1190//usage: "\n -a[MSEC],--arping[=MSEC] Validate offered address with ARP ping"
1191//usage: )
1192//usage: "\n -r,--request IP Request this IP address"
1193//usage: "\n -o,--no-default-options Don't request any options (unless -O is given)"
1194//usage: "\n -O,--request-option OPT Request option OPT from server (cumulative)"
1195//usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
1196//usage: "\n Examples of string, numeric, and hex byte opts:"
1197//usage: "\n -x hostname:bbox - option 12"
1198//usage: "\n -x lease:3600 - option 51 (lease time)"
1199//usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
1200//usage: "\n -F,--fqdn NAME Ask server to update DNS mapping for NAME"
1201//usage: "\n -V,--vendorclass VENDOR Vendor identifier (default 'udhcp VERSION')"
1202//usage: "\n -C,--clientid-none Don't send MAC as client identifier"
1203//usage: IF_UDHCP_VERBOSE(
1204//usage: "\n -v Verbose"
1205//usage: )
1206//usage: )
1207//usage: IF_NOT_LONG_OPTS(
1208//usage: "\n -i IFACE Interface to use (default eth0)"
1209//usage: IF_FEATURE_UDHCP_PORT(
1210//usage: "\n -P PORT Use PORT (default 68)"
1211//usage: )
1212//usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
1213//usage: "\n -p FILE Create pidfile"
1214//usage: "\n -B Request broadcast replies"
1215//usage: "\n -t N Send up to N discover packets (default 3)"
1216//usage: "\n -T SEC Pause between packets (default 3)"
1217//usage: "\n -A SEC Wait if lease is not obtained (default 20)"
1218//usage: "\n -n Exit if lease is not obtained"
1219//usage: "\n -q Exit after obtaining lease"
1220//usage: "\n -R Release IP on exit"
1221//usage: "\n -f Run in foreground"
1222//usage: USE_FOR_MMU(
1223//usage: "\n -b Background if lease is not obtained"
1224//usage: )
1225//usage: "\n -S Log to syslog too"
1226//usage: IF_FEATURE_UDHCPC_ARPING(
1227//usage: "\n -a[MSEC] Validate offered address with ARP ping"
1228//usage: )
1229//usage: "\n -r IP Request this IP address"
1230//usage: "\n -o Don't request any options (unless -O is given)"
1231//usage: "\n -O OPT Request option OPT from server (cumulative)"
1232//usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
1233//usage: "\n Examples of string, numeric, and hex byte opts:"
1234//usage: "\n -x hostname:bbox - option 12"
1235//usage: "\n -x lease:3600 - option 51 (lease time)"
1236//usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
1237//usage: "\n -F NAME Ask server to update DNS mapping for NAME"
1238//usage: "\n -V VENDOR Vendor identifier (default 'udhcp VERSION')"
1239//usage: "\n -C Don't send MAC as client identifier"
1240//usage: IF_UDHCP_VERBOSE(
1241//usage: "\n -v Verbose"
1242//usage: )
1243//usage: )
1244//usage: "\nSignals:"
1245//usage: "\n USR1 Renew lease"
1246//usage: "\n USR2 Release lease"
1247
1248
1249int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1250int udhcpc_main(int argc UNUSED_PARAM, char **argv)
1251{
1252 uint8_t *message;
1253 const char *str_V, *str_h, *str_F, *str_r;
1254 IF_FEATURE_UDHCPC_ARPING(const char *str_a = "2000";)
1255 IF_FEATURE_UDHCP_PORT(char *str_P;)
1256 void *clientid_mac_ptr;
1257 llist_t *list_O = NULL;
1258 llist_t *list_x = NULL;
1259 int tryagain_timeout = 20;
1260 int discover_timeout = 3;
1261 int discover_retries = 3;
1262 uint32_t server_addr = server_addr; /* for compiler */
1263 uint32_t requested_ip = 0;
1264 uint32_t xid = xid; /* for compiler */
1265 int packet_num;
1266 int timeout; /* must be signed */
1267 unsigned already_waited_sec;
1268 unsigned opt;
1269 IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;)
1270 int max_fd;
1271 int retval;
1272 fd_set rfds;
1273
1274 setup_common_bufsiz();
1275
1276 /* Default options */
1277 IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
1278 IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
1279 client_config.interface = "eth0";
1280 client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
1281 str_V = "udhcp "BB_VER;
1282
1283 /* Parse command line */
1284 /* O,x: list; -T,-t,-A take numeric param */
1285 opt_complementary = "O::x::T+:t+:A+" IF_UDHCP_VERBOSE(":vv") ;
1286 IF_LONG_OPTS(applet_long_options = udhcpc_longopts;)
1287 opt = getopt32(argv, "CV:H:h:F:i:np:qRr:s:T:t:SA:O:ox:fB"
1288 USE_FOR_MMU("b")
1289 IF_FEATURE_UDHCPC_ARPING("a::")
1290 IF_FEATURE_UDHCP_PORT("P:")
1291 "v"
1292 , &str_V, &str_h, &str_h, &str_F
1293 , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
1294 , &client_config.script /* s */
1295 , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
1296 , &list_O
1297 , &list_x
1298 IF_FEATURE_UDHCPC_ARPING(, &str_a)
1299 IF_FEATURE_UDHCP_PORT(, &str_P)
1300 IF_UDHCP_VERBOSE(, &dhcp_verbose)
1301 );
1302 if (opt & (OPT_h|OPT_H)) {
1303 //msg added 2011-11
1304 bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME");
1305 client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
1306 }
1307 if (opt & OPT_F) {
1308 /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
1309 client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
1310 /* Flag bits: 0000NEOS
1311 * S: 1 = Client requests server to update A RR in DNS as well as PTR
1312 * O: 1 = Server indicates to client that DNS has been updated regardless
1313 * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
1314 * not "host.domain.com". Format 0 is obsolete.
1315 * N: 1 = Client requests server to not update DNS (S must be 0 then)
1316 * Two [0] bytes which follow are deprecated and must be 0.
1317 */
1318 client_config.fqdn[OPT_DATA + 0] = 0x1;
1319 /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
1320 /*client_config.fqdn[OPT_DATA + 2] = 0; */
1321 }
1322 if (opt & OPT_r)
1323 requested_ip = inet_addr(str_r);
1324#if ENABLE_FEATURE_UDHCP_PORT
1325 if (opt & OPT_P) {
1326 CLIENT_PORT = xatou16(str_P);
1327 SERVER_PORT = CLIENT_PORT - 1;
1328 }
1329#endif
1330 IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);)
1331 while (list_O) {
1332 char *optstr = llist_pop(&list_O);
1333 unsigned n = bb_strtou(optstr, NULL, 0);
1334 if (errno || n > 254) {
1335 n = udhcp_option_idx(optstr);
1336 n = dhcp_optflags[n].code;
1337 }
1338 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
1339 }
1340 if (!(opt & OPT_o)) {
1341 unsigned i, n;
1342 for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
1343 if (dhcp_optflags[i].flags & OPTION_REQ) {
1344 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
1345 }
1346 }
1347 }
1348 while (list_x) {
1349 char *optstr = llist_pop(&list_x);
1350 char *colon = strchr(optstr, ':');
1351 if (colon)
1352 *colon = ' ';
1353 /* now it looks similar to udhcpd's config file line:
1354 * "optname optval", using the common routine: */
1355 udhcp_str2optset(optstr, &client_config.options);
1356 }
1357
1358 if (udhcp_read_interface(client_config.interface,
1359 &client_config.ifindex,
1360 NULL,
1361 client_config.client_mac)
1362 ) {
1363 return 1;
1364 }
1365
1366 clientid_mac_ptr = NULL;
1367 if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) {
1368 /* not suppressed and not set, set the default client ID */
1369 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
1370 client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
1371 clientid_mac_ptr = client_config.clientid + OPT_DATA+1;
1372 memcpy(clientid_mac_ptr, client_config.client_mac, 6);
1373 }
1374 if (str_V[0] != '\0') {
1375 // can drop -V, str_V, client_config.vendorclass,
1376 // but need to add "vendor" to the list of recognized
1377 // string opts for this to work;
1378 // and need to tweak add_client_options() too...
1379 // ...so the question is, should we?
1380 //bb_error_msg("option -V VENDOR is deprecated, use -x vendor:VENDOR");
1381 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
1382 }
1383
1384#if !BB_MMU
1385 /* on NOMMU reexec (i.e., background) early */
1386 if (!(opt & OPT_f)) {
1387 bb_daemonize_or_rexec(0 /* flags */, argv);
1388 logmode = LOGMODE_NONE;
1389 }
1390#endif
1391 if (opt & OPT_S) {
1392 openlog(applet_name, LOG_PID, LOG_DAEMON);
1393 logmode |= LOGMODE_SYSLOG;
1394 }
1395
1396 /* Make sure fd 0,1,2 are open */
1397 bb_sanitize_stdio();
1398 /* Equivalent of doing a fflush after every \n */
1399 setlinebuf(stdout);
1400 /* Create pidfile */
1401 write_pidfile(client_config.pidfile);
1402 /* Goes to stdout (unless NOMMU) and possibly syslog */
1403 bb_error_msg("started, v"BB_VER);
1404 /* Set up the signal pipe */
1405 udhcp_sp_setup();
1406 /* We want random_xid to be random... */
1407 srand(monotonic_us());
1408
1409 state = INIT_SELECTING;
1410 udhcp_run_script(NULL, "deconfig");
1411 change_listen_mode(LISTEN_RAW);
1412 packet_num = 0;
1413 timeout = 0;
1414 already_waited_sec = 0;
1415
1416 /* Main event loop. select() waits on signal pipe and possibly
1417 * on sockfd.
1418 * "continue" statements in code below jump to the top of the loop.
1419 */
1420 for (;;) {
1421 struct timeval tv;
1422 struct dhcp_packet packet;
1423 /* silence "uninitialized!" warning */
1424 unsigned timestamp_before_wait = timestamp_before_wait;
1425
1426 //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
1427
1428 /* Was opening raw or udp socket here
1429 * if (listen_mode != LISTEN_NONE && sockfd < 0),
1430 * but on fast network renew responses return faster
1431 * than we open sockets. Thus this code is moved
1432 * to change_listen_mode(). Thus we open listen socket
1433 * BEFORE we send renew request (see "case BOUND:"). */
1434
1435 max_fd = udhcp_sp_fd_set(&rfds, sockfd);
1436
1437 tv.tv_sec = timeout - already_waited_sec;
1438 tv.tv_usec = 0;
1439 retval = 0;
1440 /* If we already timed out, fall through with retval = 0, else... */
1441 if ((int)tv.tv_sec > 0) {
1442 log1("waiting on select %u seconds", (int)tv.tv_sec);
1443 timestamp_before_wait = (unsigned)monotonic_sec();
1444 retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
1445 if (retval < 0) {
1446 /* EINTR? A signal was caught, don't panic */
1447 if (errno == EINTR) {
1448 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1449 continue;
1450 }
1451 /* Else: an error occured, panic! */
1452 bb_perror_msg_and_die("select");
1453 }
1454 }
1455
1456 /* If timeout dropped to zero, time to become active:
1457 * resend discover/renew/whatever
1458 */
1459 if (retval == 0) {
1460 /* When running on a bridge, the ifindex may have changed
1461 * (e.g. if member interfaces were added/removed
1462 * or if the status of the bridge changed).
1463 * Refresh ifindex and client_mac:
1464 */
1465 if (udhcp_read_interface(client_config.interface,
1466 &client_config.ifindex,
1467 NULL,
1468 client_config.client_mac)
1469 ) {
1470 goto ret0; /* iface is gone? */
1471 }
1472 if (clientid_mac_ptr)
1473 memcpy(clientid_mac_ptr, client_config.client_mac, 6);
1474
1475 /* We will restart the wait in any case */
1476 already_waited_sec = 0;
1477
1478 switch (state) {
1479 case INIT_SELECTING:
1480 if (!discover_retries || packet_num < discover_retries) {
1481 if (packet_num == 0)
1482 xid = random_xid();
1483 /* broadcast */
1484 send_discover(xid, requested_ip);
1485 timeout = discover_timeout;
1486 packet_num++;
1487 continue;
1488 }
1489 leasefail:
1490 udhcp_run_script(NULL, "leasefail");
1491#if BB_MMU /* -b is not supported on NOMMU */
1492 if (opt & OPT_b) { /* background if no lease */
1493 bb_error_msg("no lease, forking to background");
1494 client_background();
1495 /* do not background again! */
1496 opt = ((opt & ~OPT_b) | OPT_f);
1497 } else
1498#endif
1499 if (opt & OPT_n) { /* abort if no lease */
1500 bb_error_msg("no lease, failing");
1501 retval = 1;
1502 goto ret;
1503 }
1504 /* wait before trying again */
1505 timeout = tryagain_timeout;
1506 packet_num = 0;
1507 continue;
1508 case REQUESTING:
1509 if (packet_num < 3) {
1510 /* send broadcast select packet */
1511 send_select(xid, server_addr, requested_ip);
1512 timeout = discover_timeout;
1513 packet_num++;
1514 continue;
1515 }
1516 /* Timed out, go back to init state.
1517 * "discover...select...discover..." loops
1518 * were seen in the wild. Treat them similarly
1519 * to "no response to discover" case */
1520 change_listen_mode(LISTEN_RAW);
1521 state = INIT_SELECTING;
1522 goto leasefail;
1523 case BOUND:
1524 /* 1/2 lease passed, enter renewing state */
1525 state = RENEWING;
1526 client_config.first_secs = 0; /* make secs field count from 0 */
1527 change_listen_mode(LISTEN_KERNEL);
1528 log1("entering renew state");
1529 /* fall right through */
1530 case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
1531 case_RENEW_REQUESTED:
1532 case RENEWING:
1533 if (timeout > 60) {
1534 /* send an unicast renew request */
1535 /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
1536 * a new UDP socket for sending inside send_renew.
1537 * I hazard to guess existing listening socket
1538 * is somehow conflicting with it, but why is it
1539 * not deterministic then?! Strange.
1540 * Anyway, it does recover by eventually failing through
1541 * into INIT_SELECTING state.
1542 */
1543 send_renew(xid, server_addr, requested_ip);
1544 timeout >>= 1;
1545 continue;
1546 }
1547 /* Timed out, enter rebinding state */
1548 log1("entering rebinding state");
1549 state = REBINDING;
1550 /* fall right through */
1551 case REBINDING:
1552 /* Switch to bcast receive */
1553 change_listen_mode(LISTEN_RAW);
1554 /* Lease is *really* about to run out,
1555 * try to find DHCP server using broadcast */
1556 if (timeout > 0) {
1557 /* send a broadcast renew request */
1558 send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
1559 timeout >>= 1;
1560 continue;
1561 }
1562 /* Timed out, enter init state */
1563 bb_error_msg("lease lost, entering init state");
1564 udhcp_run_script(NULL, "deconfig");
1565 state = INIT_SELECTING;
1566 client_config.first_secs = 0; /* make secs field count from 0 */
1567 /*timeout = 0; - already is */
1568 packet_num = 0;
1569 continue;
1570 /* case RELEASED: */
1571 }
1572 /* yah, I know, *you* say it would never happen */
1573 timeout = INT_MAX;
1574 continue; /* back to main loop */
1575 } /* if select timed out */
1576
1577 /* select() didn't timeout, something happened */
1578
1579 /* Is it a signal? */
1580 /* note: udhcp_sp_read checks FD_ISSET before reading */
1581 switch (udhcp_sp_read(&rfds)) {
1582 case SIGUSR1:
1583 client_config.first_secs = 0; /* make secs field count from 0 */
1584 already_waited_sec = 0;
1585 perform_renew();
1586 if (state == RENEW_REQUESTED) {
1587 /* We might be either on the same network
1588 * (in which case renew might work),
1589 * or we might be on a completely different one
1590 * (in which case renew won't ever succeed).
1591 * For the second case, must make sure timeout
1592 * is not too big, or else we can send
1593 * futile renew requests for hours.
1594 * (Ab)use -A TIMEOUT value (usually 20 sec)
1595 * as a cap on the timeout.
1596 */
1597 if (timeout > tryagain_timeout)
1598 timeout = tryagain_timeout;
1599 goto case_RENEW_REQUESTED;
1600 }
1601 /* Start things over */
1602 packet_num = 0;
1603 /* Kill any timeouts, user wants this to hurry along */
1604 timeout = 0;
1605 continue;
1606 case SIGUSR2:
1607 perform_release(server_addr, requested_ip);
1608 timeout = INT_MAX;
1609 continue;
1610 case SIGTERM:
1611 bb_error_msg("received %s", "SIGTERM");
1612 goto ret0;
1613 }
1614
1615 /* Is it a packet? */
1616 if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
1617 continue; /* no */
1618
1619 {
1620 int len;
1621
1622 /* A packet is ready, read it */
1623 if (listen_mode == LISTEN_KERNEL)
1624 len = udhcp_recv_kernel_packet(&packet, sockfd);
1625 else
1626 len = udhcp_recv_raw_packet(&packet, sockfd);
1627 if (len == -1) {
1628 /* Error is severe, reopen socket */
1629 bb_error_msg("read error: %s, reopening socket", strerror(errno));
1630 sleep(discover_timeout); /* 3 seconds by default */
1631 change_listen_mode(listen_mode); /* just close and reopen */
1632 }
1633 /* If this packet will turn out to be unrelated/bogus,
1634 * we will go back and wait for next one.
1635 * Be sure timeout is properly decreased. */
1636 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1637 if (len < 0)
1638 continue;
1639 }
1640
1641 if (packet.xid != xid) {
1642 log1("xid %x (our is %x), ignoring packet",
1643 (unsigned)packet.xid, (unsigned)xid);
1644 continue;
1645 }
1646
1647 /* Ignore packets that aren't for us */
1648 if (packet.hlen != 6
1649 || memcmp(packet.chaddr, client_config.client_mac, 6) != 0
1650 ) {
1651//FIXME: need to also check that last 10 bytes are zero
1652 log1("chaddr does not match, ignoring packet"); // log2?
1653 continue;
1654 }
1655
1656 message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
1657 if (message == NULL) {
1658 bb_error_msg("no message type option, ignoring packet");
1659 continue;
1660 }
1661
1662 switch (state) {
1663 case INIT_SELECTING:
1664 /* Must be a DHCPOFFER */
1665 if (*message == DHCPOFFER) {
1666 uint8_t *temp;
1667
1668/* What exactly is server's IP? There are several values.
1669 * Example DHCP offer captured with tchdump:
1670 *
1671 * 10.34.25.254:67 > 10.34.25.202:68 // IP header's src
1672 * BOOTP fields:
1673 * Your-IP 10.34.25.202
1674 * Server-IP 10.34.32.125 // "next server" IP
1675 * Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use)
1676 * DHCP options:
1677 * DHCP-Message Option 53, length 1: Offer
1678 * Server-ID Option 54, length 4: 10.34.255.7 // "server ID"
1679 * Default-Gateway Option 3, length 4: 10.34.25.254 // router
1680 *
1681 * We think that real server IP (one to use in renew/release)
1682 * is one in Server-ID option. But I am not 100% sure.
1683 * IP header's src and Gateway-IP (same in this example)
1684 * might work too.
1685 * "Next server" and router are definitely wrong ones to use, though...
1686 */
1687/* We used to ignore pcakets without DHCP_SERVER_ID.
1688 * I've got user reports from people who run "address-less" servers.
1689 * They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all.
1690 * They say ISC DHCP client supports this case.
1691 */
1692 server_addr = 0;
1693 temp = udhcp_get_option(&packet, DHCP_SERVER_ID);
1694 if (!temp) {
1695 bb_error_msg("no server ID, using 0.0.0.0");
1696 } else {
1697 /* it IS unaligned sometimes, don't "optimize" */
1698 move_from_unaligned32(server_addr, temp);
1699 }
1700 /*xid = packet.xid; - already is */
1701 requested_ip = packet.yiaddr;
1702
1703 /* enter requesting state */
1704 state = REQUESTING;
1705 timeout = 0;
1706 packet_num = 0;
1707 already_waited_sec = 0;
1708 }
1709 continue;
1710 case REQUESTING:
1711 case RENEWING:
1712 case RENEW_REQUESTED:
1713 case REBINDING:
1714 if (*message == DHCPACK) {
1715 unsigned start;
1716 uint32_t lease_seconds;
1717 struct in_addr temp_addr;
1718 uint8_t *temp;
1719
1720 temp = udhcp_get_option(&packet, DHCP_LEASE_TIME);
1721 if (!temp) {
1722 bb_error_msg("no lease time with ACK, using 1 hour lease");
1723 lease_seconds = 60 * 60;
1724 } else {
1725 /* it IS unaligned sometimes, don't "optimize" */
1726 move_from_unaligned32(lease_seconds, temp);
1727 lease_seconds = ntohl(lease_seconds);
1728 /* paranoia: must not be too small and not prone to overflows */
1729 if (lease_seconds < 0x10)
1730 lease_seconds = 0x10;
1731 if (lease_seconds >= 0x10000000)
1732 lease_seconds = 0x0fffffff;
1733 }
1734#if ENABLE_FEATURE_UDHCPC_ARPING
1735 if (opt & OPT_a) {
1736/* RFC 2131 3.1 paragraph 5:
1737 * "The client receives the DHCPACK message with configuration
1738 * parameters. The client SHOULD perform a final check on the
1739 * parameters (e.g., ARP for allocated network address), and notes
1740 * the duration of the lease specified in the DHCPACK message. At this
1741 * point, the client is configured. If the client detects that the
1742 * address is already in use (e.g., through the use of ARP),
1743 * the client MUST send a DHCPDECLINE message to the server and restarts
1744 * the configuration process..." */
1745 if (!arpping(packet.yiaddr,
1746 NULL,
1747 (uint32_t) 0,
1748 client_config.client_mac,
1749 client_config.interface,
1750 arpping_ms)
1751 ) {
1752 bb_error_msg("offered address is in use "
1753 "(got ARP reply), declining");
1754 send_decline(/*xid,*/ server_addr, packet.yiaddr);
1755
1756 if (state != REQUESTING)
1757 udhcp_run_script(NULL, "deconfig");
1758 change_listen_mode(LISTEN_RAW);
1759 state = INIT_SELECTING;
1760 client_config.first_secs = 0; /* make secs field count from 0 */
1761 requested_ip = 0;
1762 timeout = tryagain_timeout;
1763 packet_num = 0;
1764 already_waited_sec = 0;
1765 continue; /* back to main loop */
1766 }
1767 }
1768#endif
1769 /* enter bound state */
1770 temp_addr.s_addr = packet.yiaddr;
1771 bb_error_msg("lease of %s obtained, lease time %u",
1772 inet_ntoa(temp_addr), (unsigned)lease_seconds);
1773 requested_ip = packet.yiaddr;
1774
1775 start = monotonic_sec();
1776 udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
1777 already_waited_sec = (unsigned)monotonic_sec() - start;
1778 timeout = lease_seconds / 2;
1779 if ((unsigned)timeout < already_waited_sec) {
1780 /* Something went wrong. Back to discover state */
1781 timeout = already_waited_sec = 0;
1782 }
1783
1784 state = BOUND;
1785 change_listen_mode(LISTEN_NONE);
1786 if (opt & OPT_q) { /* quit after lease */
1787 goto ret0;
1788 }
1789 /* future renew failures should not exit (JM) */
1790 opt &= ~OPT_n;
1791#if BB_MMU /* NOMMU case backgrounded earlier */
1792 if (!(opt & OPT_f)) {
1793 client_background();
1794 /* do not background again! */
1795 opt = ((opt & ~OPT_b) | OPT_f);
1796 }
1797#endif
1798 /* make future renew packets use different xid */
1799 /* xid = random_xid(); ...but why bother? */
1800
1801 continue; /* back to main loop */
1802 }
1803 if (*message == DHCPNAK) {
1804 /* If network has more than one DHCP server,
1805 * "wrong" server can reply first, with a NAK.
1806 * Do not interpret it as a NAK from "our" server.
1807 */
1808 if (server_addr != 0) {
1809 uint32_t svid;
1810 uint8_t *temp;
1811
1812 temp = udhcp_get_option(&packet, DHCP_SERVER_ID);
1813 if (!temp) {
1814 non_matching_svid:
1815 log1("%s with wrong server ID, ignoring packet",
1816 "Received DHCP NAK"
1817 );
1818 continue;
1819 }
1820 move_from_unaligned32(svid, temp);
1821 if (svid != server_addr)
1822 goto non_matching_svid;
1823 }
1824 /* return to init state */
1825 bb_error_msg("received %s", "DHCP NAK");
1826 udhcp_run_script(&packet, "nak");
1827 if (state != REQUESTING)
1828 udhcp_run_script(NULL, "deconfig");
1829 change_listen_mode(LISTEN_RAW);
1830 sleep(3); /* avoid excessive network traffic */
1831 state = INIT_SELECTING;
1832 client_config.first_secs = 0; /* make secs field count from 0 */
1833 requested_ip = 0;
1834 timeout = 0;
1835 packet_num = 0;
1836 already_waited_sec = 0;
1837 }
1838 continue;
1839 /* case BOUND: - ignore all packets */
1840 /* case RELEASED: - ignore all packets */
1841 }
1842 /* back to main loop */
1843 } /* for (;;) - main loop ends */
1844
1845 ret0:
1846 if (opt & OPT_R) /* release on quit */
1847 perform_release(server_addr, requested_ip);
1848 retval = 0;
1849 ret:
1850 /*if (client_config.pidfile) - remove_pidfile has its own check */
1851 remove_pidfile(client_config.pidfile);
1852 return retval;
1853}
Note: See TracBrowser for help on using the repository browser.