lpr: add more accurate comments
[oweals/busybox.git] / networking / udhcp / dhcpc.c
1 /* vi: set sw=4 ts=4: */
2 /* dhcpc.c
3  *
4  * udhcp DHCP client
5  *
6  * Russ Dill <Russ.Dill@asu.edu> July 2001
7  *
8  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
9  */
10
11 #include <syslog.h>
12
13 /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
14 #define WANT_PIDFILE 1
15 #include "common.h"
16 #include "dhcpd.h"
17 #include "dhcpc.h"
18 #include "options.h"
19
20
21 static int timeout; /* = 0. Must be signed */
22 static uint32_t requested_ip; /* = 0 */
23 static uint32_t server_addr;
24 static int sockfd = -1;
25
26 #define LISTEN_NONE 0
27 #define LISTEN_KERNEL 1
28 #define LISTEN_RAW 2
29 static smallint listen_mode;
30
31 static smallint state;
32
33 /* struct client_config_t client_config is in bb_common_bufsiz1 */
34
35
36 /* just a little helper */
37 static void change_listen_mode(int new_mode)
38 {
39         DEBUG("entering %s listen mode",
40                 new_mode ? (new_mode == 1 ? "kernel" : "raw") : "none");
41         if (sockfd >= 0) {
42                 close(sockfd);
43                 sockfd = -1;
44         }
45         listen_mode = new_mode;
46 }
47
48
49 /* perform a renew */
50 static void perform_renew(void)
51 {
52         bb_info_msg("Performing a DHCP renew");
53         switch (state) {
54         case BOUND:
55                 change_listen_mode(LISTEN_KERNEL);
56         case RENEWING:
57         case REBINDING:
58                 state = RENEW_REQUESTED;
59                 break;
60         case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
61                 udhcp_run_script(NULL, "deconfig");
62         case REQUESTING:
63         case RELEASED:
64                 change_listen_mode(LISTEN_RAW);
65                 state = INIT_SELECTING;
66                 break;
67         case INIT_SELECTING:
68                 break;
69         }
70 }
71
72
73 /* perform a release */
74 static void perform_release(void)
75 {
76         char buffer[sizeof("255.255.255.255")];
77         struct in_addr temp_addr;
78
79         /* send release packet */
80         if (state == BOUND || state == RENEWING || state == REBINDING) {
81                 temp_addr.s_addr = server_addr;
82                 strcpy(buffer, inet_ntoa(temp_addr));
83                 temp_addr.s_addr = requested_ip;
84                 bb_info_msg("Unicasting a release of %s to %s",
85                                 inet_ntoa(temp_addr), buffer);
86                 send_release(server_addr, requested_ip); /* unicast */
87                 udhcp_run_script(NULL, "deconfig");
88         }
89         bb_info_msg("Entering released state");
90
91         change_listen_mode(LISTEN_NONE);
92         state = RELEASED;
93         timeout = INT_MAX;
94 }
95
96
97 static void client_background(void)
98 {
99 #if !BB_MMU
100         bb_error_msg("cannot background in uclinux (yet)");
101 /* ... mainly because udhcpc calls client_background()
102  * in _the _middle _of _udhcpc _run_, not at the start!
103  * If that will be properly disabled for NOMMU, client_background()
104  * will work on NOMMU too */
105 #else
106         bb_daemonize(0);
107         logmode &= ~LOGMODE_STDIO;
108         /* rewrite pidfile, as our pid is different now */
109         write_pidfile(client_config.pidfile);
110 #endif
111         /* Do not fork again. */
112         client_config.foreground = 1;
113         client_config.background_if_no_lease = 0;
114 }
115
116
117 static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
118 {
119         uint8_t *storage;
120         int len = strlen(str);
121         if (len > 255) len = 255;
122         storage = xzalloc(len + extra + OPT_DATA);
123         storage[OPT_CODE] = code;
124         storage[OPT_LEN] = len + extra;
125         memcpy(storage + extra + OPT_DATA, str, len);
126         return storage;
127 }
128
129
130 int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
131 int udhcpc_main(int argc ATTRIBUTE_UNUSED, char **argv)
132 {
133         uint8_t *temp, *message;
134         char *str_c, *str_V, *str_h, *str_F, *str_r;
135         USE_FEATURE_UDHCP_PORT(char *str_P;)
136         llist_t *list_O = NULL;
137 #if ENABLE_FEATURE_UDHCPC_ARPING
138         char *str_W;
139 #endif
140         int tryagain_timeout = 20;
141         int discover_timeout = 3;
142         int discover_retries = 3;
143         uint32_t xid = 0;
144         uint32_t lease_seconds = 0; /* can be given as 32-bit quantity */
145         int packet_num;
146         /* t1, t2... what a wonderful names... */
147         unsigned t1 = t1; /* for gcc */
148         unsigned t2 = t2;
149         unsigned timestamp_got_lease = timestamp_got_lease;
150         unsigned opt;
151         int max_fd;
152         int retval;
153         int len;
154         struct timeval tv;
155         struct in_addr temp_addr;
156         struct dhcpMessage packet;
157         fd_set rfds;
158
159         enum {
160                 OPT_c = 1 << 0,
161                 OPT_C = 1 << 1,
162                 OPT_V = 1 << 2,
163                 OPT_f = 1 << 3,
164                 OPT_b = 1 << 4,
165                 OPT_H = 1 << 5,
166                 OPT_h = 1 << 6,
167                 OPT_F = 1 << 7,
168                 OPT_i = 1 << 8,
169                 OPT_n = 1 << 9,
170                 OPT_p = 1 << 10,
171                 OPT_q = 1 << 11,
172                 OPT_R = 1 << 12,
173                 OPT_r = 1 << 13,
174                 OPT_s = 1 << 14,
175                 OPT_T = 1 << 15,
176                 OPT_t = 1 << 16,
177                 OPT_v = 1 << 17,
178                 OPT_S = 1 << 18,
179                 OPT_A = 1 << 19,
180 #if ENABLE_FEATURE_UDHCPC_ARPING
181                 OPT_a = 1 << 20,
182                 OPT_W = 1 << 21,
183 #endif
184                 OPT_P = 1 << 22,
185         };
186 #if ENABLE_GETOPT_LONG
187         static const char udhcpc_longopts[] ALIGN1 =
188                 "clientid\0"       Required_argument "c"
189                 "clientid-none\0"  No_argument       "C"
190                 "vendorclass\0"    Required_argument "V"
191                 "foreground\0"     No_argument       "f"
192                 "background\0"     No_argument       "b"
193                 "hostname\0"       Required_argument "H"
194                 "fqdn\0"           Required_argument "F"
195                 "interface\0"      Required_argument "i"
196                 "now\0"            No_argument       "n"
197                 "pidfile\0"        Required_argument "p"
198                 "quit\0"           No_argument       "q"
199                 "release\0"        No_argument       "R"
200                 "request\0"        Required_argument "r"
201                 "script\0"         Required_argument "s"
202                 "timeout\0"        Required_argument "T"
203                 "version\0"        No_argument       "v"
204                 "retries\0"        Required_argument "t"
205                 "tryagain\0"       Required_argument "A"
206                 "syslog\0"         No_argument       "S"
207 #if ENABLE_FEATURE_UDHCPC_ARPING
208                 "arping\0"         No_argument       "a"
209 #endif
210                 "request-option\0" Required_argument "O"
211 #if ENABLE_FEATURE_UDHCP_PORT
212                 "client-port\0"    Required_argument "P"
213 #endif
214                 ;
215 #endif
216         /* Default options. */
217 #if ENABLE_FEATURE_UDHCP_PORT
218         SERVER_PORT = 67;
219         CLIENT_PORT = 68;
220 #endif
221         client_config.interface = "eth0";
222         client_config.script = DEFAULT_SCRIPT;
223
224         /* Parse command line */
225         /* Cc: mutually exclusive; O: list; -T,-t,-A take numeric param */
226         opt_complementary = "c--C:C--c:O::T+:t+:A+";
227 #if ENABLE_GETOPT_LONG
228         applet_long_options = udhcpc_longopts;
229 #endif
230         opt = getopt32(argv, "c:CV:fbH:h:F:i:np:qRr:s:T:t:vSA:"
231                 USE_FEATURE_UDHCPC_ARPING("aW:")
232                 USE_FEATURE_UDHCP_PORT("P:")
233                 "O:"
234                 , &str_c, &str_V, &str_h, &str_h, &str_F
235                 , &client_config.interface, &client_config.pidfile, &str_r
236                 , &client_config.script
237                 , &discover_timeout, &discover_retries, &tryagain_timeout
238                 USE_FEATURE_UDHCPC_ARPING(, &str_W)
239                 USE_FEATURE_UDHCP_PORT(, &str_P)
240                 , &list_O
241                 );
242
243         if (opt & OPT_c)
244                 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, str_c, 0);
245         //if (opt & OPT_C)
246         if (opt & OPT_V)
247                 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
248         if (opt & OPT_f)
249                 client_config.foreground = 1;
250         if (opt & OPT_b)
251                 client_config.background_if_no_lease = 1;
252         if (opt & (OPT_h|OPT_H))
253                 client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
254         if (opt & OPT_F) {
255                 client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
256                 /* Flags: 0000NEOS
257                 S: 1 => Client requests Server to update A RR in DNS as well as PTR
258                 O: 1 => Server indicates to client that DNS has been updated regardless
259                 E: 1 => Name data is DNS format, i.e. <4>host<6>domain<4>com<0> not "host.domain.com"
260                 N: 1 => Client requests Server to not update DNS
261                 */
262                 client_config.fqdn[OPT_DATA + 0] = 0x1;
263                 /* client_config.fqdn[OPT_DATA + 1] = 0; - redundant */
264                 /* client_config.fqdn[OPT_DATA + 2] = 0; - redundant */
265         }
266         // if (opt & OPT_i) client_config.interface = ...
267         if (opt & OPT_n)
268                 client_config.abort_if_no_lease = 1;
269         // if (opt & OPT_p) client_config.pidfile = ...
270         if (opt & OPT_q)
271                 client_config.quit_after_lease = 1;
272         if (opt & OPT_R)
273                 client_config.release_on_quit = 1;
274         if (opt & OPT_r)
275                 requested_ip = inet_addr(str_r);
276         // if (opt & OPT_s) client_config.script = ...
277         // if (opt & OPT_T) discover_timeout = xatoi_u(str_T);
278         // if (opt & OPT_t) discover_retries = xatoi_u(str_t);
279         // if (opt & OPT_A) tryagain_timeout = xatoi_u(str_A);
280         if (opt & OPT_v) {
281                 puts("version "BB_VER);
282                 return 0;
283         }
284         if (opt & OPT_S) {
285                 openlog(applet_name, LOG_PID, LOG_LOCAL0);
286                 logmode |= LOGMODE_SYSLOG;
287         }
288 #if ENABLE_FEATURE_UDHCP_PORT
289         if (opt & OPT_P) {
290                 CLIENT_PORT = xatou16(str_P);
291                 SERVER_PORT = CLIENT_PORT - 1;
292         }
293 #endif
294         while (list_O) {
295                 int n = index_in_strings(dhcp_option_strings, list_O->data);
296                 if (n < 0)
297                         bb_error_msg_and_die("unknown option '%s'", list_O->data);
298                 n = dhcp_options[n].code;
299                 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
300                 list_O = list_O->link;
301         }
302
303         if (read_interface(client_config.interface, &client_config.ifindex,
304                            NULL, client_config.arp))
305                 return 1;
306
307         /* Make sure fd 0,1,2 are open */
308         bb_sanitize_stdio();
309         /* Equivalent of doing a fflush after every \n */
310         setlinebuf(stdout);
311
312         /* Create pidfile */
313         write_pidfile(client_config.pidfile);
314         /* if (!..) bb_perror_msg("cannot create pidfile %s", pidfile); */
315
316         /* Goes to stdout and possibly syslog */
317         bb_info_msg("%s (v"BB_VER") started", applet_name);
318
319         /* if not set, and not suppressed, setup the default client ID */
320         if (!client_config.clientid && !(opt & OPT_C)) {
321                 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
322                 client_config.clientid[OPT_DATA] = 1;
323                 memcpy(client_config.clientid + OPT_DATA+1, client_config.arp, 6);
324         }
325
326         if (!client_config.vendorclass)
327                 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, "udhcp "BB_VER, 0);
328
329         /* setup the signal pipe */
330         udhcp_sp_setup();
331
332         state = INIT_SELECTING;
333         udhcp_run_script(NULL, "deconfig");
334         change_listen_mode(LISTEN_RAW);
335         packet_num = 0;
336
337         /* Main event loop. select() waits on signal pipe and possibly
338          * on sockfd.
339          * "continue" statements in code below jump to the top of the loop.
340          */
341         for (;;) {
342                 tv.tv_sec = timeout;
343                 tv.tv_usec = 0;
344
345                 if (listen_mode != LISTEN_NONE && sockfd < 0) {
346                         if (listen_mode == LISTEN_KERNEL)
347                                 sockfd = listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
348                         else
349                                 sockfd = raw_socket(client_config.ifindex);
350                 }
351                 max_fd = udhcp_sp_fd_set(&rfds, sockfd);
352
353                 retval = 0; /* If we already timed out, fall through, else... */
354                 if (tv.tv_sec > 0) {
355                         DEBUG("Waiting on select...");
356                         retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
357                 }
358
359                 if (retval < 0) {
360                         /* EINTR? signal was caught, don't panic */
361                         if (errno != EINTR) {
362                                 /* Else: an error occured, panic! */
363                                 bb_perror_msg_and_die("select");
364                         }
365                         continue;
366                 }
367
368                 /* If timeout dropped to zero, time to become active:
369                  * resend discover/renew/whatever
370                  */
371                 if (retval == 0) {
372                         switch (state) {
373                         case INIT_SELECTING:
374                                 if (packet_num < discover_retries) {
375                                         if (packet_num == 0)
376                                                 xid = random_xid();
377
378                                         /* send discover packet */
379                                         send_discover(xid, requested_ip); /* broadcast */
380
381                                         timeout = discover_timeout;
382                                         packet_num++;
383                                         continue;
384                                 }
385                                 udhcp_run_script(NULL, "leasefail");
386                                 if (client_config.background_if_no_lease) {
387                                         bb_info_msg("No lease, forking to background");
388                                         client_background();
389                                 } else if (client_config.abort_if_no_lease) {
390                                         bb_info_msg("No lease, failing");
391                                         retval = 1;
392                                         goto ret;
393                                 }
394                                 /* wait to try again */
395                                 timeout = tryagain_timeout;
396                                 packet_num = 0;
397                                 continue;
398                         case RENEW_REQUESTED:
399                         case REQUESTING:
400                                 if (packet_num < discover_retries) {
401                                         /* send request packet */
402                                         if (state == RENEW_REQUESTED)
403                                                 send_renew(xid, server_addr, requested_ip); /* unicast */
404                                         else send_selecting(xid, server_addr, requested_ip); /* broadcast */
405
406                                         timeout = ((packet_num == 2) ? 10 : 2);
407                                         packet_num++;
408                                         continue;
409                                 }
410                                 /* timed out, go back to init state */
411                                 if (state == RENEW_REQUESTED)
412                                         udhcp_run_script(NULL, "deconfig");
413                                 change_listen_mode(LISTEN_RAW);
414                                 state = INIT_SELECTING;
415                                 timeout = 0;
416                                 packet_num = 0;
417                                 continue;
418                         case BOUND:
419                                 /* Lease is starting to run out, time to enter renewing state */
420                                 change_listen_mode(LISTEN_KERNEL);
421                                 DEBUG("Entering renew state");
422                                 state = RENEWING;
423                                 /* fall right through */
424                         case RENEWING:
425                                 /* Either set a new T1, or enter REBINDING state */
426                                 if ((t2 - t1) > (lease_seconds / (4*60*60) + 1)) {
427                                         /* send a request packet */
428                                         send_renew(xid, server_addr, requested_ip); /* unicast */
429                                         t1 += (t2 - t1) / 2;
430                                         timeout = t1 - ((int)monotonic_sec() - timestamp_got_lease);
431                                         continue;
432                                 }
433                                 /* Timed out, enter rebinding state */
434                                 DEBUG("Entering rebinding state");
435                                 state = REBINDING;
436                                 timeout = (t2 - t1);
437                                 continue;
438                         case REBINDING:
439                                 /* Lease is *really* about to run out,
440                                  * try to find DHCP server using broadcast */
441                                 if ((lease_seconds - t2) > (lease_seconds / (4*60*60) + 1)) {
442                                         /* send a request packet */
443                                         send_renew(xid, 0, requested_ip); /* broadcast */
444                                         t2 += (lease_seconds - t2) / 2;
445                                         timeout = t2 - ((int)monotonic_sec() - timestamp_got_lease);
446                                         continue;
447                                 }
448                                 /* Timed out, enter init state */
449                                 bb_info_msg("Lease lost, entering init state");
450                                 udhcp_run_script(NULL, "deconfig");
451                                 change_listen_mode(LISTEN_RAW);
452                                 state = INIT_SELECTING;
453                                 timeout = 0;
454                                 packet_num = 0;
455                                 continue;
456                         /* case RELEASED: */
457                         }
458                         /* yah, I know, *you* say it would never happen */
459                         timeout = INT_MAX;
460                         continue; /* back to main loop */
461                 }
462
463                 /* select() didn't timeout, something did happen. */
464                 /* Is is a packet? */
465                 if (listen_mode != LISTEN_NONE && FD_ISSET(sockfd, &rfds)) {
466                         /* A packet is ready, read it */
467
468                         if (listen_mode == LISTEN_KERNEL)
469                                 len = udhcp_recv_packet(&packet, sockfd);
470                         else
471                                 len = get_raw_packet(&packet, sockfd);
472
473                         if (len == -1) { /* error is severe, reopen socket */
474                                 DEBUG("error on read, %s, reopening socket", strerror(errno));
475                                 change_listen_mode(listen_mode); /* just close and reopen */
476                         }
477                         if (len < 0) continue;
478
479                         if (packet.xid != xid) {
480                                 DEBUG("Ignoring XID %x (our xid is %x)",
481                                         (unsigned)packet.xid, (unsigned)xid);
482                                 continue;
483                         }
484
485                         /* Ignore packets that aren't for us */
486                         if (memcmp(packet.chaddr, client_config.arp, 6)) {
487                                 DEBUG("Packet does not have our chaddr - ignoring");
488                                 continue;
489                         }
490
491                         message = get_option(&packet, DHCP_MESSAGE_TYPE);
492                         if (message == NULL) {
493                                 bb_error_msg("cannot get message type from packet - ignoring");
494                                 continue;
495                         }
496
497                         switch (state) {
498                         case INIT_SELECTING:
499                                 /* Must be a DHCPOFFER to one of our xid's */
500                                 if (*message == DHCPOFFER) {
501                         /* TODO: why we don't just fetch server's IP from IP header? */
502                                         temp = get_option(&packet, DHCP_SERVER_ID);
503                                         if (!temp) {
504                                                 bb_error_msg("no server ID in message");
505                                                 continue;
506                                                 /* still selecting - this server looks bad */
507                                         }
508                                         /* can be misaligned, thus memcpy */
509                                         memcpy(&server_addr, temp, 4);
510                                         xid = packet.xid;
511                                         requested_ip = packet.yiaddr;
512
513                                         /* enter requesting state */
514                                         state = REQUESTING;
515                                         timeout = 0;
516                                         packet_num = 0;
517                                 }
518                                 continue;
519                         case RENEW_REQUESTED:
520                         case REQUESTING:
521                         case RENEWING:
522                         case REBINDING:
523                                 if (*message == DHCPACK) {
524                                         temp = get_option(&packet, DHCP_LEASE_TIME);
525                                         if (!temp) {
526                                                 bb_error_msg("no lease time with ACK, using 1 hour lease");
527                                                 lease_seconds = 60 * 60;
528                                         } else {
529                                                 /* can be misaligned, thus memcpy */
530                                                 memcpy(&lease_seconds, temp, 4);
531                                                 lease_seconds = ntohl(lease_seconds);
532                                         }
533 #if ENABLE_FEATURE_UDHCPC_ARPING
534                                         if (opt & OPT_a) {
535                                                 if (!arpping(packet.yiaddr,
536                                                             (uint32_t) 0,
537                                                             client_config.arp,
538                                                             client_config.interface)
539                                                 ) {
540                                                         bb_info_msg("offered address is in use "
541                                                                 "(got ARP reply), declining");
542                                                         send_decline(xid, server_addr, packet.yiaddr);
543
544                                                         if (state != REQUESTING)
545                                                                 udhcp_run_script(NULL, "deconfig");
546                                                         change_listen_mode(LISTEN_RAW);
547                                                         state = INIT_SELECTING;
548                                                         requested_ip = 0;
549                                                         timeout = tryagain_timeout;
550                                                         packet_num = 0;
551                                                         continue; /* back to main loop */
552                                                 }
553                                         }
554 #endif
555                                         /* enter bound state */
556                                         t1 = lease_seconds / 2;
557
558                                         /* little fixed point for n * .875 */
559                                         t2 = (lease_seconds * 7) >> 3;
560                                         temp_addr.s_addr = packet.yiaddr;
561                                         bb_info_msg("Lease of %s obtained, lease time %u",
562                                                 inet_ntoa(temp_addr), (unsigned)lease_seconds);
563                                         timestamp_got_lease = monotonic_sec();
564                                         timeout = t1;
565                                         requested_ip = packet.yiaddr;
566                                         udhcp_run_script(&packet,
567                                                    ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));
568
569                                         state = BOUND;
570                                         change_listen_mode(LISTEN_NONE);
571                                         if (client_config.quit_after_lease) {
572                                                 if (client_config.release_on_quit)
573                                                         perform_release();
574                                                 goto ret0;
575                                         }
576                                         if (!client_config.foreground)
577                                                 client_background();
578
579                                         continue; /* back to main loop */
580                                 }
581                                 if (*message == DHCPNAK) {
582                                         /* return to init state */
583                                         bb_info_msg("Received DHCP NAK");
584                                         udhcp_run_script(&packet, "nak");
585                                         if (state != REQUESTING)
586                                                 udhcp_run_script(NULL, "deconfig");
587                                         change_listen_mode(LISTEN_RAW);
588                                         sleep(3); /* avoid excessive network traffic */
589                                         state = INIT_SELECTING;
590                                         requested_ip = 0;
591                                         timeout = 0;
592                                         packet_num = 0;
593                                 }
594                                 continue;
595                         /* case BOUND, RELEASED: - ignore all packets */
596                         }
597                         continue; /* back to main loop */
598                 }
599
600                 /* select() didn't timeout, something did happen.
601                  * But it wasn't a packet. It's a signal pipe then. */
602                 {
603                         int signo = udhcp_sp_read(&rfds);
604                         switch (signo) {
605                         case SIGUSR1:
606                                 perform_renew();
607                                 /* start things over */
608                                 packet_num = 0;
609                                 /* Kill any timeouts because the user wants this to hurry along */
610                                 timeout = 0;
611                                 break;
612                         case SIGUSR2:
613                                 perform_release();
614                                 break;
615                         case SIGTERM:
616                                 bb_info_msg("Received SIGTERM");
617                                 if (client_config.release_on_quit)
618                                         perform_release();
619                                 goto ret0;
620                         }
621                 }
622         } /* for (;;) - main loop ends */
623
624  ret0:
625         retval = 0;
626  ret:
627         /*if (client_config.pidfile) - remove_pidfile has it's own check */
628                 remove_pidfile(client_config.pidfile);
629         return retval;
630 }