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