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