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