1 /* vi: set sw=4 ts=4: */
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
17 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
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.
36 //config:config IFDOWN
37 //config: bool "ifdown"
40 //config: Deactivate the specified interfaces.
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
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.
53 //config:config FEATURE_IFUPDOWN_IP
54 //config: bool "Use ip applet"
56 //config: depends on IFUP || IFDOWN
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.
61 //config:config FEATURE_IFUPDOWN_IP_BUILTIN
62 //config: bool "Use busybox ip applet"
64 //config: depends on FEATURE_IFUPDOWN_IP
65 //config: select PLATFORM_LINUX
67 //config: select FEATURE_IP_ADDRESS
68 //config: select FEATURE_IP_LINK
69 //config: select FEATURE_IP_ROUTE
71 //config: Use the busybox iproute "ip" applet to implement "ifupdown".
73 //config: If left disabled, you must install the full-blown iproute2
74 //config: utility or the "ifup" and "ifdown" applets will not work.
76 //config:config FEATURE_IFUPDOWN_IFCONFIG_BUILTIN
77 //config: bool "Use busybox ifconfig and route applets"
79 //config: depends on (IFUP || IFDOWN) && !FEATURE_IFUPDOWN_IP
80 //config: select IFCONFIG
81 //config: select ROUTE
83 //config: Use the busybox iproute "ifconfig" and "route" applets to
84 //config: implement the "ifup" and "ifdown" utilities.
86 //config: If left disabled, you must install the full-blown ifconfig
87 //config: and route utilities, or the "ifup" and "ifdown" applets will not
90 //config:config FEATURE_IFUPDOWN_IPV4
91 //config: bool "Support for IPv4"
93 //config: depends on IFUP || IFDOWN
95 //config: If you want ifup/ifdown to talk IPv4, leave this on.
97 //config:config FEATURE_IFUPDOWN_IPV6
98 //config: bool "Support for IPv6"
100 //config: depends on (IFUP || IFDOWN) && FEATURE_IPV6
102 //config: If you need support for IPv6, turn this option on.
105 ////////:config FEATURE_IFUPDOWN_IPX
106 ////////: bool "Support for IPX"
108 ////////: depends on IFUP || IFDOWN
110 ////////: If this option is selected you can use busybox to work with IPX
113 //config:config FEATURE_IFUPDOWN_MAPPING
114 //config: bool "Enable mapping support"
116 //config: depends on IFUP || IFDOWN
118 //config: This enables support for the "mapping" stanza, unless you have
119 //config: a weird network setup you don't need it.
121 //config:config FEATURE_IFUPDOWN_EXTERNAL_DHCP
122 //config: bool "Support for external dhcp clients"
124 //config: depends on IFUP || IFDOWN
126 //config: This enables support for the external dhcp clients. Clients are
127 //config: tried in the following order: dhcpcd, dhclient, pump and udhcpc.
128 //config: Otherwise, if udhcpc applet is enabled, it is used.
129 //config: Otherwise, ifup/ifdown will have no support for DHCP.
131 //applet:IF_IFUP(APPLET_ODDNAME(ifup, ifupdown, BB_DIR_SBIN, BB_SUID_DROP, ifup))
132 //applet:IF_IFDOWN(APPLET_ODDNAME(ifdown, ifupdown, BB_DIR_SBIN, BB_SUID_DROP, ifdown))
134 //kbuild:lib-$(CONFIG_IFUP) += ifupdown.o
135 //kbuild:lib-$(CONFIG_IFDOWN) += ifupdown.o
137 //usage:#define ifup_trivial_usage
138 //usage: "[-an"IF_FEATURE_IFUPDOWN_MAPPING("m")"vf] [-i FILE] IFACE..."
139 //usage:#define ifup_full_usage "\n\n"
140 //usage: " -a Configure all interfaces"
141 //usage: "\n -i FILE Use FILE instead of /etc/network/interfaces"
142 //usage: "\n -n Print out what would happen, but don't do it"
143 //usage: IF_FEATURE_IFUPDOWN_MAPPING(
144 //usage: "\n (note: doesn't disable mappings)"
145 //usage: "\n -m Don't run any mappings"
147 //usage: "\n -v Print out what would happen before doing it"
148 //usage: "\n -f Force configuration"
150 //usage:#define ifdown_trivial_usage
151 //usage: "[-an"IF_FEATURE_IFUPDOWN_MAPPING("m")"vf] [-i FILE] IFACE..."
152 //usage:#define ifdown_full_usage "\n\n"
153 //usage: " -a Deconfigure all interfaces"
154 //usage: "\n -i FILE Use FILE for interface definitions"
155 //usage: "\n -n Print out what would happen, but don't do it"
156 //usage: IF_FEATURE_IFUPDOWN_MAPPING(
157 //usage: "\n (note: doesn't disable mappings)"
158 //usage: "\n -m Don't run any mappings"
160 //usage: "\n -v Print out what would happen before doing it"
161 //usage: "\n -f Force deconfiguration"
164 #include "common_bufsiz.h"
165 /* After libbb.h, since it needs sys/types.h on some systems */
166 #include <sys/utsname.h>
169 #define MAX_OPT_DEPTH 10
171 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
172 #define MAX_INTERFACE_LENGTH 10
175 #define UDHCPC_CMD_OPTIONS CONFIG_IFUPDOWN_UDHCPC_CMD_OPTIONS
176 #define IFSTATE_FILE_PATH CONFIG_IFUPDOWN_IFSTATE_PATH
178 #define debug_noise(args...) /*fprintf(stderr, args)*/
180 /* Forward declaration */
181 struct interface_defn_t;
183 typedef int execfn(char *command);
187 int (*up)(struct interface_defn_t *ifd, execfn *e) FAST_FUNC;
188 int (*down)(struct interface_defn_t *ifd, execfn *e) FAST_FUNC;
191 struct address_family_t {
194 const struct method_t *method;
197 struct mapping_defn_t {
198 struct mapping_defn_t *next;
215 struct interface_defn_t {
216 const struct address_family_t *address_family;
217 const struct method_t *method;
221 struct variable_t *option;
224 struct interfaces_file_t {
225 llist_t *autointerfaces;
227 struct mapping_defn_t *mappings;
231 #define OPTION_STR "anvf" IF_FEATURE_IFUPDOWN_MAPPING("m") "i:"
237 OPT_no_mappings = 0x10,
239 #define DO_ALL (option_mask32 & OPT_do_all)
240 #define NO_ACT (option_mask32 & OPT_no_act)
241 #define VERBOSE (option_mask32 & OPT_verbose)
242 #define FORCE (option_mask32 & OPT_force)
243 #define NO_MAPPINGS (option_mask32 & OPT_no_mappings)
248 const char *startup_PATH;
251 #define G (*(struct globals*)bb_common_bufsiz1)
252 #define INIT_G() do { setup_common_bufsiz(); } while (0)
255 static const char keywords_up_down[] ALIGN1 =
263 #if ENABLE_FEATURE_IFUPDOWN_IPV4 || ENABLE_FEATURE_IFUPDOWN_IPV6
265 static void addstr(char **bufp, const char *str, size_t str_length)
267 /* xasprintf trick will be smaller, but we are often
268 * called with str_length == 1 - don't want to have
269 * THAT much of malloc/freeing! */
271 int len = (buf ? strlen(buf) : 0);
273 buf = xrealloc(buf, len + str_length);
274 /* copies at most str_length-1 chars! */
275 safe_strncpy(buf + len, str, str_length);
279 static int strncmpz(const char *l, const char *r, size_t llen)
281 int i = strncmp(l, r, llen);
284 return - (unsigned char)r[llen];
288 static char *get_var(const char *id, size_t idlen, struct interface_defn_t *ifd)
292 if (strncmpz(id, "iface", idlen) == 0) {
293 // ubuntu's ifup doesn't do this:
294 //static char *label_buf;
297 //label_buf = xstrdup(ifd->iface);
298 // Remove virtual iface suffix
299 //result = strchrnul(label_buf, ':');
305 if (strncmpz(id, "label", idlen) == 0) {
308 for (i = 0; i < ifd->n_options; i++) {
309 if (strncmpz(id, ifd->option[i].name, idlen) == 0) {
310 return ifd->option[i].value;
316 # if ENABLE_FEATURE_IFUPDOWN_IP
317 static int count_netmask_bits(const char *dotted_quad)
320 // unsigned a, b, c, d;
321 // /* Found a netmask... Check if it is dotted quad */
322 // if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
324 // if ((a|b|c|d) >> 8)
325 // return -1; /* one of numbers is >= 256 */
326 // d |= (a << 24) | (b << 16) | (c << 8); /* IP */
327 // d = ~d; /* 11110000 -> 00001111 */
329 /* Shorter version */
334 if (inet_aton(dotted_quad, &ip) == 0)
335 return -1; /* malformed dotted IP */
336 d = ntohl(ip.s_addr); /* IP in host order */
337 d = ~d; /* 11110000 -> 00001111 */
338 if (d & (d+1)) /* check that it is in 00001111 form */
339 return -1; /* no it is not */
349 static char *parse(const char *command, struct interface_defn_t *ifd)
351 size_t old_pos[MAX_OPT_DEPTH] = { 0 };
352 smallint okay[MAX_OPT_DEPTH] = { 1 };
359 addstr(&result, command, 1);
365 addstr(&result, command, 1);
369 if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
370 old_pos[opt_depth] = result ? strlen(result) : 0;
375 addstr(&result, command, 1);
380 if (command[1] == ']' && opt_depth > 1) {
382 if (!okay[opt_depth]) {
383 result[old_pos[opt_depth]] = '\0';
387 addstr(&result, command, 1);
397 nextpercent = strchr(command, '%');
399 /* Unterminated %var% */
404 varvalue = get_var(command, nextpercent - command, ifd);
407 # if ENABLE_FEATURE_IFUPDOWN_IP
408 /* "hwaddress <class> <address>":
409 * unlike ifconfig, ip doesnt want <class>
410 * (usually "ether" keyword). Skip it. */
411 if (is_prefixed_with(command, "hwaddress")) {
412 varvalue = skip_whitespace(skip_non_whitespace(varvalue));
415 addstr(&result, varvalue, strlen(varvalue));
417 # if ENABLE_FEATURE_IFUPDOWN_IP
418 /* Sigh... Add a special case for 'ip' to convert from
419 * dotted quad to bit count style netmasks. */
420 if (is_prefixed_with(command, "bnmask")) {
422 varvalue = get_var("netmask", 7, ifd);
424 res = count_netmask_bits(varvalue);
426 const char *argument = utoa(res);
427 addstr(&result, argument, strlen(argument));
428 command = nextpercent + 1;
434 okay[opt_depth - 1] = 0;
437 command = nextpercent + 1;
444 /* Unbalanced bracket */
450 /* Undefined variable and we aren't in a bracket */
458 /* execute() returns 1 for success and 0 for failure */
459 static int execute(const char *command, struct interface_defn_t *ifd, execfn *exec)
464 out = parse(command, ifd);
469 /* out == "": parsed ok but not all needed variables known, skip */
470 ret = out[0] ? (*exec)(out) : 1;
479 #endif /* FEATURE_IFUPDOWN_IPV4 || FEATURE_IFUPDOWN_IPV6 */
482 #if ENABLE_FEATURE_IFUPDOWN_IPV6
484 static int FAST_FUNC loopback_up6(struct interface_defn_t *ifd, execfn *exec)
486 # if ENABLE_FEATURE_IFUPDOWN_IP
488 result = execute("ip addr add ::1 dev %iface%", ifd, exec);
489 result += execute("ip link set %iface% up", ifd, exec);
490 return ((result == 2) ? 2 : 0);
492 return execute("ifconfig %iface% add ::1", ifd, exec);
496 static int FAST_FUNC loopback_down6(struct interface_defn_t *ifd, execfn *exec)
498 # if ENABLE_FEATURE_IFUPDOWN_IP
499 return execute("ip link set %iface% down", ifd, exec);
501 return execute("ifconfig %iface% del ::1", ifd, exec);
505 static int FAST_FUNC manual_up_down6(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
510 static int FAST_FUNC static_up6(struct interface_defn_t *ifd, execfn *exec)
513 # if ENABLE_FEATURE_IFUPDOWN_IP
514 result = execute("ip addr add %address%/%netmask% dev %iface%[[ label %label%]]", ifd, exec);
515 result += execute("ip link set[[ mtu %mtu%]][[ addr %hwaddress%]] %iface% up", ifd, exec);
516 /* Reportedly, IPv6 needs "dev %iface%", but IPv4 does not: */
517 result += execute("[[ip route add ::/0 via %gateway% dev %iface%]][[ metric %metric%]]", ifd, exec);
519 result = execute("ifconfig %iface%[[ media %media%]][[ hw %hwaddress%]][[ mtu %mtu%]] up", ifd, exec);
520 result += execute("ifconfig %iface% add %address%/%netmask%", ifd, exec);
521 result += execute("[[route -A inet6 add ::/0 gw %gateway%[[ metric %metric%]]]]", ifd, exec);
523 return ((result == 3) ? 3 : 0);
526 static int FAST_FUNC static_down6(struct interface_defn_t *ifd, execfn *exec)
528 # if ENABLE_FEATURE_IFUPDOWN_IP
529 return execute("ip link set %iface% down", ifd, exec);
531 return execute("ifconfig %iface% down", ifd, exec);
535 # if ENABLE_FEATURE_IFUPDOWN_IP
536 static int FAST_FUNC v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
539 result = execute("ip tunnel add %iface% mode sit remote "
540 "%endpoint%[[ local %local%]][[ ttl %ttl%]]", ifd, exec);
541 result += execute("ip link set %iface% up", ifd, exec);
542 result += execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec);
543 /* Reportedly, IPv6 needs "dev %iface%", but IPv4 does not: */
544 result += execute("[[ip route add ::/0 via %gateway% dev %iface%]]", ifd, exec);
545 return ((result == 4) ? 4 : 0);
548 static int FAST_FUNC v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
550 return execute("ip tunnel del %iface%", ifd, exec);
554 static const struct method_t methods6[] = {
555 # if ENABLE_FEATURE_IFUPDOWN_IP
556 { "v4tunnel" , v4tunnel_up , v4tunnel_down , },
558 { "static" , static_up6 , static_down6 , },
559 { "manual" , manual_up_down6 , manual_up_down6 , },
560 { "loopback" , loopback_up6 , loopback_down6 , },
563 static const struct address_family_t addr_inet6 = {
565 ARRAY_SIZE(methods6),
569 #endif /* FEATURE_IFUPDOWN_IPV6 */
572 #if ENABLE_FEATURE_IFUPDOWN_IPV4
574 static int FAST_FUNC loopback_up(struct interface_defn_t *ifd, execfn *exec)
576 # if ENABLE_FEATURE_IFUPDOWN_IP
578 result = execute("ip addr add 127.0.0.1/8 dev %iface%", ifd, exec);
579 result += execute("ip link set %iface% up", ifd, exec);
580 return ((result == 2) ? 2 : 0);
582 return execute("ifconfig %iface% 127.0.0.1 up", ifd, exec);
586 static int FAST_FUNC loopback_down(struct interface_defn_t *ifd, execfn *exec)
588 # if ENABLE_FEATURE_IFUPDOWN_IP
590 result = execute("ip addr flush dev %iface%", ifd, exec);
591 result += execute("ip link set %iface% down", ifd, exec);
592 return ((result == 2) ? 2 : 0);
594 return execute("ifconfig %iface% 127.0.0.1 down", ifd, exec);
598 static int FAST_FUNC static_up(struct interface_defn_t *ifd, execfn *exec)
601 # if ENABLE_FEATURE_IFUPDOWN_IP
602 result = execute("ip addr add %address%/%bnmask%[[ broadcast %broadcast%]] "
603 "dev %iface%[[ peer %pointopoint%]][[ label %label%]]", ifd, exec);
604 result += execute("ip link set[[ mtu %mtu%]][[ addr %hwaddress%]] %iface% up", ifd, exec);
605 result += execute("[[ip route add default via %gateway% dev %iface%[[ metric %metric%]]]]", ifd, exec);
606 return ((result == 3) ? 3 : 0);
608 /* ifconfig said to set iface up before it processes hw %hwaddress%,
609 * which then of course fails. Thus we run two separate ifconfig */
610 result = execute("ifconfig %iface%[[ hw %hwaddress%]][[ media %media%]][[ mtu %mtu%]] up",
612 result += execute("ifconfig %iface% %address% netmask %netmask%"
613 "[[ broadcast %broadcast%]][[ pointopoint %pointopoint%]]",
615 result += execute("[[route add default gw %gateway%[[ metric %metric%]] %iface%]]", ifd, exec);
616 return ((result == 3) ? 3 : 0);
620 static int FAST_FUNC static_down(struct interface_defn_t *ifd, execfn *exec)
623 # if ENABLE_FEATURE_IFUPDOWN_IP
624 /* Optional "label LBL" is necessary if interface is an alias (eth0:0),
625 * otherwise "ip addr flush dev eth0:0" flushes all addresses on eth0.
627 result = execute("ip addr flush dev %iface%[[ label %label%]]", ifd, exec);
628 result += execute("ip link set %iface% down", ifd, exec);
630 /* result = execute("[[route del default gw %gateway% %iface%]]", ifd, exec); */
631 /* Bringing the interface down deletes the routes in itself.
632 Otherwise this fails if we reference 'gateway' when using this from dhcp_down */
634 result += execute("ifconfig %iface% down", ifd, exec);
636 return ((result == 2) ? 2 : 0);
639 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
640 struct dhcp_client_t {
642 const char *startcmd;
646 static const struct dhcp_client_t ext_dhcp_clients[] = {
648 "dhcpcd[[ -h %hostname%]][[ -i %vendor%]][[ -I %client%]][[ -l %leasetime%]] %iface%",
652 "dhclient -pf /var/run/dhclient.%iface%.pid %iface%",
653 "kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null",
656 "pump -i %iface%[[ -h %hostname%]][[ -l %leasehours%]]",
657 "pump -i %iface% -k",
660 "udhcpc " UDHCPC_CMD_OPTIONS " -p /var/run/udhcpc.%iface%.pid -i %iface%[[ -x hostname:%hostname%]][[ -c %client%]]"
661 "[[ -s %script%]][[ %udhcpc_opts%]]",
662 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
665 # endif /* FEATURE_IFUPDOWN_EXTERNAL_DHCPC */
667 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
668 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
671 # if ENABLE_FEATURE_IFUPDOWN_IP
672 /* ip doesn't up iface when it configures it (unlike ifconfig) */
673 if (!execute("ip link set[[ addr %hwaddress%]] %iface% up", ifd, exec))
676 /* needed if we have hwaddress on dhcp iface */
677 if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
680 for (i = 0; i < ARRAY_SIZE(ext_dhcp_clients); i++) {
681 if (executable_exists(ext_dhcp_clients[i].name))
682 return execute(ext_dhcp_clients[i].startcmd, ifd, exec);
684 bb_error_msg("no dhcp clients found");
688 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
690 # if ENABLE_FEATURE_IFUPDOWN_IP
691 /* ip doesn't up iface when it configures it (unlike ifconfig) */
692 if (!execute("ip link set[[ addr %hwaddress%]] %iface% up", ifd, exec))
695 /* needed if we have hwaddress on dhcp iface */
696 if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
699 return execute("udhcpc " UDHCPC_CMD_OPTIONS " -p /var/run/udhcpc.%iface%.pid "
700 "-i %iface%[[ -x hostname:%hostname%]][[ -c %client%]][[ -s %script%]][[ %udhcpc_opts%]]",
704 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd UNUSED_PARAM,
705 execfn *exec UNUSED_PARAM)
707 return 0; /* no dhcp support */
711 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
712 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
717 for (i = 0; i < ARRAY_SIZE(ext_dhcp_clients); i++) {
718 if (executable_exists(ext_dhcp_clients[i].name)) {
719 result = execute(ext_dhcp_clients[i].stopcmd, ifd, exec);
726 bb_error_msg("warning: no dhcp clients found and stopped");
728 /* Sleep a bit, otherwise static_down tries to bring down interface too soon,
729 and it may come back up because udhcpc is still shutting down */
731 result += static_down(ifd, exec);
732 return ((result == 3) ? 3 : 0);
735 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
739 "test -f /var/run/udhcpc.%iface%.pid && "
740 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
742 /* Also bring the hardware interface down since
743 killing the dhcp client alone doesn't do it.
744 This enables consecutive ifup->ifdown->ifup */
745 /* Sleep a bit, otherwise static_down tries to bring down interface too soon,
746 and it may come back up because udhcpc is still shutting down */
748 result += static_down(ifd, exec);
749 return ((result == 3) ? 3 : 0);
752 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd UNUSED_PARAM,
753 execfn *exec UNUSED_PARAM)
755 return 0; /* no dhcp support */
759 static int FAST_FUNC manual_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
764 static int FAST_FUNC bootp_up(struct interface_defn_t *ifd, execfn *exec)
766 return execute("bootpc[[ --bootfile %bootfile%]] --dev %iface%"
767 "[[ --server %server%]][[ --hwaddr %hwaddr%]]"
768 " --returniffail --serverbcast", ifd, exec);
771 static int FAST_FUNC ppp_up(struct interface_defn_t *ifd, execfn *exec)
773 return execute("pon[[ %provider%]]", ifd, exec);
776 static int FAST_FUNC ppp_down(struct interface_defn_t *ifd, execfn *exec)
778 return execute("poff[[ %provider%]]", ifd, exec);
781 static int FAST_FUNC wvdial_up(struct interface_defn_t *ifd, execfn *exec)
783 return execute("start-stop-daemon --start -x wvdial "
784 "-p /var/run/wvdial.%iface% -b -m --[[ %provider%]]", ifd, exec);
787 static int FAST_FUNC wvdial_down(struct interface_defn_t *ifd, execfn *exec)
789 return execute("start-stop-daemon --stop -x wvdial "
790 "-p /var/run/wvdial.%iface% -s 2", ifd, exec);
793 static const struct method_t methods[] = {
794 { "manual" , manual_up_down, manual_up_down, },
795 { "wvdial" , wvdial_up , wvdial_down , },
796 { "ppp" , ppp_up , ppp_down , },
797 { "static" , static_up , static_down , },
798 { "bootp" , bootp_up , static_down , },
799 { "dhcp" , dhcp_up , dhcp_down , },
800 { "loopback", loopback_up , loopback_down , },
803 static const struct address_family_t addr_inet = {
809 #endif /* FEATURE_IFUPDOWN_IPV4 */
811 static int FAST_FUNC link_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
816 static const struct method_t link_methods[] = {
817 { "none", link_up_down, link_up_down }
820 static const struct address_family_t addr_link = {
821 "link", ARRAY_SIZE(link_methods), link_methods
824 /* Returns pointer to the next word, or NULL.
825 * In 1st case, advances *buf to the word after this one.
827 static char *next_word(char **buf)
832 /* Skip over leading whitespace */
833 word = skip_whitespace(*buf);
839 /* Find the length of this word (can't be 0) */
840 length = strcspn(word, " \t\n");
842 /* Unless we are already at NUL, store NUL and advance */
843 if (word[length] != '\0')
844 word[length++] = '\0';
846 *buf = skip_whitespace(word + length);
851 static const struct address_family_t *get_address_family(const struct address_family_t *const af[], char *name)
858 for (i = 0; af[i]; i++) {
859 if (strcmp(af[i]->name, name) == 0) {
866 static const struct method_t *get_method(const struct address_family_t *af, char *name)
872 /* TODO: use index_in_str_array() */
873 for (i = 0; i < af->n_methods; i++) {
874 if (strcmp(af->method[i].name, name) == 0) {
875 return &af->method[i];
881 static struct interfaces_file_t *read_interfaces(const char *filename, struct interfaces_file_t *defn)
883 /* Let's try to be compatible.
885 * "man 5 interfaces" says:
886 * Lines starting with "#" are ignored. Note that end-of-line
887 * comments are NOT supported, comments must be on a line of their own.
888 * A line may be extended across multiple lines by making
889 * the last character a backslash.
891 * Seen elsewhere in example config file:
892 * A first non-blank "#" character makes the rest of the line
893 * be ignored. Blank lines are ignored. Lines may be indented freely.
894 * A "\" character at the very end of the line indicates the next line
895 * should be treated as a continuation of the current one.
897 * Lines beginning with "source" are used to include stanzas from
898 * other files, so configuration can be split into many files.
899 * The word "source" is followed by the path of file to be sourced.
901 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
902 struct mapping_defn_t *currmap = NULL;
904 struct interface_defn_t *currif = NULL;
909 enum { NONE, IFACE, MAPPING } currently_processing = NONE;
912 defn = xzalloc(sizeof(*defn));
914 debug_noise("reading %s file:\n", filename);
915 f = xfopen_for_read(filename);
917 while ((buf = xmalloc_fgetline(f)) != NULL) {
919 /* Trailing "\" concatenates lines */
921 while ((p = last_char_is(buf, '\\')) != NULL) {
923 rest_of_line = xmalloc_fgetline(f);
926 p = xasprintf("%s%s", buf, rest_of_line);
933 first_word = next_word(&rest_of_line);
934 if (!first_word || *first_word == '#') {
936 continue; /* blank/comment line */
939 if (strcmp(first_word, "mapping") == 0) {
940 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
941 currmap = xzalloc(sizeof(*currmap));
943 while ((first_word = next_word(&rest_of_line)) != NULL) {
944 currmap->match = xrealloc_vector(currmap->match, 4, currmap->n_matches);
945 currmap->match[currmap->n_matches++] = xstrdup(first_word);
947 /*currmap->n_mappings = 0;*/
948 /*currmap->mapping = NULL;*/
949 /*currmap->script = NULL;*/
951 struct mapping_defn_t **where = &defn->mappings;
952 while (*where != NULL) {
953 where = &(*where)->next;
956 /*currmap->next = NULL;*/
958 debug_noise("Added mapping\n");
960 currently_processing = MAPPING;
961 } else if (strcmp(first_word, "iface") == 0) {
962 static const struct address_family_t *const addr_fams[] = {
963 #if ENABLE_FEATURE_IFUPDOWN_IPV4
966 #if ENABLE_FEATURE_IFUPDOWN_IPV6
973 char *address_family_name;
976 currif = xzalloc(sizeof(*currif));
977 iface_name = next_word(&rest_of_line);
978 address_family_name = next_word(&rest_of_line);
979 method_name = next_word(&rest_of_line);
981 if (method_name == NULL)
982 bb_error_msg_and_die("too few parameters for line \"%s\"", buf);
984 /* ship any trailing whitespace */
985 rest_of_line = skip_whitespace(rest_of_line);
987 if (rest_of_line[0] != '\0' /* && rest_of_line[0] != '#' */)
988 bb_error_msg_and_die("too many parameters \"%s\"", buf);
990 currif->iface = xstrdup(iface_name);
992 currif->address_family = get_address_family(addr_fams, address_family_name);
993 if (!currif->address_family)
994 bb_error_msg_and_die("unknown address type \"%s\"", address_family_name);
996 currif->method = get_method(currif->address_family, method_name);
998 bb_error_msg_and_die("unknown method \"%s\"", method_name);
1000 // Allegedly, Debian allows a duplicate definition:
1001 // iface eth0 inet static
1002 // address 192.168.0.15
1003 // netmask 255.255.0.0
1004 // gateway 192.168.0.1
1006 // iface eth0 inet static
1008 // netmask 255.255.255.0
1010 // This adds *two* addresses to eth0 (probably requires use of "ip", not "ifconfig"
1012 llist_t *iface_list;
1013 for (iface_list = defn->ifaces; iface_list; iface_list = iface_list->link) {
1014 struct interface_defn_t *tmp = (struct interface_defn_t *) iface_list->data;
1015 if ((strcmp(tmp->iface, currif->iface) == 0)
1016 && (tmp->address_family == currif->address_family)
1018 bb_error_msg_and_die("duplicate interface \"%s\"", tmp->iface);
1022 llist_add_to_end(&(defn->ifaces), (char*)currif);
1024 debug_noise("iface %s %s %s\n", currif->iface, address_family_name, method_name);
1025 currently_processing = IFACE;
1026 } else if (strcmp(first_word, "auto") == 0) {
1027 while ((first_word = next_word(&rest_of_line)) != NULL) {
1029 /* Check the interface isnt already listed */
1030 if (llist_find_str(defn->autointerfaces, first_word)) {
1031 bb_perror_msg_and_die("interface declared auto twice \"%s\"", buf);
1034 /* Add the interface to the list */
1035 llist_add_to_end(&(defn->autointerfaces), xstrdup(first_word));
1036 debug_noise("\nauto %s\n", first_word);
1038 currently_processing = NONE;
1039 } else if (strcmp(first_word, "source") == 0) {
1040 read_interfaces(next_word(&rest_of_line), defn);
1042 switch (currently_processing) {
1044 if (rest_of_line[0] == '\0')
1045 bb_error_msg_and_die("option with empty value \"%s\"", buf);
1047 if (strcmp(first_word, "post-up") == 0)
1048 first_word += 5; /* "up" */
1049 else if (strcmp(first_word, "pre-down") == 0)
1050 first_word += 4; /* "down" */
1052 /* If not one of "up", "down",... words... */
1053 if (index_in_strings(keywords_up_down, first_word) < 0) {
1055 for (i = 0; i < currif->n_options; i++) {
1056 if (strcmp(currif->option[i].name, first_word) == 0)
1057 bb_error_msg_and_die("duplicate option \"%s\"", buf);
1060 debug_noise("\t%s=%s\n", first_word, rest_of_line);
1061 currif->option = xrealloc_vector(currif->option, 4, currif->n_options);
1062 currif->option[currif->n_options].name = xstrdup(first_word);
1063 currif->option[currif->n_options].value = xstrdup(rest_of_line);
1064 currif->n_options++;
1067 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1068 if (strcmp(first_word, "script") == 0) {
1069 if (currmap->script != NULL)
1070 bb_error_msg_and_die("duplicate script in mapping \"%s\"", buf);
1071 currmap->script = xstrdup(next_word(&rest_of_line));
1072 } else if (strcmp(first_word, "map") == 0) {
1073 currmap->mapping = xrealloc_vector(currmap->mapping, 2, currmap->n_mappings);
1074 currmap->mapping[currmap->n_mappings] = xstrdup(next_word(&rest_of_line));
1075 currmap->n_mappings++;
1077 bb_error_msg_and_die("misplaced option \"%s\"", buf);
1083 bb_error_msg_and_die("misplaced option \"%s\"", buf);
1087 } /* while (fgets) */
1089 if (ferror(f) != 0) {
1090 /* ferror does NOT set errno! */
1091 bb_error_msg_and_die("%s: I/O error", filename);
1094 debug_noise("\ndone reading %s\n\n", filename);
1099 static char *setlocalenv(const char *format, const char *name, const char *value)
1106 result = xasprintf(format, name, value);
1108 for (dst = src = result; (c = *src) != '=' && c; src++) {
1111 if (c >= 'a' && c <= 'z')
1113 if (isalnum(c) || c == '_')
1116 overlapping_strcpy(dst, src);
1121 static void set_environ(struct interface_defn_t *iface, const char *mode, const char *opt)
1126 if (G.my_environ != NULL) {
1127 for (pp = G.my_environ; *pp; pp++) {
1133 /* note: last element will stay NULL: */
1134 G.my_environ = xzalloc(sizeof(char *) * (iface->n_options + 7));
1137 for (i = 0; i < iface->n_options; i++) {
1138 if (index_in_strings(keywords_up_down, iface->option[i].name) >= 0) {
1141 *pp++ = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
1144 *pp++ = setlocalenv("%s=%s", "IFACE", iface->iface);
1145 *pp++ = setlocalenv("%s=%s", "ADDRFAM", iface->address_family->name);
1146 *pp++ = setlocalenv("%s=%s", "METHOD", iface->method->name);
1147 *pp++ = setlocalenv("%s=%s", "MODE", mode);
1148 *pp++ = setlocalenv("%s=%s", "PHASE", opt);
1150 *pp++ = setlocalenv("%s=%s", "PATH", G.startup_PATH);
1153 static int doit(char *str)
1155 if (option_mask32 & (OPT_no_act|OPT_verbose)) {
1158 if (!(option_mask32 & OPT_no_act)) {
1164 if (child < 0) /* failure */
1166 if (child == 0) { /* child */
1167 execle(G.shell, G.shell, "-c", str, (char *) NULL, G.my_environ);
1170 safe_waitpid(child, &status, 0);
1171 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1178 static int execute_all(struct interface_defn_t *ifd, const char *opt)
1182 for (i = 0; i < ifd->n_options; i++) {
1183 if (strcmp(ifd->option[i].name, opt) == 0) {
1184 if (!doit(ifd->option[i].value)) {
1190 /* Tested on Debian Squeeze: "standard" ifup runs this without
1191 * checking that directory exists. If it doesn't, run-parts
1192 * complains, and this message _is_ annoyingly visible.
1193 * Don't "fix" this (unless newer Debian does).
1195 buf = xasprintf("run-parts /etc/network/if-%s.d", opt);
1196 /* heh, we don't bother free'ing it */
1200 static int check(char *str)
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;
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;
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;
1242 /* NB: close _first_, then move fds! */
1245 xmove_fd(infd.rd, 0);
1246 xmove_fd(outfd.wr, 1);
1247 BB_EXECVP_or_die(argv);
1252 *in = xfdopen_for_write(infd.wr);
1253 *out = xfdopen_for_read(outfd.rd);
1257 static char *run_mapping(char *physical, struct mapping_defn_t *map)
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]);
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);
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))
1291 logical = new_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;
1306 char *after_iface = is_prefixed_with(search->data, iface);
1308 && *after_iface == '='
1312 search = search->link;
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);
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");
1329 llist_add_to(&state_list, start);
1336 /* read the previous state from the state file */
1337 static FILE *open_new_state_file(void)
1342 flags = (O_WRONLY | O_CREAT | O_EXCL);
1344 fd = open(IFSTATE_FILE_PATH".new", flags, 0666);
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 * 1000) {
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);
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;
1379 G.startup_PATH = getenv("PATH");
1380 G.shell = xstrdup(get_shell_name());
1383 && (!ENABLE_IFDOWN || applet_name[2] == 'u')
1391 getopt32(argv, OPTION_STR, &interfaces);
1394 if (DO_ALL) bb_show_usage();
1396 if (!DO_ALL) bb_show_usage();
1399 defn = read_interfaces(interfaces, NULL);
1401 /* Create a list of interfaces to work on */
1403 target_list = defn->autointerfaces;
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;
1417 bool curr_failure = 0;
1419 iface = xstrdup(target_list->data);
1420 target_list = target_list->link;
1422 pch = strchr(iface, '=');
1425 liface = xstrdup(pch + 1);
1427 liface = xstrdup(iface);
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) {
1437 bb_error_msg("interface %s already configured", iface);
1443 bb_error_msg("interface %s not configured", iface);
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) {
1456 for (i = 0; i < currmap->n_matches; i++) {
1457 if (fnmatch(currmap->match[i], liface, 0) != 0)
1460 printf("Running mapping script %s on %s\n", currmap->script, liface);
1462 liface = run_mapping(iface, currmap);
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;
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;
1498 if (!okay && !FORCE) {
1499 bb_error_msg("ignoring unknown interface %s", liface);
1501 } else if (!NO_ACT) {
1502 /* update the state file */
1503 FILE *new_state_fp = open_new_state_file();
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);
1511 llist_add_to_end(&state_list, newiface);
1513 free(iface_state->data);
1514 iface_state->data = newiface;
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 */
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);
1539 return any_failures;