- spelling
[oweals/busybox.git] / networking / ifupdown.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *  ifupdown for busybox
4  *  Copyright (c) 2002 Glenn McGrath <bug1@iinet.net.au>
5  *  Copyright (c) 2003-2004 Erik Andersen <andersen@codepoet.org>
6  *
7  *  Based on ifupdown v 0.6.4 by Anthony Towns
8  *  Copyright (c) 1999 Anthony Towns <aj@azure.humbug.org.au>
9  *
10  *  Changes to upstream version
11  *  Remove checks for kernel version, assume kernel version 2.2.0 or better.
12  *  Lines in the interfaces file cannot wrap.
13  *  To adhere to the FHS, the default state file is /var/run/ifstate.
14  *
15  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
16  */
17
18 /* TODO: standardise execute() return codes to return 0 for success and 1 for failure */
19
20 #include <sys/stat.h>
21 #include <sys/utsname.h>
22 #include <sys/wait.h>
23
24 #include <ctype.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <fnmatch.h>
28 #include <getopt.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34
35 #include "busybox.h"
36
37 #define MAX_OPT_DEPTH 10
38 #define EUNBALBRACK 10001
39 #define EUNDEFVAR   10002
40 #define EUNBALPER   10000
41
42 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
43 #define MAX_INTERFACE_LENGTH 10
44 #endif
45
46 #if 0
47 #define debug_noise(fmt, args...) printf(fmt, ## args)
48 #else
49 #define debug_noise(fmt, args...)
50 #endif
51
52 /* Forward declaration */
53 struct interface_defn_t;
54
55 typedef int (execfn)(char *command);
56
57 struct method_t
58 {
59         char *name;
60         int (*up)(struct interface_defn_t *ifd, execfn *e);
61         int (*down)(struct interface_defn_t *ifd, execfn *e);
62 };
63
64 struct address_family_t
65 {
66         char *name;
67         int n_methods;
68         struct method_t *method;
69 };
70
71 struct mapping_defn_t
72 {
73         struct mapping_defn_t *next;
74
75         int max_matches;
76         int n_matches;
77         char **match;
78
79         char *script;
80
81         int max_mappings;
82         int n_mappings;
83         char **mapping;
84 };
85
86 struct variable_t
87 {
88         char *name;
89         char *value;
90 };
91
92 struct interface_defn_t
93 {
94         struct address_family_t *address_family;
95         struct method_t *method;
96
97         char *iface;
98         int max_options;
99         int n_options;
100         struct variable_t *option;
101 };
102
103 struct interfaces_file_t
104 {
105         llist_t *autointerfaces;
106         llist_t *ifaces;
107         struct mapping_defn_t *mappings;
108 };
109
110 static char no_act = 0;
111 static char verbose = 0;
112 static char **__myenviron = NULL;
113
114 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
115
116 static unsigned int count_bits(unsigned int a)
117 {
118         unsigned int result;
119         result = (a & 0x55) + ((a >> 1) & 0x55);
120         result = (result & 0x33) + ((result >> 2) & 0x33);
121         return((result & 0x0F) + ((result >> 4) & 0x0F));
122 }
123
124 static int count_netmask_bits(char *dotted_quad)
125 {
126         unsigned int result, a, b, c, d;
127         /* Found a netmask...  Check if it is dotted quad */
128         if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
129                 return -1;
130         result = count_bits(a);
131         result += count_bits(b);
132         result += count_bits(c);
133         result += count_bits(d);
134         return ((int)result);
135 }
136 #endif
137
138 #if ENABLE_FEATURE_IFUPDOWN_IPV4 || ENABLE_FEATURE_IFUPDOWN_IPV6
139 static void addstr(char **buf, size_t *len, size_t *pos, char *str, size_t str_length)
140 {
141         if (*pos + str_length >= *len) {
142                 char *newbuf;
143
144                 newbuf = xrealloc(*buf, *len * 2 + str_length + 1);
145                 *buf = newbuf;
146                 *len = *len * 2 + str_length + 1;
147         }
148
149         while (str_length-- >= 1) {
150                 (*buf)[(*pos)++] = *str;
151                 str++;
152         }
153         (*buf)[*pos] = '\0';
154 }
155
156 static int strncmpz(char *l, char *r, size_t llen)
157 {
158         int i = strncmp(l, r, llen);
159
160         if (i == 0) {
161                 return(-r[llen]);
162         } else {
163                 return(i);
164         }
165 }
166
167 static char *get_var(char *id, size_t idlen, struct interface_defn_t *ifd)
168 {
169         int i;
170
171         if (strncmpz(id, "iface", idlen) == 0) {
172                 char *result;
173                 static char label_buf[20];
174                 strncpy(label_buf, ifd->iface, 19);
175                 label_buf[19]=0;
176                 result = strchr(label_buf, ':');
177                 if (result) {
178                         *result=0;
179                 }
180                 return( label_buf);
181         } else if (strncmpz(id, "label", idlen) == 0) {
182                 return (ifd->iface);
183         } else {
184                 for (i = 0; i < ifd->n_options; i++) {
185                         if (strncmpz(id, ifd->option[i].name, idlen) == 0) {
186                                 return (ifd->option[i].value);
187                         }
188                 }
189         }
190
191         return(NULL);
192 }
193
194 static char *parse(char *command, struct interface_defn_t *ifd)
195 {
196
197         char *result = NULL;
198         size_t pos = 0, len = 0;
199         size_t old_pos[MAX_OPT_DEPTH] = { 0 };
200         int okay[MAX_OPT_DEPTH] = { 1 };
201         int opt_depth = 1;
202
203         while (*command) {
204                 switch (*command) {
205
206                         default:
207                                 addstr(&result, &len, &pos, command, 1);
208                                 command++;
209                                 break;
210                         case '\\':
211                                 if (command[1]) {
212                                         addstr(&result, &len, &pos, command + 1, 1);
213                                         command += 2;
214                                 } else {
215                                         addstr(&result, &len, &pos, command, 1);
216                                         command++;
217                                 }
218                                 break;
219                         case '[':
220                                 if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
221                                         old_pos[opt_depth] = pos;
222                                         okay[opt_depth] = 1;
223                                         opt_depth++;
224                                         command += 2;
225                                 } else {
226                                         addstr(&result, &len, &pos, "[", 1);
227                                         command++;
228                                 }
229                                 break;
230                         case ']':
231                                 if (command[1] == ']' && opt_depth > 1) {
232                                         opt_depth--;
233                                         if (!okay[opt_depth]) {
234                                                 pos = old_pos[opt_depth];
235                                                 result[pos] = '\0';
236                                         }
237                                         command += 2;
238                                 } else {
239                                         addstr(&result, &len, &pos, "]", 1);
240                                         command++;
241                                 }
242                                 break;
243                         case '%':
244                                 {
245                                         char *nextpercent;
246                                         char *varvalue;
247
248                                         command++;
249                                         nextpercent = strchr(command, '%');
250                                         if (!nextpercent) {
251                                                 errno = EUNBALPER;
252                                                 free(result);
253                                                 return (NULL);
254                                         }
255
256                                         varvalue = get_var(command, nextpercent - command, ifd);
257
258                                         if (varvalue) {
259                                                 addstr(&result, &len, &pos, varvalue, strlen(varvalue));
260                                         } else {
261 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
262                                                 /* Sigh...  Add a special case for 'ip' to convert from
263                                                  * dotted quad to bit count style netmasks.  */
264                                                 if (strncmp(command, "bnmask", 6)==0) {
265                                                         int res;
266                                                         varvalue = get_var("netmask", 7, ifd);
267                                                         if (varvalue && (res=count_netmask_bits(varvalue)) > 0) {
268                                                                 char argument[255];
269                                                                 sprintf(argument, "%d", res);
270                                                                 addstr(&result, &len, &pos, argument, strlen(argument));
271                                                                 command = nextpercent + 1;
272                                                                 break;
273                                                         }
274                                                 }
275 #endif
276                                                 okay[opt_depth - 1] = 0;
277                                         }
278
279                                         command = nextpercent + 1;
280                                 }
281                                 break;
282                 }
283         }
284
285         if (opt_depth > 1) {
286                 errno = EUNBALBRACK;
287                 free(result);
288                 return(NULL);
289         }
290
291         if (!okay[0]) {
292                 errno = EUNDEFVAR;
293                 free(result);
294                 return(NULL);
295         }
296
297         return(result);
298 }
299
300 static int execute(char *command, struct interface_defn_t *ifd, execfn *exec)
301 {
302         char *out;
303         int ret;
304
305         out = parse(command, ifd);
306         if (!out) {
307                 return(0);
308         }
309         ret = (*exec) (out);
310
311         free(out);
312         if (ret != 1) {
313                 return(0);
314         }
315         return(1);
316 }
317 #endif
318
319 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV6
320 static int loopback_up6(struct interface_defn_t *ifd, execfn *exec)
321 {
322 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
323         int result;
324         result =execute("ip addr add ::1 dev %iface%", ifd, exec);
325         result += execute("ip link set %iface% up", ifd, exec);
326         return ((result == 2) ? 2 : 0);
327 #else
328         return( execute("ifconfig %iface% add ::1", ifd, exec));
329 #endif
330 }
331
332 static int loopback_down6(struct interface_defn_t *ifd, execfn *exec)
333 {
334 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
335         return(execute("ip link set %iface% down", ifd, exec));
336 #else
337         return(execute("ifconfig %iface% del ::1", ifd, exec));
338 #endif
339 }
340
341 static int static_up6(struct interface_defn_t *ifd, execfn *exec)
342 {
343         int result;
344 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
345         result = execute("ip addr add %address%/%netmask% dev %iface% [[label %label%]]", ifd, exec);
346         result += execute("ip link set [[mtu %mtu%]] [[address %hwaddress%]] %iface% up", ifd, exec);
347         result += execute("[[ ip route add ::/0 via %gateway% ]]", ifd, exec);
348 #else
349         result = execute("ifconfig %iface% [[media %media%]] [[hw %hwaddress%]] [[mtu %mtu%]] up", ifd, exec);
350         result += execute("ifconfig %iface% add %address%/%netmask%", ifd, exec);
351         result += execute("[[ route -A inet6 add ::/0 gw %gateway% ]]", ifd, exec);
352 #endif
353         return ((result == 3) ? 3 : 0);
354 }
355
356 static int static_down6(struct interface_defn_t *ifd, execfn *exec)
357 {
358 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
359         return(execute("ip link set %iface% down", ifd, exec));
360 #else
361         return(execute("ifconfig %iface% down", ifd, exec));
362 #endif
363 }
364
365 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
366 static int v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
367 {
368         int result;
369         result = execute("ip tunnel add %iface% mode sit remote "
370                                 "%endpoint% [[local %local%]] [[ttl %ttl%]]", ifd, exec);
371         result += execute("ip link set %iface% up", ifd, exec);
372         result += execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec);
373         result += execute("[[ ip route add ::/0 via %gateway% ]]", ifd, exec);
374         return ((result == 4) ? 4 : 0);
375 }
376
377 static int v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
378 {
379         return( execute("ip tunnel del %iface%", ifd, exec));
380 }
381 #endif
382
383 static struct method_t methods6[] = {
384 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
385         { "v4tunnel", v4tunnel_up, v4tunnel_down, },
386 #endif
387         { "static", static_up6, static_down6, },
388         { "loopback", loopback_up6, loopback_down6, },
389 };
390
391 static struct address_family_t addr_inet6 = {
392         "inet6",
393         sizeof(methods6) / sizeof(struct method_t),
394         methods6
395 };
396 #endif /* CONFIG_FEATURE_IFUPDOWN_IPV6 */
397
398 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV4
399 static int loopback_up(struct interface_defn_t *ifd, execfn *exec)
400 {
401 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
402         int result;
403         result = execute("ip addr add 127.0.0.1/8 dev %iface%", ifd, exec);
404         result += execute("ip link set %iface% up", ifd, exec);
405         return ((result == 2) ? 2 : 0);
406 #else
407         return( execute("ifconfig %iface% 127.0.0.1 up", ifd, exec));
408 #endif
409 }
410
411 static int loopback_down(struct interface_defn_t *ifd, execfn *exec)
412 {
413 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
414         int result;
415         result = execute("ip addr flush dev %iface%", ifd, exec);
416         result += execute("ip link set %iface% down", ifd, exec);
417         return ((result == 2) ? 2 : 0);
418 #else
419         return( execute("ifconfig %iface% 127.0.0.1 down", ifd, exec));
420 #endif
421 }
422
423 static int static_up(struct interface_defn_t *ifd, execfn *exec)
424 {
425         int result;
426 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
427         result = execute("ip addr add %address%/%bnmask% [[broadcast %broadcast%]] "
428                         "dev %iface% [[peer %pointopoint%]] [[label %label%]]", ifd, exec);
429         result += execute("ip link set [[mtu %mtu%]] [[address %hwaddress%]] %iface% up", ifd, exec);
430         result += execute("[[ ip route add default via %gateway% dev %iface% ]]", ifd, exec);
431         return ((result == 3) ? 3 : 0);
432 #else
433         result = execute("ifconfig %iface% %address% netmask %netmask% "
434                                 "[[broadcast %broadcast%]] [[pointopoint %pointopoint%]] "
435                                 "[[media %media%]] [[mtu %mtu%]] [[hw %hwaddress%]] up",
436                                 ifd, exec);
437         result += execute("[[ route add default gw %gateway% %iface% ]]", ifd, exec);
438         return ((result == 2) ? 2 : 0);
439 #endif
440 }
441
442 static int static_down(struct interface_defn_t *ifd, execfn *exec)
443 {
444         int result;
445 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
446         result = execute("ip addr flush dev %iface%", ifd, exec);
447         result += execute("ip link set %iface% down", ifd, exec);
448 #else
449         result = execute("[[ route del default gw %gateway% %iface% ]]", ifd, exec);
450         result += execute("ifconfig %iface% down", ifd, exec);
451 #endif
452         return ((result == 2) ? 2 : 0);
453 }
454
455 static int execable(char *program)
456 {
457         struct stat buf;
458         if (0 == stat(program, &buf)) {
459                 if (S_ISREG(buf.st_mode) && (S_IXUSR & buf.st_mode)) {
460                         return(1);
461                 }
462         }
463         return(0);
464 }
465
466 static int dhcp_up(struct interface_defn_t *ifd, execfn *exec)
467 {
468         if (execable("/sbin/udhcpc")) {
469                 return( execute("udhcpc -n -p /var/run/udhcpc.%iface%.pid -i "
470                                         "%iface% [[-H %hostname%]] [[-c %clientid%]]", ifd, exec));
471         } else if (execable("/sbin/pump")) {
472                 return( execute("pump -i %iface% [[-h %hostname%]] [[-l %leasehours%]]", ifd, exec));
473         } else if (execable("/sbin/dhclient")) {
474                 return( execute("dhclient -pf /var/run/dhclient.%iface%.pid %iface%", ifd, exec));
475         } else if (execable("/sbin/dhcpcd")) {
476                 return( execute("dhcpcd [[-h %hostname%]] [[-i %vendor%]] [[-I %clientid%]] "
477                                         "[[-l %leasetime%]] %iface%", ifd, exec));
478         }
479         return(0);
480 }
481
482 static int dhcp_down(struct interface_defn_t *ifd, execfn *exec)
483 {
484         int result = 0;
485         if (execable("/sbin/udhcpc")) {
486                 /* SIGUSR2 forces udhcpc to release the current lease and go inactive,
487                  * and SIGTERM causes udhcpc to exit.  Signals are queued and processed
488                  * sequentially so we don't need to sleep */
489                 result = execute("kill -USR2 `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
490                 result += execute("kill -TERM `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
491         } else if (execable("/sbin/pump")) {
492                 result = execute("pump -i %iface% -k", ifd, exec);
493         } else if (execable("/sbin/dhclient")) {
494                 result = execute("kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null", ifd, exec);
495         } else if (execable("/sbin/dhcpcd")) {
496                 result = execute("dhcpcd -k %iface%", ifd, exec);
497         }
498         return (result || static_down(ifd, exec));
499 }
500
501 static int bootp_up(struct interface_defn_t *ifd, execfn *exec)
502 {
503         return( execute("bootpc [[--bootfile %bootfile%]] --dev %iface% "
504                                 "[[--server %server%]] [[--hwaddr %hwaddr%]] "
505                                 "--returniffail --serverbcast", ifd, exec));
506 }
507
508 static int ppp_up(struct interface_defn_t *ifd, execfn *exec)
509 {
510         return( execute("pon [[%provider%]]", ifd, exec));
511 }
512
513 static int ppp_down(struct interface_defn_t *ifd, execfn *exec)
514 {
515         return( execute("poff [[%provider%]]", ifd, exec));
516 }
517
518 static int wvdial_up(struct interface_defn_t *ifd, execfn *exec)
519 {
520         return( execute("/sbin/start-stop-daemon --start -x /usr/bin/wvdial "
521                                 "-p /var/run/wvdial.%iface% -b -m -- [[ %provider% ]]", ifd, exec));
522 }
523
524 static int wvdial_down(struct interface_defn_t *ifd, execfn *exec)
525 {
526         return( execute("/sbin/start-stop-daemon --stop -x /usr/bin/wvdial "
527                                 "-p /var/run/wvdial.%iface% -s 2", ifd, exec));
528 }
529
530 static struct method_t methods[] =
531 {
532         { "wvdial", wvdial_up, wvdial_down, },
533         { "ppp", ppp_up, ppp_down, },
534         { "static", static_up, static_down, },
535         { "bootp", bootp_up, static_down, },
536         { "dhcp", dhcp_up, dhcp_down, },
537         { "loopback", loopback_up, loopback_down, },
538 };
539
540 static struct address_family_t addr_inet =
541 {
542         "inet",
543         sizeof(methods) / sizeof(struct method_t),
544         methods
545 };
546
547 #endif  /* ifdef CONFIG_FEATURE_IFUPDOWN_IPV4 */
548
549 static char *next_word(char **buf)
550 {
551         unsigned short length;
552         char *word;
553
554         if ((buf == NULL) || (*buf == NULL) || (**buf == '\0')) {
555                 return NULL;
556         }
557
558         /* Skip over leading whitespace */
559         word = *buf;
560         while (isspace(*word)) {
561                 ++word;
562         }
563
564         /* Skip over comments */
565         if (*word == '#') {
566                 return(NULL);
567         }
568
569         /* Find the length of this word */
570         length = strcspn(word, " \t\n");
571         if (length == 0) {
572                 return(NULL);
573         }
574         *buf = word + length;
575         /*DBU:[dave@cray.com] if we are already at EOL dont't increment beyond it */
576         if (**buf) {
577                 **buf = '\0';
578                 (*buf)++;
579         }
580
581         return word;
582 }
583
584 static struct address_family_t *get_address_family(struct address_family_t *af[], char *name)
585 {
586         int i;
587
588         for (i = 0; af[i]; i++) {
589                 if (strcmp(af[i]->name, name) == 0) {
590                         return af[i];
591                 }
592         }
593         return NULL;
594 }
595
596 static struct method_t *get_method(struct address_family_t *af, char *name)
597 {
598         int i;
599
600         for (i = 0; i < af->n_methods; i++) {
601                 if (strcmp(af->method[i].name, name) == 0) {
602                         return &af->method[i];
603                 }
604         }
605         return(NULL);
606 }
607
608 static const llist_t *find_list_string(const llist_t *list, const char *string)
609 {
610         while (list) {
611                 if (strcmp(list->data, string) == 0) {
612                         return(list);
613                 }
614                 list = list->link;
615         }
616         return(NULL);
617 }
618
619 static struct interfaces_file_t *read_interfaces(const char *filename)
620 {
621 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
622         struct mapping_defn_t *currmap = NULL;
623 #endif
624         struct interface_defn_t *currif = NULL;
625         struct interfaces_file_t *defn;
626         FILE *f;
627         char *firstword;
628         char *buf;
629
630         enum { NONE, IFACE, MAPPING } currently_processing = NONE;
631
632         defn = xzalloc(sizeof(struct interfaces_file_t));
633
634         f = bb_xfopen(filename, "r");
635
636         while ((buf = bb_get_chomped_line_from_file(f)) != NULL) {
637                 char *buf_ptr = buf;
638
639                 firstword = next_word(&buf_ptr);
640                 if (firstword == NULL) {
641                         free(buf);
642                         continue;       /* blank line */
643                 }
644
645                 if (strcmp(firstword, "mapping") == 0) {
646 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
647                         currmap = xzalloc(sizeof(struct mapping_defn_t));
648
649                         while ((firstword = next_word(&buf_ptr)) != NULL) {
650                                 if (currmap->max_matches == currmap->n_matches) {
651                                         currmap->max_matches = currmap->max_matches * 2 + 1;
652                                         currmap->match = xrealloc(currmap->match, sizeof(currmap->match) * currmap->max_matches);
653                                 }
654
655                                 currmap->match[currmap->n_matches++] = bb_xstrdup(firstword);
656                         }
657                         currmap->max_mappings = 0;
658                         currmap->n_mappings = 0;
659                         currmap->mapping = NULL;
660                         currmap->script = NULL;
661                         {
662                                 struct mapping_defn_t **where = &defn->mappings;
663                                 while (*where != NULL) {
664                                         where = &(*where)->next;
665                                 }
666                                 *where = currmap;
667                                 currmap->next = NULL;
668                         }
669                         debug_noise("Added mapping\n");
670 #endif
671                         currently_processing = MAPPING;
672                 } else if (strcmp(firstword, "iface") == 0) {
673                         {
674                                 char *iface_name;
675                                 char *address_family_name;
676                                 char *method_name;
677                                 struct address_family_t *addr_fams[] = {
678 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV4
679                                         &addr_inet,
680 #endif
681 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV6
682                                         &addr_inet6,
683 #endif
684                                         NULL
685                                 };
686
687                                 currif = xzalloc(sizeof(struct interface_defn_t));
688                                 iface_name = next_word(&buf_ptr);
689                                 address_family_name = next_word(&buf_ptr);
690                                 method_name = next_word(&buf_ptr);
691
692                                 if (buf_ptr == NULL) {
693                                         bb_error_msg("too few parameters for line \"%s\"", buf);
694                                         return NULL;
695                                 }
696
697                                 /* ship any trailing whitespace */
698                                 while (isspace(*buf_ptr)) {
699                                         ++buf_ptr;
700                                 }
701
702                                 if (buf_ptr[0] != '\0') {
703                                         bb_error_msg("too many parameters \"%s\"", buf);
704                                         return NULL;
705                                 }
706
707                                 currif->iface = bb_xstrdup(iface_name);
708
709                                 currif->address_family = get_address_family(addr_fams, address_family_name);
710                                 if (!currif->address_family) {
711                                         bb_error_msg("unknown address type \"%s\"", address_family_name);
712                                         return NULL;
713                                 }
714
715                                 currif->method = get_method(currif->address_family, method_name);
716                                 if (!currif->method) {
717                                         bb_error_msg("unknown method \"%s\"", method_name);
718                                         return NULL;
719                                 }
720
721
722                                 {
723                                         llist_t *iface_list;
724                                         for (iface_list = defn->ifaces; iface_list; iface_list = iface_list->link) {
725                                                 struct interface_defn_t *tmp = (struct interface_defn_t *) iface_list->data;
726                                                 if ((strcmp(tmp->iface, currif->iface) == 0) && 
727                                                         (tmp->address_family == currif->address_family)) {
728                                                         bb_error_msg("duplicate interface \"%s\"", tmp->iface);
729                                                         return NULL;
730                                                 }
731                                         }
732
733                                         llist_add_to_end(&(defn->ifaces), (char*)currif);
734                                 }
735                                 debug_noise("iface %s %s %s\n", currif->iface, address_family_name, method_name);
736                         }
737                         currently_processing = IFACE;
738                 } else if (strcmp(firstword, "auto") == 0) {
739                         while ((firstword = next_word(&buf_ptr)) != NULL) {
740
741                                 /* Check the interface isnt already listed */
742                                 if (find_list_string(defn->autointerfaces, firstword)) {
743                                         bb_perror_msg_and_die("interface declared auto twice \"%s\"", buf);
744                                 }
745
746                                 /* Add the interface to the list */
747                                 llist_add_to_end(&(defn->autointerfaces), bb_xstrdup(firstword));
748                                 debug_noise("\nauto %s\n", firstword);
749                         }
750                         currently_processing = NONE;
751                 } else {
752                         switch (currently_processing) {
753                                 case IFACE:
754                                         {
755                                                 int i;
756
757                                                 if (strlen(buf_ptr) == 0) {
758                                                         bb_error_msg("option with empty value \"%s\"", buf);
759                                                         return NULL;
760                                                 }
761
762                                                 if (strcmp(firstword, "up") != 0
763                                                                 && strcmp(firstword, "down") != 0
764                                                                 && strcmp(firstword, "pre-up") != 0
765                                                                 && strcmp(firstword, "post-down") != 0) {
766                                                         for (i = 0; i < currif->n_options; i++) {
767                                                                 if (strcmp(currif->option[i].name, firstword) == 0) {
768                                                                         bb_error_msg("duplicate option \"%s\"", buf);
769                                                                         return NULL;
770                                                                 }
771                                                         }
772                                                 }
773                                         }
774                                         if (currif->n_options >= currif->max_options) {
775                                                 struct variable_t *opt;
776
777                                                 currif->max_options = currif->max_options + 10;
778                                                 opt = xrealloc(currif->option, sizeof(*opt) * currif->max_options);
779                                                 currif->option = opt;
780                                         }
781                                         currif->option[currif->n_options].name = bb_xstrdup(firstword);
782                                         currif->option[currif->n_options].value = bb_xstrdup(buf_ptr);
783                                         if (!currif->option[currif->n_options].name) {
784                                                 perror(filename);
785                                                 return NULL;
786                                         }
787                                         if (!currif->option[currif->n_options].value) {
788                                                 perror(filename);
789                                                 return NULL;
790                                         }
791                                         debug_noise("\t%s=%s\n", currif->option[currif->n_options].name,
792                                                         currif->option[currif->n_options].value);
793                                         currif->n_options++;
794                                         break;
795                                 case MAPPING:
796 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
797                                         if (strcmp(firstword, "script") == 0) {
798                                                 if (currmap->script != NULL) {
799                                                         bb_error_msg("duplicate script in mapping \"%s\"", buf);
800                                                         return NULL;
801                                                 } else {
802                                                         currmap->script = bb_xstrdup(next_word(&buf_ptr));
803                                                 }
804                                         } else if (strcmp(firstword, "map") == 0) {
805                                                 if (currmap->max_mappings == currmap->n_mappings) {
806                                                         currmap->max_mappings = currmap->max_mappings * 2 + 1;
807                                                         currmap->mapping = xrealloc(currmap->mapping, sizeof(char *) * currmap->max_mappings);
808                                                 }
809                                                 currmap->mapping[currmap->n_mappings] = bb_xstrdup(next_word(&buf_ptr));
810                                                 currmap->n_mappings++;
811                                         } else {
812                                                 bb_error_msg("misplaced option \"%s\"", buf);
813                                                 return NULL;
814                                         }
815 #endif
816                                         break;
817                                 case NONE:
818                                 default:
819                                         bb_error_msg("misplaced option \"%s\"", buf);
820                                         return NULL;
821                         }
822                 }
823                 free(buf);
824         }
825         if (ferror(f) != 0) {
826                 bb_perror_msg_and_die("%s", filename);
827         }
828         fclose(f);
829
830         return defn;
831 }
832
833 static char *setlocalenv(char *format, const char *name, const char *value)
834 {
835         char *result;
836         char *here;
837         char *there;
838
839         result = bb_xasprintf(format, name, value);
840
841         for (here = there = result; *there != '=' && *there; there++) {
842                 if (*there == '-')
843                         *there = '_';
844                 if (isalpha(*there))
845                         *there = toupper(*there);
846
847                 if (isalnum(*there) || *there == '_') {
848                         *here = *there;
849                         here++;
850                 }
851         }
852         memmove(here, there, strlen(there) + 1);
853
854         return result;
855 }
856
857 static void set_environ(struct interface_defn_t *iface, const char *mode)
858 {
859         char **environend;
860         int i;
861         const int n_env_entries = iface->n_options + 5;
862         char **ppch;
863
864         if (__myenviron != NULL) {
865                 for (ppch = __myenviron; *ppch; ppch++) {
866                         free(*ppch);
867                         *ppch = NULL;
868                 }
869                 free(__myenviron);
870         }
871         __myenviron = xzalloc(sizeof(char *) * (n_env_entries + 1 /* for final NULL */ ));
872         environend = __myenviron;
873
874         for (i = 0; i < iface->n_options; i++) {
875                 if (strcmp(iface->option[i].name, "up") == 0
876                                 || strcmp(iface->option[i].name, "down") == 0
877                                 || strcmp(iface->option[i].name, "pre-up") == 0
878                                 || strcmp(iface->option[i].name, "post-down") == 0) {
879                         continue;
880                 }
881                 *(environend++) = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
882         }
883
884         *(environend++) = setlocalenv("%s=%s", "IFACE", iface->iface);
885         *(environend++) = setlocalenv("%s=%s", "ADDRFAM", iface->address_family->name);
886         *(environend++) = setlocalenv("%s=%s", "METHOD", iface->method->name);
887         *(environend++) = setlocalenv("%s=%s", "MODE", mode);
888         *(environend++) = setlocalenv("%s=%s", "PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
889 }
890
891 static int doit(char *str)
892 {
893         if (verbose || no_act) {
894                 printf("%s\n", str);
895         }
896         if (!no_act) {
897                 pid_t child;
898                 int status;
899
900                 fflush(NULL);
901                 switch (child = fork()) {
902                         case -1:                /* failure */
903                                 return 0;
904                         case 0:         /* child */
905                                 execle(DEFAULT_SHELL, DEFAULT_SHELL, "-c", str, NULL, __myenviron);
906                                 exit(127);
907                 }
908                 waitpid(child, &status, 0);
909                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
910                         return 0;
911                 }
912         }
913         return (1);
914 }
915
916 static int execute_all(struct interface_defn_t *ifd, const char *opt)
917 {
918         int i;
919         char *buf;
920         for (i = 0; i < ifd->n_options; i++) {
921                 if (strcmp(ifd->option[i].name, opt) == 0) {
922                         if (!doit(ifd->option[i].value)) {
923                                 return 0;
924                         }
925                 }
926         }
927
928         buf = bb_xasprintf("run-parts /etc/network/if-%s.d", opt);
929         if (doit(buf) != 1) {
930                 return 0;
931         }
932         return 1;
933 }
934
935 static int check(char *str) {
936         return str != NULL;
937 }
938
939 static int iface_up(struct interface_defn_t *iface)
940 {
941         if (!iface->method->up(iface,check)) return -1;
942         set_environ(iface, "start");
943         if (!execute_all(iface, "pre-up")) return 0;
944         if (!iface->method->up(iface, doit)) return 0;
945         if (!execute_all(iface, "up")) return 0;
946         return 1;
947 }
948
949 static int iface_down(struct interface_defn_t *iface)
950 {
951         if (!iface->method->down(iface,check)) return -1;
952         set_environ(iface, "stop");
953         if (!execute_all(iface, "down")) return 0;
954         if (!iface->method->down(iface, doit)) return 0;
955         if (!execute_all(iface, "post-down")) return 0;
956         return 1;
957 }
958
959 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
960 static int popen2(FILE **in, FILE **out, char *command, ...)
961 {
962         va_list ap;
963         char *argv[11] = { command };
964         int argc;
965         int infd[2], outfd[2];
966         pid_t pid;
967
968         argc = 1;
969         va_start(ap, command);
970         while ((argc < 10) && (argv[argc] = va_arg(ap, char *))) {
971                 argc++;
972         }
973         argv[argc] = NULL;      /* make sure */
974         va_end(ap);
975
976         if (pipe(infd) != 0) {
977                 return 0;
978         }
979
980         if (pipe(outfd) != 0) {
981                 close(infd[0]);
982                 close(infd[1]);
983                 return 0;
984         }
985
986         fflush(NULL);
987         switch (pid = fork()) {
988                 case -1:                        /* failure */
989                         close(infd[0]);
990                         close(infd[1]);
991                         close(outfd[0]);
992                         close(outfd[1]);
993                         return 0;
994                 case 0:                 /* child */
995                         dup2(infd[0], 0);
996                         dup2(outfd[1], 1);
997                         close(infd[0]);
998                         close(infd[1]);
999                         close(outfd[0]);
1000                         close(outfd[1]);
1001                         execvp(command, argv);
1002                         exit(127);
1003                 default:                        /* parent */
1004                         *in = fdopen(infd[1], "w");
1005                         *out = fdopen(outfd[0], "r");
1006                         close(infd[0]);
1007                         close(outfd[1]);
1008                         return pid;
1009         }
1010         /* unreached */
1011 }
1012
1013 static char *run_mapping(char *physical, struct mapping_defn_t * map)
1014 {
1015         FILE *in, *out;
1016         int i, status;
1017         pid_t pid;
1018
1019         char *logical = bb_xstrdup(physical);
1020
1021         /* Run the mapping script. */
1022         pid = popen2(&in, &out, map->script, physical, NULL);
1023
1024         /* popen2() returns 0 on failure. */
1025         if (pid == 0)
1026                 return logical;
1027
1028         /* Write mappings to stdin of mapping script. */
1029         for (i = 0; i < map->n_mappings; i++) {
1030                 fprintf(in, "%s\n", map->mapping[i]);
1031         }
1032         fclose(in);
1033         waitpid(pid, &status, 0);
1034
1035         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1036                 /* If the mapping script exited successfully, try to
1037                  * grab a line of output and use that as the name of the
1038                  * logical interface. */
1039                 char *new_logical = (char *)xmalloc(MAX_INTERFACE_LENGTH);
1040
1041                 if (fgets(new_logical, MAX_INTERFACE_LENGTH, out)) {
1042                         /* If we are able to read a line of output from the script,
1043                          * remove any trailing whitespace and use this value
1044                          * as the name of the logical interface. */
1045                         char *pch = new_logical + strlen(new_logical) - 1;
1046
1047                         while (pch >= new_logical && isspace(*pch))
1048                                 *(pch--) = '\0';
1049
1050                         free(logical);
1051                         logical = new_logical;
1052                 } else {
1053                         /* If we are UNABLE to read a line of output, discard our
1054                          * freshly allocated memory. */
1055                         free(new_logical);
1056                 }
1057         }
1058
1059         fclose(out);
1060
1061         return logical;
1062 }
1063 #endif /* CONFIG_FEATURE_IFUPDOWN_MAPPING */
1064
1065 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1066 {
1067         unsigned short iface_len = strlen(iface);
1068         llist_t *search = state_list;
1069
1070         while (search) {
1071                 if ((strncmp(search->data, iface, iface_len) == 0) &&
1072                                 (search->data[iface_len] == '=')) {
1073                         return(search);
1074                 }
1075                 search = search->link;
1076         }
1077         return(NULL);
1078 }
1079
1080 int ifupdown_main(int argc, char **argv)
1081 {
1082         int (*cmds) (struct interface_defn_t *) = NULL;
1083         struct interfaces_file_t *defn;
1084         llist_t *state_list = NULL;
1085         llist_t *target_list = NULL;
1086         const char *interfaces = "/etc/network/interfaces";
1087         const char *statefile = "/var/run/ifstate";
1088
1089 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1090         int run_mappings = 1;
1091 #endif
1092         int do_all = 0;
1093         int force = 0;
1094         int any_failures = 0;
1095         int i;
1096
1097         if (bb_applet_name[2] == 'u') {
1098                 /* ifup command */
1099                 cmds = iface_up;
1100         } else {
1101                 /* ifdown command */
1102                 cmds = iface_down;
1103         }
1104
1105 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1106         while ((i = getopt(argc, argv, "i:hvnamf")) != -1)
1107 #else
1108                 while ((i = getopt(argc, argv, "i:hvnaf")) != -1)
1109 #endif
1110                 {
1111                         switch (i) {
1112                                 case 'i':       /* interfaces */
1113                                         interfaces = optarg;
1114                                         break;
1115                                 case 'v':       /* verbose */
1116                                         verbose = 1;
1117                                         break;
1118                                 case 'a':       /* all */
1119                                         do_all = 1;
1120                                         break;
1121                                 case 'n':       /* no-act */
1122                                         no_act = 1;
1123                                         break;
1124 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1125                                 case 'm':       /* no-mappings */
1126                                         run_mappings = 0;
1127                                         break;
1128 #endif
1129                                 case 'f':       /* force */
1130                                         force = 1;
1131                                         break;
1132                                 default:
1133                                         bb_show_usage();
1134                                         break;
1135                         }
1136                 }
1137
1138         if (argc - optind > 0) {
1139                 if (do_all) {
1140                         bb_show_usage();
1141                 }
1142         } else {
1143                 if (!do_all) {
1144                         bb_show_usage();
1145                 }
1146         }
1147
1148         debug_noise("reading %s file:\n", interfaces);
1149         defn = read_interfaces(interfaces);
1150         debug_noise("\ndone reading %s\n\n", interfaces);
1151
1152         if (!defn) {
1153                 exit(EXIT_FAILURE);
1154         }
1155
1156         /* Create a list of interfaces to work on */
1157         if (do_all) {
1158                 if (cmds == iface_up) {
1159                         target_list = defn->autointerfaces;
1160                 } else {
1161                         /* iface_down */
1162                         const llist_t *list = state_list;
1163                         while (list) {
1164                                 llist_add_to_end(&target_list, bb_xstrdup(list->data));
1165                                 list = list->link;
1166                         }
1167                         target_list = defn->autointerfaces;
1168                 }
1169         } else {
1170                 llist_add_to_end(&target_list, argv[optind]);
1171         }
1172
1173
1174         /* Update the interfaces */
1175         while (target_list) {
1176                 llist_t *iface_list;
1177                 struct interface_defn_t *currif;
1178                 char *iface;
1179                 char *liface;
1180                 char *pch;
1181                 int okay = 0;
1182                 int cmds_ret;
1183
1184                 iface = bb_xstrdup(target_list->data);
1185                 target_list = target_list->link;
1186
1187                 pch = strchr(iface, '=');
1188                 if (pch) {
1189                         *pch = '\0';
1190                         liface = bb_xstrdup(pch + 1);
1191                 } else {
1192                         liface = bb_xstrdup(iface);
1193                 }
1194
1195                 if (!force) {
1196                         const llist_t *iface_state = find_iface_state(state_list, iface);
1197
1198                         if (cmds == iface_up) {
1199                                 /* ifup */
1200                                 if (iface_state) {
1201                                         bb_error_msg("interface %s already configured", iface);
1202                                         continue;
1203                                 }
1204                         } else {
1205                                 /* ifdown */
1206                                 if (iface_state) {
1207                                         bb_error_msg("interface %s not configured", iface);
1208                                         continue;
1209                                 }
1210                         }
1211                 }
1212
1213 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1214                 if ((cmds == iface_up) && run_mappings) {
1215                         struct mapping_defn_t *currmap;
1216
1217                         for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1218
1219                                 for (i = 0; i < currmap->n_matches; i++) {
1220                                         if (fnmatch(currmap->match[i], liface, 0) != 0)
1221                                                 continue;
1222                                         if (verbose) {
1223                                                 printf("Running mapping script %s on %s\n", currmap->script, liface);
1224                                         }
1225                                         liface = run_mapping(iface, currmap);
1226                                         break;
1227                                 }
1228                         }
1229                 }
1230 #endif
1231
1232
1233                 iface_list = defn->ifaces;
1234                 while (iface_list) {
1235                         currif = (struct interface_defn_t *) iface_list->data;
1236                         if (strcmp(liface, currif->iface) == 0) {
1237                                 char *oldiface = currif->iface;
1238
1239                                 okay = 1;
1240                                 currif->iface = iface;
1241
1242                                 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1243
1244                                 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1245                                 cmds_ret = cmds(currif);
1246                                 if (cmds_ret == -1) {
1247                                         bb_error_msg("Don't seem to have all the variables for %s/%s.",
1248                                                         liface, currif->address_family->name);
1249                                         any_failures += 1;
1250                                 } else if (cmds_ret == 0) {
1251                                         any_failures += 1;
1252                                 }
1253
1254                                 currif->iface = oldiface;
1255                         }
1256                         iface_list = iface_list->link;
1257                 }
1258                 if (verbose) {
1259                         printf("\n");
1260                 }
1261
1262                 if (!okay && !force) {
1263                         bb_error_msg("Ignoring unknown interface %s", liface);
1264                         any_failures += 1;
1265                 } else {
1266                         llist_t *iface_state = find_iface_state(state_list, iface);
1267
1268                         if (cmds == iface_up) {
1269                                 char *newiface = bb_xasprintf("%s=%s", iface, liface);
1270                                 if (iface_state == NULL) {
1271                                         llist_add_to_end(&state_list, newiface);
1272                                 } else {
1273                                         free(iface_state->data);
1274                                         iface_state->data = newiface;
1275                                 }
1276                         } else {
1277                                 /* Remove an interface from the linked list */
1278                                 free(llist_pop(&iface_state));
1279                         }
1280                 }
1281         }
1282
1283         /* Actually write the new state */
1284         if (!no_act) {
1285                 FILE *state_fp = NULL;
1286
1287                 state_fp = bb_xfopen(statefile, "w");
1288                 while (state_list) {
1289                         if (state_list->data) {
1290                                 fputs(state_list->data, state_fp);
1291                                 fputc('\n', state_fp);
1292                         }
1293                         state_list = state_list->link;
1294                 }
1295                 fclose(state_fp);
1296         }
1297
1298         if (any_failures)
1299                 return 1;
1300         return 0;
1301 }