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