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