1 /* vi: set sw=4 ts=4: */
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.
20 //usage:#define ifup_trivial_usage
21 //usage: "[-an"IF_FEATURE_IFUPDOWN_MAPPING("m")"vf] [-i FILE] IFACE..."
22 //usage:#define ifup_full_usage "\n\n"
23 //usage: " -a De/configure all interfaces automatically"
24 //usage: "\n -i FILE Use FILE instead of /etc/network/interfaces"
25 //usage: "\n -n Print out what would happen, but don't do it"
26 //usage: IF_FEATURE_IFUPDOWN_MAPPING(
27 //usage: "\n (note: doesn't disable mappings)"
28 //usage: "\n -m Don't run any mappings"
30 //usage: "\n -v Print out what would happen before doing it"
31 //usage: "\n -f Force de/configuration"
33 //usage:#define ifdown_trivial_usage
34 //usage: "[-an"IF_FEATURE_IFUPDOWN_MAPPING("m")"vf] [-i FILE] IFACE..."
35 //usage:#define ifdown_full_usage "\n\n"
36 //usage: " -a De/configure all interfaces automatically"
37 //usage: "\n -i FILE Use FILE for interface definitions"
38 //usage: "\n -n Print out what would happen, but don't do it"
39 //usage: IF_FEATURE_IFUPDOWN_MAPPING(
40 //usage: "\n (note: doesn't disable mappings)"
41 //usage: "\n -m Don't run any mappings"
43 //usage: "\n -v Print out what would happen before doing it"
44 //usage: "\n -f Force de/configuration"
47 #include "common_bufsiz.h"
48 /* After libbb.h, since it needs sys/types.h on some systems */
49 #include <sys/utsname.h>
52 #define MAX_OPT_DEPTH 10
54 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
55 #define MAX_INTERFACE_LENGTH 10
58 #define UDHCPC_CMD_OPTIONS CONFIG_IFUPDOWN_UDHCPC_CMD_OPTIONS
60 #define debug_noise(args...) /*fprintf(stderr, args)*/
62 /* Forward declaration */
63 struct interface_defn_t;
65 typedef int execfn(char *command);
69 int (*up)(struct interface_defn_t *ifd, execfn *e) FAST_FUNC;
70 int (*down)(struct interface_defn_t *ifd, execfn *e) FAST_FUNC;
73 struct address_family_t {
76 const struct method_t *method;
79 struct mapping_defn_t {
80 struct mapping_defn_t *next;
97 struct interface_defn_t {
98 const struct address_family_t *address_family;
99 const struct method_t *method;
103 struct variable_t *option;
106 struct interfaces_file_t {
107 llist_t *autointerfaces;
109 struct mapping_defn_t *mappings;
113 #define OPTION_STR "anvf" IF_FEATURE_IFUPDOWN_MAPPING("m") "i:"
119 OPT_no_mappings = 0x10,
121 #define DO_ALL (option_mask32 & OPT_do_all)
122 #define NO_ACT (option_mask32 & OPT_no_act)
123 #define VERBOSE (option_mask32 & OPT_verbose)
124 #define FORCE (option_mask32 & OPT_force)
125 #define NO_MAPPINGS (option_mask32 & OPT_no_mappings)
130 const char *startup_PATH;
133 #define G (*(struct globals*)bb_common_bufsiz1)
134 #define INIT_G() do { setup_common_bufsiz(); } while (0)
137 static const char keywords_up_down[] ALIGN1 =
145 #if ENABLE_FEATURE_IFUPDOWN_IPV4 || ENABLE_FEATURE_IFUPDOWN_IPV6
147 static void addstr(char **bufp, const char *str, size_t str_length)
149 /* xasprintf trick will be smaller, but we are often
150 * called with str_length == 1 - don't want to have
151 * THAT much of malloc/freeing! */
153 int len = (buf ? strlen(buf) : 0);
155 buf = xrealloc(buf, len + str_length);
156 /* copies at most str_length-1 chars! */
157 safe_strncpy(buf + len, str, str_length);
161 static int strncmpz(const char *l, const char *r, size_t llen)
163 int i = strncmp(l, r, llen);
166 return - (unsigned char)r[llen];
170 static char *get_var(const char *id, size_t idlen, struct interface_defn_t *ifd)
174 if (strncmpz(id, "iface", idlen) == 0) {
175 // ubuntu's ifup doesn't do this:
176 //static char *label_buf;
179 //label_buf = xstrdup(ifd->iface);
180 // Remove virtual iface suffix
181 //result = strchrnul(label_buf, ':');
187 if (strncmpz(id, "label", idlen) == 0) {
190 for (i = 0; i < ifd->n_options; i++) {
191 if (strncmpz(id, ifd->option[i].name, idlen) == 0) {
192 return ifd->option[i].value;
198 # if ENABLE_FEATURE_IFUPDOWN_IP
199 static int count_netmask_bits(const char *dotted_quad)
202 // unsigned a, b, c, d;
203 // /* Found a netmask... Check if it is dotted quad */
204 // if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
206 // if ((a|b|c|d) >> 8)
207 // return -1; /* one of numbers is >= 256 */
208 // d |= (a << 24) | (b << 16) | (c << 8); /* IP */
209 // d = ~d; /* 11110000 -> 00001111 */
211 /* Shorter version */
216 if (inet_aton(dotted_quad, &ip) == 0)
217 return -1; /* malformed dotted IP */
218 d = ntohl(ip.s_addr); /* IP in host order */
219 d = ~d; /* 11110000 -> 00001111 */
220 if (d & (d+1)) /* check that it is in 00001111 form */
221 return -1; /* no it is not */
231 static char *parse(const char *command, struct interface_defn_t *ifd)
233 size_t old_pos[MAX_OPT_DEPTH] = { 0 };
234 smallint okay[MAX_OPT_DEPTH] = { 1 };
241 addstr(&result, command, 1);
247 addstr(&result, command, 1);
251 if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
252 old_pos[opt_depth] = result ? strlen(result) : 0;
257 addstr(&result, command, 1);
262 if (command[1] == ']' && opt_depth > 1) {
264 if (!okay[opt_depth]) {
265 result[old_pos[opt_depth]] = '\0';
269 addstr(&result, command, 1);
279 nextpercent = strchr(command, '%');
281 /* Unterminated %var% */
286 varvalue = get_var(command, nextpercent - command, ifd);
289 # if ENABLE_FEATURE_IFUPDOWN_IP
290 /* "hwaddress <class> <address>":
291 * unlike ifconfig, ip doesnt want <class>
292 * (usually "ether" keyword). Skip it. */
293 if (is_prefixed_with(command, "hwaddress")) {
294 varvalue = skip_whitespace(skip_non_whitespace(varvalue));
297 addstr(&result, varvalue, strlen(varvalue));
299 # if ENABLE_FEATURE_IFUPDOWN_IP
300 /* Sigh... Add a special case for 'ip' to convert from
301 * dotted quad to bit count style netmasks. */
302 if (is_prefixed_with(command, "bnmask")) {
304 varvalue = get_var("netmask", 7, ifd);
306 res = count_netmask_bits(varvalue);
308 const char *argument = utoa(res);
309 addstr(&result, argument, strlen(argument));
310 command = nextpercent + 1;
316 okay[opt_depth - 1] = 0;
319 command = nextpercent + 1;
326 /* Unbalanced bracket */
332 /* Undefined variable and we aren't in a bracket */
340 /* execute() returns 1 for success and 0 for failure */
341 static int execute(const char *command, struct interface_defn_t *ifd, execfn *exec)
346 out = parse(command, ifd);
351 /* out == "": parsed ok but not all needed variables known, skip */
352 ret = out[0] ? (*exec)(out) : 1;
361 #endif /* FEATURE_IFUPDOWN_IPV4 || FEATURE_IFUPDOWN_IPV6 */
364 #if ENABLE_FEATURE_IFUPDOWN_IPV6
366 static int FAST_FUNC loopback_up6(struct interface_defn_t *ifd, execfn *exec)
368 # if ENABLE_FEATURE_IFUPDOWN_IP
370 result = execute("ip addr add ::1 dev %iface%", ifd, exec);
371 result += execute("ip link set %iface% up", ifd, exec);
372 return ((result == 2) ? 2 : 0);
374 return execute("ifconfig %iface% add ::1", ifd, exec);
378 static int FAST_FUNC loopback_down6(struct interface_defn_t *ifd, execfn *exec)
380 # if ENABLE_FEATURE_IFUPDOWN_IP
381 return execute("ip link set %iface% down", ifd, exec);
383 return execute("ifconfig %iface% del ::1", ifd, exec);
387 static int FAST_FUNC manual_up_down6(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
392 static int FAST_FUNC static_up6(struct interface_defn_t *ifd, execfn *exec)
395 # if ENABLE_FEATURE_IFUPDOWN_IP
396 result = execute("ip addr add %address%/%netmask% dev %iface%[[ label %label%]]", ifd, exec);
397 result += execute("ip link set[[ mtu %mtu%]][[ addr %hwaddress%]] %iface% up", ifd, exec);
398 /* Reportedly, IPv6 needs "dev %iface%", but IPv4 does not: */
399 result += execute("[[ip route add ::/0 via %gateway% dev %iface%]][[ metric %metric%]]", ifd, exec);
401 result = execute("ifconfig %iface%[[ media %media%]][[ hw %hwaddress%]][[ mtu %mtu%]] up", ifd, exec);
402 result += execute("ifconfig %iface% add %address%/%netmask%", ifd, exec);
403 result += execute("[[route -A inet6 add ::/0 gw %gateway%[[ metric %metric%]]]]", ifd, exec);
405 return ((result == 3) ? 3 : 0);
408 static int FAST_FUNC static_down6(struct interface_defn_t *ifd, execfn *exec)
410 # if ENABLE_FEATURE_IFUPDOWN_IP
411 return execute("ip link set %iface% down", ifd, exec);
413 return execute("ifconfig %iface% down", ifd, exec);
417 # if ENABLE_FEATURE_IFUPDOWN_IP
418 static int FAST_FUNC v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
421 result = execute("ip tunnel add %iface% mode sit remote "
422 "%endpoint%[[ local %local%]][[ ttl %ttl%]]", ifd, exec);
423 result += execute("ip link set %iface% up", ifd, exec);
424 result += execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec);
425 /* Reportedly, IPv6 needs "dev %iface%", but IPv4 does not: */
426 result += execute("[[ip route add ::/0 via %gateway% dev %iface%]]", ifd, exec);
427 return ((result == 4) ? 4 : 0);
430 static int FAST_FUNC v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
432 return execute("ip tunnel del %iface%", ifd, exec);
436 static const struct method_t methods6[] = {
437 # if ENABLE_FEATURE_IFUPDOWN_IP
438 { "v4tunnel" , v4tunnel_up , v4tunnel_down , },
440 { "static" , static_up6 , static_down6 , },
441 { "manual" , manual_up_down6 , manual_up_down6 , },
442 { "loopback" , loopback_up6 , loopback_down6 , },
445 static const struct address_family_t addr_inet6 = {
447 ARRAY_SIZE(methods6),
451 #endif /* FEATURE_IFUPDOWN_IPV6 */
454 #if ENABLE_FEATURE_IFUPDOWN_IPV4
456 static int FAST_FUNC loopback_up(struct interface_defn_t *ifd, execfn *exec)
458 # if ENABLE_FEATURE_IFUPDOWN_IP
460 result = execute("ip addr add 127.0.0.1/8 dev %iface%", ifd, exec);
461 result += execute("ip link set %iface% up", ifd, exec);
462 return ((result == 2) ? 2 : 0);
464 return execute("ifconfig %iface% 127.0.0.1 up", ifd, exec);
468 static int FAST_FUNC loopback_down(struct interface_defn_t *ifd, execfn *exec)
470 # if ENABLE_FEATURE_IFUPDOWN_IP
472 result = execute("ip addr flush dev %iface%", ifd, exec);
473 result += execute("ip link set %iface% down", ifd, exec);
474 return ((result == 2) ? 2 : 0);
476 return execute("ifconfig %iface% 127.0.0.1 down", ifd, exec);
480 static int FAST_FUNC static_up(struct interface_defn_t *ifd, execfn *exec)
483 # if ENABLE_FEATURE_IFUPDOWN_IP
484 result = execute("ip addr add %address%/%bnmask%[[ broadcast %broadcast%]] "
485 "dev %iface%[[ peer %pointopoint%]][[ label %label%]]", ifd, exec);
486 result += execute("ip link set[[ mtu %mtu%]][[ addr %hwaddress%]] %iface% up", ifd, exec);
487 result += execute("[[ip route add default via %gateway% dev %iface%[[ metric %metric%]]]]", ifd, exec);
488 return ((result == 3) ? 3 : 0);
490 /* ifconfig said to set iface up before it processes hw %hwaddress%,
491 * which then of course fails. Thus we run two separate ifconfig */
492 result = execute("ifconfig %iface%[[ hw %hwaddress%]][[ media %media%]][[ mtu %mtu%]] up",
494 result += execute("ifconfig %iface% %address% netmask %netmask%"
495 "[[ broadcast %broadcast%]][[ pointopoint %pointopoint%]]",
497 result += execute("[[route add default gw %gateway%[[ metric %metric%]] %iface%]]", ifd, exec);
498 return ((result == 3) ? 3 : 0);
502 static int FAST_FUNC static_down(struct interface_defn_t *ifd, execfn *exec)
505 # if ENABLE_FEATURE_IFUPDOWN_IP
506 /* Optional "label LBL" is necessary if interface is an alias (eth0:0),
507 * otherwise "ip addr flush dev eth0:0" flushes all addresses on eth0.
509 result = execute("ip addr flush dev %iface%[[ label %label%]]", ifd, exec);
510 result += execute("ip link set %iface% down", ifd, exec);
512 /* result = execute("[[route del default gw %gateway% %iface%]]", ifd, exec); */
513 /* Bringing the interface down deletes the routes in itself.
514 Otherwise this fails if we reference 'gateway' when using this from dhcp_down */
516 result += execute("ifconfig %iface% down", ifd, exec);
518 return ((result == 2) ? 2 : 0);
521 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
522 struct dhcp_client_t {
524 const char *startcmd;
528 static const struct dhcp_client_t ext_dhcp_clients[] = {
530 "dhcpcd[[ -h %hostname%]][[ -i %vendor%]][[ -I %client%]][[ -l %leasetime%]] %iface%",
534 "dhclient -pf /var/run/dhclient.%iface%.pid %iface%",
535 "kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null",
538 "pump -i %iface%[[ -h %hostname%]][[ -l %leasehours%]]",
539 "pump -i %iface% -k",
542 "udhcpc " UDHCPC_CMD_OPTIONS " -p /var/run/udhcpc.%iface%.pid -i %iface%[[ -x hostname:%hostname%]][[ -c %client%]]"
543 "[[ -s %script%]][[ %udhcpc_opts%]]",
544 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
547 # endif /* FEATURE_IFUPDOWN_EXTERNAL_DHCPC */
549 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
550 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
553 # if ENABLE_FEATURE_IFUPDOWN_IP
554 /* ip doesn't up iface when it configures it (unlike ifconfig) */
555 if (!execute("ip link set[[ addr %hwaddress%]] %iface% up", ifd, exec))
558 /* needed if we have hwaddress on dhcp iface */
559 if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
562 for (i = 0; i < ARRAY_SIZE(ext_dhcp_clients); i++) {
563 if (executable_exists(ext_dhcp_clients[i].name))
564 return execute(ext_dhcp_clients[i].startcmd, ifd, exec);
566 bb_error_msg("no dhcp clients found");
570 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
572 # if ENABLE_FEATURE_IFUPDOWN_IP
573 /* ip doesn't up iface when it configures it (unlike ifconfig) */
574 if (!execute("ip link set[[ addr %hwaddress%]] %iface% up", ifd, exec))
577 /* needed if we have hwaddress on dhcp iface */
578 if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
581 return execute("udhcpc " UDHCPC_CMD_OPTIONS " -p /var/run/udhcpc.%iface%.pid "
582 "-i %iface%[[ -x hostname:%hostname%]][[ -c %client%]][[ -s %script%]][[ %udhcpc_opts%]]",
586 static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd UNUSED_PARAM,
587 execfn *exec UNUSED_PARAM)
589 return 0; /* no dhcp support */
593 # if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
594 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
599 for (i = 0; i < ARRAY_SIZE(ext_dhcp_clients); i++) {
600 if (executable_exists(ext_dhcp_clients[i].name)) {
601 result = execute(ext_dhcp_clients[i].stopcmd, ifd, exec);
608 bb_error_msg("warning: no dhcp clients found and stopped");
610 /* Sleep a bit, otherwise static_down tries to bring down interface too soon,
611 and it may come back up because udhcpc is still shutting down */
613 result += static_down(ifd, exec);
614 return ((result == 3) ? 3 : 0);
617 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
621 "test -f /var/run/udhcpc.%iface%.pid && "
622 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
624 /* Also bring the hardware interface down since
625 killing the dhcp client alone doesn't do it.
626 This enables consecutive ifup->ifdown->ifup */
627 /* Sleep a bit, otherwise static_down tries to bring down interface too soon,
628 and it may come back up because udhcpc is still shutting down */
630 result += static_down(ifd, exec);
631 return ((result == 3) ? 3 : 0);
634 static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd UNUSED_PARAM,
635 execfn *exec UNUSED_PARAM)
637 return 0; /* no dhcp support */
641 static int FAST_FUNC manual_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
646 static int FAST_FUNC bootp_up(struct interface_defn_t *ifd, execfn *exec)
648 return execute("bootpc[[ --bootfile %bootfile%]] --dev %iface%"
649 "[[ --server %server%]][[ --hwaddr %hwaddr%]]"
650 " --returniffail --serverbcast", ifd, exec);
653 static int FAST_FUNC ppp_up(struct interface_defn_t *ifd, execfn *exec)
655 return execute("pon[[ %provider%]]", ifd, exec);
658 static int FAST_FUNC ppp_down(struct interface_defn_t *ifd, execfn *exec)
660 return execute("poff[[ %provider%]]", ifd, exec);
663 static int FAST_FUNC wvdial_up(struct interface_defn_t *ifd, execfn *exec)
665 return execute("start-stop-daemon --start -x wvdial "
666 "-p /var/run/wvdial.%iface% -b -m --[[ %provider%]]", ifd, exec);
669 static int FAST_FUNC wvdial_down(struct interface_defn_t *ifd, execfn *exec)
671 return execute("start-stop-daemon --stop -x wvdial "
672 "-p /var/run/wvdial.%iface% -s 2", ifd, exec);
675 static const struct method_t methods[] = {
676 { "manual" , manual_up_down, manual_up_down, },
677 { "wvdial" , wvdial_up , wvdial_down , },
678 { "ppp" , ppp_up , ppp_down , },
679 { "static" , static_up , static_down , },
680 { "bootp" , bootp_up , static_down , },
681 { "dhcp" , dhcp_up , dhcp_down , },
682 { "loopback", loopback_up , loopback_down , },
685 static const struct address_family_t addr_inet = {
691 #endif /* FEATURE_IFUPDOWN_IPV4 */
693 static int FAST_FUNC link_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
698 static const struct method_t link_methods[] = {
699 { "none", link_up_down, link_up_down }
702 static const struct address_family_t addr_link = {
703 "link", ARRAY_SIZE(link_methods), link_methods
706 /* Returns pointer to the next word, or NULL.
707 * In 1st case, advances *buf to the word after this one.
709 static char *next_word(char **buf)
714 /* Skip over leading whitespace */
715 word = skip_whitespace(*buf);
721 /* Find the length of this word (can't be 0) */
722 length = strcspn(word, " \t\n");
724 /* Unless we are already at NUL, store NUL and advance */
725 if (word[length] != '\0')
726 word[length++] = '\0';
728 *buf = skip_whitespace(word + length);
733 static const struct address_family_t *get_address_family(const struct address_family_t *const af[], char *name)
740 for (i = 0; af[i]; i++) {
741 if (strcmp(af[i]->name, name) == 0) {
748 static const struct method_t *get_method(const struct address_family_t *af, char *name)
754 /* TODO: use index_in_str_array() */
755 for (i = 0; i < af->n_methods; i++) {
756 if (strcmp(af->method[i].name, name) == 0) {
757 return &af->method[i];
763 static struct interfaces_file_t *read_interfaces(const char *filename, struct interfaces_file_t *defn)
765 /* Let's try to be compatible.
767 * "man 5 interfaces" says:
768 * Lines starting with "#" are ignored. Note that end-of-line
769 * comments are NOT supported, comments must be on a line of their own.
770 * A line may be extended across multiple lines by making
771 * the last character a backslash.
773 * Seen elsewhere in example config file:
774 * A first non-blank "#" character makes the rest of the line
775 * be ignored. Blank lines are ignored. Lines may be indented freely.
776 * A "\" character at the very end of the line indicates the next line
777 * should be treated as a continuation of the current one.
779 * Lines beginning with "source" are used to include stanzas from
780 * other files, so configuration can be split into many files.
781 * The word "source" is followed by the path of file to be sourced.
783 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
784 struct mapping_defn_t *currmap = NULL;
786 struct interface_defn_t *currif = NULL;
791 enum { NONE, IFACE, MAPPING } currently_processing = NONE;
794 defn = xzalloc(sizeof(*defn));
796 debug_noise("reading %s file:\n", filename);
797 f = xfopen_for_read(filename);
799 while ((buf = xmalloc_fgetline(f)) != NULL) {
801 /* Trailing "\" concatenates lines */
803 while ((p = last_char_is(buf, '\\')) != NULL) {
805 rest_of_line = xmalloc_fgetline(f);
808 p = xasprintf("%s%s", buf, rest_of_line);
815 first_word = next_word(&rest_of_line);
816 if (!first_word || *first_word == '#') {
818 continue; /* blank/comment line */
821 if (strcmp(first_word, "mapping") == 0) {
822 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
823 currmap = xzalloc(sizeof(*currmap));
825 while ((first_word = next_word(&rest_of_line)) != NULL) {
826 currmap->match = xrealloc_vector(currmap->match, 4, currmap->n_matches);
827 currmap->match[currmap->n_matches++] = xstrdup(first_word);
829 /*currmap->n_mappings = 0;*/
830 /*currmap->mapping = NULL;*/
831 /*currmap->script = NULL;*/
833 struct mapping_defn_t **where = &defn->mappings;
834 while (*where != NULL) {
835 where = &(*where)->next;
838 /*currmap->next = NULL;*/
840 debug_noise("Added mapping\n");
842 currently_processing = MAPPING;
843 } else if (strcmp(first_word, "iface") == 0) {
844 static const struct address_family_t *const addr_fams[] = {
845 #if ENABLE_FEATURE_IFUPDOWN_IPV4
848 #if ENABLE_FEATURE_IFUPDOWN_IPV6
855 char *address_family_name;
858 currif = xzalloc(sizeof(*currif));
859 iface_name = next_word(&rest_of_line);
860 address_family_name = next_word(&rest_of_line);
861 method_name = next_word(&rest_of_line);
863 if (method_name == NULL)
864 bb_error_msg_and_die("too few parameters for line \"%s\"", buf);
866 /* ship any trailing whitespace */
867 rest_of_line = skip_whitespace(rest_of_line);
869 if (rest_of_line[0] != '\0' /* && rest_of_line[0] != '#' */)
870 bb_error_msg_and_die("too many parameters \"%s\"", buf);
872 currif->iface = xstrdup(iface_name);
874 currif->address_family = get_address_family(addr_fams, address_family_name);
875 if (!currif->address_family)
876 bb_error_msg_and_die("unknown address type \"%s\"", address_family_name);
878 currif->method = get_method(currif->address_family, method_name);
880 bb_error_msg_and_die("unknown method \"%s\"", method_name);
882 // Allegedly, Debian allows a duplicate definition:
883 // iface eth0 inet static
884 // address 192.168.0.15
885 // netmask 255.255.0.0
886 // gateway 192.168.0.1
888 // iface eth0 inet static
890 // netmask 255.255.255.0
892 // This adds *two* addresses to eth0 (probably requires use of "ip", not "ifconfig"
895 for (iface_list = defn->ifaces; iface_list; iface_list = iface_list->link) {
896 struct interface_defn_t *tmp = (struct interface_defn_t *) iface_list->data;
897 if ((strcmp(tmp->iface, currif->iface) == 0)
898 && (tmp->address_family == currif->address_family)
900 bb_error_msg_and_die("duplicate interface \"%s\"", tmp->iface);
904 llist_add_to_end(&(defn->ifaces), (char*)currif);
906 debug_noise("iface %s %s %s\n", currif->iface, address_family_name, method_name);
907 currently_processing = IFACE;
908 } else if (strcmp(first_word, "auto") == 0) {
909 while ((first_word = next_word(&rest_of_line)) != NULL) {
911 /* Check the interface isnt already listed */
912 if (llist_find_str(defn->autointerfaces, first_word)) {
913 bb_perror_msg_and_die("interface declared auto twice \"%s\"", buf);
916 /* Add the interface to the list */
917 llist_add_to_end(&(defn->autointerfaces), xstrdup(first_word));
918 debug_noise("\nauto %s\n", first_word);
920 currently_processing = NONE;
921 } else if (strcmp(first_word, "source") == 0) {
922 read_interfaces(next_word(&rest_of_line), defn);
924 switch (currently_processing) {
926 if (rest_of_line[0] == '\0')
927 bb_error_msg_and_die("option with empty value \"%s\"", buf);
929 if (strcmp(first_word, "post-up") == 0)
930 first_word += 5; /* "up" */
931 else if (strcmp(first_word, "pre-down") == 0)
932 first_word += 4; /* "down" */
934 /* If not one of "up", "down",... words... */
935 if (index_in_strings(keywords_up_down, first_word) < 0) {
937 for (i = 0; i < currif->n_options; i++) {
938 if (strcmp(currif->option[i].name, first_word) == 0)
939 bb_error_msg_and_die("duplicate option \"%s\"", buf);
942 debug_noise("\t%s=%s\n", first_word, rest_of_line);
943 currif->option = xrealloc_vector(currif->option, 4, currif->n_options);
944 currif->option[currif->n_options].name = xstrdup(first_word);
945 currif->option[currif->n_options].value = xstrdup(rest_of_line);
949 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
950 if (strcmp(first_word, "script") == 0) {
951 if (currmap->script != NULL)
952 bb_error_msg_and_die("duplicate script in mapping \"%s\"", buf);
953 currmap->script = xstrdup(next_word(&rest_of_line));
954 } else if (strcmp(first_word, "map") == 0) {
955 currmap->mapping = xrealloc_vector(currmap->mapping, 2, currmap->n_mappings);
956 currmap->mapping[currmap->n_mappings] = xstrdup(next_word(&rest_of_line));
957 currmap->n_mappings++;
959 bb_error_msg_and_die("misplaced option \"%s\"", buf);
965 bb_error_msg_and_die("misplaced option \"%s\"", buf);
969 } /* while (fgets) */
971 if (ferror(f) != 0) {
972 /* ferror does NOT set errno! */
973 bb_error_msg_and_die("%s: I/O error", filename);
976 debug_noise("\ndone reading %s\n\n", filename);
981 static char *setlocalenv(const char *format, const char *name, const char *value)
988 result = xasprintf(format, name, value);
990 for (dst = src = result; (c = *src) != '=' && c; src++) {
993 if (c >= 'a' && c <= 'z')
995 if (isalnum(c) || c == '_')
998 overlapping_strcpy(dst, src);
1003 static void set_environ(struct interface_defn_t *iface, const char *mode, const char *opt)
1008 if (G.my_environ != NULL) {
1009 for (pp = G.my_environ; *pp; pp++) {
1015 /* note: last element will stay NULL: */
1016 G.my_environ = xzalloc(sizeof(char *) * (iface->n_options + 7));
1019 for (i = 0; i < iface->n_options; i++) {
1020 if (index_in_strings(keywords_up_down, iface->option[i].name) >= 0) {
1023 *pp++ = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
1026 *pp++ = setlocalenv("%s=%s", "IFACE", iface->iface);
1027 *pp++ = setlocalenv("%s=%s", "ADDRFAM", iface->address_family->name);
1028 *pp++ = setlocalenv("%s=%s", "METHOD", iface->method->name);
1029 *pp++ = setlocalenv("%s=%s", "MODE", mode);
1030 *pp++ = setlocalenv("%s=%s", "PHASE", opt);
1032 *pp++ = setlocalenv("%s=%s", "PATH", G.startup_PATH);
1035 static int doit(char *str)
1037 if (option_mask32 & (OPT_no_act|OPT_verbose)) {
1040 if (!(option_mask32 & OPT_no_act)) {
1046 if (child < 0) /* failure */
1048 if (child == 0) { /* child */
1049 execle(G.shell, G.shell, "-c", str, (char *) NULL, G.my_environ);
1052 safe_waitpid(child, &status, 0);
1053 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1060 static int execute_all(struct interface_defn_t *ifd, const char *opt)
1064 for (i = 0; i < ifd->n_options; i++) {
1065 if (strcmp(ifd->option[i].name, opt) == 0) {
1066 if (!doit(ifd->option[i].value)) {
1072 /* Tested on Debian Squeeze: "standard" ifup runs this without
1073 * checking that directory exists. If it doesn't, run-parts
1074 * complains, and this message _is_ annoyingly visible.
1075 * Don't "fix" this (unless newer Debian does).
1077 buf = xasprintf("run-parts /etc/network/if-%s.d", opt);
1078 /* heh, we don't bother free'ing it */
1082 static int check(char *str)
1087 static int iface_up(struct interface_defn_t *iface)
1089 if (!iface->method->up(iface, check)) return -1;
1090 set_environ(iface, "start", "pre-up");
1091 if (!execute_all(iface, "pre-up")) return 0;
1092 if (!iface->method->up(iface, doit)) return 0;
1093 set_environ(iface, "start", "post-up");
1094 if (!execute_all(iface, "up")) return 0;
1098 static int iface_down(struct interface_defn_t *iface)
1100 if (!iface->method->down(iface, check)) return -1;
1101 set_environ(iface, "stop", "pre-down");
1102 if (!execute_all(iface, "down")) return 0;
1103 if (!iface->method->down(iface, doit)) return 0;
1104 set_environ(iface, "stop", "post-down");
1105 if (!execute_all(iface, "post-down")) return 0;
1109 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1110 static int popen2(FILE **in, FILE **out, char *command, char *param)
1112 char *argv[3] = { command, param, NULL };
1113 struct fd_pair infd, outfd;
1124 /* NB: close _first_, then move fds! */
1127 xmove_fd(infd.rd, 0);
1128 xmove_fd(outfd.wr, 1);
1129 BB_EXECVP_or_die(argv);
1134 *in = xfdopen_for_write(infd.wr);
1135 *out = xfdopen_for_read(outfd.rd);
1139 static char *run_mapping(char *physical, struct mapping_defn_t *map)
1145 char *logical = xstrdup(physical);
1147 /* Run the mapping script. Never fails. */
1148 pid = popen2(&in, &out, map->script, physical);
1150 /* Write mappings to stdin of mapping script. */
1151 for (i = 0; i < map->n_mappings; i++) {
1152 fprintf(in, "%s\n", map->mapping[i]);
1155 safe_waitpid(pid, &status, 0);
1157 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1158 /* If the mapping script exited successfully, try to
1159 * grab a line of output and use that as the name of the
1160 * logical interface. */
1161 char *new_logical = xmalloc_fgetline(out);
1164 /* If we are able to read a line of output from the script,
1165 * remove any trailing whitespace and use this value
1166 * as the name of the logical interface. */
1167 char *pch = new_logical + strlen(new_logical) - 1;
1169 while (pch >= new_logical && isspace(*pch))
1173 logical = new_logical;
1181 #endif /* FEATURE_IFUPDOWN_MAPPING */
1183 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1185 llist_t *search = state_list;
1188 char *after_iface = is_prefixed_with(search->data, iface);
1190 && *after_iface == '='
1194 search = search->link;
1199 /* read the previous state from the state file */
1200 static llist_t *read_iface_state(void)
1202 llist_t *state_list = NULL;
1203 FILE *state_fp = fopen_for_read(CONFIG_IFUPDOWN_IFSTATE_PATH);
1206 char *start, *end_ptr;
1207 while ((start = xmalloc_fgets(state_fp)) != NULL) {
1208 /* We should only need to check for a single character */
1209 end_ptr = start + strcspn(start, " \t\n");
1211 llist_add_to(&state_list, start);
1219 int ifupdown_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1220 int ifupdown_main(int argc UNUSED_PARAM, char **argv)
1222 int (*cmds)(struct interface_defn_t *);
1223 struct interfaces_file_t *defn;
1224 llist_t *target_list = NULL;
1225 const char *interfaces = "/etc/network/interfaces";
1226 bool any_failures = 0;
1230 G.startup_PATH = getenv("PATH");
1231 G.shell = xstrdup(get_shell_name());
1234 if (applet_name[2] == 'u') {
1239 getopt32(argv, OPTION_STR, &interfaces);
1242 if (DO_ALL) bb_show_usage();
1244 if (!DO_ALL) bb_show_usage();
1247 defn = read_interfaces(interfaces, NULL);
1249 /* Create a list of interfaces to work on */
1251 target_list = defn->autointerfaces;
1253 llist_add_to_end(&target_list, argv[0]);
1256 /* Update the interfaces */
1257 while (target_list) {
1258 llist_t *iface_list;
1259 struct interface_defn_t *currif;
1265 bool curr_failure = 0;
1267 iface = xstrdup(target_list->data);
1268 target_list = target_list->link;
1270 pch = strchr(iface, '=');
1273 liface = xstrdup(pch + 1);
1275 liface = xstrdup(iface);
1279 llist_t *state_list = read_iface_state();
1280 const llist_t *iface_state = find_iface_state(state_list, iface);
1282 if (cmds == iface_up) {
1285 bb_error_msg("interface %s already configured", iface);
1291 bb_error_msg("interface %s not configured", iface);
1295 llist_free(state_list, free);
1298 #if ENABLE_FEATURE_IFUPDOWN_MAPPING
1299 if ((cmds == iface_up) && !NO_MAPPINGS) {
1300 struct mapping_defn_t *currmap;
1302 for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1304 for (i = 0; i < currmap->n_matches; i++) {
1305 if (fnmatch(currmap->match[i], liface, 0) != 0)
1308 printf("Running mapping script %s on %s\n", currmap->script, liface);
1310 liface = run_mapping(iface, currmap);
1317 iface_list = defn->ifaces;
1318 while (iface_list) {
1319 currif = (struct interface_defn_t *) iface_list->data;
1320 if (strcmp(liface, currif->iface) == 0) {
1321 char *oldiface = currif->iface;
1324 currif->iface = iface;
1326 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1328 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1329 cmds_ret = cmds(currif);
1330 if (cmds_ret == -1) {
1331 bb_error_msg("don't have all variables for %s/%s",
1332 liface, currif->address_family->name);
1333 any_failures = curr_failure = 1;
1334 } else if (cmds_ret == 0) {
1335 any_failures = curr_failure = 1;
1338 currif->iface = oldiface;
1340 iface_list = iface_list->link;
1346 if (!okay && !FORCE) {
1347 bb_error_msg("ignoring unknown interface %s", liface);
1349 } else if (!NO_ACT) {
1350 /* update the state file */
1353 llist_t *state_list = read_iface_state();
1354 llist_t *iface_state = find_iface_state(state_list, iface);
1356 if (cmds == iface_up && !curr_failure) {
1357 char *newiface = xasprintf("%s=%s", iface, liface);
1359 llist_add_to_end(&state_list, newiface);
1361 free(iface_state->data);
1362 iface_state->data = newiface;
1365 /* Remove an interface from state_list */
1366 llist_unlink(&state_list, iface_state);
1367 free(llist_pop(&iface_state));
1370 /* Actually write the new state */
1371 state_fp = xfopen_for_write(CONFIG_IFUPDOWN_IFSTATE_PATH);
1375 fprintf(state_fp, "%s\n", state->data);
1377 state = state->link;
1380 llist_free(state_list, free);
1387 return any_failures;