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