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