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