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