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