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