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