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