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