b0bc0d70f0cbb5233e18af0f47f561070419c328
[oweals/busybox.git] / networking / ifupdown.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *  ifupdown for busybox
4  *  Copyright (c) 2002 Glenn McGrath
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 GPLv2 or later, see file LICENSE in this source tree.
18  */
19
20 //usage:#define ifup_trivial_usage
21 //usage:       "[-an"IF_FEATURE_IFUPDOWN_MAPPING("m")"vf] [-i FILE] IFACE..."
22 //usage:#define ifup_full_usage "\n\n"
23 //usage:       "        -a      De/configure all interfaces automatically"
24 //usage:     "\n        -i FILE Use FILE instead of /etc/network/interfaces"
25 //usage:     "\n        -n      Print out what would happen, but don't do it"
26 //usage:        IF_FEATURE_IFUPDOWN_MAPPING(
27 //usage:     "\n                (note: doesn't disable mappings)"
28 //usage:     "\n        -m      Don't run any mappings"
29 //usage:        )
30 //usage:     "\n        -v      Print out what would happen before doing it"
31 //usage:     "\n        -f      Force de/configuration"
32 //usage:
33 //usage:#define ifdown_trivial_usage
34 //usage:       "[-an"IF_FEATURE_IFUPDOWN_MAPPING("m")"vf] [-i FILE] IFACE..."
35 //usage:#define ifdown_full_usage "\n\n"
36 //usage:       "        -a      De/configure all interfaces automatically"
37 //usage:     "\n        -i FILE Use FILE for interface definitions"
38 //usage:     "\n        -n      Print out what would happen, but don't do it"
39 //usage:        IF_FEATURE_IFUPDOWN_MAPPING(
40 //usage:     "\n                (note: doesn't disable mappings)"
41 //usage:     "\n        -m      Don't run any mappings"
42 //usage:        )
43 //usage:     "\n        -v      Print out what would happen before doing it"
44 //usage:     "\n        -f      Force de/configuration"
45
46 #include "libbb.h"
47 #include "common_bufsiz.h"
48 /* After libbb.h, since it needs sys/types.h on some systems */
49 #include <sys/utsname.h>
50 #include <fnmatch.h>
51
52 #define MAX_OPT_DEPTH 10
53
54 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
55 #define MAX_INTERFACE_LENGTH 10
56 #endif
57
58 #define UDHCPC_CMD_OPTIONS CONFIG_IFUPDOWN_UDHCPC_CMD_OPTIONS
59
60 #define debug_noise(args...) /*fprintf(stderr, args)*/
61
62 /* Forward declaration */
63 struct interface_defn_t;
64
65 typedef int execfn(char *command);
66
67 struct method_t {
68         const char *name;
69         int (*up)(struct interface_defn_t *ifd, execfn *e) FAST_FUNC;
70         int (*down)(struct interface_defn_t *ifd, execfn *e) FAST_FUNC;
71 };
72
73 struct address_family_t {
74         const char *name;
75         int n_methods;
76         const struct method_t *method;
77 };
78
79 struct mapping_defn_t {
80         struct mapping_defn_t *next;
81
82         int max_matches;
83         int n_matches;
84         char **match;
85
86         char *script;
87
88         int n_mappings;
89         char **mapping;
90 };
91
92 struct variable_t {
93         char *name;
94         char *value;
95 };
96
97 struct interface_defn_t {
98         const struct address_family_t *address_family;
99         const struct method_t *method;
100
101         char *iface;
102         int n_options;
103         struct variable_t *option;
104 };
105
106 struct interfaces_file_t {
107         llist_t *autointerfaces;
108         llist_t *ifaces;
109         struct mapping_defn_t *mappings;
110 };
111
112
113 #define OPTION_STR "anvf" IF_FEATURE_IFUPDOWN_MAPPING("m") "i:"
114 enum {
115         OPT_do_all      = 0x1,
116         OPT_no_act      = 0x2,
117         OPT_verbose     = 0x4,
118         OPT_force       = 0x8,
119         OPT_no_mappings = 0x10,
120 };
121 #define DO_ALL      (option_mask32 & OPT_do_all)
122 #define NO_ACT      (option_mask32 & OPT_no_act)
123 #define VERBOSE     (option_mask32 & OPT_verbose)
124 #define FORCE       (option_mask32 & OPT_force)
125 #define NO_MAPPINGS (option_mask32 & OPT_no_mappings)
126
127
128 struct globals {
129         char **my_environ;
130         const char *startup_PATH;
131         char *shell;
132 } FIX_ALIASING;
133 #define G (*(struct globals*)bb_common_bufsiz1)
134 #define INIT_G() do { setup_common_bufsiz(); } while (0)
135
136
137 static const char keywords_up_down[] ALIGN1 =
138         "up\0"
139         "down\0"
140         "pre-up\0"
141         "post-down\0"
142 ;
143
144
145 #if ENABLE_FEATURE_IFUPDOWN_IPV4 || ENABLE_FEATURE_IFUPDOWN_IPV6
146
147 static void addstr(char **bufp, const char *str, size_t str_length)
148 {
149         /* xasprintf trick will be smaller, but we are often
150          * called with str_length == 1 - don't want to have
151          * THAT much of malloc/freeing! */
152         char *buf = *bufp;
153         int len = (buf ? strlen(buf) : 0);
154         str_length++;
155         buf = xrealloc(buf, len + str_length);
156         /* copies at most str_length-1 chars! */
157         safe_strncpy(buf + len, str, str_length);
158         *bufp = buf;
159 }
160
161 static int strncmpz(const char *l, const char *r, size_t llen)
162 {
163         int i = strncmp(l, r, llen);
164
165         if (i == 0)
166                 return - (unsigned char)r[llen];
167         return i;
168 }
169
170 static char *get_var(const char *id, size_t idlen, struct interface_defn_t *ifd)
171 {
172         int i;
173
174         if (strncmpz(id, "iface", idlen) == 0) {
175                 // ubuntu's ifup doesn't do this:
176                 //static char *label_buf;
177                 //char *result;
178                 //free(label_buf);
179                 //label_buf = xstrdup(ifd->iface);
180                 // Remove virtual iface suffix
181                 //result = strchrnul(label_buf, ':');
182                 //*result = '\0';
183                 //return label_buf;
184
185                 return ifd->iface;
186         }
187         if (strncmpz(id, "label", idlen) == 0) {
188                 return ifd->iface;
189         }
190         for (i = 0; i < ifd->n_options; i++) {
191                 if (strncmpz(id, ifd->option[i].name, idlen) == 0) {
192                         return ifd->option[i].value;
193                 }
194         }
195         return NULL;
196 }
197
198 # if ENABLE_FEATURE_IFUPDOWN_IP
199 static int count_netmask_bits(const char *dotted_quad)
200 {
201 //      int result;
202 //      unsigned a, b, c, d;
203 //      /* Found a netmask...  Check if it is dotted quad */
204 //      if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
205 //              return -1;
206 //      if ((a|b|c|d) >> 8)
207 //              return -1; /* one of numbers is >= 256 */
208 //      d |= (a << 24) | (b << 16) | (c << 8); /* IP */
209 //      d = ~d; /* 11110000 -> 00001111 */
210
211         /* Shorter version */
212         int result;
213         struct in_addr ip;
214         unsigned d;
215
216         if (inet_aton(dotted_quad, &ip) == 0)
217                 return -1; /* malformed dotted IP */
218         d = ntohl(ip.s_addr); /* IP in host order */
219         d = ~d; /* 11110000 -> 00001111 */
220         if (d & (d+1)) /* check that it is in 00001111 form */
221                 return -1; /* no it is not */
222         result = 32;
223         while (d) {
224                 d >>= 1;
225                 result--;
226         }
227         return result;
228 }
229 # endif
230
231 static char *parse(const char *command, struct interface_defn_t *ifd)
232 {
233         size_t old_pos[MAX_OPT_DEPTH] = { 0 };
234         smallint okay[MAX_OPT_DEPTH] = { 1 };
235         int opt_depth = 1;
236         char *result = NULL;
237
238         while (*command) {
239                 switch (*command) {
240                 default:
241                         addstr(&result, command, 1);
242                         command++;
243                         break;
244                 case '\\':
245                         if (command[1])
246                                 command++;
247                         addstr(&result, command, 1);
248                         command++;
249                         break;
250                 case '[':
251                         if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
252                                 old_pos[opt_depth] = result ? strlen(result) : 0;
253                                 okay[opt_depth] = 1;
254                                 opt_depth++;
255                                 command += 2;
256                         } else {
257                                 addstr(&result, command, 1);
258                                 command++;
259                         }
260                         break;
261                 case ']':
262                         if (command[1] == ']' && opt_depth > 1) {
263                                 opt_depth--;
264                                 if (!okay[opt_depth]) {
265                                         result[old_pos[opt_depth]] = '\0';
266                                 }
267                                 command += 2;
268                         } else {
269                                 addstr(&result, command, 1);
270                                 command++;
271                         }
272                         break;
273                 case '%':
274                         {
275                                 char *nextpercent;
276                                 char *varvalue;
277
278                                 command++;
279                                 nextpercent = strchr(command, '%');
280                                 if (!nextpercent) {
281                                         /* Unterminated %var% */
282                                         free(result);
283                                         return NULL;
284                                 }
285
286                                 varvalue = get_var(command, nextpercent - command, ifd);
287
288                                 if (varvalue) {
289 # if ENABLE_FEATURE_IFUPDOWN_IP
290                                         /* "hwaddress <class> <address>":
291                                          * unlike ifconfig, ip doesnt want <class>
292                                          * (usually "ether" keyword). Skip it. */
293                                         if (is_prefixed_with(command, "hwaddress")) {
294                                                 varvalue = skip_whitespace(skip_non_whitespace(varvalue));
295                                         }
296 # endif
297                                         addstr(&result, varvalue, strlen(varvalue));
298                                 } else {
299 # if ENABLE_FEATURE_IFUPDOWN_IP
300                                         /* Sigh...  Add a special case for 'ip' to convert from
301                                          * dotted quad to bit count style netmasks.  */
302                                         if (is_prefixed_with(command, "bnmask")) {
303                                                 unsigned res;
304                                                 varvalue = get_var("netmask", 7, ifd);
305                                                 if (varvalue) {
306                                                         res = count_netmask_bits(varvalue);
307                                                         if (res > 0) {
308                                                                 const char *argument = utoa(res);
309                                                                 addstr(&result, argument, strlen(argument));
310                                                                 command = nextpercent + 1;
311                                                                 break;
312                                                         }
313                                                 }
314                                         }
315 # endif
316                                         okay[opt_depth - 1] = 0;
317                                 }
318
319                                 command = nextpercent + 1;
320                         }
321                         break;
322                 }
323         }
324
325         if (opt_depth > 1) {
326                 /* Unbalanced bracket */
327                 free(result);
328                 return NULL;
329         }
330
331         if (!okay[0]) {
332                 /* Undefined variable and we aren't in a bracket */
333                 free(result);
334                 return NULL;
335         }
336
337         return result;
338 }
339
340 /* execute() returns 1 for success and 0 for failure */
341 static int execute(const char *command, struct interface_defn_t *ifd, execfn *exec)
342 {
343         char *out;
344         int ret;
345
346         out = parse(command, ifd);
347         if (!out) {
348                 /* parse error? */
349                 return 0;
350         }
351         /* out == "": parsed ok but not all needed variables known, skip */
352         ret = out[0] ? (*exec)(out) : 1;
353
354         free(out);
355         if (ret != 1) {
356                 return 0;
357         }
358         return 1;
359 }
360
361 #endif /* FEATURE_IFUPDOWN_IPV4 || FEATURE_IFUPDOWN_IPV6 */
362
363
364 #if ENABLE_FEATURE_IFUPDOWN_IPV6
365
366 static int FAST_FUNC loopback_up6(struct interface_defn_t *ifd, execfn *exec)
367 {
368 # if ENABLE_FEATURE_IFUPDOWN_IP
369         int result;
370         result = execute("ip addr add ::1 dev %iface%", ifd, exec);
371         result += execute("ip link set %iface% up", ifd, exec);
372         return ((result == 2) ? 2 : 0);
373 # else
374         return execute("ifconfig %iface% add ::1", ifd, exec);
375 # endif
376 }
377
378 static int FAST_FUNC loopback_down6(struct interface_defn_t *ifd, execfn *exec)
379 {
380 # if ENABLE_FEATURE_IFUPDOWN_IP
381         return execute("ip link set %iface% down", ifd, exec);
382 # else
383         return execute("ifconfig %iface% del ::1", ifd, exec);
384 # endif
385 }
386
387 static int FAST_FUNC manual_up_down6(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
388 {
389         return 1;
390 }
391
392 static int FAST_FUNC static_up6(struct interface_defn_t *ifd, execfn *exec)
393 {
394         int result;
395 # if ENABLE_FEATURE_IFUPDOWN_IP
396         result = execute("ip addr add %address%/%netmask% dev %iface%[[ label %label%]]", ifd, exec);
397         result += execute("ip link set[[ mtu %mtu%]][[ addr %hwaddress%]] %iface% up", ifd, exec);
398         /* Reportedly, IPv6 needs "dev %iface%", but IPv4 does not: */
399         result += execute("[[ip route add ::/0 via %gateway% dev %iface%]][[ metric %metric%]]", ifd, exec);
400 # else
401         result = execute("ifconfig %iface%[[ media %media%]][[ hw %hwaddress%]][[ mtu %mtu%]] up", ifd, exec);
402         result += execute("ifconfig %iface% add %address%/%netmask%", ifd, exec);
403         result += execute("[[route -A inet6 add ::/0 gw %gateway%[[ metric %metric%]]]]", ifd, exec);
404 # endif
405         return ((result == 3) ? 3 : 0);
406 }
407
408 static int FAST_FUNC static_down6(struct interface_defn_t *ifd, execfn *exec)
409 {
410 # if ENABLE_FEATURE_IFUPDOWN_IP
411         return execute("ip link set %iface% down", ifd, exec);
412 # else
413         return execute("ifconfig %iface% down", ifd, exec);
414 # endif
415 }
416
417 # if ENABLE_FEATURE_IFUPDOWN_IP
418 static int FAST_FUNC v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
419 {
420         int result;
421         result = execute("ip tunnel add %iface% mode sit remote "
422                         "%endpoint%[[ local %local%]][[ ttl %ttl%]]", ifd, exec);
423         result += execute("ip link set %iface% up", ifd, exec);
424         result += execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec);
425         /* Reportedly, IPv6 needs "dev %iface%", but IPv4 does not: */
426         result += execute("[[ip route add ::/0 via %gateway% dev %iface%]]", ifd, exec);
427         return ((result == 4) ? 4 : 0);
428 }
429
430 static int FAST_FUNC v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
431 {
432         return execute("ip tunnel del %iface%", ifd, exec);
433 }
434 # endif
435
436 static const struct method_t methods6[] = {
437 # if ENABLE_FEATURE_IFUPDOWN_IP
438         { "v4tunnel" , v4tunnel_up     , v4tunnel_down   , },
439 # endif
440         { "static"   , static_up6      , static_down6    , },
441         { "manual"   , manual_up_down6 , manual_up_down6 , },
442         { "loopback" , loopback_up6    , loopback_down6  , },
443 };
444
445 static const struct address_family_t addr_inet6 = {
446         "inet6",
447         ARRAY_SIZE(methods6),
448         methods6
449 };
450
451 #endif /* FEATURE_IFUPDOWN_IPV6 */
452
453
454 #if ENABLE_FEATURE_IFUPDOWN_IPV4
455
456 static int FAST_FUNC loopback_up(struct interface_defn_t *ifd, execfn *exec)
457 {
458 # if ENABLE_FEATURE_IFUPDOWN_IP
459         int result;
460         result = execute("ip addr add 127.0.0.1/8 dev %iface%", ifd, exec);
461         result += execute("ip link set %iface% up", ifd, exec);
462         return ((result == 2) ? 2 : 0);
463 # else
464         return execute("ifconfig %iface% 127.0.0.1 up", ifd, exec);
465 # endif
466 }
467
468 static int FAST_FUNC loopback_down(struct interface_defn_t *ifd, execfn *exec)
469 {
470 # if ENABLE_FEATURE_IFUPDOWN_IP
471         int result;
472         result = execute("ip addr flush dev %iface%", ifd, exec);
473         result += execute("ip link set %iface% down", ifd, exec);
474         return ((result == 2) ? 2 : 0);
475 # else
476         return execute("ifconfig %iface% 127.0.0.1 down", ifd, exec);
477 # endif
478 }
479
480 static int FAST_FUNC static_up(struct interface_defn_t *ifd, execfn *exec)
481 {
482         int result;
483 # if ENABLE_FEATURE_IFUPDOWN_IP
484         result = execute("ip addr add %address%/%bnmask%[[ broadcast %broadcast%]] "
485                         "dev %iface%[[ peer %pointopoint%]][[ label %label%]]", ifd, exec);
486         result += execute("ip link set[[ mtu %mtu%]][[ addr %hwaddress%]] %iface% up", ifd, exec);
487         result += execute("[[ip route add default via %gateway% dev %iface%[[ metric %metric%]]]]", ifd, exec);
488         return ((result == 3) ? 3 : 0);
489 # else
490         /* ifconfig said to set iface up before it processes hw %hwaddress%,
491          * which then of course fails. Thus we run two separate ifconfig */
492         result = execute("ifconfig %iface%[[ hw %hwaddress%]][[ media %media%]][[ mtu %mtu%]] up",
493                                 ifd, exec);
494         result += execute("ifconfig %iface% %address% netmask %netmask%"
495                                 "[[ broadcast %broadcast%]][[ pointopoint %pointopoint%]]",
496                                 ifd, exec);
497         result += execute("[[route add default gw %gateway%[[ metric %metric%]] %iface%]]", ifd, exec);
498         return ((result == 3) ? 3 : 0);
499 # endif
500 }
501
502 static int FAST_FUNC static_down(struct interface_defn_t *ifd, execfn *exec)
503 {
504         int result;
505 # if ENABLE_FEATURE_IFUPDOWN_IP
506         /* Optional "label LBL" is necessary if interface is an alias (eth0:0),
507          * otherwise "ip addr flush dev eth0:0" flushes all addresses on eth0.
508          */
509         result = execute("ip addr flush dev %iface%[[ label %label%]]", ifd, exec);
510         result += execute("ip link set %iface% down", ifd, exec);
511 # else
512         /* result = execute("[[route del default gw %gateway% %iface%]]", ifd, exec); */
513         /* Bringing the interface down deletes the routes in itself.
514            Otherwise this fails if we reference 'gateway' when using this from dhcp_down */
515         result = 1;
516         result += execute("ifconfig %iface% down", ifd, exec);
517 # endif
518         return ((result == 2) ? 2 : 0);
519 }
520
521 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
522 struct dhcp_client_t {
523         const char *name;
524         const char *startcmd;
525         const char *stopcmd;
526 };
527
528 static const struct dhcp_client_t ext_dhcp_clients[] = {
529         { "dhcpcd",
530                 "dhcpcd[[ -h %hostname%]][[ -i %vendor%]][[ -I %client%]][[ -l %leasetime%]] %iface%",
531                 "dhcpcd -k %iface%",
532         },
533         { "dhclient",
534                 "dhclient -pf /var/run/dhclient.%iface%.pid %iface%",
535                 "kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null",
536         },
537         { "pump",
538                 "pump -i %iface%[[ -h %hostname%]][[ -l %leasehours%]]",
539                 "pump -i %iface% -k",
540         },
541         { "udhcpc",
542                 "udhcpc " UDHCPC_CMD_OPTIONS " -p /var/run/udhcpc.%iface%.pid -i %iface%[[ -x hostname:%hostname%]][[ -c %client%]]"
543                                 "[[ -s %script%]][[ %udhcpc_opts%]]",
544                 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
545         },
546 };
547 # endif /* FEATURE_IFUPDOWN_EXTERNAL_DHCPC */
548
549 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
550 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
551 {
552         unsigned i;
553 #  if ENABLE_FEATURE_IFUPDOWN_IP
554         /* ip doesn't up iface when it configures it (unlike ifconfig) */
555         if (!execute("ip link set[[ addr %hwaddress%]] %iface% up", ifd, exec))
556                 return 0;
557 #  else
558         /* needed if we have hwaddress on dhcp iface */
559         if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
560                 return 0;
561 #  endif
562         for (i = 0; i < ARRAY_SIZE(ext_dhcp_clients); i++) {
563                 if (executable_exists(ext_dhcp_clients[i].name))
564                         return execute(ext_dhcp_clients[i].startcmd, ifd, exec);
565         }
566         bb_error_msg("no dhcp clients found");
567         return 0;
568 }
569 # elif ENABLE_UDHCPC
570 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
571 {
572 #  if ENABLE_FEATURE_IFUPDOWN_IP
573         /* ip doesn't up iface when it configures it (unlike ifconfig) */
574         if (!execute("ip link set[[ addr %hwaddress%]] %iface% up", ifd, exec))
575                 return 0;
576 #  else
577         /* needed if we have hwaddress on dhcp iface */
578         if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
579                 return 0;
580 #  endif
581         return execute("udhcpc " UDHCPC_CMD_OPTIONS " -p /var/run/udhcpc.%iface%.pid "
582                         "-i %iface%[[ -x hostname:%hostname%]][[ -c %client%]][[ -s %script%]][[ %udhcpc_opts%]]",
583                         ifd, exec);
584 }
585 # else
586 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd UNUSED_PARAM,
587                 execfn *exec UNUSED_PARAM)
588 {
589         return 0; /* no dhcp support */
590 }
591 # endif
592
593 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
594 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
595 {
596         int result = 0;
597         unsigned i;
598
599         for (i = 0; i < ARRAY_SIZE(ext_dhcp_clients); i++) {
600                 if (executable_exists(ext_dhcp_clients[i].name)) {
601                         result = execute(ext_dhcp_clients[i].stopcmd, ifd, exec);
602                         if (result)
603                                 break;
604                 }
605         }
606
607         if (!result)
608                 bb_error_msg("warning: no dhcp clients found and stopped");
609
610         /* Sleep a bit, otherwise static_down tries to bring down interface too soon,
611            and it may come back up because udhcpc is still shutting down */
612         usleep(100000);
613         result += static_down(ifd, exec);
614         return ((result == 3) ? 3 : 0);
615 }
616 # elif ENABLE_UDHCPC
617 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
618 {
619         int result;
620         result = execute(
621                 "test -f /var/run/udhcpc.%iface%.pid && "
622                 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
623                 ifd, exec);
624         /* Also bring the hardware interface down since
625            killing the dhcp client alone doesn't do it.
626            This enables consecutive ifup->ifdown->ifup */
627         /* Sleep a bit, otherwise static_down tries to bring down interface too soon,
628            and it may come back up because udhcpc is still shutting down */
629         usleep(100000);
630         result += static_down(ifd, exec);
631         return ((result == 3) ? 3 : 0);
632 }
633 # else
634 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd UNUSED_PARAM,
635                 execfn *exec UNUSED_PARAM)
636 {
637         return 0; /* no dhcp support */
638 }
639 # endif
640
641 static int FAST_FUNC manual_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
642 {
643         return 1;
644 }
645
646 static int FAST_FUNC bootp_up(struct interface_defn_t *ifd, execfn *exec)
647 {
648         return execute("bootpc[[ --bootfile %bootfile%]] --dev %iface%"
649                         "[[ --server %server%]][[ --hwaddr %hwaddr%]]"
650                         " --returniffail --serverbcast", ifd, exec);
651 }
652
653 static int FAST_FUNC ppp_up(struct interface_defn_t *ifd, execfn *exec)
654 {
655         return execute("pon[[ %provider%]]", ifd, exec);
656 }
657
658 static int FAST_FUNC ppp_down(struct interface_defn_t *ifd, execfn *exec)
659 {
660         return execute("poff[[ %provider%]]", ifd, exec);
661 }
662
663 static int FAST_FUNC wvdial_up(struct interface_defn_t *ifd, execfn *exec)
664 {
665         return execute("start-stop-daemon --start -x wvdial "
666                 "-p /var/run/wvdial.%iface% -b -m --[[ %provider%]]", ifd, exec);
667 }
668
669 static int FAST_FUNC wvdial_down(struct interface_defn_t *ifd, execfn *exec)
670 {
671         return execute("start-stop-daemon --stop -x wvdial "
672                         "-p /var/run/wvdial.%iface% -s 2", ifd, exec);
673 }
674
675 static const struct method_t methods[] = {
676         { "manual"  , manual_up_down, manual_up_down, },
677         { "wvdial"  , wvdial_up     , wvdial_down   , },
678         { "ppp"     , ppp_up        , ppp_down      , },
679         { "static"  , static_up     , static_down   , },
680         { "bootp"   , bootp_up      , static_down   , },
681         { "dhcp"    , dhcp_up       , dhcp_down     , },
682         { "loopback", loopback_up   , loopback_down , },
683 };
684
685 static const struct address_family_t addr_inet = {
686         "inet",
687         ARRAY_SIZE(methods),
688         methods
689 };
690
691 #endif  /* FEATURE_IFUPDOWN_IPV4 */
692
693 static int FAST_FUNC link_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
694 {
695         return 1;
696 }
697
698 static const struct method_t link_methods[] = {
699         { "none", link_up_down, link_up_down }
700 };
701
702 static const struct address_family_t addr_link = {
703         "link", ARRAY_SIZE(link_methods), link_methods
704 };
705
706 /* Returns pointer to the next word, or NULL.
707  * In 1st case, advances *buf to the word after this one.
708  */
709 static char *next_word(char **buf)
710 {
711         unsigned length;
712         char *word;
713
714         /* Skip over leading whitespace */
715         word = skip_whitespace(*buf);
716
717         /* Stop on EOL */
718         if (*word == '\0')
719                 return NULL;
720
721         /* Find the length of this word (can't be 0) */
722         length = strcspn(word, " \t\n");
723
724         /* Unless we are already at NUL, store NUL and advance */
725         if (word[length] != '\0')
726                 word[length++] = '\0';
727
728         *buf = skip_whitespace(word + length);
729
730         return word;
731 }
732
733 static const struct address_family_t *get_address_family(const struct address_family_t *const af[], char *name)
734 {
735         int i;
736
737         if (!name)
738                 return NULL;
739
740         for (i = 0; af[i]; i++) {
741                 if (strcmp(af[i]->name, name) == 0) {
742                         return af[i];
743                 }
744         }
745         return NULL;
746 }
747
748 static const struct method_t *get_method(const struct address_family_t *af, char *name)
749 {
750         int i;
751
752         if (!name)
753                 return NULL;
754         /* TODO: use index_in_str_array() */
755         for (i = 0; i < af->n_methods; i++) {
756                 if (strcmp(af->method[i].name, name) == 0) {
757                         return &af->method[i];
758                 }
759         }
760         return NULL;
761 }
762
763 static struct interfaces_file_t *read_interfaces(const char *filename, struct interfaces_file_t *defn)
764 {
765         /* Let's try to be compatible.
766          *
767          * "man 5 interfaces" says:
768          * Lines starting with "#" are ignored. Note that end-of-line
769          * comments are NOT supported, comments must be on a line of their own.
770          * A line may be extended across multiple lines by making
771          * the last character a backslash.
772          *
773          * Seen elsewhere in example config file:
774          * A first non-blank "#" character makes the rest of the line
775          * be ignored. Blank lines are ignored. Lines may be indented freely.
776          * A "\" character at the very end of the line indicates the next line
777          * should be treated as a continuation of the current one.
778          *
779          * Lines  beginning with "source" are used to include stanzas from
780          * other files, so configuration can be split into many files.
781          * The word "source" is followed by the path of file to be sourced.
782          */
783 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
784         struct mapping_defn_t *currmap = NULL;
785 #endif
786         struct interface_defn_t *currif = NULL;
787         FILE *f;
788         char *buf;
789         char *first_word;
790         char *rest_of_line;
791         enum { NONE, IFACE, MAPPING } currently_processing = NONE;
792
793         if (!defn)
794                 defn = xzalloc(sizeof(*defn));
795
796         debug_noise("reading %s file:\n", filename);
797         f = xfopen_for_read(filename);
798
799         while ((buf = xmalloc_fgetline(f)) != NULL) {
800 #if ENABLE_DESKTOP
801                 /* Trailing "\" concatenates lines */
802                 char *p;
803                 while ((p = last_char_is(buf, '\\')) != NULL) {
804                         *p = '\0';
805                         rest_of_line = xmalloc_fgetline(f);
806                         if (!rest_of_line)
807                                 break;
808                         p = xasprintf("%s%s", buf, rest_of_line);
809                         free(buf);
810                         free(rest_of_line);
811                         buf = p;
812                 }
813 #endif
814                 rest_of_line = buf;
815                 first_word = next_word(&rest_of_line);
816                 if (!first_word || *first_word == '#') {
817                         free(buf);
818                         continue; /* blank/comment line */
819                 }
820
821                 if (strcmp(first_word, "mapping") == 0) {
822 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
823                         currmap = xzalloc(sizeof(*currmap));
824
825                         while ((first_word = next_word(&rest_of_line)) != NULL) {
826                                 currmap->match = xrealloc_vector(currmap->match, 4, currmap->n_matches);
827                                 currmap->match[currmap->n_matches++] = xstrdup(first_word);
828                         }
829                         /*currmap->n_mappings = 0;*/
830                         /*currmap->mapping = NULL;*/
831                         /*currmap->script = NULL;*/
832                         {
833                                 struct mapping_defn_t **where = &defn->mappings;
834                                 while (*where != NULL) {
835                                         where = &(*where)->next;
836                                 }
837                                 *where = currmap;
838                                 /*currmap->next = NULL;*/
839                         }
840                         debug_noise("Added mapping\n");
841 #endif
842                         currently_processing = MAPPING;
843                 } else if (strcmp(first_word, "iface") == 0) {
844                         static const struct address_family_t *const addr_fams[] = {
845 #if ENABLE_FEATURE_IFUPDOWN_IPV4
846                                 &addr_inet,
847 #endif
848 #if ENABLE_FEATURE_IFUPDOWN_IPV6
849                                 &addr_inet6,
850 #endif
851                                 &addr_link,
852                                 NULL
853                         };
854                         char *iface_name;
855                         char *address_family_name;
856                         char *method_name;
857
858                         currif = xzalloc(sizeof(*currif));
859                         iface_name = next_word(&rest_of_line);
860                         address_family_name = next_word(&rest_of_line);
861                         method_name = next_word(&rest_of_line);
862
863                         if (method_name == NULL)
864                                 bb_error_msg_and_die("too few parameters for line \"%s\"", buf);
865
866                         /* ship any trailing whitespace */
867                         rest_of_line = skip_whitespace(rest_of_line);
868
869                         if (rest_of_line[0] != '\0' /* && rest_of_line[0] != '#' */)
870                                 bb_error_msg_and_die("too many parameters \"%s\"", buf);
871
872                         currif->iface = xstrdup(iface_name);
873
874                         currif->address_family = get_address_family(addr_fams, address_family_name);
875                         if (!currif->address_family)
876                                 bb_error_msg_and_die("unknown address type \"%s\"", address_family_name);
877
878                         currif->method = get_method(currif->address_family, method_name);
879                         if (!currif->method)
880                                 bb_error_msg_and_die("unknown method \"%s\"", method_name);
881 #if 0
882 // Allegedly, Debian allows a duplicate definition:
883 // iface eth0 inet static
884 //     address 192.168.0.15
885 //     netmask 255.255.0.0
886 //     gateway 192.168.0.1
887 //
888 // iface eth0 inet static
889 //     address 10.0.0.1
890 //     netmask 255.255.255.0
891 //
892 // This adds *two* addresses to eth0 (probably requires use of "ip", not "ifconfig"
893 //
894                         llist_t *iface_list;
895                         for (iface_list = defn->ifaces; iface_list; iface_list = iface_list->link) {
896                                 struct interface_defn_t *tmp = (struct interface_defn_t *) iface_list->data;
897                                 if ((strcmp(tmp->iface, currif->iface) == 0)
898                                  && (tmp->address_family == currif->address_family)
899                                 ) {
900                                         bb_error_msg_and_die("duplicate interface \"%s\"", tmp->iface);
901                                 }
902                         }
903 #endif
904                         llist_add_to_end(&(defn->ifaces), (char*)currif);
905
906                         debug_noise("iface %s %s %s\n", currif->iface, address_family_name, method_name);
907                         currently_processing = IFACE;
908                 } else if (strcmp(first_word, "auto") == 0) {
909                         while ((first_word = next_word(&rest_of_line)) != NULL) {
910
911                                 /* Check the interface isnt already listed */
912                                 if (llist_find_str(defn->autointerfaces, first_word)) {
913                                         bb_perror_msg_and_die("interface declared auto twice \"%s\"", buf);
914                                 }
915
916                                 /* Add the interface to the list */
917                                 llist_add_to_end(&(defn->autointerfaces), xstrdup(first_word));
918                                 debug_noise("\nauto %s\n", first_word);
919                         }
920                         currently_processing = NONE;
921                 } else if (strcmp(first_word, "source") == 0) {
922                         read_interfaces(next_word(&rest_of_line), defn);
923                 } else {
924                         switch (currently_processing) {
925                         case IFACE:
926                                 if (rest_of_line[0] == '\0')
927                                         bb_error_msg_and_die("option with empty value \"%s\"", buf);
928
929                                 if (strcmp(first_word, "post-up") == 0)
930                                         first_word += 5; /* "up" */
931                                 else if (strcmp(first_word, "pre-down") == 0)
932                                         first_word += 4; /* "down" */
933
934                                 /* If not one of "up", "down",... words... */
935                                 if (index_in_strings(keywords_up_down, first_word) < 0) {
936                                         int i;
937                                         for (i = 0; i < currif->n_options; i++) {
938                                                 if (strcmp(currif->option[i].name, first_word) == 0)
939                                                         bb_error_msg_and_die("duplicate option \"%s\"", buf);
940                                         }
941                                 }
942                                 debug_noise("\t%s=%s\n", first_word, rest_of_line);
943                                 currif->option = xrealloc_vector(currif->option, 4, currif->n_options);
944                                 currif->option[currif->n_options].name = xstrdup(first_word);
945                                 currif->option[currif->n_options].value = xstrdup(rest_of_line);
946                                 currif->n_options++;
947                                 break;
948                         case MAPPING:
949 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
950                                 if (strcmp(first_word, "script") == 0) {
951                                         if (currmap->script != NULL)
952                                                 bb_error_msg_and_die("duplicate script in mapping \"%s\"", buf);
953                                         currmap->script = xstrdup(next_word(&rest_of_line));
954                                 } else if (strcmp(first_word, "map") == 0) {
955                                         currmap->mapping = xrealloc_vector(currmap->mapping, 2, currmap->n_mappings);
956                                         currmap->mapping[currmap->n_mappings] = xstrdup(next_word(&rest_of_line));
957                                         currmap->n_mappings++;
958                                 } else {
959                                         bb_error_msg_and_die("misplaced option \"%s\"", buf);
960                                 }
961 #endif
962                                 break;
963                         case NONE:
964                         default:
965                                 bb_error_msg_and_die("misplaced option \"%s\"", buf);
966                         }
967                 }
968                 free(buf);
969         } /* while (fgets) */
970
971         if (ferror(f) != 0) {
972                 /* ferror does NOT set errno! */
973                 bb_error_msg_and_die("%s: I/O error", filename);
974         }
975         fclose(f);
976         debug_noise("\ndone reading %s\n\n", filename);
977
978         return defn;
979 }
980
981 static char *setlocalenv(const char *format, const char *name, const char *value)
982 {
983         char *result;
984         char *dst;
985         char *src;
986         char c;
987
988         result = xasprintf(format, name, value);
989
990         for (dst = src = result; (c = *src) != '=' && c; src++) {
991                 if (c == '-')
992                         c = '_';
993                 if (c >= 'a' && c <= 'z')
994                         c -= ('a' - 'A');
995                 if (isalnum(c) || c == '_')
996                         *dst++ = c;
997         }
998         overlapping_strcpy(dst, src);
999
1000         return result;
1001 }
1002
1003 static void set_environ(struct interface_defn_t *iface, const char *mode, const char *opt)
1004 {
1005         int i;
1006         char **pp;
1007
1008         if (G.my_environ != NULL) {
1009                 for (pp = G.my_environ; *pp; pp++) {
1010                         free(*pp);
1011                 }
1012                 free(G.my_environ);
1013         }
1014
1015         /* note: last element will stay NULL: */
1016         G.my_environ = xzalloc(sizeof(char *) * (iface->n_options + 7));
1017         pp = G.my_environ;
1018
1019         for (i = 0; i < iface->n_options; i++) {
1020                 if (index_in_strings(keywords_up_down, iface->option[i].name) >= 0) {
1021                         continue;
1022                 }
1023                 *pp++ = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
1024         }
1025
1026         *pp++ = setlocalenv("%s=%s", "IFACE", iface->iface);
1027         *pp++ = setlocalenv("%s=%s", "ADDRFAM", iface->address_family->name);
1028         *pp++ = setlocalenv("%s=%s", "METHOD", iface->method->name);
1029         *pp++ = setlocalenv("%s=%s", "MODE", mode);
1030         *pp++ = setlocalenv("%s=%s", "PHASE", opt);
1031         if (G.startup_PATH)
1032                 *pp++ = setlocalenv("%s=%s", "PATH", G.startup_PATH);
1033 }
1034
1035 static int doit(char *str)
1036 {
1037         if (option_mask32 & (OPT_no_act|OPT_verbose)) {
1038                 puts(str);
1039         }
1040         if (!(option_mask32 & OPT_no_act)) {
1041                 pid_t child;
1042                 int status;
1043
1044                 fflush_all();
1045                 child = vfork();
1046                 if (child < 0) /* failure */
1047                         return 0;
1048                 if (child == 0) { /* child */
1049                         execle(G.shell, G.shell, "-c", str, (char *) NULL, G.my_environ);
1050                         _exit(127);
1051                 }
1052                 safe_waitpid(child, &status, 0);
1053                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1054                         return 0;
1055                 }
1056         }
1057         return 1;
1058 }
1059
1060 static int execute_all(struct interface_defn_t *ifd, const char *opt)
1061 {
1062         int i;
1063         char *buf;
1064         for (i = 0; i < ifd->n_options; i++) {
1065                 if (strcmp(ifd->option[i].name, opt) == 0) {
1066                         if (!doit(ifd->option[i].value)) {
1067                                 return 0;
1068                         }
1069                 }
1070         }
1071
1072         /* Tested on Debian Squeeze: "standard" ifup runs this without
1073          * checking that directory exists. If it doesn't, run-parts
1074          * complains, and this message _is_ annoyingly visible.
1075          * Don't "fix" this (unless newer Debian does).
1076          */
1077         buf = xasprintf("run-parts /etc/network/if-%s.d", opt);
1078         /* heh, we don't bother free'ing it */
1079         return doit(buf);
1080 }
1081
1082 static int check(char *str)
1083 {
1084         return str != NULL;
1085 }
1086
1087 static int iface_up(struct interface_defn_t *iface)
1088 {
1089         if (!iface->method->up(iface, check)) return -1;
1090         set_environ(iface, "start", "pre-up");
1091         if (!execute_all(iface, "pre-up")) return 0;
1092         if (!iface->method->up(iface, doit)) return 0;
1093         set_environ(iface, "start", "post-up");
1094         if (!execute_all(iface, "up")) return 0;
1095         return 1;
1096 }
1097
1098 static int iface_down(struct interface_defn_t *iface)
1099 {
1100         if (!iface->method->down(iface, check)) return -1;
1101         set_environ(iface, "stop", "pre-down");
1102         if (!execute_all(iface, "down")) return 0;
1103         if (!iface->method->down(iface, doit)) return 0;
1104         set_environ(iface, "stop", "post-down");
1105         if (!execute_all(iface, "post-down")) return 0;
1106         return 1;
1107 }
1108
1109 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1110 static int popen2(FILE **in, FILE **out, char *command, char *param)
1111 {
1112         char *argv[3] = { command, param, NULL };
1113         struct fd_pair infd, outfd;
1114         pid_t pid;
1115
1116         xpiped_pair(infd);
1117         xpiped_pair(outfd);
1118
1119         fflush_all();
1120         pid = xvfork();
1121
1122         if (pid == 0) {
1123                 /* Child */
1124                 /* NB: close _first_, then move fds! */
1125                 close(infd.wr);
1126                 close(outfd.rd);
1127                 xmove_fd(infd.rd, 0);
1128                 xmove_fd(outfd.wr, 1);
1129                 BB_EXECVP_or_die(argv);
1130         }
1131         /* parent */
1132         close(infd.rd);
1133         close(outfd.wr);
1134         *in = xfdopen_for_write(infd.wr);
1135         *out = xfdopen_for_read(outfd.rd);
1136         return pid;
1137 }
1138
1139 static char *run_mapping(char *physical, struct mapping_defn_t *map)
1140 {
1141         FILE *in, *out;
1142         int i, status;
1143         pid_t pid;
1144
1145         char *logical = xstrdup(physical);
1146
1147         /* Run the mapping script. Never fails. */
1148         pid = popen2(&in, &out, map->script, physical);
1149
1150         /* Write mappings to stdin of mapping script. */
1151         for (i = 0; i < map->n_mappings; i++) {
1152                 fprintf(in, "%s\n", map->mapping[i]);
1153         }
1154         fclose(in);
1155         safe_waitpid(pid, &status, 0);
1156
1157         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1158                 /* If the mapping script exited successfully, try to
1159                  * grab a line of output and use that as the name of the
1160                  * logical interface. */
1161                 char *new_logical = xmalloc_fgetline(out);
1162
1163                 if (new_logical) {
1164                         /* If we are able to read a line of output from the script,
1165                          * remove any trailing whitespace and use this value
1166                          * as the name of the logical interface. */
1167                         char *pch = new_logical + strlen(new_logical) - 1;
1168
1169                         while (pch >= new_logical && isspace(*pch))
1170                                 *(pch--) = '\0';
1171
1172                         free(logical);
1173                         logical = new_logical;
1174                 }
1175         }
1176
1177         fclose(out);
1178
1179         return logical;
1180 }
1181 #endif /* FEATURE_IFUPDOWN_MAPPING */
1182
1183 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1184 {
1185         llist_t *search = state_list;
1186
1187         while (search) {
1188                 char *after_iface = is_prefixed_with(search->data, iface);
1189                 if (after_iface
1190                  && *after_iface == '='
1191                 ) {
1192                         return search;
1193                 }
1194                 search = search->link;
1195         }
1196         return NULL;
1197 }
1198
1199 /* read the previous state from the state file */
1200 static llist_t *read_iface_state(void)
1201 {
1202         llist_t *state_list = NULL;
1203         FILE *state_fp = fopen_for_read(CONFIG_IFUPDOWN_IFSTATE_PATH);
1204
1205         if (state_fp) {
1206                 char *start, *end_ptr;
1207                 while ((start = xmalloc_fgets(state_fp)) != NULL) {
1208                         /* We should only need to check for a single character */
1209                         end_ptr = start + strcspn(start, " \t\n");
1210                         *end_ptr = '\0';
1211                         llist_add_to(&state_list, start);
1212                 }
1213                 fclose(state_fp);
1214         }
1215         return state_list;
1216 }
1217
1218
1219 int ifupdown_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1220 int ifupdown_main(int argc UNUSED_PARAM, char **argv)
1221 {
1222         int (*cmds)(struct interface_defn_t *);
1223         struct interfaces_file_t *defn;
1224         llist_t *target_list = NULL;
1225         const char *interfaces = "/etc/network/interfaces";
1226         bool any_failures = 0;
1227
1228         INIT_G();
1229
1230         G.startup_PATH = getenv("PATH");
1231         G.shell = xstrdup(get_shell_name());
1232
1233         cmds = iface_down;
1234         if (applet_name[2] == 'u') {
1235                 /* ifup command */
1236                 cmds = iface_up;
1237         }
1238
1239         getopt32(argv, OPTION_STR, &interfaces);
1240         argv += optind;
1241         if (argv[0]) {
1242                 if (DO_ALL) bb_show_usage();
1243         } else {
1244                 if (!DO_ALL) bb_show_usage();
1245         }
1246
1247         defn = read_interfaces(interfaces, NULL);
1248
1249         /* Create a list of interfaces to work on */
1250         if (DO_ALL) {
1251                 target_list = defn->autointerfaces;
1252         } else {
1253                 llist_add_to_end(&target_list, argv[0]);
1254         }
1255
1256         /* Update the interfaces */
1257         while (target_list) {
1258                 llist_t *iface_list;
1259                 struct interface_defn_t *currif;
1260                 char *iface;
1261                 char *liface;
1262                 char *pch;
1263                 bool okay = 0;
1264                 int cmds_ret;
1265                 bool curr_failure = 0;
1266
1267                 iface = xstrdup(target_list->data);
1268                 target_list = target_list->link;
1269
1270                 pch = strchr(iface, '=');
1271                 if (pch) {
1272                         *pch = '\0';
1273                         liface = xstrdup(pch + 1);
1274                 } else {
1275                         liface = xstrdup(iface);
1276                 }
1277
1278                 if (!FORCE) {
1279                         llist_t *state_list = read_iface_state();
1280                         const llist_t *iface_state = find_iface_state(state_list, iface);
1281
1282                         if (cmds == iface_up) {
1283                                 /* ifup */
1284                                 if (iface_state) {
1285                                         bb_error_msg("interface %s already configured", iface);
1286                                         goto next;
1287                                 }
1288                         } else {
1289                                 /* ifdown */
1290                                 if (!iface_state) {
1291                                         bb_error_msg("interface %s not configured", iface);
1292                                         goto next;
1293                                 }
1294                         }
1295                         llist_free(state_list, free);
1296                 }
1297
1298 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1299                 if ((cmds == iface_up) && !NO_MAPPINGS) {
1300                         struct mapping_defn_t *currmap;
1301
1302                         for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1303                                 int i;
1304                                 for (i = 0; i < currmap->n_matches; i++) {
1305                                         if (fnmatch(currmap->match[i], liface, 0) != 0)
1306                                                 continue;
1307                                         if (VERBOSE) {
1308                                                 printf("Running mapping script %s on %s\n", currmap->script, liface);
1309                                         }
1310                                         liface = run_mapping(iface, currmap);
1311                                         break;
1312                                 }
1313                         }
1314                 }
1315 #endif
1316
1317                 iface_list = defn->ifaces;
1318                 while (iface_list) {
1319                         currif = (struct interface_defn_t *) iface_list->data;
1320                         if (strcmp(liface, currif->iface) == 0) {
1321                                 char *oldiface = currif->iface;
1322
1323                                 okay = 1;
1324                                 currif->iface = iface;
1325
1326                                 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1327
1328                                 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1329                                 cmds_ret = cmds(currif);
1330                                 if (cmds_ret == -1) {
1331                                         bb_error_msg("don't have all variables for %s/%s",
1332                                                         liface, currif->address_family->name);
1333                                         any_failures = curr_failure = 1;
1334                                 } else if (cmds_ret == 0) {
1335                                         any_failures = curr_failure = 1;
1336                                 }
1337
1338                                 currif->iface = oldiface;
1339                         }
1340                         iface_list = iface_list->link;
1341                 }
1342                 if (VERBOSE) {
1343                         bb_putchar('\n');
1344                 }
1345
1346                 if (!okay && !FORCE) {
1347                         bb_error_msg("ignoring unknown interface %s", liface);
1348                         any_failures = 1;
1349                 } else if (!NO_ACT) {
1350                         /* update the state file */
1351                         FILE *state_fp;
1352                         llist_t *state;
1353                         llist_t *state_list = read_iface_state();
1354                         llist_t *iface_state = find_iface_state(state_list, iface);
1355
1356                         if (cmds == iface_up && !curr_failure) {
1357                                 char *newiface = xasprintf("%s=%s", iface, liface);
1358                                 if (!iface_state) {
1359                                         llist_add_to_end(&state_list, newiface);
1360                                 } else {
1361                                         free(iface_state->data);
1362                                         iface_state->data = newiface;
1363                                 }
1364                         } else {
1365                                 /* Remove an interface from state_list */
1366                                 llist_unlink(&state_list, iface_state);
1367                                 free(llist_pop(&iface_state));
1368                         }
1369
1370                         /* Actually write the new state */
1371                         state_fp = xfopen_for_write(CONFIG_IFUPDOWN_IFSTATE_PATH);
1372                         state = state_list;
1373                         while (state) {
1374                                 if (state->data) {
1375                                         fprintf(state_fp, "%s\n", state->data);
1376                                 }
1377                                 state = state->link;
1378                         }
1379                         fclose(state_fp);
1380                         llist_free(state_list, free);
1381                 }
1382  next:
1383                 free(iface);
1384                 free(liface);
1385         }
1386
1387         return any_failures;
1388 }