cut: code shrink
[busybox-git.git] / networking / ifupdown.c
blob9c3640be7985e386f2e0a1ce503a86ca92cc01bb
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>
7 * Based on ifupdown v 0.6.4 by Anthony Towns
8 * Copyright (c) 1999 Anthony Towns <aj@azure.humbug.org.au>
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.
17 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config:config IFUP
20 //config: bool "ifup (14 kb)"
21 //config: default y
22 //config: help
23 //config: Activate the specified interfaces. This applet makes use
24 //config: of either "ifconfig" and "route" or the "ip" command to actually
25 //config: configure network interfaces. Therefore, you will probably also want
26 //config: to enable either IFCONFIG and ROUTE, or enable
27 //config: FEATURE_IFUPDOWN_IP and the various IP options. Of
28 //config: course you could use non-busybox versions of these programs, so
29 //config: against my better judgement (since this will surely result in plenty
30 //config: of support questions on the mailing list), I do not force you to
31 //config: enable these additional options. It is up to you to supply either
32 //config: "ifconfig", "route" and "run-parts" or the "ip" command, either
33 //config: via busybox or via standalone utilities.
34 //config:
35 //config:config IFDOWN
36 //config: bool "ifdown (13 kb)"
37 //config: default y
38 //config: help
39 //config: Deactivate the specified interfaces.
40 //config:
41 //config:config IFUPDOWN_IFSTATE_PATH
42 //config: string "Absolute path to ifstate file"
43 //config: default "/var/run/ifstate"
44 //config: depends on IFUP || IFDOWN
45 //config: help
46 //config: ifupdown keeps state information in a file called ifstate.
47 //config: Typically it is located in /var/run/ifstate, however
48 //config: some distributions tend to put it in other places
49 //config: (debian, for example, uses /etc/network/run/ifstate).
50 //config: This config option defines location of ifstate.
51 //config:
52 //config:config FEATURE_IFUPDOWN_IP
53 //config: bool "Use ip tool (else ifconfig/route is used)"
54 //config: default y
55 //config: depends on IFUP || IFDOWN
56 //config: help
57 //config: Use the iproute "ip" command to implement "ifup" and "ifdown", rather
58 //config: than the default of using the older "ifconfig" and "route" utilities.
59 //config:
60 //config: If Y: you must install either the full-blown iproute2 package
61 //config: or enable "ip" applet in busybox, or the "ifup" and "ifdown" applets
62 //config: will not work.
63 //config:
64 //config: If N: you must install either the full-blown ifconfig and route
65 //config: utilities, or enable these applets in busybox.
66 //config:
67 //config:config FEATURE_IFUPDOWN_IPV4
68 //config: bool "Support IPv4"
69 //config: default y
70 //config: depends on IFUP || IFDOWN
71 //config: help
72 //config: If you want ifup/ifdown to talk IPv4, leave this on.
73 //config:
74 //config:config FEATURE_IFUPDOWN_IPV6
75 //config: bool "Support IPv6"
76 //config: default y
77 //config: depends on (IFUP || IFDOWN) && FEATURE_IPV6
78 //config: help
79 //config: If you need support for IPv6, turn this option on.
80 //config:
81 //UNUSED:
82 ////////:config FEATURE_IFUPDOWN_IPX
83 ////////: bool "Support IPX"
84 ////////: default y
85 ////////: depends on IFUP || IFDOWN
86 ////////: help
87 ////////: If this option is selected you can use busybox to work with IPX
88 ////////: networks.
89 //config:
90 //config:config FEATURE_IFUPDOWN_MAPPING
91 //config: bool "Enable mapping support"
92 //config: default y
93 //config: depends on IFUP || IFDOWN
94 //config: help
95 //config: This enables support for the "mapping" stanza, unless you have
96 //config: a weird network setup you don't need it.
97 //config:
98 //config:config FEATURE_IFUPDOWN_EXTERNAL_DHCP
99 //config: bool "Support external DHCP clients"
100 //config: default n
101 //config: depends on IFUP || IFDOWN
102 //config: help
103 //config: This enables support for the external dhcp clients. Clients are
104 //config: tried in the following order: dhcpcd, dhclient, pump and udhcpc.
105 //config: Otherwise, if udhcpc applet is enabled, it is used.
106 //config: Otherwise, ifup/ifdown will have no support for DHCP.
108 // APPLET_ODDNAME:name main location suid_type help
109 //applet:IF_IFUP( APPLET_ODDNAME(ifup, ifupdown, BB_DIR_SBIN, BB_SUID_DROP, ifup))
110 //applet:IF_IFDOWN(APPLET_ODDNAME(ifdown, ifupdown, BB_DIR_SBIN, BB_SUID_DROP, ifdown))
112 //kbuild:lib-$(CONFIG_IFUP) += ifupdown.o
113 //kbuild:lib-$(CONFIG_IFDOWN) += ifupdown.o
115 //usage:#define ifup_trivial_usage
116 //usage: "[-n"IF_FEATURE_IFUPDOWN_MAPPING("m")"vf] [-i FILE] -a | IFACE..."
117 //usage:#define ifup_full_usage "\n\n"
118 //usage: " -a Configure all interfaces"
119 //usage: "\n -i FILE Use FILE instead of /etc/network/interfaces"
120 //usage: "\n -n Dry run"
121 //usage: IF_FEATURE_IFUPDOWN_MAPPING(
122 //usage: "\n (note: doesn't disable mappings)"
123 //usage: "\n -m Don't run any mappings"
124 //usage: )
125 //usage: "\n -v Print out what would happen before doing it"
126 //usage: "\n -f Force"
127 //usage:
128 //usage:#define ifdown_trivial_usage
129 //usage: "[-n"IF_FEATURE_IFUPDOWN_MAPPING("m")"vf] [-i FILE] -a | IFACE..."
130 //usage:#define ifdown_full_usage "\n\n"
131 //usage: " -a Deconfigure all interfaces"
132 //usage: "\n -i FILE Use FILE instead of /etc/network/interfaces"
133 //usage: "\n -n Dry run"
134 //usage: IF_FEATURE_IFUPDOWN_MAPPING(
135 //usage: "\n (note: doesn't disable mappings)"
136 //usage: "\n -m Don't run any mappings"
137 //usage: )
138 //usage: "\n -v Print out what would happen before doing it"
139 //usage: "\n -f Force"
141 #include <net/if.h>
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>
148 #define MAX_OPT_DEPTH 10
150 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
151 #define MAX_INTERFACE_LENGTH 10
152 #endif
154 #define UDHCPC_CMD_OPTIONS CONFIG_IFUPDOWN_UDHCPC_CMD_OPTIONS
155 #define IFSTATE_FILE_PATH CONFIG_IFUPDOWN_IFSTATE_PATH
157 #define debug_noise(args...) /*fprintf(stderr, args)*/
159 /* Forward declaration */
160 struct interface_defn_t;
162 typedef int execfn(char *command);
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;
170 struct address_family_t {
171 const char *name;
172 int n_methods;
173 const struct method_t *method;
176 struct mapping_defn_t {
177 struct mapping_defn_t *next;
179 int max_matches;
180 int n_matches;
181 char **match;
183 char *script;
185 int n_mappings;
186 char **mapping;
189 struct variable_t {
190 char *name;
191 char *value;
194 struct interface_defn_t {
195 const struct address_family_t *address_family;
196 const struct method_t *method;
198 char *iface;
199 int n_options;
200 struct variable_t *option;
203 struct interfaces_file_t {
204 llist_t *autointerfaces;
205 llist_t *ifaces;
206 struct mapping_defn_t *mappings;
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,
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)
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)
234 static const char keywords_up_down[] ALIGN1 =
235 "up\0"
236 "down\0"
237 "pre-up\0"
238 "post-down\0"
242 #if ENABLE_FEATURE_IFUPDOWN_IPV4 || ENABLE_FEATURE_IFUPDOWN_IPV6
244 static void addstr(char **bufp, const char *str, size_t str_length)
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;
258 static int strncmpz(const char *l, const char *r, size_t llen)
260 int i = strncmp(l, r, llen);
262 if (i == 0)
263 return - (unsigned char)r[llen];
264 return i;
267 static char *get_var(const char *id, size_t idlen, struct interface_defn_t *ifd)
269 int i;
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;
282 return ifd->iface;
284 if (strncmpz(id, "label", idlen) == 0) {
285 return ifd->iface;
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;
292 return NULL;
295 # if ENABLE_FEATURE_IFUPDOWN_IP
296 static int count_netmask_bits(const char *dotted_quad)
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 */
308 /* Shorter version */
309 struct in_addr ip;
310 unsigned d;
312 if (inet_aton(dotted_quad, &ip) == 0)
313 return -1; /* malformed dotted IP */
314 d = ntohl(ip.s_addr); /* IP in host order */
315 d = ~d; /* 11110000 -> 00001111 */
316 if (d & (d+1)) /* check that it is in 00001111 form */
317 return -1; /* no it is not */
318 return bb_popcnt_32(~d);
320 # endif
322 static char *parse(const char *command, struct interface_defn_t *ifd)
324 size_t old_pos[MAX_OPT_DEPTH] = { 0 };
325 smallint okay[MAX_OPT_DEPTH] = { 1 };
326 int opt_depth = 1;
327 char *result = NULL;
329 while (*command) {
330 switch (*command) {
331 default:
332 addstr(&result, command, 1);
333 command++;
334 break;
335 case '\\':
336 if (command[1])
337 command++;
338 addstr(&result, command, 1);
339 command++;
340 break;
341 case '[':
342 if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
343 old_pos[opt_depth] = result ? strlen(result) : 0;
344 okay[opt_depth] = 1;
345 opt_depth++;
346 command += 2;
347 } else {
348 addstr(&result, command, 1);
349 command++;
351 break;
352 case ']':
353 if (command[1] == ']' && opt_depth > 1) {
354 opt_depth--;
355 if (!okay[opt_depth]) {
356 result[old_pos[opt_depth]] = '\0';
358 command += 2;
359 } else {
360 addstr(&result, command, 1);
361 command++;
363 break;
364 case '%':
366 char *nextpercent;
367 char *varvalue;
369 command++;
370 nextpercent = strchr(command, '%');
371 if (!nextpercent) {
372 /* Unterminated %var% */
373 free(result);
374 return NULL;
377 varvalue = get_var(command, nextpercent - command, ifd);
379 if (varvalue) {
380 # if ENABLE_FEATURE_IFUPDOWN_IP
381 /* "hwaddress <class> <address>":
382 * unlike ifconfig, ip doesnt want <class>
383 * (usually "ether" keyword). Skip it. */
384 if (is_prefixed_with(command, "hwaddress")) {
385 varvalue = skip_whitespace(skip_non_whitespace(varvalue));
387 # endif
388 addstr(&result, varvalue, strlen(varvalue));
389 } else {
390 # if ENABLE_FEATURE_IFUPDOWN_IP
391 /* Sigh... Add a special case for 'ip' to convert from
392 * dotted quad to bit count style netmasks. */
393 if (is_prefixed_with(command, "bnmask")) {
394 unsigned res;
395 varvalue = get_var("netmask", 7, ifd);
396 if (varvalue) {
397 res = count_netmask_bits(varvalue);
398 if (res > 0) {
399 const char *argument = utoa(res);
400 addstr(&result, argument, strlen(argument));
401 command = nextpercent + 1;
402 break;
406 # endif
407 okay[opt_depth - 1] = 0;
410 command = nextpercent + 1;
412 break;
416 if (opt_depth > 1) {
417 /* Unbalanced bracket */
418 free(result);
419 return NULL;
422 if (!okay[0]) {
423 /* Undefined variable and we aren't in a bracket */
424 free(result);
425 return NULL;
428 return result;
431 /* execute() returns 1 for success and 0 for failure */
432 static int execute(const char *command, struct interface_defn_t *ifd, execfn *exec)
434 char *out;
435 int ret;
437 out = parse(command, ifd);
438 if (!out) {
439 /* parse error? */
440 return 0;
442 /* out == "": parsed ok but not all needed variables known, skip */
443 ret = out[0] ? (*exec)(out) : 1;
445 free(out);
446 if (ret != 1) {
447 return 0;
449 return 1;
452 #endif /* FEATURE_IFUPDOWN_IPV4 || FEATURE_IFUPDOWN_IPV6 */
455 #if ENABLE_FEATURE_IFUPDOWN_IPV6
457 static int FAST_FUNC loopback_up6(struct interface_defn_t *ifd, execfn *exec)
459 # if ENABLE_FEATURE_IFUPDOWN_IP
460 int result;
461 result = execute("ip addr add ::1 dev %iface%", ifd, exec);
462 result += execute("ip link set %iface% up", ifd, exec);
463 return ((result == 2) ? 2 : 0);
464 # else
465 return execute("ifconfig %iface% add ::1", ifd, exec);
466 # endif
469 static int FAST_FUNC loopback_down6(struct interface_defn_t *ifd, execfn *exec)
471 # if ENABLE_FEATURE_IFUPDOWN_IP
472 return execute("ip link set %iface% down", ifd, exec);
473 # else
474 return execute("ifconfig %iface% del ::1", ifd, exec);
475 # endif
478 static int FAST_FUNC manual_up_down6(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
480 return 1;
483 static int FAST_FUNC static_up6(struct interface_defn_t *ifd, execfn *exec)
485 int result;
486 # if ENABLE_FEATURE_IFUPDOWN_IP
487 result = execute("ip addr add %address%/%netmask% dev %iface%[[ label %label%]]", ifd, exec);
488 result += execute("ip link set[[ mtu %mtu%]][[ addr %hwaddress%]] %iface% up", ifd, exec);
489 /* Reportedly, IPv6 needs "dev %iface%", but IPv4 does not: */
490 result += execute("[[ip route add ::/0 via %gateway% dev %iface%]][[ metric %metric%]]", ifd, exec);
491 # else
492 result = execute("ifconfig %iface%[[ media %media%]][[ hw %hwaddress%]][[ mtu %mtu%]] up", ifd, exec);
493 result += execute("ifconfig %iface% add %address%/%netmask%", ifd, exec);
494 result += execute("[[route -A inet6 add ::/0 gw %gateway%[[ metric %metric%]]]]", ifd, exec);
495 # endif
496 return ((result == 3) ? 3 : 0);
499 static int FAST_FUNC static_down6(struct interface_defn_t *ifd, execfn *exec)
501 if (!if_nametoindex(ifd->iface))
502 return 1; /* already gone */
503 # if ENABLE_FEATURE_IFUPDOWN_IP
504 return execute("ip link set %iface% down", ifd, exec);
505 # else
506 return execute("ifconfig %iface% down", ifd, exec);
507 # endif
510 # if ENABLE_FEATURE_IFUPDOWN_IP
511 static int FAST_FUNC v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
513 int result;
514 result = execute("ip tunnel add %iface% mode sit remote "
515 "%endpoint%[[ local %local%]][[ ttl %ttl%]]", ifd, exec);
516 result += execute("ip link set %iface% up", ifd, exec);
517 result += execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec);
518 /* Reportedly, IPv6 needs "dev %iface%", but IPv4 does not: */
519 result += execute("[[ip route add ::/0 via %gateway% dev %iface%]]", ifd, exec);
520 return ((result == 4) ? 4 : 0);
523 static int FAST_FUNC v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
525 return execute("ip tunnel del %iface%", ifd, exec);
527 # endif
529 static const struct method_t methods6[] ALIGN_PTR = {
530 # if ENABLE_FEATURE_IFUPDOWN_IP
531 { "v4tunnel" , v4tunnel_up , v4tunnel_down , },
532 # endif
533 { "static" , static_up6 , static_down6 , },
534 { "manual" , manual_up_down6 , manual_up_down6 , },
535 { "loopback" , loopback_up6 , loopback_down6 , },
538 static const struct address_family_t addr_inet6 = {
539 "inet6",
540 ARRAY_SIZE(methods6),
541 methods6
544 #endif /* FEATURE_IFUPDOWN_IPV6 */
547 #if ENABLE_FEATURE_IFUPDOWN_IPV4
549 static int FAST_FUNC loopback_up(struct interface_defn_t *ifd, execfn *exec)
551 # if ENABLE_FEATURE_IFUPDOWN_IP
552 int result;
553 result = execute("ip addr add 127.0.0.1/8 dev %iface%", ifd, exec);
554 result += execute("ip link set %iface% up", ifd, exec);
555 return ((result == 2) ? 2 : 0);
556 # else
557 return execute("ifconfig %iface% 127.0.0.1 up", ifd, exec);
558 # endif
561 static int FAST_FUNC loopback_down(struct interface_defn_t *ifd, execfn *exec)
563 # if ENABLE_FEATURE_IFUPDOWN_IP
564 int result;
565 result = execute("ip addr flush dev %iface%", ifd, exec);
566 result += execute("ip link set %iface% down", ifd, exec);
567 return ((result == 2) ? 2 : 0);
568 # else
569 return execute("ifconfig %iface% 127.0.0.1 down", ifd, exec);
570 # endif
573 static int FAST_FUNC static_up(struct interface_defn_t *ifd, execfn *exec)
575 int result;
576 # if ENABLE_FEATURE_IFUPDOWN_IP
577 result = execute("ip addr add %address%/%bnmask%[[ broadcast %broadcast%]] "
578 "dev %iface%[[ peer %pointopoint%]][[ label %label%]]", ifd, exec);
579 result += execute("ip link set[[ mtu %mtu%]][[ addr %hwaddress%]] %iface% up", ifd, exec);
580 result += execute("[[ip route add default via %gateway% dev %iface%[[ metric %metric%]]]]", ifd, exec);
581 return ((result == 3) ? 3 : 0);
582 # else
583 /* ifconfig said to set iface up before it processes hw %hwaddress%,
584 * which then of course fails. Thus we run two separate ifconfig */
585 result = execute("ifconfig %iface%[[ hw %hwaddress%]][[ media %media%]][[ mtu %mtu%]] up",
586 ifd, exec);
587 result += execute("ifconfig %iface% %address% netmask %netmask%"
588 "[[ broadcast %broadcast%]][[ pointopoint %pointopoint%]]",
589 ifd, exec);
590 result += execute("[[route add default gw %gateway%[[ metric %metric%]] %iface%]]", ifd, exec);
591 return ((result == 3) ? 3 : 0);
592 # endif
595 static int FAST_FUNC static_down(struct interface_defn_t *ifd, execfn *exec)
597 int result;
599 if (!if_nametoindex(ifd->iface))
600 return 2; /* already gone */
601 # if ENABLE_FEATURE_IFUPDOWN_IP
602 /* Optional "label LBL" is necessary if interface is an alias (eth0:0),
603 * otherwise "ip addr flush dev eth0:0" flushes all addresses on eth0.
605 result = execute("ip addr flush dev %iface%[[ label %label%]]", ifd, exec);
606 result += execute("ip link set %iface% down", ifd, exec);
607 # else
608 /* result = execute("[[route del default gw %gateway% %iface%]]", ifd, exec); */
609 /* Bringing the interface down deletes the routes in itself.
610 Otherwise this fails if we reference 'gateway' when using this from dhcp_down */
611 result = 1;
612 result += execute("ifconfig %iface% down", ifd, exec);
613 # endif
614 return ((result == 2) ? 2 : 0);
617 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
618 struct dhcp_client_t {
619 const char *name;
620 const char *startcmd;
621 const char *stopcmd;
624 static const struct dhcp_client_t ext_dhcp_clients[] ALIGN_PTR = {
625 { "dhcpcd",
626 "dhcpcd[[ -h %hostname%]][[ -i %vendor%]][[ -I %client%]][[ -l %leasetime%]] %iface%",
627 "dhcpcd -k %iface%",
629 { "dhclient",
630 "dhclient -pf /var/run/dhclient.%iface%.pid %iface%",
631 "kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null",
633 { "pump",
634 "pump -i %iface%[[ -h %hostname%]][[ -l %leasehours%]]",
635 "pump -i %iface% -k",
637 { "udhcpc",
638 "udhcpc " UDHCPC_CMD_OPTIONS " -p /var/run/udhcpc.%iface%.pid -i %iface%[[ -x hostname:%hostname%]][[ -c %client%]]"
639 "[[ -s %script%]][[ %udhcpc_opts%]]",
640 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
643 # endif /* FEATURE_IFUPDOWN_EXTERNAL_DHCPC */
645 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
646 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
648 unsigned i;
649 # if ENABLE_FEATURE_IFUPDOWN_IP
650 /* ip doesn't up iface when it configures it (unlike ifconfig) */
651 if (!execute("ip link set[[ addr %hwaddress%]] %iface% up", ifd, exec))
652 return 0;
653 # else
654 /* needed if we have hwaddress on dhcp iface */
655 if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
656 return 0;
657 # endif
658 for (i = 0; i < ARRAY_SIZE(ext_dhcp_clients); i++) {
659 if (executable_exists(ext_dhcp_clients[i].name))
660 return execute(ext_dhcp_clients[i].startcmd, ifd, exec);
662 bb_simple_error_msg("no dhcp clients found");
663 return 0;
665 # elif ENABLE_UDHCPC
666 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
668 # if ENABLE_FEATURE_IFUPDOWN_IP
669 /* ip doesn't up iface when it configures it (unlike ifconfig) */
670 if (!execute("ip link set[[ addr %hwaddress%]] %iface% up", ifd, exec))
671 return 0;
672 # else
673 /* needed if we have hwaddress on dhcp iface */
674 if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
675 return 0;
676 # endif
677 return execute("udhcpc " UDHCPC_CMD_OPTIONS " -p /var/run/udhcpc.%iface%.pid "
678 "-i %iface%[[ -x hostname:%hostname%]][[ -c %client%]][[ -s %script%]][[ %udhcpc_opts%]]",
679 ifd, exec);
681 # else
682 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd UNUSED_PARAM,
683 execfn *exec UNUSED_PARAM)
685 return 0; /* no dhcp support */
687 # endif
689 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
690 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
692 int result = 0;
693 unsigned i;
695 for (i = 0; i < ARRAY_SIZE(ext_dhcp_clients); i++) {
696 if (executable_exists(ext_dhcp_clients[i].name)) {
697 result = execute(ext_dhcp_clients[i].stopcmd, ifd, exec);
698 if (result)
699 break;
703 if (!result)
704 bb_simple_error_msg("warning: no dhcp clients found and stopped");
706 /* Sleep a bit, otherwise static_down tries to bring down interface too soon,
707 and it may come back up because udhcpc is still shutting down */
708 usleep(100000);
709 result += static_down(ifd, exec);
710 return ((result == 3) ? 3 : 0);
712 # elif ENABLE_UDHCPC
713 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
715 int result;
716 result = execute(
717 "test -f /var/run/udhcpc.%iface%.pid && "
718 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
719 ifd, exec);
720 /* Also bring the hardware interface down since
721 killing the dhcp client alone doesn't do it.
722 This enables consecutive ifup->ifdown->ifup */
723 /* Sleep a bit, otherwise static_down tries to bring down interface too soon,
724 and it may come back up because udhcpc is still shutting down */
725 usleep(100000);
726 result += static_down(ifd, exec);
727 return ((result == 3) ? 3 : 0);
729 # else
730 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd UNUSED_PARAM,
731 execfn *exec UNUSED_PARAM)
733 return 0; /* no dhcp support */
735 # endif
737 static int FAST_FUNC manual_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
739 return 1;
742 static int FAST_FUNC bootp_up(struct interface_defn_t *ifd, execfn *exec)
744 return execute("bootpc[[ --bootfile %bootfile%]] --dev %iface%"
745 "[[ --server %server%]][[ --hwaddr %hwaddr%]]"
746 " --returniffail --serverbcast", ifd, exec);
749 static int FAST_FUNC ppp_up(struct interface_defn_t *ifd, execfn *exec)
751 return execute("pon[[ %provider%]]", ifd, exec);
754 static int FAST_FUNC ppp_down(struct interface_defn_t *ifd, execfn *exec)
756 return execute("poff[[ %provider%]]", ifd, exec);
759 static int FAST_FUNC wvdial_up(struct interface_defn_t *ifd, execfn *exec)
761 return execute("start-stop-daemon --start -x wvdial "
762 "-p /var/run/wvdial.%iface% -b -m --[[ %provider%]]", ifd, exec);
765 static int FAST_FUNC wvdial_down(struct interface_defn_t *ifd, execfn *exec)
767 return execute("start-stop-daemon --stop -x wvdial "
768 "-p /var/run/wvdial.%iface% -s 2", ifd, exec);
771 static const struct method_t methods[] ALIGN_PTR = {
772 { "manual" , manual_up_down, manual_up_down, },
773 { "wvdial" , wvdial_up , wvdial_down , },
774 { "ppp" , ppp_up , ppp_down , },
775 { "static" , static_up , static_down , },
776 { "bootp" , bootp_up , static_down , },
777 { "dhcp" , dhcp_up , dhcp_down , },
778 { "loopback", loopback_up , loopback_down , },
781 static const struct address_family_t addr_inet = {
782 "inet",
783 ARRAY_SIZE(methods),
784 methods
787 #endif /* FEATURE_IFUPDOWN_IPV4 */
789 static int FAST_FUNC link_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
791 return 1;
794 static const struct method_t link_methods[] ALIGN_PTR = {
795 { "none", link_up_down, link_up_down }
798 static const struct address_family_t addr_link = {
799 "link", ARRAY_SIZE(link_methods), link_methods
802 /* Returns pointer to the next word, or NULL.
803 * In 1st case, advances *buf to the word after this one.
805 static char *next_word(char **buf)
807 unsigned length;
808 char *word;
810 /* Skip over leading whitespace */
811 word = skip_whitespace(*buf);
813 /* Stop on EOL */
814 if (*word == '\0')
815 return NULL;
817 /* Find the length of this word (can't be 0) */
818 length = strcspn(word, " \t\n");
820 /* Unless we are already at NUL, store NUL and advance */
821 if (word[length] != '\0')
822 word[length++] = '\0';
824 *buf = skip_whitespace(word + length);
826 return word;
829 static const struct address_family_t *get_address_family(const struct address_family_t *const af[], char *name)
831 int i;
833 if (!name)
834 return NULL;
836 for (i = 0; af[i]; i++) {
837 if (strcmp(af[i]->name, name) == 0) {
838 return af[i];
841 return NULL;
844 static const struct method_t *get_method(const struct address_family_t *af, char *name)
846 int i;
848 if (!name)
849 return NULL;
850 /* TODO: use index_in_str_array() */
851 for (i = 0; i < af->n_methods; i++) {
852 if (strcmp(af->method[i].name, name) == 0) {
853 return &af->method[i];
856 return NULL;
859 static struct interfaces_file_t *read_interfaces(const char *filename, struct interfaces_file_t *defn)
861 /* Let's try to be compatible.
863 * "man 5 interfaces" says:
864 * Lines starting with "#" are ignored. Note that end-of-line
865 * comments are NOT supported, comments must be on a line of their own.
866 * A line may be extended across multiple lines by making
867 * the last character a backslash.
869 * Seen elsewhere in example config file:
870 * A first non-blank "#" character makes the rest of the line
871 * be ignored. Blank lines are ignored. Lines may be indented freely.
872 * A "\" character at the very end of the line indicates the next line
873 * should be treated as a continuation of the current one.
875 * Lines beginning with "source" are used to include stanzas from
876 * other files, so configuration can be split into many files.
877 * The word "source" is followed by the path of file to be sourced.
879 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
880 struct mapping_defn_t *currmap = NULL;
881 #endif
882 struct interface_defn_t *currif = NULL;
883 FILE *f;
884 char *buf;
885 char *first_word;
886 char *rest_of_line;
887 enum { NONE, IFACE, MAPPING } currently_processing = NONE;
889 if (!defn)
890 defn = xzalloc(sizeof(*defn));
892 debug_noise("reading %s file:\n", filename);
893 f = xfopen_for_read(filename);
895 while ((buf = xmalloc_fgetline(f)) != NULL) {
896 #if ENABLE_DESKTOP
897 /* Trailing "\" concatenates lines */
898 char *p;
899 while ((p = last_char_is(buf, '\\')) != NULL) {
900 *p = '\0';
901 rest_of_line = xmalloc_fgetline(f);
902 if (!rest_of_line)
903 break;
904 p = xasprintf("%s%s", buf, rest_of_line);
905 free(buf);
906 free(rest_of_line);
907 buf = p;
909 #endif
910 rest_of_line = buf;
911 first_word = next_word(&rest_of_line);
912 if (!first_word || *first_word == '#') {
913 free(buf);
914 continue; /* blank/comment line */
917 if (strcmp(first_word, "mapping") == 0) {
918 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
919 currmap = xzalloc(sizeof(*currmap));
921 while ((first_word = next_word(&rest_of_line)) != NULL) {
922 currmap->match = xrealloc_vector(currmap->match, 4, currmap->n_matches);
923 currmap->match[currmap->n_matches++] = xstrdup(first_word);
925 /*currmap->n_mappings = 0;*/
926 /*currmap->mapping = NULL;*/
927 /*currmap->script = NULL;*/
929 struct mapping_defn_t **where = &defn->mappings;
930 while (*where != NULL) {
931 where = &(*where)->next;
933 *where = currmap;
934 /*currmap->next = NULL;*/
936 debug_noise("Added mapping\n");
937 #endif
938 currently_processing = MAPPING;
939 } else if (strcmp(first_word, "iface") == 0) {
940 static const struct address_family_t *const addr_fams[] = {
941 #if ENABLE_FEATURE_IFUPDOWN_IPV4
942 &addr_inet,
943 #endif
944 #if ENABLE_FEATURE_IFUPDOWN_IPV6
945 &addr_inet6,
946 #endif
947 &addr_link,
948 NULL
950 char *iface_name;
951 char *address_family_name;
952 char *method_name;
954 currif = xzalloc(sizeof(*currif));
955 iface_name = next_word(&rest_of_line);
956 address_family_name = next_word(&rest_of_line);
957 method_name = next_word(&rest_of_line);
959 if (method_name == NULL)
960 bb_error_msg_and_die("too few parameters for line \"%s\"", buf);
962 /* ship any trailing whitespace */
963 rest_of_line = skip_whitespace(rest_of_line);
965 if (rest_of_line[0] != '\0' /* && rest_of_line[0] != '#' */)
966 bb_error_msg_and_die("too many parameters \"%s\"", buf);
968 currif->iface = xstrdup(iface_name);
970 currif->address_family = get_address_family(addr_fams, address_family_name);
971 if (!currif->address_family)
972 bb_error_msg_and_die("unknown address type \"%s\"", address_family_name);
974 currif->method = get_method(currif->address_family, method_name);
975 if (!currif->method)
976 bb_error_msg_and_die("unknown method \"%s\"", method_name);
977 #if 0
978 // Allegedly, Debian allows a duplicate definition:
979 // iface eth0 inet static
980 // address 192.168.0.15
981 // netmask 255.255.0.0
982 // gateway 192.168.0.1
984 // iface eth0 inet static
985 // address 10.0.0.1
986 // netmask 255.255.255.0
988 // This adds *two* addresses to eth0 (probably requires use of "ip", not "ifconfig"
990 llist_t *iface_list;
991 for (iface_list = defn->ifaces; iface_list; iface_list = iface_list->link) {
992 struct interface_defn_t *tmp = (struct interface_defn_t *) iface_list->data;
993 if ((strcmp(tmp->iface, currif->iface) == 0)
994 && (tmp->address_family == currif->address_family)
996 bb_error_msg_and_die("duplicate interface \"%s\"", tmp->iface);
999 #endif
1000 llist_add_to_end(&(defn->ifaces), (char*)currif);
1002 debug_noise("iface %s %s %s\n", currif->iface, address_family_name, method_name);
1003 currently_processing = IFACE;
1004 } else if (strcmp(first_word, "auto") == 0) {
1005 while ((first_word = next_word(&rest_of_line)) != NULL) {
1007 /* Check the interface isnt already listed */
1008 if (llist_find_str(defn->autointerfaces, first_word)) {
1009 bb_perror_msg_and_die("interface declared auto twice \"%s\"", buf);
1012 /* Add the interface to the list */
1013 llist_add_to_end(&(defn->autointerfaces), xstrdup(first_word));
1014 debug_noise("\nauto %s\n", first_word);
1016 currently_processing = NONE;
1017 } else if (strcmp(first_word, "source") == 0) {
1018 read_interfaces(next_word(&rest_of_line), defn);
1019 } else if (is_prefixed_with(first_word, "source-dir")) {
1020 const char *dirpath;
1021 DIR *dir;
1022 struct dirent *entry;
1024 dirpath = next_word(&rest_of_line);
1025 dir = xopendir(dirpath);
1026 while ((entry = readdir(dir)) != NULL) {
1027 char *path;
1028 if (entry->d_name[0] == '.')
1029 continue;
1030 path = concat_path_file(dirpath, entry->d_name);
1031 read_interfaces(path, defn);
1032 free(path);
1034 closedir(dir);
1035 } else {
1036 switch (currently_processing) {
1037 case IFACE:
1038 if (rest_of_line[0] == '\0')
1039 bb_error_msg_and_die("option with empty value \"%s\"", buf);
1041 if (strcmp(first_word, "post-up") == 0)
1042 first_word += 5; /* "up" */
1043 else if (strcmp(first_word, "pre-down") == 0)
1044 first_word += 4; /* "down" */
1046 /* If not one of "up", "down",... words... */
1047 if (index_in_strings(keywords_up_down, first_word) < 0) {
1048 int i;
1049 for (i = 0; i < currif->n_options; i++) {
1050 if (strcmp(currif->option[i].name, first_word) == 0)
1051 bb_error_msg_and_die("duplicate option \"%s\"", buf);
1054 debug_noise("\t%s=%s\n", first_word, rest_of_line);
1055 currif->option = xrealloc_vector(currif->option, 4, currif->n_options);
1056 currif->option[currif->n_options].name = xstrdup(first_word);
1057 currif->option[currif->n_options].value = xstrdup(rest_of_line);
1058 currif->n_options++;
1059 break;
1060 case MAPPING:
1061 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1062 if (strcmp(first_word, "script") == 0) {
1063 if (currmap->script != NULL)
1064 bb_error_msg_and_die("duplicate script in mapping \"%s\"", buf);
1065 currmap->script = xstrdup(next_word(&rest_of_line));
1066 } else if (strcmp(first_word, "map") == 0) {
1067 currmap->mapping = xrealloc_vector(currmap->mapping, 2, currmap->n_mappings);
1068 currmap->mapping[currmap->n_mappings] = xstrdup(next_word(&rest_of_line));
1069 currmap->n_mappings++;
1070 } else {
1071 bb_error_msg_and_die("misplaced option \"%s\"", buf);
1073 #endif
1074 break;
1075 case NONE:
1076 default:
1077 bb_error_msg_and_die("misplaced option \"%s\"", buf);
1080 free(buf);
1081 } /* while (fgets) */
1083 if (ferror(f) != 0) {
1084 /* ferror does NOT set errno! */
1085 bb_error_msg_and_die("%s: I/O error", filename);
1087 fclose(f);
1088 debug_noise("\ndone reading %s\n\n", filename);
1090 return defn;
1093 static char *setlocalenv(const char *format, const char *name, const char *value)
1095 char *result;
1096 char *dst;
1097 char *src;
1098 char c;
1100 result = xasprintf(format, name, value);
1102 for (dst = src = result; (c = *src) != '=' && c; src++) {
1103 if (c == '-')
1104 c = '_';
1105 if (c >= 'a' && c <= 'z')
1106 c -= ('a' - 'A');
1107 if (isalnum(c) || c == '_')
1108 *dst++ = c;
1110 overlapping_strcpy(dst, src);
1112 return result;
1115 static void set_environ(struct interface_defn_t *iface, const char *mode, const char *opt)
1117 int i;
1118 char **pp;
1120 if (G.my_environ != NULL) {
1121 for (pp = G.my_environ; *pp; pp++) {
1122 free(*pp);
1124 free(G.my_environ);
1127 /* note: last element will stay NULL: */
1128 G.my_environ = xzalloc(sizeof(char *) * (iface->n_options + 7));
1129 pp = G.my_environ;
1131 for (i = 0; i < iface->n_options; i++) {
1132 if (index_in_strings(keywords_up_down, iface->option[i].name) >= 0) {
1133 continue;
1135 *pp++ = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
1138 *pp++ = setlocalenv("%s=%s", "IFACE", iface->iface);
1139 *pp++ = setlocalenv("%s=%s", "ADDRFAM", iface->address_family->name);
1140 *pp++ = setlocalenv("%s=%s", "METHOD", iface->method->name);
1141 *pp++ = setlocalenv("%s=%s", "MODE", mode);
1142 *pp++ = setlocalenv("%s=%s", "PHASE", opt);
1143 if (G.startup_PATH)
1144 *pp++ = setlocalenv("%s=%s", "PATH", G.startup_PATH);
1147 static int doit(char *str)
1149 if (option_mask32 & (OPT_no_act|OPT_verbose)) {
1150 puts(str);
1152 if (!(option_mask32 & OPT_no_act)) {
1153 pid_t child;
1154 int status;
1156 fflush_all();
1157 child = vfork();
1158 if (child < 0) /* failure */
1159 return 0;
1160 if (child == 0) { /* child */
1161 execle(G.shell, G.shell, "-c", str, (char *) NULL, G.my_environ);
1162 _exit(127);
1164 safe_waitpid(child, &status, 0);
1165 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1166 return 0;
1169 return 1;
1172 static int execute_all(struct interface_defn_t *ifd, const char *opt)
1174 /* 'opt' is always short, the longest value is "post-down".
1175 * Can use on-stack buffer instead of xasprintf'ed one.
1177 char buf[sizeof("run-parts /etc/network/if-%s.d")
1178 + sizeof("post-down")
1179 /*paranoia:*/ + 8
1181 int i;
1183 for (i = 0; i < ifd->n_options; i++) {
1184 if (strcmp(ifd->option[i].name, opt) == 0) {
1185 if (!doit(ifd->option[i].value)) {
1186 return 0;
1191 /* Tested on Debian Squeeze: "standard" ifup runs this without
1192 * checking that directory exists. If it doesn't, run-parts
1193 * complains, and this message _is_ annoyingly visible.
1194 * Don't "fix" this (unless newer Debian does).
1196 sprintf(buf, "run-parts /etc/network/if-%s.d", opt);
1197 return doit(buf);
1200 static int check(char *str)
1202 return str != NULL;
1205 static int iface_up(struct interface_defn_t *iface)
1207 if (!iface->method->up(iface, check)) return -1;
1208 set_environ(iface, "start", "pre-up");
1209 if (!execute_all(iface, "pre-up")) return 0;
1210 if (!iface->method->up(iface, doit)) return 0;
1211 set_environ(iface, "start", "post-up");
1212 if (!execute_all(iface, "up")) return 0;
1213 return 1;
1216 static int iface_down(struct interface_defn_t *iface)
1218 if (!iface->method->down(iface, check)) return -1;
1219 set_environ(iface, "stop", "pre-down");
1220 if (!execute_all(iface, "down")) return 0;
1221 if (!iface->method->down(iface, doit)) return 0;
1222 set_environ(iface, "stop", "post-down");
1223 if (!execute_all(iface, "post-down")) return 0;
1224 return 1;
1227 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1228 static int popen2(FILE **in, FILE **out, char *command, char *param)
1230 char *argv[3] = { command, param, NULL };
1231 struct fd_pair infd, outfd;
1232 pid_t pid;
1234 xpiped_pair(infd);
1235 xpiped_pair(outfd);
1237 fflush_all();
1238 pid = xvfork();
1240 if (pid == 0) {
1241 /* Child */
1242 /* NB: close _first_, then move fds! */
1243 close(infd.wr);
1244 close(outfd.rd);
1245 xmove_fd(infd.rd, 0);
1246 xmove_fd(outfd.wr, 1);
1247 BB_EXECVP_or_die(argv);
1249 /* parent */
1250 close(infd.rd);
1251 close(outfd.wr);
1252 *in = xfdopen_for_write(infd.wr);
1253 *out = xfdopen_for_read(outfd.rd);
1254 return pid;
1257 static char *run_mapping(char *physical, struct mapping_defn_t *map)
1259 FILE *in, *out;
1260 int i, status;
1261 pid_t pid;
1263 char *logical = xstrdup(physical);
1265 /* Run the mapping script. Never fails. */
1266 pid = popen2(&in, &out, map->script, physical);
1268 /* Write mappings to stdin of mapping script. */
1269 for (i = 0; i < map->n_mappings; i++) {
1270 fprintf(in, "%s\n", map->mapping[i]);
1272 fclose(in);
1273 safe_waitpid(pid, &status, 0);
1275 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1276 /* If the mapping script exited successfully, try to
1277 * grab a line of output and use that as the name of the
1278 * logical interface. */
1279 char *new_logical = xmalloc_fgetline(out);
1281 if (new_logical) {
1282 /* If we are able to read a line of output from the script,
1283 * remove any trailing whitespace and use this value
1284 * as the name of the logical interface. */
1285 char *pch = new_logical + strlen(new_logical) - 1;
1287 while (pch >= new_logical && isspace(*pch))
1288 *(pch--) = '\0';
1290 free(logical);
1291 logical = new_logical;
1295 fclose(out);
1297 return logical;
1299 #endif /* FEATURE_IFUPDOWN_MAPPING */
1301 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1303 llist_t *search = state_list;
1305 while (search) {
1306 char *after_iface = is_prefixed_with(search->data, iface);
1307 if (after_iface
1308 && *after_iface == '='
1310 return search;
1312 search = search->link;
1314 return NULL;
1317 /* read the previous state from the state file */
1318 static llist_t *read_iface_state(void)
1320 llist_t *state_list = NULL;
1321 FILE *state_fp = fopen_for_read(IFSTATE_FILE_PATH);
1323 if (state_fp) {
1324 char *start, *end_ptr;
1325 while ((start = xmalloc_fgets(state_fp)) != NULL) {
1326 /* We should only need to check for a single character */
1327 end_ptr = start + strcspn(start, " \t\n");
1328 *end_ptr = '\0';
1329 llist_add_to(&state_list, start);
1331 fclose(state_fp);
1333 return state_list;
1336 /* read the previous state from the state file */
1337 static FILE *open_new_state_file(void)
1339 int fd, flags, cnt;
1341 cnt = 0;
1342 flags = (O_WRONLY | O_CREAT | O_EXCL);
1343 for (;;) {
1344 fd = open(IFSTATE_FILE_PATH".new", flags, 0666);
1345 if (fd >= 0)
1346 break;
1347 if (errno != EEXIST
1348 || flags == (O_WRONLY | O_CREAT | O_TRUNC)
1350 bb_perror_msg_and_die("can't open '%s'",
1351 IFSTATE_FILE_PATH".new");
1353 /* Someone else created the .new file */
1354 if (cnt > 30) {
1355 /* Waited for 30*30/2 = 450 milliseconds, still EEXIST.
1356 * Assuming a stale file, rewriting it.
1358 flags = (O_WRONLY | O_CREAT | O_TRUNC);
1359 continue;
1361 msleep(cnt);
1362 cnt++;
1365 return xfdopen_for_write(fd);
1368 int ifupdown_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1369 int ifupdown_main(int argc UNUSED_PARAM, char **argv)
1371 int (*cmds)(struct interface_defn_t *);
1372 struct interfaces_file_t *defn;
1373 llist_t *target_list = NULL;
1374 const char *interfaces = "/etc/network/interfaces";
1375 bool any_failures = 0;
1377 INIT_G();
1379 G.startup_PATH = getenv("PATH");
1380 G.shell = xstrdup(get_shell_name());
1382 if (ENABLE_IFUP
1383 && (!ENABLE_IFDOWN || applet_name[2] == 'u')
1385 /* ifup command */
1386 cmds = iface_up;
1387 } else {
1388 cmds = iface_down;
1391 getopt32(argv, OPTION_STR, &interfaces);
1392 argv += optind;
1393 if (argv[0]) {
1394 if (DO_ALL) bb_show_usage();
1395 } else {
1396 if (!DO_ALL) bb_show_usage();
1399 defn = read_interfaces(interfaces, NULL);
1401 /* Create a list of interfaces to work on */
1402 if (DO_ALL) {
1403 target_list = defn->autointerfaces;
1404 } else {
1405 llist_add_to_end(&target_list, argv[0]);
1408 /* Update the interfaces */
1409 while (target_list) {
1410 llist_t *iface_list;
1411 struct interface_defn_t *currif;
1412 char *iface;
1413 char *liface;
1414 char *pch;
1415 bool okay = 0;
1416 int cmds_ret;
1417 bool curr_failure = 0;
1419 iface = xstrdup(target_list->data);
1420 target_list = target_list->link;
1422 pch = strchr(iface, '=');
1423 if (pch) {
1424 *pch = '\0';
1425 liface = xstrdup(pch + 1);
1426 } else {
1427 liface = xstrdup(iface);
1430 if (!FORCE) {
1431 llist_t *state_list = read_iface_state();
1432 const llist_t *iface_state = find_iface_state(state_list, iface);
1434 if (cmds == iface_up) {
1435 /* ifup */
1436 if (iface_state) {
1437 bb_error_msg("interface %s already configured", iface);
1438 goto next;
1440 } else {
1441 /* ifdown */
1442 if (!iface_state) {
1443 bb_error_msg("interface %s not configured", iface);
1444 goto next;
1447 llist_free(state_list, free);
1450 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1451 if ((cmds == iface_up) && !NO_MAPPINGS) {
1452 struct mapping_defn_t *currmap;
1454 for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1455 int i;
1456 for (i = 0; i < currmap->n_matches; i++) {
1457 if (fnmatch(currmap->match[i], liface, 0) != 0)
1458 continue;
1459 if (VERBOSE) {
1460 printf("Running mapping script %s on %s\n", currmap->script, liface);
1462 liface = run_mapping(iface, currmap);
1463 break;
1467 #endif
1469 iface_list = defn->ifaces;
1470 while (iface_list) {
1471 currif = (struct interface_defn_t *) iface_list->data;
1472 if (strcmp(liface, currif->iface) == 0) {
1473 char *oldiface = currif->iface;
1475 okay = 1;
1476 currif->iface = iface;
1478 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1480 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1481 cmds_ret = cmds(currif);
1482 if (cmds_ret == -1) {
1483 bb_error_msg("don't have all variables for %s/%s",
1484 liface, currif->address_family->name);
1485 any_failures = curr_failure = 1;
1486 } else if (cmds_ret == 0) {
1487 any_failures = curr_failure = 1;
1490 currif->iface = oldiface;
1492 iface_list = iface_list->link;
1494 if (VERBOSE) {
1495 bb_putchar('\n');
1498 if (!okay && !FORCE) {
1499 bb_error_msg("ignoring unknown interface %s", liface);
1500 any_failures = 1;
1501 } else if (!NO_ACT) {
1502 /* update the state file */
1503 FILE *new_state_fp = open_new_state_file();
1504 llist_t *state;
1505 llist_t *state_list = read_iface_state();
1506 llist_t *iface_state = find_iface_state(state_list, iface);
1508 if (cmds == iface_up && !curr_failure) {
1509 char *newiface = xasprintf("%s=%s", iface, liface);
1510 if (!iface_state) {
1511 llist_add_to_end(&state_list, newiface);
1512 } else {
1513 free(iface_state->data);
1514 iface_state->data = newiface;
1516 } else {
1517 /* Remove an interface from state_list */
1518 llist_unlink(&state_list, iface_state);
1519 free(llist_pop(&iface_state));
1522 /* Actually write the new state */
1523 state = state_list;
1524 while (state) {
1525 if (state->data) {
1526 fprintf(new_state_fp, "%s\n", state->data);
1528 state = state->link;
1530 fclose(new_state_fp);
1531 xrename(IFSTATE_FILE_PATH".new", IFSTATE_FILE_PATH);
1532 llist_free(state_list, free);
1534 next:
1535 free(iface);
1536 free(liface);
1539 return any_failures;