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