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