summaryrefslogtreecommitdiff
path: root/networking/ifupdown.c (plain)
blob: 7ac517afd6b2b74c90d163c708c826e5c8cd2d2c
1/* vi: set sw=4 ts=4: */
2/*
3 * ifup/ifdown for busybox
4 * Copyright (c) 2002 Glenn McGrath
5 * Copyright (c) 2003-2004 Erik Andersen <andersen@codepoet.org>
6 *
7 * Based on ifupdown v 0.6.4 by Anthony Towns
8 * Copyright (c) 1999 Anthony Towns <aj@azure.humbug.org.au>
9 *
10 * Changes to upstream version
11 * Remove checks for kernel version, assume kernel version 2.2.0 or better.
12 * Lines in the interfaces file cannot wrap.
13 * To adhere to the FHS, the default state file is /var/run/ifstate
14 * (defined via CONFIG_IFUPDOWN_IFSTATE_PATH) and can be overridden by build
15 * configuration.
16 *
17 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
18 */
19
20//config:config IFUP
21//config: bool "ifup"
22//config: default y
23//config: help
24//config: Activate the specified interfaces. This applet makes use
25//config: of either "ifconfig" and "route" or the "ip" command to actually
26//config: configure network interfaces. Therefore, you will probably also want
27//config: to enable either IFCONFIG and ROUTE, or enable
28//config: FEATURE_IFUPDOWN_IP and the various IP options. Of
29//config: course you could use non-busybox versions of these programs, so
30//config: against my better judgement (since this will surely result in plenty
31//config: of support questions on the mailing list), I do not force you to
32//config: enable these additional options. It is up to you to supply either
33//config: "ifconfig", "route" and "run-parts" or the "ip" command, either
34//config: via busybox or via standalone utilities.
35//config:
36//config:config IFDOWN
37//config: bool "ifdown"
38//config: default y
39//config: help
40//config: Deactivate the specified interfaces.
41//config:
42//config:config IFUPDOWN_IFSTATE_PATH
43//config: string "Absolute path to ifstate file"
44//config: default "/var/run/ifstate"
45//config: depends on IFUP || IFDOWN
46//config: help
47//config: ifupdown keeps state information in a file called ifstate.
48//config: Typically it is located in /var/run/ifstate, however
49//config: some distributions tend to put it in other places
50//config: (debian, for example, uses /etc/network/run/ifstate).
51//config: This config option defines location of ifstate.
52//config:
53//config:config FEATURE_IFUPDOWN_IP
54//config: bool "Use ip applet"
55//config: default y
56//config: depends on IFUP || IFDOWN
57//config: help
58//config: Use the iproute "ip" command to implement "ifup" and "ifdown", rather
59//config: than the default of using the older 'ifconfig' and 'route' utilities.
60//config:
61//config:config FEATURE_IFUPDOWN_IP_BUILTIN
62//config: bool "Use busybox ip applet"
63//config: default y
64//config: depends on FEATURE_IFUPDOWN_IP
65//config: select PLATFORM_LINUX
66//config: select IP
67//config: select FEATURE_IP_ADDRESS
68//config: select FEATURE_IP_LINK
69//config: select FEATURE_IP_ROUTE
70//config: help
71//config: Use the busybox iproute "ip" applet to implement "ifupdown".
72//config:
73//config: If left disabled, you must install the full-blown iproute2
74//config: utility or the "ifup" and "ifdown" applets will not work.
75//config:
76//config:config FEATURE_IFUPDOWN_IFCONFIG_BUILTIN
77//config: bool "Use busybox ifconfig and route applets"
78//config: default n
79//config: depends on (IFUP || IFDOWN) && !FEATURE_IFUPDOWN_IP
80//config: select IFCONFIG
81//config: select ROUTE
82//config: help
83//config: Use the busybox iproute "ifconfig" and "route" applets to
84//config: implement the "ifup" and "ifdown" utilities.
85//config:
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
88//config: work.
89//config:
90//config:config FEATURE_IFUPDOWN_IPV4
91//config: bool "Support for IPv4"
92//config: default y
93//config: depends on IFUP || IFDOWN
94//config: help
95//config: If you want ifup/ifdown to talk IPv4, leave this on.
96//config:
97//config:config FEATURE_IFUPDOWN_IPV6
98//config: bool "Support for IPv6"
99//config: default y
100//config: depends on (IFUP || IFDOWN) && FEATURE_IPV6
101//config: help
102//config: If you need support for IPv6, turn this option on.
103//config:
104//UNUSED:
105////////:config FEATURE_IFUPDOWN_IPX
106////////: bool "Support for IPX"
107////////: default y
108////////: depends on IFUP || IFDOWN
109////////: help
110////////: If this option is selected you can use busybox to work with IPX
111////////: networks.
112//config:
113//config:config FEATURE_IFUPDOWN_MAPPING
114//config: bool "Enable mapping support"
115//config: default y
116//config: depends on IFUP || IFDOWN
117//config: help
118//config: This enables support for the "mapping" stanza, unless you have
119//config: a weird network setup you don't need it.
120//config:
121//config:config FEATURE_IFUPDOWN_EXTERNAL_DHCP
122//config: bool "Support for external dhcp clients"
123//config: default n
124//config: depends on IFUP || IFDOWN
125//config: help
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.
130
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))
133
134//kbuild:lib-$(CONFIG_IFUP) += ifupdown.o
135//kbuild:lib-$(CONFIG_IFDOWN) += ifupdown.o
136
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"
146//usage: )
147//usage: "\n -v Print out what would happen before doing it"
148//usage: "\n -f Force configuration"
149//usage:
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"
159//usage: )
160//usage: "\n -v Print out what would happen before doing it"
161//usage: "\n -f Force deconfiguration"
162
163#include "libbb.h"
164#include "common_bufsiz.h"
165/* After libbb.h, since it needs sys/types.h on some systems */
166#include <sys/utsname.h>
167#include <fnmatch.h>
168
169#define MAX_OPT_DEPTH 10
170
171#if ENABLE_FEATURE_IFUPDOWN_MAPPING
172#define MAX_INTERFACE_LENGTH 10
173#endif
174
175#define UDHCPC_CMD_OPTIONS CONFIG_IFUPDOWN_UDHCPC_CMD_OPTIONS
176#define IFSTATE_FILE_PATH CONFIG_IFUPDOWN_IFSTATE_PATH
177
178#define debug_noise(args...) /*fprintf(stderr, args)*/
179
180/* Forward declaration */
181struct interface_defn_t;
182
183typedef int execfn(char *command);
184
185struct method_t {
186 const char *name;
187 int (*up)(struct interface_defn_t *ifd, execfn *e) FAST_FUNC;
188 int (*down)(struct interface_defn_t *ifd, execfn *e) FAST_FUNC;
189};
190
191struct address_family_t {
192 const char *name;
193 int n_methods;
194 const struct method_t *method;
195};
196
197struct mapping_defn_t {
198 struct mapping_defn_t *next;
199
200 int max_matches;
201 int n_matches;
202 char **match;
203
204 char *script;
205
206 int n_mappings;
207 char **mapping;
208};
209
210struct variable_t {
211 char *name;
212 char *value;
213};
214
215struct interface_defn_t {
216 const struct address_family_t *address_family;
217 const struct method_t *method;
218
219 char *iface;
220 int n_options;
221 struct variable_t *option;
222};
223
224struct interfaces_file_t {
225 llist_t *autointerfaces;
226 llist_t *ifaces;
227 struct mapping_defn_t *mappings;
228};
229
230
231#define OPTION_STR "anvf" IF_FEATURE_IFUPDOWN_MAPPING("m") "i:"
232enum {
233 OPT_do_all = 0x1,
234 OPT_no_act = 0x2,
235 OPT_verbose = 0x4,
236 OPT_force = 0x8,
237 OPT_no_mappings = 0x10,
238};
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)
244
245
246struct globals {
247 char **my_environ;
248 const char *startup_PATH;
249 char *shell;
250} FIX_ALIASING;
251#define G (*(struct globals*)bb_common_bufsiz1)
252#define INIT_G() do { setup_common_bufsiz(); } while (0)
253
254
255static const char keywords_up_down[] ALIGN1 =
256 "up\0"
257 "down\0"
258 "pre-up\0"
259 "post-down\0"
260;
261
262
263#if ENABLE_FEATURE_IFUPDOWN_IPV4 || ENABLE_FEATURE_IFUPDOWN_IPV6
264
265static void addstr(char **bufp, const char *str, size_t str_length)
266{
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! */
270 char *buf = *bufp;
271 int len = (buf ? strlen(buf) : 0);
272 str_length++;
273 buf = xrealloc(buf, len + str_length);
274 /* copies at most str_length-1 chars! */
275 safe_strncpy(buf + len, str, str_length);
276 *bufp = buf;
277}
278
279static int strncmpz(const char *l, const char *r, size_t llen)
280{
281 int i = strncmp(l, r, llen);
282
283 if (i == 0)
284 return - (unsigned char)r[llen];
285 return i;
286}
287
288static char *get_var(const char *id, size_t idlen, struct interface_defn_t *ifd)
289{
290 int i;
291
292 if (strncmpz(id, "iface", idlen) == 0) {
293 // ubuntu's ifup doesn't do this:
294 //static char *label_buf;
295 //char *result;
296 //free(label_buf);
297 //label_buf = xstrdup(ifd->iface);
298 // Remove virtual iface suffix
299 //result = strchrnul(label_buf, ':');
300 //*result = '\0';
301 //return label_buf;
302
303 return ifd->iface;
304 }
305 if (strncmpz(id, "label", idlen) == 0) {
306 return ifd->iface;
307 }
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;
311 }
312 }
313 return NULL;
314}
315
316# if ENABLE_FEATURE_IFUPDOWN_IP
317static int count_netmask_bits(const char *dotted_quad)
318{
319// int result;
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)
323// return -1;
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 */
328
329 /* Shorter version */
330 int result;
331 struct in_addr ip;
332 unsigned d;
333
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 */
340 result = 32;
341 while (d) {
342 d >>= 1;
343 result--;
344 }
345 return result;
346}
347# endif
348
349static char *parse(const char *command, struct interface_defn_t *ifd)
350{
351 size_t old_pos[MAX_OPT_DEPTH] = { 0 };
352 smallint okay[MAX_OPT_DEPTH] = { 1 };
353 int opt_depth = 1;
354 char *result = NULL;
355
356 while (*command) {
357 switch (*command) {
358 default:
359 addstr(&result, command, 1);
360 command++;
361 break;
362 case '\\':
363 if (command[1])
364 command++;
365 addstr(&result, command, 1);
366 command++;
367 break;
368 case '[':
369 if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
370 old_pos[opt_depth] = result ? strlen(result) : 0;
371 okay[opt_depth] = 1;
372 opt_depth++;
373 command += 2;
374 } else {
375 addstr(&result, command, 1);
376 command++;
377 }
378 break;
379 case ']':
380 if (command[1] == ']' && opt_depth > 1) {
381 opt_depth--;
382 if (!okay[opt_depth]) {
383 result[old_pos[opt_depth]] = '\0';
384 }
385 command += 2;
386 } else {
387 addstr(&result, command, 1);
388 command++;
389 }
390 break;
391 case '%':
392 {
393 char *nextpercent;
394 char *varvalue;
395
396 command++;
397 nextpercent = strchr(command, '%');
398 if (!nextpercent) {
399 /* Unterminated %var% */
400 free(result);
401 return NULL;
402 }
403
404 varvalue = get_var(command, nextpercent - command, ifd);
405
406 if (varvalue) {
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));
413 }
414# endif
415 addstr(&result, varvalue, strlen(varvalue));
416 } else {
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")) {
421 unsigned res;
422 varvalue = get_var("netmask", 7, ifd);
423 if (varvalue) {
424 res = count_netmask_bits(varvalue);
425 if (res > 0) {
426 const char *argument = utoa(res);
427 addstr(&result, argument, strlen(argument));
428 command = nextpercent + 1;
429 break;
430 }
431 }
432 }
433# endif
434 okay[opt_depth - 1] = 0;
435 }
436
437 command = nextpercent + 1;
438 }
439 break;
440 }
441 }
442
443 if (opt_depth > 1) {
444 /* Unbalanced bracket */
445 free(result);
446 return NULL;
447 }
448
449 if (!okay[0]) {
450 /* Undefined variable and we aren't in a bracket */
451 free(result);
452 return NULL;
453 }
454
455 return result;
456}
457
458/* execute() returns 1 for success and 0 for failure */
459static int execute(const char *command, struct interface_defn_t *ifd, execfn *exec)
460{
461 char *out;
462 int ret;
463
464 out = parse(command, ifd);
465 if (!out) {
466 /* parse error? */
467 return 0;
468 }
469 /* out == "": parsed ok but not all needed variables known, skip */
470 ret = out[0] ? (*exec)(out) : 1;
471
472 free(out);
473 if (ret != 1) {
474 return 0;
475 }
476 return 1;
477}
478
479#endif /* FEATURE_IFUPDOWN_IPV4 || FEATURE_IFUPDOWN_IPV6 */
480
481
482#if ENABLE_FEATURE_IFUPDOWN_IPV6
483
484static int FAST_FUNC loopback_up6(struct interface_defn_t *ifd, execfn *exec)
485{
486# if ENABLE_FEATURE_IFUPDOWN_IP
487 int result;
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);
491# else
492 return execute("ifconfig %iface% add ::1", ifd, exec);
493# endif
494}
495
496static int FAST_FUNC loopback_down6(struct interface_defn_t *ifd, execfn *exec)
497{
498# if ENABLE_FEATURE_IFUPDOWN_IP
499 return execute("ip link set %iface% down", ifd, exec);
500# else
501 return execute("ifconfig %iface% del ::1", ifd, exec);
502# endif
503}
504
505static int FAST_FUNC manual_up_down6(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
506{
507 return 1;
508}
509
510static int FAST_FUNC static_up6(struct interface_defn_t *ifd, execfn *exec)
511{
512 int result;
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);
518# else
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);
522# endif
523 return ((result == 3) ? 3 : 0);
524}
525
526static int FAST_FUNC static_down6(struct interface_defn_t *ifd, execfn *exec)
527{
528# if ENABLE_FEATURE_IFUPDOWN_IP
529 return execute("ip link set %iface% down", ifd, exec);
530# else
531 return execute("ifconfig %iface% down", ifd, exec);
532# endif
533}
534
535# if ENABLE_FEATURE_IFUPDOWN_IP
536static int FAST_FUNC v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
537{
538 int result;
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);
546}
547
548static int FAST_FUNC v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
549{
550 return execute("ip tunnel del %iface%", ifd, exec);
551}
552# endif
553
554static const struct method_t methods6[] = {
555# if ENABLE_FEATURE_IFUPDOWN_IP
556 { "v4tunnel" , v4tunnel_up , v4tunnel_down , },
557# endif
558 { "static" , static_up6 , static_down6 , },
559 { "manual" , manual_up_down6 , manual_up_down6 , },
560 { "loopback" , loopback_up6 , loopback_down6 , },
561};
562
563static const struct address_family_t addr_inet6 = {
564 "inet6",
565 ARRAY_SIZE(methods6),
566 methods6
567};
568
569#endif /* FEATURE_IFUPDOWN_IPV6 */
570
571
572#if ENABLE_FEATURE_IFUPDOWN_IPV4
573
574static int FAST_FUNC loopback_up(struct interface_defn_t *ifd, execfn *exec)
575{
576# if ENABLE_FEATURE_IFUPDOWN_IP
577 int result;
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);
581# else
582 return execute("ifconfig %iface% 127.0.0.1 up", ifd, exec);
583# endif
584}
585
586static int FAST_FUNC loopback_down(struct interface_defn_t *ifd, execfn *exec)
587{
588# if ENABLE_FEATURE_IFUPDOWN_IP
589 int result;
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);
593# else
594 return execute("ifconfig %iface% 127.0.0.1 down", ifd, exec);
595# endif
596}
597
598static int FAST_FUNC static_up(struct interface_defn_t *ifd, execfn *exec)
599{
600 int result;
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);
607# else
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",
611 ifd, exec);
612 result += execute("ifconfig %iface% %address% netmask %netmask%"
613 "[[ broadcast %broadcast%]][[ pointopoint %pointopoint%]]",
614 ifd, exec);
615 result += execute("[[route add default gw %gateway%[[ metric %metric%]] %iface%]]", ifd, exec);
616 return ((result == 3) ? 3 : 0);
617# endif
618}
619
620static int FAST_FUNC static_down(struct interface_defn_t *ifd, execfn *exec)
621{
622 int result;
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.
626 */
627 result = execute("ip addr flush dev %iface%[[ label %label%]]", ifd, exec);
628 result += execute("ip link set %iface% down", ifd, exec);
629# else
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 */
633 result = 1;
634 result += execute("ifconfig %iface% down", ifd, exec);
635# endif
636 return ((result == 2) ? 2 : 0);
637}
638
639# if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
640struct dhcp_client_t {
641 const char *name;
642 const char *startcmd;
643 const char *stopcmd;
644};
645
646static const struct dhcp_client_t ext_dhcp_clients[] = {
647 { "dhcpcd",
648 "dhcpcd[[ -h %hostname%]][[ -i %vendor%]][[ -I %client%]][[ -l %leasetime%]] %iface%",
649 "dhcpcd -k %iface%",
650 },
651 { "dhclient",
652 "dhclient -pf /var/run/dhclient.%iface%.pid %iface%",
653 "kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null",
654 },
655 { "pump",
656 "pump -i %iface%[[ -h %hostname%]][[ -l %leasehours%]]",
657 "pump -i %iface% -k",
658 },
659 { "udhcpc",
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",
663 },
664};
665# endif /* FEATURE_IFUPDOWN_EXTERNAL_DHCPC */
666
667# if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
668static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
669{
670 unsigned i;
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))
674 return 0;
675# else
676 /* needed if we have hwaddress on dhcp iface */
677 if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
678 return 0;
679# endif
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);
683 }
684 bb_error_msg("no dhcp clients found");
685 return 0;
686}
687# elif ENABLE_UDHCPC
688static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd, execfn *exec)
689{
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))
693 return 0;
694# else
695 /* needed if we have hwaddress on dhcp iface */
696 if (!execute("ifconfig %iface%[[ hw %hwaddress%]] up", ifd, exec))
697 return 0;
698# endif
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%]]",
701 ifd, exec);
702}
703# else
704static int FAST_FUNC dhcp_up(struct interface_defn_t *ifd UNUSED_PARAM,
705 execfn *exec UNUSED_PARAM)
706{
707 return 0; /* no dhcp support */
708}
709# endif
710
711# if ENABLE_FEATURE_IFUPDOWN_EXTERNAL_DHCP
712static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
713{
714 int result = 0;
715 unsigned i;
716
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);
720 if (result)
721 break;
722 }
723 }
724
725 if (!result)
726 bb_error_msg("warning: no dhcp clients found and stopped");
727
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 */
730 usleep(100000);
731 result += static_down(ifd, exec);
732 return ((result == 3) ? 3 : 0);
733}
734# elif ENABLE_UDHCPC
735static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd, execfn *exec)
736{
737 int result;
738 result = execute(
739 "test -f /var/run/udhcpc.%iface%.pid && "
740 "kill `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null",
741 ifd, exec);
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 */
747 usleep(100000);
748 result += static_down(ifd, exec);
749 return ((result == 3) ? 3 : 0);
750}
751# else
752static int FAST_FUNC dhcp_down(struct interface_defn_t *ifd UNUSED_PARAM,
753 execfn *exec UNUSED_PARAM)
754{
755 return 0; /* no dhcp support */
756}
757# endif
758
759static int FAST_FUNC manual_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
760{
761 return 1;
762}
763
764static int FAST_FUNC bootp_up(struct interface_defn_t *ifd, execfn *exec)
765{
766 return execute("bootpc[[ --bootfile %bootfile%]] --dev %iface%"
767 "[[ --server %server%]][[ --hwaddr %hwaddr%]]"
768 " --returniffail --serverbcast", ifd, exec);
769}
770
771static int FAST_FUNC ppp_up(struct interface_defn_t *ifd, execfn *exec)
772{
773 return execute("pon[[ %provider%]]", ifd, exec);
774}
775
776static int FAST_FUNC ppp_down(struct interface_defn_t *ifd, execfn *exec)
777{
778 return execute("poff[[ %provider%]]", ifd, exec);
779}
780
781static int FAST_FUNC wvdial_up(struct interface_defn_t *ifd, execfn *exec)
782{
783 return execute("start-stop-daemon --start -x wvdial "
784 "-p /var/run/wvdial.%iface% -b -m --[[ %provider%]]", ifd, exec);
785}
786
787static int FAST_FUNC wvdial_down(struct interface_defn_t *ifd, execfn *exec)
788{
789 return execute("start-stop-daemon --stop -x wvdial "
790 "-p /var/run/wvdial.%iface% -s 2", ifd, exec);
791}
792
793static 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 , },
801};
802
803static const struct address_family_t addr_inet = {
804 "inet",
805 ARRAY_SIZE(methods),
806 methods
807};
808
809#endif /* FEATURE_IFUPDOWN_IPV4 */
810
811static int FAST_FUNC link_up_down(struct interface_defn_t *ifd UNUSED_PARAM, execfn *exec UNUSED_PARAM)
812{
813 return 1;
814}
815
816static const struct method_t link_methods[] = {
817 { "none", link_up_down, link_up_down }
818};
819
820static const struct address_family_t addr_link = {
821 "link", ARRAY_SIZE(link_methods), link_methods
822};
823
824/* Returns pointer to the next word, or NULL.
825 * In 1st case, advances *buf to the word after this one.
826 */
827static char *next_word(char **buf)
828{
829 unsigned length;
830 char *word;
831
832 /* Skip over leading whitespace */
833 word = skip_whitespace(*buf);
834
835 /* Stop on EOL */
836 if (*word == '\0')
837 return NULL;
838
839 /* Find the length of this word (can't be 0) */
840 length = strcspn(word, " \t\n");
841
842 /* Unless we are already at NUL, store NUL and advance */
843 if (word[length] != '\0')
844 word[length++] = '\0';
845
846 *buf = skip_whitespace(word + length);
847
848 return word;
849}
850
851static const struct address_family_t *get_address_family(const struct address_family_t *const af[], char *name)
852{
853 int i;
854
855 if (!name)
856 return NULL;
857
858 for (i = 0; af[i]; i++) {
859 if (strcmp(af[i]->name, name) == 0) {
860 return af[i];
861 }
862 }
863 return NULL;
864}
865
866static const struct method_t *get_method(const struct address_family_t *af, char *name)
867{
868 int i;
869
870 if (!name)
871 return NULL;
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];
876 }
877 }
878 return NULL;
879}
880
881static struct interfaces_file_t *read_interfaces(const char *filename, struct interfaces_file_t *defn)
882{
883 /* Let's try to be compatible.
884 *
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.
890 *
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.
896 *
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.
900 */
901#if ENABLE_FEATURE_IFUPDOWN_MAPPING
902 struct mapping_defn_t *currmap = NULL;
903#endif
904 struct interface_defn_t *currif = NULL;
905 FILE *f;
906 char *buf;
907 char *first_word;
908 char *rest_of_line;
909 enum { NONE, IFACE, MAPPING } currently_processing = NONE;
910
911 if (!defn)
912 defn = xzalloc(sizeof(*defn));
913
914 debug_noise("reading %s file:\n", filename);
915 f = xfopen_for_read(filename);
916
917 while ((buf = xmalloc_fgetline(f)) != NULL) {
918#if ENABLE_DESKTOP
919 /* Trailing "\" concatenates lines */
920 char *p;
921 while ((p = last_char_is(buf, '\\')) != NULL) {
922 *p = '\0';
923 rest_of_line = xmalloc_fgetline(f);
924 if (!rest_of_line)
925 break;
926 p = xasprintf("%s%s", buf, rest_of_line);
927 free(buf);
928 free(rest_of_line);
929 buf = p;
930 }
931#endif
932 rest_of_line = buf;
933 first_word = next_word(&rest_of_line);
934 if (!first_word || *first_word == '#') {
935 free(buf);
936 continue; /* blank/comment line */
937 }
938
939 if (strcmp(first_word, "mapping") == 0) {
940#if ENABLE_FEATURE_IFUPDOWN_MAPPING
941 currmap = xzalloc(sizeof(*currmap));
942
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);
946 }
947 /*currmap->n_mappings = 0;*/
948 /*currmap->mapping = NULL;*/
949 /*currmap->script = NULL;*/
950 {
951 struct mapping_defn_t **where = &defn->mappings;
952 while (*where != NULL) {
953 where = &(*where)->next;
954 }
955 *where = currmap;
956 /*currmap->next = NULL;*/
957 }
958 debug_noise("Added mapping\n");
959#endif
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
964 &addr_inet,
965#endif
966#if ENABLE_FEATURE_IFUPDOWN_IPV6
967 &addr_inet6,
968#endif
969 &addr_link,
970 NULL
971 };
972 char *iface_name;
973 char *address_family_name;
974 char *method_name;
975
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);
980
981 if (method_name == NULL)
982 bb_error_msg_and_die("too few parameters for line \"%s\"", buf);
983
984 /* ship any trailing whitespace */
985 rest_of_line = skip_whitespace(rest_of_line);
986
987 if (rest_of_line[0] != '\0' /* && rest_of_line[0] != '#' */)
988 bb_error_msg_and_die("too many parameters \"%s\"", buf);
989
990 currif->iface = xstrdup(iface_name);
991
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);
995
996 currif->method = get_method(currif->address_family, method_name);
997 if (!currif->method)
998 bb_error_msg_and_die("unknown method \"%s\"", method_name);
999#if 0
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
1005//
1006// iface eth0 inet static
1007// address 10.0.0.1
1008// netmask 255.255.255.0
1009//
1010// This adds *two* addresses to eth0 (probably requires use of "ip", not "ifconfig"
1011//
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)
1017 ) {
1018 bb_error_msg_and_die("duplicate interface \"%s\"", tmp->iface);
1019 }
1020 }
1021#endif
1022 llist_add_to_end(&(defn->ifaces), (char*)currif);
1023
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) {
1028
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);
1032 }
1033
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);
1037 }
1038 currently_processing = NONE;
1039 } else if (strcmp(first_word, "source") == 0) {
1040 read_interfaces(next_word(&rest_of_line), defn);
1041 } else {
1042 switch (currently_processing) {
1043 case IFACE:
1044 if (rest_of_line[0] == '\0')
1045 bb_error_msg_and_die("option with empty value \"%s\"", buf);
1046
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" */
1051
1052 /* If not one of "up", "down",... words... */
1053 if (index_in_strings(keywords_up_down, first_word) < 0) {
1054 int i;
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);
1058 }
1059 }
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++;
1065 break;
1066 case MAPPING:
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++;
1076 } else {
1077 bb_error_msg_and_die("misplaced option \"%s\"", buf);
1078 }
1079#endif
1080 break;
1081 case NONE:
1082 default:
1083 bb_error_msg_and_die("misplaced option \"%s\"", buf);
1084 }
1085 }
1086 free(buf);
1087 } /* while (fgets) */
1088
1089 if (ferror(f) != 0) {
1090 /* ferror does NOT set errno! */
1091 bb_error_msg_and_die("%s: I/O error", filename);
1092 }
1093 fclose(f);
1094 debug_noise("\ndone reading %s\n\n", filename);
1095
1096 return defn;
1097}
1098
1099static char *setlocalenv(const char *format, const char *name, const char *value)
1100{
1101 char *result;
1102 char *dst;
1103 char *src;
1104 char c;
1105
1106 result = xasprintf(format, name, value);
1107
1108 for (dst = src = result; (c = *src) != '=' && c; src++) {
1109 if (c == '-')
1110 c = '_';
1111 if (c >= 'a' && c <= 'z')
1112 c -= ('a' - 'A');
1113 if (isalnum(c) || c == '_')
1114 *dst++ = c;
1115 }
1116 overlapping_strcpy(dst, src);
1117
1118 return result;
1119}
1120
1121static void set_environ(struct interface_defn_t *iface, const char *mode, const char *opt)
1122{
1123 int i;
1124 char **pp;
1125
1126 if (G.my_environ != NULL) {
1127 for (pp = G.my_environ; *pp; pp++) {
1128 free(*pp);
1129 }
1130 free(G.my_environ);
1131 }
1132
1133 /* note: last element will stay NULL: */
1134 G.my_environ = xzalloc(sizeof(char *) * (iface->n_options + 7));
1135 pp = G.my_environ;
1136
1137 for (i = 0; i < iface->n_options; i++) {
1138 if (index_in_strings(keywords_up_down, iface->option[i].name) >= 0) {
1139 continue;
1140 }
1141 *pp++ = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
1142 }
1143
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);
1149 if (G.startup_PATH)
1150 *pp++ = setlocalenv("%s=%s", "PATH", G.startup_PATH);
1151}
1152
1153static int doit(char *str)
1154{
1155 if (option_mask32 & (OPT_no_act|OPT_verbose)) {
1156 puts(str);
1157 }
1158 if (!(option_mask32 & OPT_no_act)) {
1159 pid_t child;
1160 int status;
1161
1162 fflush_all();
1163 child = vfork();
1164 if (child < 0) /* failure */
1165 return 0;
1166 if (child == 0) { /* child */
1167 execle(G.shell, G.shell, "-c", str, (char *) NULL, G.my_environ);
1168 _exit(127);
1169 }
1170 safe_waitpid(child, &status, 0);
1171 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1172 return 0;
1173 }
1174 }
1175 return 1;
1176}
1177
1178static int execute_all(struct interface_defn_t *ifd, const char *opt)
1179{
1180 int i;
1181 char *buf;
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)) {
1185 return 0;
1186 }
1187 }
1188 }
1189
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).
1194 */
1195 buf = xasprintf("run-parts /etc/network/if-%s.d", opt);
1196 /* heh, we don't bother free'ing it */
1197 return doit(buf);
1198}
1199
1200static int check(char *str)
1201{
1202 return str != NULL;
1203}
1204
1205static int iface_up(struct interface_defn_t *iface)
1206{
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;
1214}
1215
1216static int iface_down(struct interface_defn_t *iface)
1217{
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;
1225}
1226
1227#if ENABLE_FEATURE_IFUPDOWN_MAPPING
1228static int popen2(FILE **in, FILE **out, char *command, char *param)
1229{
1230 char *argv[3] = { command, param, NULL };
1231 struct fd_pair infd, outfd;
1232 pid_t pid;
1233
1234 xpiped_pair(infd);
1235 xpiped_pair(outfd);
1236
1237 fflush_all();
1238 pid = xvfork();
1239
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);
1248 }
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;
1255}
1256
1257static char *run_mapping(char *physical, struct mapping_defn_t *map)
1258{
1259 FILE *in, *out;
1260 int i, status;
1261 pid_t pid;
1262
1263 char *logical = xstrdup(physical);
1264
1265 /* Run the mapping script. Never fails. */
1266 pid = popen2(&in, &out, map->script, physical);
1267
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]);
1271 }
1272 fclose(in);
1273 safe_waitpid(pid, &status, 0);
1274
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);
1280
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;
1286
1287 while (pch >= new_logical && isspace(*pch))
1288 *(pch--) = '\0';
1289
1290 free(logical);
1291 logical = new_logical;
1292 }
1293 }
1294
1295 fclose(out);
1296
1297 return logical;
1298}
1299#endif /* FEATURE_IFUPDOWN_MAPPING */
1300
1301static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1302{
1303 llist_t *search = state_list;
1304
1305 while (search) {
1306 char *after_iface = is_prefixed_with(search->data, iface);
1307 if (after_iface
1308 && *after_iface == '='
1309 ) {
1310 return search;
1311 }
1312 search = search->link;
1313 }
1314 return NULL;
1315}
1316
1317/* read the previous state from the state file */
1318static llist_t *read_iface_state(void)
1319{
1320 llist_t *state_list = NULL;
1321 FILE *state_fp = fopen_for_read(IFSTATE_FILE_PATH);
1322
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);
1330 }
1331 fclose(state_fp);
1332 }
1333 return state_list;
1334}
1335
1336/* read the previous state from the state file */
1337static FILE *open_new_state_file(void)
1338{
1339 int fd, flags, cnt;
1340
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)
1349 ) {
1350 bb_perror_msg_and_die("can't open '%s'",
1351 IFSTATE_FILE_PATH".new");
1352 }
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.
1357 */
1358 flags = (O_WRONLY | O_CREAT | O_TRUNC);
1359 continue;
1360 }
1361 usleep(cnt);
1362 cnt += 1000;
1363 }
1364
1365 return xfdopen_for_write(fd);
1366}
1367
1368int ifupdown_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1369int ifupdown_main(int argc UNUSED_PARAM, char **argv)
1370{
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;
1376
1377 INIT_G();
1378
1379 G.startup_PATH = getenv("PATH");
1380 G.shell = xstrdup(get_shell_name());
1381
1382 if (ENABLE_IFUP
1383 && (!ENABLE_IFDOWN || applet_name[2] == 'u')
1384 ) {
1385 /* ifup command */
1386 cmds = iface_up;
1387 } else {
1388 cmds = iface_down;
1389 }
1390
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();
1397 }
1398
1399 defn = read_interfaces(interfaces, NULL);
1400
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]);
1406 }
1407
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;
1418
1419 iface = xstrdup(target_list->data);
1420 target_list = target_list->link;
1421
1422 pch = strchr(iface, '=');
1423 if (pch) {
1424 *pch = '\0';
1425 liface = xstrdup(pch + 1);
1426 } else {
1427 liface = xstrdup(iface);
1428 }
1429
1430 if (!FORCE) {
1431 llist_t *state_list = read_iface_state();
1432 const llist_t *iface_state = find_iface_state(state_list, iface);
1433
1434 if (cmds == iface_up) {
1435 /* ifup */
1436 if (iface_state) {
1437 bb_error_msg("interface %s already configured", iface);
1438 goto next;
1439 }
1440 } else {
1441 /* ifdown */
1442 if (!iface_state) {
1443 bb_error_msg("interface %s not configured", iface);
1444 goto next;
1445 }
1446 }
1447 llist_free(state_list, free);
1448 }
1449
1450#if ENABLE_FEATURE_IFUPDOWN_MAPPING
1451 if ((cmds == iface_up) && !NO_MAPPINGS) {
1452 struct mapping_defn_t *currmap;
1453
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);
1461 }
1462 liface = run_mapping(iface, currmap);
1463 break;
1464 }
1465 }
1466 }
1467#endif
1468
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;
1474
1475 okay = 1;
1476 currif->iface = iface;
1477
1478 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1479
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;
1488 }
1489
1490 currif->iface = oldiface;
1491 }
1492 iface_list = iface_list->link;
1493 }
1494 if (VERBOSE) {
1495 bb_putchar('\n');
1496 }
1497
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);
1507
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;
1515 }
1516 } else {
1517 /* Remove an interface from state_list */
1518 llist_unlink(&state_list, iface_state);
1519 free(llist_pop(&iface_state));
1520 }
1521
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);
1527 }
1528 state = state->link;
1529 }
1530 fclose(new_state_fp);
1531 xrename(IFSTATE_FILE_PATH".new", IFSTATE_FILE_PATH);
1532 llist_free(state_list, free);
1533 }
1534 next:
1535 free(iface);
1536 free(liface);
1537 }
1538
1539 return any_failures;
1540}
1541