6abca6d1c81f43b5e138f83107f00b70841dbe05
[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 = -1;
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 IN_BUSYBOX
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         if (fd >= 0) 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         client_config.background_if_no_lease = 0;
202         pidfile_write_release(pid_fd);
203 }
204
205
206 #ifdef COMBINED_BINARY
207 int udhcpc_main(int argc, char *argv[])
208 #else
209 int main(int argc, char *argv[])
210 #endif
211 {
212         unsigned char *temp, *message;
213         unsigned long t1 = 0, t2 = 0, xid = 0;
214         unsigned long start = 0, lease;
215         fd_set rfds;
216         int retval;
217         struct timeval tv;
218         int c, len;
219         struct dhcpMessage packet;
220         struct in_addr temp_addr;
221         int pid_fd;
222         time_t now;
223         int max_fd;
224         int sig;
225
226         static struct option arg_options[] = {
227                 {"clientid",    required_argument,      0, 'c'},
228                 {"foreground",  no_argument,            0, 'f'},
229                 {"background",  no_argument,            0, 'b'},
230                 {"hostname",    required_argument,      0, 'H'},
231                 {"hostname",    required_argument,      0, 'h'},
232                 {"interface",   required_argument,      0, 'i'},
233                 {"now",         no_argument,            0, 'n'},
234                 {"pidfile",     required_argument,      0, 'p'},
235                 {"quit",        no_argument,            0, 'q'},
236                 {"request",     required_argument,      0, 'r'},
237                 {"script",      required_argument,      0, 's'},
238                 {"version",     no_argument,            0, 'v'},
239                 {"help",        no_argument,            0, '?'},
240                 {0, 0, 0, 0}
241         };
242
243         /* get options */
244         while (1) {
245                 int option_index = 0;
246                 c = getopt_long(argc, argv, "c:fbH:h:i:np:qr:s:v", arg_options, &option_index);
247                 if (c == -1) break;
248                 
249                 switch (c) {
250                 case 'c':
251                         len = strlen(optarg) > 255 ? 255 : strlen(optarg);
252                         if (client_config.clientid) free(client_config.clientid);
253                         client_config.clientid = xmalloc(len + 2);
254                         client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
255                         client_config.clientid[OPT_LEN] = len;
256                         client_config.clientid[OPT_DATA] = '\0';
257                         strncpy(client_config.clientid + OPT_DATA, optarg, len);
258                         break;
259                 case 'f':
260                         client_config.foreground = 1;
261                         break;
262                 case 'b':
263                         client_config.background_if_no_lease = 1;
264                         break;
265                 case 'h':
266                 case 'H':
267                         len = strlen(optarg) > 255 ? 255 : strlen(optarg);
268                         if (client_config.hostname) free(client_config.hostname);
269                         client_config.hostname = xmalloc(len + 2);
270                         client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
271                         client_config.hostname[OPT_LEN] = len;
272                         strncpy(client_config.hostname + 2, 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 'v':
293                         printf("udhcpcd, version %s\n\n", VERSION);
294                         exit_client(0);
295                         break;
296                 default:
297                         show_usage();
298                 }
299         }
300
301         OPEN_LOG("udhcpc");
302         LOG(LOG_INFO, "udhcp client (v%s) started", VERSION);
303
304         pid_fd = pidfile_acquire(client_config.pidfile);
305         pidfile_write_release(pid_fd);
306
307         if (read_interface(client_config.interface, &client_config.ifindex, 
308                            NULL, client_config.arp) < 0)
309                 exit_client(1);
310                 
311         if (!client_config.clientid) {
312                 client_config.clientid = xmalloc(6 + 3);
313                 client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
314                 client_config.clientid[OPT_LEN] = 7;
315                 client_config.clientid[OPT_DATA] = 1;
316                 memcpy(client_config.clientid + 3, client_config.arp, 6);
317         }
318
319         /* setup signal handlers */
320         socketpair(AF_UNIX, SOCK_STREAM, 0, signal_pipe);
321         signal(SIGUSR1, signal_handler);
322         signal(SIGUSR2, signal_handler);
323         signal(SIGTERM, signal_handler);
324         
325         state = INIT_SELECTING;
326         run_script(NULL, "deconfig");
327         change_mode(LISTEN_RAW);
328
329         for (;;) {
330
331                 tv.tv_sec = timeout - time(0);
332                 tv.tv_usec = 0;
333                 FD_ZERO(&rfds);
334
335                 if (listen_mode != LISTEN_NONE && fd < 0) {
336                         if (listen_mode == LISTEN_KERNEL)
337                                 fd = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface);
338                         else
339                                 fd = raw_socket(client_config.ifindex);
340                         if (fd < 0) {
341                                 LOG(LOG_ERR, "FATAL: couldn't listen on socket, %s", strerror(errno));
342                                 exit_client(0);
343                         }
344                 }
345                 if (fd >= 0) FD_SET(fd, &rfds);
346                 FD_SET(signal_pipe[0], &rfds);          
347
348                 if (tv.tv_sec > 0) {
349                         DEBUG(LOG_INFO, "Waiting on select...\n");
350                         max_fd = signal_pipe[0] > fd ? signal_pipe[0] : fd;
351                         retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
352                 } else retval = 0; /* If we already timed out, fall through */
353
354                 now = time(0);
355                 if (retval == 0) {
356                         /* timeout dropped to zero */
357                         switch (state) {
358                         case INIT_SELECTING:
359                                 if (packet_num < 3) {
360                                         if (packet_num == 0)
361                                                 xid = random_xid();
362
363                                         /* send discover packet */
364                                         send_discover(xid, requested_ip); /* broadcast */
365                                         
366                                         timeout = now + ((packet_num == 2) ? 4 : 2);
367                                         packet_num++;
368                                 } else {
369                                         if (client_config.background_if_no_lease) {
370                                                 LOG(LOG_INFO, "No lease, forking to background.");
371                                                 background();
372                                         } else if (client_config.abort_if_no_lease) {
373                                                 LOG(LOG_INFO, "No lease, failing.");
374                                                 exit_client(1);
375                                         }
376                                         /* wait to try again */
377                                         packet_num = 0;
378                                         timeout = now + 60;
379                                 }
380                                 break;
381                         case RENEW_REQUESTED:
382                         case REQUESTING:
383                                 if (packet_num < 3) {
384                                         /* send request packet */
385                                         if (state == RENEW_REQUESTED)
386                                                 send_renew(xid, server_addr, requested_ip); /* unicast */
387                                         else send_selecting(xid, server_addr, requested_ip); /* broadcast */
388                                         
389                                         timeout = now + ((packet_num == 2) ? 10 : 2);
390                                         packet_num++;
391                                 } else {
392                                         /* timed out, go back to init state */
393                                         if (state == RENEW_REQUESTED) run_script(NULL, "deconfig");
394                                         state = INIT_SELECTING;
395                                         timeout = now;
396                                         packet_num = 0;
397                                         change_mode(LISTEN_RAW);
398                                 }
399                                 break;
400                         case BOUND:
401                                 /* Lease is starting to run out, time to enter renewing state */
402                                 state = RENEWING;
403                                 change_mode(LISTEN_KERNEL);
404                                 DEBUG(LOG_INFO, "Entering renew state");
405                                 /* fall right through */
406                         case RENEWING:
407                                 /* Either set a new T1, or enter REBINDING state */
408                                 if ((t2 - t1) <= (lease / 14400 + 1)) {
409                                         /* timed out, enter rebinding state */
410                                         state = REBINDING;
411                                         timeout = now + (t2 - t1);
412                                         DEBUG(LOG_INFO, "Entering rebinding state");
413                                 } else {
414                                         /* send a request packet */
415                                         send_renew(xid, server_addr, requested_ip); /* unicast */
416                                         
417                                         t1 = (t2 - t1) / 2 + t1;
418                                         timeout = t1 + start;
419                                 }
420                                 break;
421                         case REBINDING:
422                                 /* Either set a new T2, or enter INIT state */
423                                 if ((lease - t2) <= (lease / 14400 + 1)) {
424                                         /* timed out, enter init state */
425                                         state = INIT_SELECTING;
426                                         LOG(LOG_INFO, "Lease lost, entering init state");
427                                         run_script(NULL, "deconfig");
428                                         timeout = now;
429                                         packet_num = 0;
430                                         change_mode(LISTEN_RAW);
431                                 } else {
432                                         /* send a request packet */
433                                         send_renew(xid, 0, requested_ip); /* broadcast */
434
435                                         t2 = (lease - t2) / 2 + t2;
436                                         timeout = t2 + start;
437                                 }
438                                 break;
439                         case RELEASED:
440                                 /* yah, I know, *you* say it would never happen */
441                                 timeout = 0x7fffffff;
442                                 break;
443                         }
444                 } else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) {
445                         /* a packet is ready, read it */
446                         
447                         if (listen_mode == LISTEN_KERNEL)
448                                 len = get_packet(&packet, fd);
449                         else len = get_raw_packet(&packet, fd);
450                         
451                         if (len == -1 && errno != EINTR) {
452                                 DEBUG(LOG_INFO, "error on read, %s, reopening socket", strerror(errno));
453                                 change_mode(listen_mode); /* just close and reopen */
454                         }
455                         if (len < 0) continue;
456                         
457                         if (packet.xid != xid) {
458                                 DEBUG(LOG_INFO, "Ignoring XID %lx (our xid is %lx)",
459                                         (unsigned long) packet.xid, xid);
460                                 continue;
461                         }
462                         
463                         if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
464                                 DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring");
465                                 continue;
466                         }
467                         
468                         switch (state) {
469                         case INIT_SELECTING:
470                                 /* Must be a DHCPOFFER to one of our xid's */
471                                 if (*message == DHCPOFFER) {
472                                         if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
473                                                 memcpy(&server_addr, temp, 4);
474                                                 xid = packet.xid;
475                                                 requested_ip = packet.yiaddr;
476                                                 
477                                                 /* enter requesting state */
478                                                 state = REQUESTING;
479                                                 timeout = now;
480                                                 packet_num = 0;
481                                         } else {
482                                                 DEBUG(LOG_ERR, "No server ID in message");
483                                         }
484                                 }
485                                 break;
486                         case RENEW_REQUESTED:
487                         case REQUESTING:
488                         case RENEWING:
489                         case REBINDING:
490                                 if (*message == DHCPACK) {
491                                         if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
492                                                 LOG(LOG_ERR, "No lease time with ACK, using 1 hour lease");
493                                                 lease = 60 * 60;
494                                         } else {
495                                                 memcpy(&lease, temp, 4);
496                                                 lease = ntohl(lease);
497                                         }
498                                                 
499                                         /* enter bound state */
500                                         t1 = lease / 2;
501                                         
502                                         /* little fixed point for n * .875 */
503                                         t2 = (lease * 0x7) >> 3;
504                                         temp_addr.s_addr = packet.yiaddr;
505                                         LOG(LOG_INFO, "Lease of %s obtained, lease time %ld", 
506                                                 inet_ntoa(temp_addr), lease);
507                                         start = now;
508                                         timeout = t1 + start;
509                                         requested_ip = packet.yiaddr;
510                                         run_script(&packet,
511                                                    ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));
512
513                                         state = BOUND;
514                                         change_mode(LISTEN_NONE);
515                                         if (client_config.quit_after_lease) 
516                                                 exit_client(0);
517                                         if (!client_config.foreground)
518                                                 background();
519
520                                 } else if (*message == DHCPNAK) {
521                                         /* return to init state */
522                                         LOG(LOG_INFO, "Received DHCP NAK");
523                                         run_script(&packet, "nak");
524                                         if (state != REQUESTING)
525                                                 run_script(NULL, "deconfig");
526                                         state = INIT_SELECTING;
527                                         timeout = now;
528                                         requested_ip = 0;
529                                         packet_num = 0;
530                                         change_mode(LISTEN_RAW);
531                                         sleep(3); /* avoid excessive network traffic */
532                                 }
533                                 break;
534                         /* case BOUND, RELEASED: - ignore all packets */
535                         }       
536                 } else if (retval > 0 && FD_ISSET(signal_pipe[0], &rfds)) {
537                         if (read(signal_pipe[0], &sig, sizeof(sig)) < 0) {
538                                 DEBUG(LOG_ERR, "Could not read signal: %s", 
539                                         strerror(errno));
540                                 continue; /* probably just EINTR */
541                         }
542                         switch (sig) {
543                         case SIGUSR1: 
544                                 perform_renew();
545                                 break;
546                         case SIGUSR2:
547                                 perform_release();
548                                 break;
549                         case SIGTERM:
550                                 LOG(LOG_INFO, "Received SIGTERM");
551                                 exit_client(0);
552                         }
553                 } else if (retval == -1 && errno == EINTR) {
554                         /* a signal was caught */               
555                 } else {
556                         /* An error occured */
557                         DEBUG(LOG_ERR, "Error on select");
558                 }
559                 
560         }
561         return 0;
562 }
563