0c822e2a1ee5fc1f175fa834ed6c243d1de541c4
[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         const char *name;
41         int (*up)(struct interface_defn_t *ifd, execfn *e);
42         int (*down)(struct interface_defn_t *ifd, execfn *e);
43 };
44
45 struct address_family_t {
46         const char *name;
47         int n_methods;
48         const struct method_t *method;
49 };
50
51 struct mapping_defn_t {
52         struct mapping_defn_t *next;
53
54         int max_matches;
55         int n_matches;
56         char **match;
57
58         char *script;
59
60         int max_mappings;
61         int n_mappings;
62         char **mapping;
63 };
64
65 struct variable_t {
66         char *name;
67         char *value;
68 };
69
70 struct interface_defn_t {
71         const struct address_family_t *address_family;
72         const struct method_t *method;
73
74         char *iface;
75         int max_options;
76         int n_options;
77         struct variable_t *option;
78 };
79
80 struct interfaces_file_t {
81         llist_t *autointerfaces;
82         llist_t *ifaces;
83         struct mapping_defn_t *mappings;
84 };
85
86 #define OPTION_STR "anvf" USE_FEATURE_IFUPDOWN_MAPPING("m") "i:"
87 enum {
88         OPT_do_all = 0x1,
89         OPT_no_act = 0x2,
90         OPT_verbose = 0x4,
91         OPT_force = 0x8,
92         OPT_no_mappings = 0x10,
93 };
94 #define DO_ALL (option_mask32 & OPT_do_all)
95 #define NO_ACT (option_mask32 & OPT_no_act)
96 #define VERBOSE (option_mask32 & OPT_verbose)
97 #define FORCE (option_mask32 & OPT_force)
98 #define NO_MAPPINGS (option_mask32 & OPT_no_mappings)
99
100 static char **my_environ;
101
102 static const char *startup_PATH;
103
104 #if ENABLE_FEATURE_IFUPDOWN_IPV4 || ENABLE_FEATURE_IFUPDOWN_IPV6
105
106 #if ENABLE_FEATURE_IFUPDOWN_IP
107
108 static unsigned count_bits(unsigned a)
109 {
110         unsigned result;
111         result = (a & 0x55) + ((a >> 1) & 0x55);
112         result = (result & 0x33) + ((result >> 2) & 0x33);
113         return (result & 0x0F) + ((result >> 4) & 0x0F);
114 }
115
116 static int count_netmask_bits(char *dotted_quad)
117 {
118         unsigned result, a, b, c, d;
119         /* Found a netmask...  Check if it is dotted quad */
120         if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
121                 return -1;
122         // FIXME: will be confused by e.g. 255.0.255.0
123         result = count_bits(a);
124         result += count_bits(b);
125         result += count_bits(c);
126         result += count_bits(d);
127         return (int)result;
128 }
129 #endif
130
131 static void addstr(char **bufp, const char *str, size_t str_length)
132 {
133         /* xasprintf trick will be smaller, but we are often
134          * called with str_length == 1 - don't want to have
135          * THAT much of malloc/freeing! */
136         char *buf = *bufp;
137         int len = (buf ? strlen(buf) : 0);
138         str_length++;
139         buf = xrealloc(buf, len + str_length);
140         /* copies at most str_length-1 chars! */
141         safe_strncpy(buf + len, str, str_length);
142         *bufp = buf;
143 }
144
145 static int strncmpz(const char *l, const char *r, size_t llen)
146 {
147         int i = strncmp(l, r, llen);
148
149         if (i == 0)
150                 return -r[llen];
151         return i;
152 }
153
154 static char *get_var(const char *id, size_t idlen, struct interface_defn_t *ifd)
155 {
156         int i;
157
158         if (strncmpz(id, "iface", idlen) == 0) {
159                 char *result;
160                 static char label_buf[20];
161                 safe_strncpy(label_buf, ifd->iface, sizeof(label_buf));
162                 result = strchr(label_buf, ':');
163                 if (result) {
164                         *result = '\0';
165                 }
166                 return label_buf;
167         }
168         if (strncmpz(id, "label", idlen) == 0) {
169                 return ifd->iface;
170         }
171         for (i = 0; i < ifd->n_options; i++) {
172                 if (strncmpz(id, ifd->option[i].name, idlen) == 0) {
173                         return ifd->option[i].value;
174                 }
175         }
176         return NULL;
177 }
178
179 static char *parse(const char *command, struct interface_defn_t *ifd)
180 {
181         size_t old_pos[MAX_OPT_DEPTH] = { 0 };
182         int okay[MAX_OPT_DEPTH] = { 1 };
183         int opt_depth = 1;
184         char *result = NULL;
185
186         while (*command) {
187                 switch (*command) {
188                 default:
189                         addstr(&result, command, 1);
190                         command++;
191                         break;
192                 case '\\':
193                         if (command[1]) {
194                                 addstr(&result, command + 1, 1);
195                                 command += 2;
196                         } else {
197                                 addstr(&result, command, 1);
198                                 command++;
199                         }
200                         break;
201                 case '[':
202                         if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
203                                 old_pos[opt_depth] = result ? strlen(result) : 0;
204                                 okay[opt_depth] = 1;
205                                 opt_depth++;
206                                 command += 2;
207                         } else {
208                                 addstr(&result, "[", 1);
209                                 command++;
210                         }
211                         break;
212                 case ']':
213                         if (command[1] == ']' && opt_depth > 1) {
214                                 opt_depth--;
215                                 if (!okay[opt_depth]) {
216                                         result[old_pos[opt_depth]] = '\0';
217                                 }
218                                 command += 2;
219                         } else {
220                                 addstr(&result, "]", 1);
221                                 command++;
222                         }
223                         break;
224                 case '%':
225                         {
226                                 char *nextpercent;
227                                 char *varvalue;
228
229                                 command++;
230                                 nextpercent = strchr(command, '%');
231                                 if (!nextpercent) {
232                                         errno = EUNBALPER;
233                                         free(result);
234                                         return NULL;
235                                 }
236
237                                 varvalue = get_var(command, nextpercent - command, ifd);
238
239                                 if (varvalue) {
240                                         addstr(&result, varvalue, strlen(varvalue));
241                                 } else {
242 #if ENABLE_FEATURE_IFUPDOWN_IP
243                                         /* Sigh...  Add a special case for 'ip' to convert from
244                                          * dotted quad to bit count style netmasks.  */
245                                         if (strncmp(command, "bnmask", 6) == 0) {
246                                                 unsigned res;
247                                                 varvalue = get_var("netmask", 7, ifd);
248                                                 if (varvalue && (res = count_netmask_bits(varvalue)) > 0) {
249                                                         const char *argument = utoa(res);
250                                                         addstr(&result, argument, strlen(argument));
251                                                         command = nextpercent + 1;
252                                                         break;
253                                                 }
254                                         }
255 #endif
256                                         okay[opt_depth - 1] = 0;
257                                 }
258
259                                 command = nextpercent + 1;
260                         }
261                         break;
262                 }
263         }
264
265         if (opt_depth > 1) {
266                 errno = EUNBALBRACK;
267                 free(result);
268                 return NULL;
269         }
270
271         if (!okay[0]) {
272                 errno = EUNDEFVAR;
273                 free(result);
274                 return NULL;
275         }
276
277         return result;
278 }
279
280 /* execute() returns 1 for success and 0 for failure */
281 static int execute(const char *command, struct interface_defn_t *ifd, execfn *exec)
282 {
283         char *out;
284         int ret;
285
286         out = parse(command, ifd);
287         if (!out) {
288                 /* parse error? */
289                 return 0;
290         }
291         /* out == "": parsed ok but not all needed variables known, skip */
292         ret = out[0] ? (*exec)(out) : 1;
293
294         free(out);
295         if (ret != 1) {
296                 return 0;
297         }
298         return 1;
299 }
300 #endif
301
302 #if ENABLE_FEATURE_IFUPDOWN_IPV6
303 static int loopback_up6(struct interface_defn_t *ifd, execfn *exec)
304 {
305 #if ENABLE_FEATURE_IFUPDOWN_IP
306         int result;
307         result = execute("ip addr add ::1 dev %iface%", ifd, exec);
308         result += execute("ip link set %iface% up", ifd, exec);
309         return ((result == 2) ? 2 : 0);
310 #else
311         return execute("ifconfig %iface% add ::1", ifd, exec);
312 #endif
313 }
314
315 static int loopback_down6(struct interface_defn_t *ifd, execfn *exec)
316 {
317 #if ENABLE_FEATURE_IFUPDOWN_IP
318         return execute("ip link set %iface% down", ifd, exec);
319 #else
320         return execute("ifconfig %iface% del ::1", ifd, exec);
321 #endif
322 }
323
324 static int static_up6(struct interface_defn_t *ifd, execfn *exec)
325 {
326         int result;
327 #if ENABLE_FEATURE_IFUPDOWN_IP
328         result = execute("ip addr add %address%/%netmask% dev %iface%[[ label %label%]]", ifd, exec);
329         result += execute("ip link set[[ mtu %mtu%]][[ address %hwaddress%]] %iface% up", ifd, exec);
330         /* Was: "[[ ip ....%gateway% ]]". Removed extra spaces w/o checking */
331         result += execute("[[ip route add ::/0 via %gateway%]]", ifd, exec);
332 #else
333         result = execute("ifconfig %iface%[[ media %media%]][[ hw %hwaddress%]][[ mtu %mtu%]] up", ifd, exec);
334         result += execute("ifconfig %iface% add %address%/%netmask%", ifd, exec);
335         result += execute("[[route -A inet6 add ::/0 gw %gateway%]]", ifd, exec);
336 #endif
337         return ((result == 3) ? 3 : 0);
338 }
339
340 static int static_down6(struct interface_defn_t *ifd, execfn *exec)
341 {
342 #if ENABLE_FEATURE_IFUPDOWN_IP
343         return execute("ip link set %iface% down", ifd, exec);
344 #else
345         return execute("ifconfig %iface% down", ifd, exec);
346 #endif
347 }
348
349 #if ENABLE_FEATURE_IFUPDOWN_IP
350 static int v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
351 {
352         int result;
353         result = execute("ip tunnel add %iface% mode sit remote "
354                         "%endpoint%[[ local %local%]][[ ttl %ttl%]]", ifd, exec);
355         result += execute("ip link set %iface% up", ifd, exec);
356         result += execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec);
357         result += execute("[[ip route add ::/0 via %gateway%]]", ifd, exec);
358         return ((result == 4) ? 4 : 0);
359 }
360
361 static int v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
362 {
363         return execute("ip tunnel del %iface%", ifd, exec);
364 }
365 #endif
366
367 static const struct method_t methods6[] = {
368 #if ENABLE_FEATURE_IFUPDOWN_IP
369         { "v4tunnel", v4tunnel_up, v4tunnel_down, },
370 #endif
371         { "static", static_up6, static_down6, },
372         { "loopback", loopback_up6, loopback_down6, },
373 };
374
375 static const struct address_family_t addr_inet6 = {
376         "inet6",
377         sizeof(methods6) / sizeof(struct method_t),
378         methods6
379 };
380 #endif /* FEATURE_IFUPDOWN_IPV6 */
381
382 #if ENABLE_FEATURE_IFUPDOWN_IPV4
383 static int loopback_up(struct interface_defn_t *ifd, execfn *exec)
384 {
385 #if ENABLE_FEATURE_IFUPDOWN_IP
386         int result;
387         result = execute("ip addr add 127.0.0.1/8 dev %iface%", ifd, exec);
388         result += execute("ip link set %iface% up", ifd, exec);
389         return ((result == 2) ? 2 : 0);
390 #else
391         return execute("ifconfig %iface% 127.0.0.1 up", ifd, exec);
392 #endif
393 }
394
395 static int loopback_down(struct interface_defn_t *ifd, execfn *exec)
396 {
397 #if ENABLE_FEATURE_IFUPDOWN_IP
398         int result;
399         result = execute("ip addr flush dev %iface%", ifd, exec);
400         result += execute("ip link set %iface% down", ifd, exec);
401         return ((result == 2) ? 2 : 0);
402 #else
403         return execute("ifconfig %iface% 127.0.0.1 down", ifd, exec);
404 #endif
405 }
406
407 static int static_up(struct interface_defn_t *ifd, execfn *exec)
408 {
409         int result;
410 #if ENABLE_FEATURE_IFUPDOWN_IP
411         result = execute("ip addr add %address%/%bnmask%[[ broadcast %broadcast%]] "
412                         "dev %iface%[[ peer %pointopoint%]][[ label %label%]]", ifd, exec);
413         result += execute("ip link set[[ mtu %mtu%]][[ address %hwaddress%]] %iface% up", ifd, exec);
414         result += execute("[[ip route add default via %gateway% dev %iface%]]", ifd, exec);
415         return ((result == 3) ? 3 : 0);
416 #else
417         /* ifconfig said to set iface up before it processes hw %hwaddress%,
418          * which then of course fails. Thus we run two separate ifconfig */
419         result = execute("ifconfig %iface%[[ hw %hwaddress%]][[ media %media%]][[ mtu %mtu%]] up",
420                                 ifd, exec);
421         result += execute("ifconfig %iface% %address% netmask %netmask%"
422                                 "[[ broadcast %broadcast%]][[ pointopoint %pointopoint%]] ",
423                                 ifd, exec);
424         result += execute("[[route add default gw %gateway% %iface%]]", ifd, exec);
425         return ((result == 3) ? 3 : 0);
426 #endif
427 }
428
429 static int static_down(struct interface_defn_t *ifd, execfn *exec)
430 {
431         int result;
432 #if ENABLE_FEATURE_IFUPDOWN_IP
433         result = execute("ip addr flush dev %iface%", ifd, exec);
434         result += execute("ip link set %iface% down", ifd, exec);
435 #else
436         result = execute("[[route del default gw %gateway% %iface%]]", ifd, exec);
437         result += execute("ifconfig %iface% down", ifd, exec);
438 #endif
439         return ((result == 2) ? 2 : 0);
440 }
441
442 #if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
443 struct dhcp_client_t
444 {
445         const char *name;
446         const char *startcmd;
447         const char *stopcmd;
448 };
449
450 static const struct dhcp_client_t ext_dhcp_clients[] = {
451         { "dhcpcd",
452                 "dhcpcd[[ -h %hostname%]][[ -i %vendor%]][[ -I %clientid%]][[ -l %leasetime%]] %iface%",
453                 "dhcpcd -k %iface%",
454         },
455         { "dhclient",
456                 "dhclient -pf /var/run/dhclient.%iface%.pid %iface%",
457                 "kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null",
458         },
459         { "pump",
460                 "pump -i %iface%[[ -h %hostname%]][[ -l %leasehours%]]",
461                 "pump -i %iface% -k",
462         },
463         { "udhcpc",
464                 "udhcpc -R -n -p /var/run/udhcpc.%iface%.pid -i %iface%[[ -H %hostname%]][[ -c %clientid%]][[ -s %script%]]",
465                 "kill -TERM `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
466         },
467 };
468 #endif /* ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCPC */
469
470 static int dhcp_up(struct interface_defn_t *ifd, execfn *exec)
471 {
472 #if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
473         int i, nclients = sizeof(ext_dhcp_clients) / sizeof(ext_dhcp_clients[0]);
474         for (i = 0; i < nclients; i++) {
475                 if (exists_execable(ext_dhcp_clients[i].name))
476                         return execute(ext_dhcp_clients[i].startcmd, ifd, exec);
477         }
478         bb_error_msg("no dhcp clients found");
479         return 0;
480 #elif ENABLE_APP_UDHCPC
481         return execute("udhcpc -R -n -p /var/run/udhcpc.%iface%.pid "
482                         "-i %iface%[[ -H %hostname%]][[ -c %clientid%]][[ -s %script%]]",
483                         ifd, exec);
484 #else
485         return 0; /* no dhcp support */
486 #endif 
487 }
488
489 static int dhcp_down(struct interface_defn_t *ifd, execfn *exec)
490 {
491 #if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
492         int i, nclients = sizeof(ext_dhcp_clients) / sizeof(ext_dhcp_clients[0]);
493         for (i = 0; i < nclients; i++) {
494                 if (exists_execable(ext_dhcp_clients[i].name))
495                         return execute(ext_dhcp_clients[i].stopcmd, ifd, exec);
496         }
497         bb_error_msg("no dhcp clients found, using static interface shutdown");
498         return static_down(ifd, exec);
499 #elif ENABLE_APP_UDHCPC
500         return execute("kill -TERM "
501                        "`cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
502 #else
503         return 0; /* no support for dhcp */
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(methods[0]),
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(const 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         if (!(option_mask32 & OPT_no_act)) {
907                 pid_t child;
908                 int status;
909
910                 fflush(NULL);
911                 child = fork();
912                 switch (child) {
913                 case -1: /* failure */
914                         return 0;
915                 case 0: /* child */
916                         execle(DEFAULT_SHELL, DEFAULT_SHELL, "-c", str, NULL, my_environ);
917                         exit(127);
918                 }
919                 waitpid(child, &status, 0);
920                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
921                         return 0;
922                 }
923         }
924         return 1;
925 }
926
927 static int execute_all(struct interface_defn_t *ifd, const char *opt)
928 {
929         int i;
930         char *buf;
931         for (i = 0; i < ifd->n_options; i++) {
932                 if (strcmp(ifd->option[i].name, opt) == 0) {
933                         if (!doit(ifd->option[i].value)) {
934                                 return 0;
935                         }
936                 }
937         }
938
939         buf = xasprintf("run-parts /etc/network/if-%s.d", opt);
940         /* heh, we don't bother free'ing it */
941         return doit(buf);
942 }
943
944 static int check(char *str)
945 {
946         return str != NULL;
947 }
948
949 static int iface_up(struct interface_defn_t *iface)
950 {
951         if (!iface->method->up(iface, check)) return -1;
952         set_environ(iface, "start");
953         if (!execute_all(iface, "pre-up")) return 0;
954         if (!iface->method->up(iface, doit)) return 0;
955         if (!execute_all(iface, "up")) return 0;
956         return 1;
957 }
958
959 static int iface_down(struct interface_defn_t *iface)
960 {
961         if (!iface->method->down(iface,check)) return -1;
962         set_environ(iface, "stop");
963         if (!execute_all(iface, "down")) return 0;
964         if (!iface->method->down(iface, doit)) return 0;
965         if (!execute_all(iface, "post-down")) return 0;
966         return 1;
967 }
968
969 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
970 static int popen2(FILE **in, FILE **out, char *command, ...)
971 {
972         va_list ap;
973         char *argv[11] = { command };
974         int argc;
975         int infd[2], outfd[2];
976         pid_t pid;
977
978         argc = 1;
979         va_start(ap, command);
980         while ((argc < 10) && (argv[argc] = va_arg(ap, char *))) {
981                 argc++;
982         }
983         argv[argc] = NULL;      /* make sure */
984         va_end(ap);
985
986         if (pipe(infd) != 0) {
987                 return 0;
988         }
989
990         if (pipe(outfd) != 0) {
991                 close(infd[0]);
992                 close(infd[1]);
993                 return 0;
994         }
995
996         fflush(NULL);
997         switch (pid = fork()) {
998         case -1:                        /* failure */
999                 close(infd[0]);
1000                 close(infd[1]);
1001                 close(outfd[0]);
1002                 close(outfd[1]);
1003                 return 0;
1004         case 0:                 /* child */
1005                 dup2(infd[0], 0);
1006                 dup2(outfd[1], 1);
1007                 close(infd[0]);
1008                 close(infd[1]);
1009                 close(outfd[0]);
1010                 close(outfd[1]);
1011                 BB_EXECVP(command, argv);
1012                 exit(127);
1013         default:                        /* parent */
1014                 *in = fdopen(infd[1], "w");
1015                 *out = fdopen(outfd[0], "r");
1016                 close(infd[0]);
1017                 close(outfd[1]);
1018                 return pid;
1019         }
1020         /* unreached */
1021 }
1022
1023 static char *run_mapping(char *physical, struct mapping_defn_t * map)
1024 {
1025         FILE *in, *out;
1026         int i, status;
1027         pid_t pid;
1028
1029         char *logical = xstrdup(physical);
1030
1031         /* Run the mapping script. */
1032         pid = popen2(&in, &out, map->script, physical, NULL);
1033
1034         /* popen2() returns 0 on failure. */
1035         if (pid == 0)
1036                 return logical;
1037
1038         /* Write mappings to stdin of mapping script. */
1039         for (i = 0; i < map->n_mappings; i++) {
1040                 fprintf(in, "%s\n", map->mapping[i]);
1041         }
1042         fclose(in);
1043         waitpid(pid, &status, 0);
1044
1045         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1046                 /* If the mapping script exited successfully, try to
1047                  * grab a line of output and use that as the name of the
1048                  * logical interface. */
1049                 char *new_logical = xmalloc(MAX_INTERFACE_LENGTH);
1050
1051                 if (fgets(new_logical, MAX_INTERFACE_LENGTH, out)) {
1052                         /* If we are able to read a line of output from the script,
1053                          * remove any trailing whitespace and use this value
1054                          * as the name of the logical interface. */
1055                         char *pch = new_logical + strlen(new_logical) - 1;
1056
1057                         while (pch >= new_logical && isspace(*pch))
1058                                 *(pch--) = '\0';
1059
1060                         free(logical);
1061                         logical = new_logical;
1062                 } else {
1063                         /* If we are UNABLE to read a line of output, discard our
1064                          * freshly allocated memory. */
1065                         free(new_logical);
1066                 }
1067         }
1068
1069         fclose(out);
1070
1071         return logical;
1072 }
1073 #endif /* FEATURE_IFUPDOWN_MAPPING */
1074
1075 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1076 {
1077         unsigned short iface_len = strlen(iface);
1078         llist_t *search = state_list;
1079
1080         while (search) {
1081                 if ((strncmp(search->data, iface, iface_len) == 0)
1082                  && (search->data[iface_len] == '=')) {
1083                         return search;
1084                 }
1085                 search = search->link;
1086         }
1087         return NULL;
1088 }
1089
1090 /* read the previous state from the state file */
1091 static llist_t *read_iface_state(void)
1092 {
1093         llist_t *state_list = NULL;
1094         FILE *state_fp = fopen("/var/run/ifstate", "r");
1095
1096         if (state_fp) {
1097                 char *start, *end_ptr;
1098                 while ((start = xmalloc_fgets(state_fp)) != NULL) {
1099                         /* We should only need to check for a single character */
1100                         end_ptr = start + strcspn(start, " \t\n");
1101                         *end_ptr = '\0';
1102                         llist_add_to(&state_list, start);
1103                 }
1104                 fclose(state_fp);
1105         }
1106         return state_list;
1107 }
1108
1109
1110 int ifupdown_main(int argc, char **argv);
1111 int ifupdown_main(int argc, char **argv)
1112 {
1113         int (*cmds)(struct interface_defn_t *) = NULL;
1114         struct interfaces_file_t *defn;
1115         llist_t *target_list = NULL;
1116         const char *interfaces = "/etc/network/interfaces";
1117         bool any_failures = 0;
1118
1119         cmds = iface_down;
1120         if (applet_name[2] == 'u') {
1121                 /* ifup command */
1122                 cmds = iface_up;
1123         }
1124
1125         getopt32(argc, argv, OPTION_STR, &interfaces);
1126         if (argc - optind > 0) {
1127                 if (DO_ALL) bb_show_usage();
1128         } else {
1129                 if (!DO_ALL) bb_show_usage();
1130         }
1131
1132         debug_noise("reading %s file:\n", interfaces);
1133         defn = read_interfaces(interfaces);
1134         debug_noise("\ndone reading %s\n\n", interfaces);
1135
1136         if (!defn) {
1137                 return EXIT_FAILURE;
1138         }
1139
1140         startup_PATH = getenv("PATH");
1141         if (!startup_PATH) startup_PATH = "";
1142
1143         /* Create a list of interfaces to work on */
1144         if (DO_ALL) {
1145                 target_list = defn->autointerfaces;
1146         } else {
1147                 llist_add_to_end(&target_list, argv[optind]);
1148         }
1149
1150         /* Update the interfaces */
1151         while (target_list) {
1152                 llist_t *iface_list;
1153                 struct interface_defn_t *currif;
1154                 char *iface;
1155                 char *liface;
1156                 char *pch;
1157                 bool okay = 0;
1158                 unsigned cmds_ret;
1159
1160                 iface = xstrdup(target_list->data);
1161                 target_list = target_list->link;
1162
1163                 pch = strchr(iface, '=');
1164                 if (pch) {
1165                         *pch = '\0';
1166                         liface = xstrdup(pch + 1);
1167                 } else {
1168                         liface = xstrdup(iface);
1169                 }
1170
1171                 if (!FORCE) {
1172                         llist_t *state_list = read_iface_state();
1173                         const llist_t *iface_state = find_iface_state(state_list, iface);
1174
1175                         if (cmds == iface_up) {
1176                                 /* ifup */
1177                                 if (iface_state) {
1178                                         bb_error_msg("interface %s already configured", iface);
1179                                         continue;
1180                                 }
1181                         } else {
1182                                 /* ifdown */
1183                                 if (!iface_state) {
1184                                         bb_error_msg("interface %s not configured", iface);
1185                                         continue;
1186                                 }
1187                         }
1188                         llist_free(state_list, free);
1189                 }
1190
1191 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1192                 if ((cmds == iface_up) && !NO_MAPPINGS) {
1193                         struct mapping_defn_t *currmap;
1194
1195                         for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1196                                 int i;
1197                                 for (i = 0; i < currmap->n_matches; i++) {
1198                                         if (fnmatch(currmap->match[i], liface, 0) != 0)
1199                                                 continue;
1200                                         if (VERBOSE) {
1201                                                 printf("Running mapping script %s on %s\n", currmap->script, liface);
1202                                         }
1203                                         liface = run_mapping(iface, currmap);
1204                                         break;
1205                                 }
1206                         }
1207                 }
1208 #endif
1209
1210                 iface_list = defn->ifaces;
1211                 while (iface_list) {
1212                         currif = (struct interface_defn_t *) iface_list->data;
1213                         if (strcmp(liface, currif->iface) == 0) {
1214                                 char *oldiface = currif->iface;
1215
1216                                 okay = 1;
1217                                 currif->iface = iface;
1218
1219                                 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1220
1221                                 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1222                                 cmds_ret = cmds(currif);
1223                                 if (cmds_ret == -1) {
1224                                         bb_error_msg("don't seem to have all the variables for %s/%s",
1225                                                         liface, currif->address_family->name);
1226                                         any_failures = 1;
1227                                 } else if (cmds_ret == 0) {
1228                                         any_failures = 1;
1229                                 }
1230
1231                                 currif->iface = oldiface;
1232                         }
1233                         iface_list = iface_list->link;
1234                 }
1235                 if (VERBOSE) {
1236                         puts("");
1237                 }
1238
1239                 if (!okay && !FORCE) {
1240                         bb_error_msg("ignoring unknown interface %s", liface);
1241                         any_failures = 1;
1242                 } else {
1243                         /* update the state file */
1244                         llist_t *state_list = read_iface_state();
1245                         llist_t *iface_state = find_iface_state(state_list, iface);
1246
1247                         if (cmds == iface_up) {
1248                                 char * const newiface = xasprintf("%s=%s", iface, liface);
1249                                 if (iface_state == NULL) {
1250                                         llist_add_to_end(&state_list, newiface);
1251                                 } else {
1252                                         free(iface_state->data);
1253                                         iface_state->data = newiface;
1254                                 }
1255                         } else {
1256                                 /* Remove an interface from state_list */
1257                                 llist_unlink(&state_list, iface_state);
1258                                 free(llist_pop(&iface_state));
1259                         }
1260
1261                         /* Actually write the new state */
1262                         if (!NO_ACT) {
1263                                 FILE *state_fp = xfopen("/var/run/ifstate", "w");
1264                                 llist_t *state = state_list;
1265                                 while (state) {
1266                                         if (state->data) {
1267                                                 fprintf(state_fp, "%s\n", state->data);
1268                                         }
1269                                         state = state->link;
1270                                 }
1271                                 fclose(state_fp);
1272                         }
1273                         llist_free(state_list, free);
1274                 }
1275         }
1276
1277         return any_failures;
1278 }