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