Patch from Bernhard Fischer to make a bunch of symbols static
[oweals/busybox.git] / networking / ifupdown.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *  ifupdown for busybox
4  *  Copyright (c) 2002 Glenn McGrath <bug1@iinet.net.au>
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  *
15  *  This program is free software; you can redistribute it and/or modify
16  *  it under the terms of the GNU General Public License as published by
17  *  the Free Software Foundation; either version 2 of the License, or
18  *  (at your option) any later version.
19  *
20  *  This program is distributed in the hope that it will be useful,
21  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  *  GNU General Public License for more details.
24  *
25  *  You should have received a copy of the GNU General Public License
26  *  along with this program; if not, write to the Free Software
27  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28  */
29
30 /* TODO: standardise execute() return codes to return 0 for success and 1 for failure */
31
32 #include <sys/stat.h>
33 #include <sys/utsname.h>
34 #include <sys/wait.h>
35
36 #include <ctype.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <fnmatch.h>
40 #include <getopt.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46
47 #include "libbb.h"
48
49 #define MAX_OPT_DEPTH 10
50 #define EUNBALBRACK 10001
51 #define EUNDEFVAR   10002
52 #define EUNBALPER   10000
53
54 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
55 #define MAX_INTERFACE_LENGTH 10
56 #endif
57
58 #if 0
59 #define debug_noise(fmt, args...) printf(fmt, ## args)
60 #else
61 #define debug_noise(fmt, args...)
62 #endif
63
64 /* Forward declaration */
65 struct interface_defn_t;
66
67 typedef int (execfn)(char *command);
68 typedef int (command_set)(struct interface_defn_t *ifd, execfn *e);
69
70 extern llist_t *llist_add_to_end(llist_t *list_head, char *data)
71 {
72         llist_t *new_item, *tmp, *prev;
73
74         new_item = xmalloc(sizeof(llist_t));
75         new_item->data = data;
76         new_item->link = NULL;
77
78         prev = NULL;
79         tmp = list_head;
80         while(tmp) {
81                 prev = tmp;
82                 tmp = tmp->link;
83         }
84         if (prev) {
85                 prev->link = new_item;
86         } else {
87                 list_head = new_item;
88         }
89
90         return(list_head);
91 }
92
93 struct method_t
94 {
95         char *name;
96         command_set *up;
97         command_set *down;
98 };
99
100 struct address_family_t
101 {
102         char *name;
103         int n_methods;
104         struct method_t *method;
105 };
106
107 struct mapping_defn_t
108 {
109         struct mapping_defn_t *next;
110
111         int max_matches;
112         int n_matches;
113         char **match;
114
115         char *script;
116
117         int max_mappings;
118         int n_mappings;
119         char **mapping;
120 };
121
122 struct variable_t
123 {
124         char *name;
125         char *value;
126 };
127
128 struct interface_defn_t
129 {
130         struct interface_defn_t *prev;
131         struct interface_defn_t *next;
132
133         char *iface;
134         struct address_family_t *address_family;
135         struct method_t *method;
136
137         int automatic;
138
139         int max_options;
140         int n_options;
141         struct variable_t *option;
142 };
143
144 struct interfaces_file_t
145 {
146         llist_t *autointerfaces;
147         llist_t *ifaces;
148         struct mapping_defn_t *mappings;
149 };
150
151 static char no_act = 0;
152 static char verbose = 0;
153 #ifndef __USE_GNU
154 static char **environ = NULL;
155 #endif
156
157 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
158
159 static unsigned int count_bits(unsigned int a)
160 {
161         unsigned int result;
162         result = (a & 0x55) + ((a >> 1) & 0x55);
163         result = (result & 0x33) + ((result >> 2) & 0x33);
164         return((result & 0x0F) + ((result >> 4) & 0x0F));
165 }
166
167 static int count_netmask_bits(char *dotted_quad)
168 {
169         unsigned int result, a, b, c, d;
170         /* Found a netmask...  Check if it is dotted quad */
171         if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
172                 return -1;
173         result = count_bits(a);
174         result += count_bits(b);
175         result += count_bits(c);
176         result += count_bits(d);
177         return ((int)result);
178 }
179 #endif
180
181 static void addstr(char **buf, size_t *len, size_t *pos, char *str, size_t str_length)
182 {
183         if (*pos + str_length >= *len) {
184                 char *newbuf;
185
186                 newbuf = xrealloc(*buf, *len * 2 + str_length + 1);
187                 *buf = newbuf;
188                 *len = *len * 2 + str_length + 1;
189         }
190
191         while (str_length-- >= 1) {
192                 (*buf)[(*pos)++] = *str;
193                 str++;
194         }
195         (*buf)[*pos] = '\0';
196 }
197
198 static int strncmpz(char *l, char *r, size_t llen)
199 {
200         int i = strncmp(l, r, llen);
201
202         if (i == 0) {
203                 return(-r[llen]);
204         } else {
205                 return(i);
206         }
207 }
208
209 static char *get_var(char *id, size_t idlen, struct interface_defn_t *ifd)
210 {
211         int i;
212
213         if (strncmpz(id, "iface", idlen) == 0) {
214                 char *result;
215                 static char label_buf[20];
216                 strncpy(label_buf, ifd->iface, 19);
217                 label_buf[19]=0;
218                 result = strchr(label_buf, ':');
219                 if (result) {
220                         *result=0;
221                 }
222                 return( label_buf);
223         } else if (strncmpz(id, "label", idlen) == 0) {
224                 return (ifd->iface);
225         } else {
226                 for (i = 0; i < ifd->n_options; i++) {
227                         if (strncmpz(id, ifd->option[i].name, idlen) == 0) {
228                                 return (ifd->option[i].value);
229                         }
230                 }
231         }
232
233         return(NULL);
234 }
235
236 static char *parse(char *command, struct interface_defn_t *ifd)
237 {
238
239         char *result = NULL;
240         size_t pos = 0, len = 0;
241         size_t old_pos[MAX_OPT_DEPTH] = { 0 };
242         int okay[MAX_OPT_DEPTH] = { 1 };
243         int opt_depth = 1;
244
245         while (*command) {
246                 switch (*command) {
247
248                         default:
249                                 addstr(&result, &len, &pos, command, 1);
250                                 command++;
251                                 break;
252                         case '\\':
253                                 if (command[1]) {
254                                         addstr(&result, &len, &pos, command + 1, 1);
255                                         command += 2;
256                                 } else {
257                                         addstr(&result, &len, &pos, command, 1);
258                                         command++;
259                                 }
260                                 break;
261                         case '[':
262                                 if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
263                                         old_pos[opt_depth] = pos;
264                                         okay[opt_depth] = 1;
265                                         opt_depth++;
266                                         command += 2;
267                                 } else {
268                                         addstr(&result, &len, &pos, "[", 1);
269                                         command++;
270                                 }
271                                 break;
272                         case ']':
273                                 if (command[1] == ']' && opt_depth > 1) {
274                                         opt_depth--;
275                                         if (!okay[opt_depth]) {
276                                                 pos = old_pos[opt_depth];
277                                                 result[pos] = '\0';
278                                         }
279                                         command += 2;
280                                 } else {
281                                         addstr(&result, &len, &pos, "]", 1);
282                                         command++;
283                                 }
284                                 break;
285                         case '%':
286                                 {
287                                         char *nextpercent;
288                                         char *varvalue;
289
290                                         command++;
291                                         nextpercent = strchr(command, '%');
292                                         if (!nextpercent) {
293                                                 errno = EUNBALPER;
294                                                 free(result);
295                                                 return (NULL);
296                                         }
297
298                                         varvalue = get_var(command, nextpercent - command, ifd);
299
300                                         if (varvalue) {
301                                                 addstr(&result, &len, &pos, varvalue, bb_strlen(varvalue));
302                                         } else {
303 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
304                                                 /* Sigh...  Add a special case for 'ip' to convert from
305                                                  * dotted quad to bit count style netmasks.  */
306                                                 if (strncmp(command, "bnmask", 6)==0) {
307                                                         int res;
308                                                         varvalue = get_var("netmask", 7, ifd);
309                                                         if (varvalue && (res=count_netmask_bits(varvalue)) > 0) {
310                                                                 char argument[255];
311                                                                 sprintf(argument, "%d", res);
312                                                                 addstr(&result, &len, &pos, argument, bb_strlen(argument));
313                                                                 command = nextpercent + 1;
314                                                                 break;
315                                                         }
316                                                 }
317 #endif
318                                                 okay[opt_depth - 1] = 0;
319                                         }
320
321                                         command = nextpercent + 1;
322                                 }
323                                 break;
324                 }
325         }
326
327         if (opt_depth > 1) {
328                 errno = EUNBALBRACK;
329                 free(result);
330                 return(NULL);
331         }
332
333         if (!okay[0]) {
334                 errno = EUNDEFVAR;
335                 free(result);
336                 return(NULL);
337         }
338
339         return(result);
340 }
341
342 static int execute(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                 return(0);
350         }
351         ret = (*exec) (out);
352
353         free(out);
354         if (ret != 1) {
355                 return(0);
356         }
357         return(1);
358 }
359
360 #ifdef CONFIG_FEATURE_IFUPDOWN_IPX
361 static int static_up_ipx(struct interface_defn_t *ifd, execfn *exec)
362 {
363         return(execute("ipx_interface add %iface% %frame% %netnum%", ifd, exec));
364 }
365
366 static int static_down_ipx(struct interface_defn_t *ifd, execfn *exec)
367 {
368         return(execute("ipx_interface del %iface% %frame%", ifd, exec));
369 }
370
371 static int dynamic_up(struct interface_defn_t *ifd, execfn *exec)
372 {
373         return(execute("ipx_interface add %iface% %frame%", ifd, exec));
374 }
375
376 static int dynamic_down(struct interface_defn_t *ifd, execfn *exec)
377 {
378         return(execute("ipx_interface del %iface% %frame%", ifd, exec));
379 }
380
381 static struct method_t methods_ipx[] = {
382         { "dynamic", dynamic_up, dynamic_down, },
383         { "static", static_up_ipx, static_down_ipx, },
384 };
385
386 struct address_family_t addr_ipx = {
387         "ipx",
388         sizeof(methods_ipx) / sizeof(struct method_t),
389         methods_ipx
390 };
391 #endif /* IFUP_FEATURE_IPX */
392
393 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV6
394 static int loopback_up6(struct interface_defn_t *ifd, execfn *exec)
395 {
396 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
397         int result;
398         result =execute("ip addr add ::1 dev %iface%", ifd, exec);
399         result += execute("ip link set %iface% up", ifd, exec);
400         return ((result == 2) ? 2 : 0);
401 #else
402         return( execute("ifconfig %iface% add ::1", ifd, exec));
403 #endif
404 }
405
406 static int loopback_down6(struct interface_defn_t *ifd, execfn *exec)
407 {
408 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
409         return(execute("ip link set %iface% down", ifd, exec));
410 #else
411         return(execute("ifconfig %iface% del ::1", ifd, exec));
412 #endif
413 }
414
415 static int static_up6(struct interface_defn_t *ifd, execfn *exec)
416 {
417         int result;
418 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
419         result = execute("ip addr add %address%/%netmask% dev %iface% [[label %label%]]", ifd, exec);
420         result += execute("ip link set [[mtu %mtu%]] [[address %hwaddress%]] %iface% up", ifd, exec);
421         result += execute("[[ ip route add ::/0 via %gateway% ]]", ifd, exec);
422 #else
423         result = execute("ifconfig %iface% [[media %media%]] [[hw %hwaddress%]] [[mtu %mtu%]] up", ifd, exec);
424         result += execute("ifconfig %iface% add %address%/%netmask%", ifd, exec);
425         result += execute("[[ route -A inet6 add ::/0 gw %gateway% ]]", ifd, exec);
426 #endif
427         return ((result == 3) ? 3 : 0);
428 }
429
430 static int static_down6(struct interface_defn_t *ifd, execfn *exec)
431 {
432 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
433         return(execute("ip link set %iface% down", ifd, exec));
434 #else
435         return(execute("ifconfig %iface% down", ifd, exec));
436 #endif
437 }
438
439 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
440 static int v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
441 {
442         int result;
443         result = execute("ip tunnel add %iface% mode sit remote "
444                                 "%endpoint% [[local %local%]] [[ttl %ttl%]]", ifd, exec);
445         result += execute("ip link set %iface% up", ifd, exec);
446         result += execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec);
447         result += execute("[[ ip route add ::/0 via %gateway% ]]", ifd, exec);
448         return ((result == 4) ? 4 : 0);
449 }
450
451 static int v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
452 {
453         return( execute("ip tunnel del %iface%", ifd, exec));
454 }
455 #endif
456
457 static struct method_t methods6[] = {
458 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
459         { "v4tunnel", v4tunnel_up, v4tunnel_down, },
460 #endif
461         { "static", static_up6, static_down6, },
462         { "loopback", loopback_up6, loopback_down6, },
463 };
464
465 static struct address_family_t addr_inet6 = {
466         "inet6",
467         sizeof(methods6) / sizeof(struct method_t),
468         methods6
469 };
470 #endif /* CONFIG_FEATURE_IFUPDOWN_IPV6 */
471
472 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV4
473 static int loopback_up(struct interface_defn_t *ifd, execfn *exec)
474 {
475 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
476         int result;
477         result = execute("ip addr add 127.0.0.1/8 dev %iface%", ifd, exec);
478         result += execute("ip link set %iface% up", ifd, exec);
479         return ((result == 2) ? 2 : 0);
480 #else
481         return( execute("ifconfig %iface% 127.0.0.1 up", ifd, exec));
482 #endif
483 }
484
485 static int loopback_down(struct interface_defn_t *ifd, execfn *exec)
486 {
487 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
488         int result;
489         result = execute("ip addr flush dev %iface%", ifd, exec);
490         result += execute("ip link set %iface% down", ifd, exec);
491         return ((result == 2) ? 2 : 0);
492 #else
493         return( execute("ifconfig %iface% 127.0.0.1 down", ifd, exec));
494 #endif
495 }
496
497 static int static_up(struct interface_defn_t *ifd, execfn *exec)
498 {
499         int result;
500 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
501         result = execute("ip addr add %address%/%bnmask% [[broadcast %broadcast%]] "
502                         "dev %iface% [[peer %pointopoint%]] [[label %label%]]", ifd, exec);
503         result += execute("ip link set [[mtu %mtu%]] [[address %hwaddress%]] %iface% up", ifd, exec);
504         result += execute("[[ ip route add default via %gateway% dev %iface% ]]", ifd, exec);
505         return ((result == 3) ? 3 : 0);
506 #else
507         result = execute("ifconfig %iface% %address% netmask %netmask% "
508                                 "[[broadcast %broadcast%]]      [[pointopoint %pointopoint%]] "
509                                 "[[media %media%]] [[mtu %mtu%]]        [[hw %hwaddress%]] up",
510                                 ifd, exec);
511         result += execute("[[ route add default gw %gateway% %iface% ]]", ifd, exec);
512         return ((result == 2) ? 2 : 0);
513 #endif
514 }
515
516 static int static_down(struct interface_defn_t *ifd, execfn *exec)
517 {
518         int result;
519 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
520         result = execute("ip addr flush dev %iface%", ifd, exec);
521         result += execute("ip link set %iface% down", ifd, exec);
522 #else
523         result = execute("[[ route del default gw %gateway% %iface% ]]", ifd, exec);
524         result += execute("ifconfig %iface% down", ifd, exec);
525 #endif
526         return ((result == 2) ? 2 : 0);
527 }
528
529 static int execable(char *program)
530 {
531         struct stat buf;
532         if (0 == stat(program, &buf)) {
533                 if (S_ISREG(buf.st_mode) && (S_IXUSR & buf.st_mode)) {
534                         return(1);
535                 }
536         }
537         return(0);
538 }
539
540 static int dhcp_up(struct interface_defn_t *ifd, execfn *exec)
541 {
542         if (execable("/sbin/udhcpc")) {
543                 return( execute("udhcpc -n -p /var/run/udhcpc.%iface%.pid -i "
544                                         "%iface% [[-H %hostname%]] [[-c %clientid%]]", ifd, exec));
545         } else if (execable("/sbin/pump")) {
546                 return( execute("pump -i %iface% [[-h %hostname%]] [[-l %leasehours%]]", ifd, exec));
547         } else if (execable("/sbin/dhclient")) {
548                 return( execute("dhclient -pf /var/run/dhclient.%iface%.pid %iface%", ifd, exec));
549         } else if (execable("/sbin/dhcpcd")) {
550                 return( execute("dhcpcd [[-h %hostname%]] [[-i %vendor%]] [[-I %clientid%]] "
551                                         "[[-l %leasetime%]] %iface%", ifd, exec));
552         }
553         return(0);
554 }
555
556 static int dhcp_down(struct interface_defn_t *ifd, execfn *exec)
557 {
558         int result = 0;
559         if (execable("/sbin/udhcpc")) {
560                 /* SIGUSR2 forces udhcpc to release the current lease and go inactive,
561                  * and SIGTERM causes udhcpc to exit.  Signals are queued and processed
562                  * sequentially so we don't need to sleep */
563                 result = execute("kill -USR2 `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
564                 result += execute("kill -TERM `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
565         } else if (execable("/sbin/pump")) {
566                 result = execute("pump -i %iface% -k", ifd, exec);
567         } else if (execable("/sbin/dhclient")) {
568                 result = execute("kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null", ifd, exec);
569         } else if (execable("/sbin/dhcpcd")) {
570                 result = execute("dhcpcd -k %iface%", ifd, exec);
571         }
572         return (result || static_down(ifd, exec));
573 }
574
575 static int bootp_up(struct interface_defn_t *ifd, execfn *exec)
576 {
577         return( execute("bootpc [[--bootfile %bootfile%]] --dev %iface% "
578                                 "[[--server %server%]] [[--hwaddr %hwaddr%]] "
579                                 "--returniffail --serverbcast", ifd, exec));
580 }
581
582 static int ppp_up(struct interface_defn_t *ifd, execfn *exec)
583 {
584         return( execute("pon [[%provider%]]", ifd, exec));
585 }
586
587 static int ppp_down(struct interface_defn_t *ifd, execfn *exec)
588 {
589         return( execute("poff [[%provider%]]", ifd, exec));
590 }
591
592 static int wvdial_up(struct interface_defn_t *ifd, execfn *exec)
593 {
594         return( execute("/sbin/start-stop-daemon --start -x /usr/bin/wvdial "
595                                 "-p /var/run/wvdial.%iface% -b -m -- [[ %provider% ]]", ifd, exec));
596 }
597
598 static int wvdial_down(struct interface_defn_t *ifd, execfn *exec)
599 {
600         return( execute("/sbin/start-stop-daemon --stop -x /usr/bin/wvdial "
601                                 "-p /var/run/wvdial.%iface% -s 2", ifd, exec));
602 }
603
604 static struct method_t methods[] =
605 {
606         { "wvdial", wvdial_up, wvdial_down, },
607         { "ppp", ppp_up, ppp_down, },
608         { "static", static_up, static_down, },
609         { "bootp", bootp_up, static_down, },
610         { "dhcp", dhcp_up, dhcp_down, },
611         { "loopback", loopback_up, loopback_down, },
612 };
613
614 static struct address_family_t addr_inet =
615 {
616         "inet",
617         sizeof(methods) / sizeof(struct method_t),
618         methods
619 };
620
621 #endif  /* ifdef CONFIG_FEATURE_IFUPDOWN_IPV4 */
622
623 static char *next_word(char **buf)
624 {
625         unsigned short length;
626         char *word;
627
628         if ((buf == NULL) || (*buf == NULL) || (**buf == '\0')) {
629                 return NULL;
630         }
631
632         /* Skip over leading whitespace */
633         word = *buf;
634         while (isspace(*word)) {
635                 ++word;
636         }
637
638         /* Skip over comments */
639         if (*word == '#') {
640                 return(NULL);
641         }
642
643         /* Find the length of this word */
644         length = strcspn(word, " \t\n");
645         if (length == 0) {
646                 return(NULL);
647         }
648         *buf = word + length;
649         /*DBU:[dave@cray.com] if we are already at EOL dont't increment beyond it */
650         if (**buf) {
651                 **buf = '\0';
652                 (*buf)++;
653         }
654
655         return word;
656 }
657
658 static struct address_family_t *get_address_family(struct address_family_t *af[], char *name)
659 {
660         int i;
661
662         for (i = 0; af[i]; i++) {
663                 if (strcmp(af[i]->name, name) == 0) {
664                         return af[i];
665                 }
666         }
667         return NULL;
668 }
669
670 static struct method_t *get_method(struct address_family_t *af, char *name)
671 {
672         int i;
673
674         for (i = 0; i < af->n_methods; i++) {
675                 if (strcmp(af->method[i].name, name) == 0) {
676                         return &af->method[i];
677                 }
678         }
679         return(NULL);
680 }
681
682 static int duplicate_if(struct interface_defn_t *ifa, struct interface_defn_t *ifb)
683 {
684         if (strcmp(ifa->iface, ifb->iface) != 0) {
685                 return(0);
686         }
687         if (ifa->address_family != ifb->address_family) {
688                 return(0);
689         }
690         return(1);
691 }
692
693 static const llist_t *find_list_string(const llist_t *list, const char *string)
694 {
695         while (list) {
696                 if (strcmp(list->data, string) == 0) {
697                         return(list);
698                 }
699                 list = list->link;
700         }
701         return(NULL);
702 }
703
704 static struct interfaces_file_t *read_interfaces(const char *filename)
705 {
706 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
707         struct mapping_defn_t *currmap = NULL;
708 #endif
709         struct interface_defn_t *currif = NULL;
710         struct interfaces_file_t *defn;
711         FILE *f;
712         char *firstword;
713         char *buf;
714
715         enum { NONE, IFACE, MAPPING } currently_processing = NONE;
716
717         defn = xmalloc(sizeof(struct interfaces_file_t));
718         defn->autointerfaces = NULL;
719         defn->mappings = NULL;
720         defn->ifaces = NULL;
721
722         f = bb_xfopen(filename, "r");
723
724         while ((buf = bb_get_chomped_line_from_file(f)) != NULL) {
725                 char *buf_ptr = buf;
726
727                 firstword = next_word(&buf_ptr);
728                 if (firstword == NULL) {
729                         free(buf);
730                         continue;       /* blank line */
731                 }
732
733                 if (strcmp(firstword, "mapping") == 0) {
734 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
735                         currmap = xmalloc(sizeof(struct mapping_defn_t));
736                         currmap->max_matches = 0;
737                         currmap->n_matches = 0;
738                         currmap->match = NULL;
739
740                         while ((firstword = next_word(&buf_ptr)) != NULL) {
741                                 if (currmap->max_matches == currmap->n_matches) {
742                                         currmap->max_matches = currmap->max_matches * 2 + 1;
743                                         currmap->match = xrealloc(currmap->match, sizeof(currmap->match) * currmap->max_matches);
744                                 }
745
746                                 currmap->match[currmap->n_matches++] = bb_xstrdup(firstword);
747                         }
748                         currmap->max_mappings = 0;
749                         currmap->n_mappings = 0;
750                         currmap->mapping = NULL;
751                         currmap->script = NULL;
752                         {
753                                 struct mapping_defn_t **where = &defn->mappings;
754                                 while (*where != NULL) {
755                                         where = &(*where)->next;
756                                 }
757                                 *where = currmap;
758                                 currmap->next = NULL;
759                         }
760                         debug_noise("Added mapping\n");
761 #endif
762                         currently_processing = MAPPING;
763                 } else if (strcmp(firstword, "iface") == 0) {
764                         {
765                                 char *iface_name;
766                                 char *address_family_name;
767                                 char *method_name;
768                                 struct address_family_t *addr_fams[] = {
769 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV4
770                                         &addr_inet,
771 #endif
772 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV6
773                                         &addr_inet6,
774 #endif
775 #ifdef CONFIG_FEATURE_IFUPDOWN_IPX
776                                         &addr_ipx,
777 #endif
778                                         NULL
779                                 };
780
781                                 currif = xmalloc(sizeof(struct interface_defn_t));
782                                 iface_name = next_word(&buf_ptr);
783                                 address_family_name = next_word(&buf_ptr);
784                                 method_name = next_word(&buf_ptr);
785
786                                 if (buf_ptr == NULL) {
787                                         bb_error_msg("too few parameters for line \"%s\"", buf);
788                                         return NULL;
789                                 }
790
791                                 /* ship any trailing whitespace */
792                                 while (isspace(*buf_ptr)) {
793                                         ++buf_ptr;
794                                 }
795
796                                 if (buf_ptr[0] != '\0') {
797                                         bb_error_msg("too many parameters \"%s\"", buf);
798                                         return NULL;
799                                 }
800
801                                 currif->iface = bb_xstrdup(iface_name);
802
803                                 currif->address_family = get_address_family(addr_fams, address_family_name);
804                                 if (!currif->address_family) {
805                                         bb_error_msg("unknown address type \"%s\"", address_family_name);
806                                         return NULL;
807                                 }
808
809                                 currif->method = get_method(currif->address_family, method_name);
810                                 if (!currif->method) {
811                                         bb_error_msg("unknown method \"%s\"", method_name);
812                                         return NULL;
813                                 }
814
815                                 currif->automatic = 1;
816                                 currif->max_options = 0;
817                                 currif->n_options = 0;
818                                 currif->option = NULL;
819
820                                 {
821                                         struct interface_defn_t *tmp;
822                                         llist_t *iface_list;
823                                         iface_list = defn->ifaces;
824                                         while (iface_list) {
825                                                 tmp = (struct interface_defn_t *) iface_list->data;
826                                                 if (duplicate_if(tmp, currif)) {
827                                                         bb_error_msg("duplicate interface \"%s\"", tmp->iface);
828                                                         return NULL;
829                                                 }
830                                                 iface_list = iface_list->link;
831                                         }
832
833                                         defn->ifaces = llist_add_to_end(defn->ifaces, (char*)currif);
834                                 }
835                                 debug_noise("iface %s %s %s\n", currif->iface, address_family_name, method_name);
836                         }
837                         currently_processing = IFACE;
838                 } else if (strcmp(firstword, "auto") == 0) {
839                         while ((firstword = next_word(&buf_ptr)) != NULL) {
840
841                                 /* Check the interface isnt already listed */
842                                 if (find_list_string(defn->autointerfaces, firstword)) {
843                                         bb_perror_msg_and_die("interface declared auto twice \"%s\"", buf);
844                                 }
845
846                                 /* Add the interface to the list */
847                                 defn->autointerfaces = llist_add_to_end(defn->autointerfaces, strdup(firstword));
848                                 debug_noise("\nauto %s\n", firstword);
849                         }
850                         currently_processing = NONE;
851                 } else {
852                         switch (currently_processing) {
853                                 case IFACE:
854                                         {
855                                                 int i;
856
857                                                 if (bb_strlen(buf_ptr) == 0) {
858                                                         bb_error_msg("option with empty value \"%s\"", buf);
859                                                         return NULL;
860                                                 }
861
862                                                 if (strcmp(firstword, "up") != 0
863                                                                 && strcmp(firstword, "down") != 0
864                                                                 && strcmp(firstword, "pre-up") != 0
865                                                                 && strcmp(firstword, "post-down") != 0) {
866                                                         for (i = 0; i < currif->n_options; i++) {
867                                                                 if (strcmp(currif->option[i].name, firstword) == 0) {
868                                                                         bb_error_msg("duplicate option \"%s\"", buf);
869                                                                         return NULL;
870                                                                 }
871                                                         }
872                                                 }
873                                         }
874                                         if (currif->n_options >= currif->max_options) {
875                                                 struct variable_t *opt;
876
877                                                 currif->max_options = currif->max_options + 10;
878                                                 opt = xrealloc(currif->option, sizeof(*opt) * currif->max_options);
879                                                 currif->option = opt;
880                                         }
881                                         currif->option[currif->n_options].name = bb_xstrdup(firstword);
882                                         currif->option[currif->n_options].value = bb_xstrdup(buf_ptr);
883                                         if (!currif->option[currif->n_options].name) {
884                                                 perror(filename);
885                                                 return NULL;
886                                         }
887                                         if (!currif->option[currif->n_options].value) {
888                                                 perror(filename);
889                                                 return NULL;
890                                         }
891                                         debug_noise("\t%s=%s\n", currif->option[currif->n_options].name,
892                                                         currif->option[currif->n_options].value);
893                                         currif->n_options++;
894                                         break;
895                                 case MAPPING:
896 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
897                                         if (strcmp(firstword, "script") == 0) {
898                                                 if (currmap->script != NULL) {
899                                                         bb_error_msg("duplicate script in mapping \"%s\"", buf);
900                                                         return NULL;
901                                                 } else {
902                                                         currmap->script = bb_xstrdup(next_word(&buf_ptr));
903                                                 }
904                                         } else if (strcmp(firstword, "map") == 0) {
905                                                 if (currmap->max_mappings == currmap->n_mappings) {
906                                                         currmap->max_mappings = currmap->max_mappings * 2 + 1;
907                                                         currmap->mapping = xrealloc(currmap->mapping, sizeof(char *) * currmap->max_mappings);
908                                                 }
909                                                 currmap->mapping[currmap->n_mappings] = bb_xstrdup(next_word(&buf_ptr));
910                                                 currmap->n_mappings++;
911                                         } else {
912                                                 bb_error_msg("misplaced option \"%s\"", buf);
913                                                 return NULL;
914                                         }
915 #endif
916                                         break;
917                                 case NONE:
918                                 default:
919                                         bb_error_msg("misplaced option \"%s\"", buf);
920                                         return NULL;
921                         }
922                 }
923                 free(buf);
924         }
925         if (ferror(f) != 0) {
926                 bb_perror_msg_and_die("%s", filename);
927         }
928         fclose(f);
929
930         return defn;
931 }
932
933 static char *setlocalenv(char *format, char *name, char *value)
934 {
935         char *result;
936         char *here;
937         char *there;
938
939         result = xmalloc(bb_strlen(format) + bb_strlen(name) + bb_strlen(value) + 1);
940
941         sprintf(result, format, name, value);
942
943         for (here = there = result; *there != '=' && *there; there++) {
944                 if (*there == '-')
945                         *there = '_';
946                 if (isalpha(*there))
947                         *there = toupper(*there);
948
949                 if (isalnum(*there) || *there == '_') {
950                         *here = *there;
951                         here++;
952                 }
953         }
954         memmove(here, there, bb_strlen(there) + 1);
955
956         return result;
957 }
958
959 static void set_environ(struct interface_defn_t *iface, char *mode)
960 {
961         char **environend;
962         int i;
963         const int n_env_entries = iface->n_options + 5;
964         char **ppch;
965
966         if (environ != NULL) {
967                 for (ppch = environ; *ppch; ppch++) {
968                         free(*ppch);
969                         *ppch = NULL;
970                 }
971                 free(environ);
972                 environ = NULL;
973         }
974         environ = xmalloc(sizeof(char *) * (n_env_entries + 1 /* for final NULL */ ));
975         environend = environ;
976         *environend = NULL;
977
978         for (i = 0; i < iface->n_options; i++) {
979                 if (strcmp(iface->option[i].name, "up") == 0
980                                 || strcmp(iface->option[i].name, "down") == 0
981                                 || strcmp(iface->option[i].name, "pre-up") == 0
982                                 || strcmp(iface->option[i].name, "post-down") == 0) {
983                         continue;
984                 }
985                 *(environend++) = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
986                 *environend = NULL;
987         }
988
989         *(environend++) = setlocalenv("%s=%s", "IFACE", iface->iface);
990         *environend = NULL;
991         *(environend++) = setlocalenv("%s=%s", "ADDRFAM", iface->address_family->name);
992         *environend = NULL;
993         *(environend++) = setlocalenv("%s=%s", "METHOD", iface->method->name);
994         *environend = NULL;
995         *(environend++) = setlocalenv("%s=%s", "MODE", mode);
996         *environend = NULL;
997         *(environend++) = setlocalenv("%s=%s", "PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
998         *environend = NULL;
999 }
1000
1001 static int doit(char *str)
1002 {
1003         if (verbose || no_act) {
1004                 printf("%s\n", str);
1005         }
1006         if (!no_act) {
1007                 pid_t child;
1008                 int status;
1009
1010                 fflush(NULL);
1011                 switch (child = fork()) {
1012                         case -1:                /* failure */
1013                                 return 0;
1014                         case 0:         /* child */
1015                                 execle(DEFAULT_SHELL, DEFAULT_SHELL, "-c", str, NULL, environ);
1016                                 exit(127);
1017                 }
1018                 waitpid(child, &status, 0);
1019                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1020                         return 0;
1021                 }
1022         }
1023         return (1);
1024 }
1025
1026 static int execute_all(struct interface_defn_t *ifd, execfn *exec, const char *opt)
1027 {
1028         int i;
1029         char *buf;
1030         for (i = 0; i < ifd->n_options; i++) {
1031                 if (strcmp(ifd->option[i].name, opt) == 0) {
1032                         if (!(*exec) (ifd->option[i].value)) {
1033                                 return 0;
1034                         }
1035                 }
1036         }
1037
1038         bb_xasprintf(&buf, "run-parts /etc/network/if-%s.d", opt);
1039         if ((*exec)(buf) != 1) {
1040                 return 0;
1041         }
1042         return 1;
1043 }
1044
1045 static int check(char *str) {
1046         return str != NULL;
1047 }
1048
1049 static int iface_up(struct interface_defn_t *iface)
1050 {
1051         if (!iface->method->up(iface,check)) return -1;
1052         set_environ(iface, "start");
1053         if (!execute_all(iface, doit, "pre-up")) return 0;
1054         if (!iface->method->up(iface, doit)) return 0;
1055         if (!execute_all(iface, doit, "up")) return 0;
1056         return 1;
1057 }
1058
1059 static int iface_down(struct interface_defn_t *iface)
1060 {
1061         if (!iface->method->down(iface,check)) return -1;
1062         set_environ(iface, "stop");
1063         if (!execute_all(iface, doit, "down")) return 0;
1064         if (!iface->method->down(iface, doit)) return 0;
1065         if (!execute_all(iface, doit, "post-down")) return 0;
1066         return 1;
1067 }
1068
1069 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1070 static int popen2(FILE **in, FILE **out, char *command, ...)
1071 {
1072         va_list ap;
1073         char *argv[11] = { command };
1074         int argc;
1075         int infd[2], outfd[2];
1076         pid_t pid;
1077
1078         argc = 1;
1079         va_start(ap, command);
1080         while ((argc < 10) && (argv[argc] = va_arg(ap, char *))) {
1081                 argc++;
1082         }
1083         argv[argc] = NULL;      /* make sure */
1084         va_end(ap);
1085
1086         if (pipe(infd) != 0) {
1087                 return 0;
1088         }
1089
1090         if (pipe(outfd) != 0) {
1091                 close(infd[0]);
1092                 close(infd[1]);
1093                 return 0;
1094         }
1095
1096         fflush(NULL);
1097         switch (pid = fork()) {
1098                 case -1:                        /* failure */
1099                         close(infd[0]);
1100                         close(infd[1]);
1101                         close(outfd[0]);
1102                         close(outfd[1]);
1103                         return 0;
1104                 case 0:                 /* child */
1105                         dup2(infd[0], 0);
1106                         dup2(outfd[1], 1);
1107                         close(infd[0]);
1108                         close(infd[1]);
1109                         close(outfd[0]);
1110                         close(outfd[1]);
1111                         execvp(command, argv);
1112                         exit(127);
1113                 default:                        /* parent */
1114                         *in = fdopen(infd[1], "w");
1115                         *out = fdopen(outfd[0], "r");
1116                         close(infd[0]);
1117                         close(outfd[1]);
1118                         return pid;
1119         }
1120         /* unreached */
1121 }
1122
1123 static char *run_mapping(char *physical, struct mapping_defn_t * map)
1124 {
1125         FILE *in, *out;
1126         int i, status;
1127         pid_t pid;
1128
1129         char *logical = bb_xstrdup(physical);
1130
1131         /* Run the mapping script. */
1132         pid = popen2(&in, &out, map->script, physical, NULL);
1133
1134         /* popen2() returns 0 on failure. */
1135         if (pid == 0)
1136                 return logical;
1137
1138         /* Write mappings to stdin of mapping script. */
1139         for (i = 0; i < map->n_mappings; i++) {
1140                 fprintf(in, "%s\n", map->mapping[i]);
1141         }
1142         fclose(in);
1143         waitpid(pid, &status, 0);
1144
1145         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1146                 /* If the mapping script exited successfully, try to
1147                  * grab a line of output and use that as the name of the
1148                  * logical interface. */
1149                 char *new_logical = (char *)xmalloc(MAX_INTERFACE_LENGTH);
1150
1151                 if (fgets(new_logical, MAX_INTERFACE_LENGTH, out)) {
1152                         /* If we are able to read a line of output from the script,
1153                          * remove any trailing whitespace and use this value
1154                          * as the name of the logical interface. */
1155                         char *pch = new_logical + bb_strlen(new_logical) - 1;
1156
1157                         while (pch >= new_logical && isspace(*pch))
1158                                 *(pch--) = '\0';
1159
1160                         free(logical);
1161                         logical = new_logical;
1162                 } else {
1163                         /* If we are UNABLE to read a line of output, discard are
1164                          * freshly allocated memory. */
1165                         free(new_logical);
1166                 }
1167         }
1168
1169         fclose(out);
1170
1171         return logical;
1172 }
1173 #endif /* CONFIG_FEATURE_IFUPDOWN_MAPPING */
1174
1175 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1176 {
1177         unsigned short iface_len = bb_strlen(iface);
1178         llist_t *search = state_list;
1179
1180         while (search) {
1181                 if ((strncmp(search->data, iface, iface_len) == 0) &&
1182                                 (search->data[iface_len] == '=')) {
1183                         return(search);
1184                 }
1185                 search = search->link;
1186         }
1187         return(NULL);
1188 }
1189
1190 extern int ifupdown_main(int argc, char **argv)
1191 {
1192         int (*cmds) (struct interface_defn_t *) = NULL;
1193         struct interfaces_file_t *defn;
1194         FILE *state_fp = NULL;
1195         llist_t *state_list = NULL;
1196         llist_t *target_list = NULL;
1197         const char *interfaces = "/etc/network/interfaces";
1198         const char *statefile = "/var/run/ifstate";
1199
1200 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1201         int run_mappings = 1;
1202 #endif
1203         int do_all = 0;
1204         int force = 0;
1205         int any_failures = 0;
1206         int i;
1207
1208         if (bb_applet_name[2] == 'u') {
1209                 /* ifup command */
1210                 cmds = iface_up;
1211         } else {
1212                 /* ifdown command */
1213                 cmds = iface_down;
1214         }
1215
1216 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1217         while ((i = getopt(argc, argv, "i:hvnamf")) != -1)
1218 #else
1219                 while ((i = getopt(argc, argv, "i:hvnaf")) != -1)
1220 #endif
1221                 {
1222                         switch (i) {
1223                                 case 'i':       /* interfaces */
1224                                         interfaces = optarg;
1225                                         break;
1226                                 case 'v':       /* verbose */
1227                                         verbose = 1;
1228                                         break;
1229                                 case 'a':       /* all */
1230                                         do_all = 1;
1231                                         break;
1232                                 case 'n':       /* no-act */
1233                                         no_act = 1;
1234                                         break;
1235 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1236                                 case 'm':       /* no-mappings */
1237                                         run_mappings = 0;
1238                                         break;
1239 #endif
1240                                 case 'f':       /* force */
1241                                         force = 1;
1242                                         break;
1243                                 default:
1244                                         bb_show_usage();
1245                                         break;
1246                         }
1247                 }
1248
1249         if (argc - optind > 0) {
1250                 if (do_all) {
1251                         bb_show_usage();
1252                 }
1253         } else {
1254                 if (!do_all) {
1255                         bb_show_usage();
1256                 }
1257         }
1258
1259         debug_noise("reading %s file:\n", interfaces);
1260         defn = read_interfaces(interfaces);
1261         debug_noise("\ndone reading %s\n\n", interfaces);
1262
1263         if (!defn) {
1264                 exit(EXIT_FAILURE);
1265         }
1266
1267         if (no_act) {
1268                 state_fp = fopen(statefile, "r");
1269         }
1270
1271         /* Create a list of interfaces to work on */
1272         if (do_all) {
1273                 if (cmds == iface_up) {
1274                         target_list = defn->autointerfaces;
1275                 } else {
1276 #if 0
1277                         /* iface_down */
1278                         llist_t *new_item;
1279                         const llist_t *list = state_list;
1280                         while (list) {
1281                                 new_item = xmalloc(sizeof(llist_t));
1282                                 new_item->data = strdup(list->data);
1283                                 new_item->link = NULL;
1284                                 list = target_list;
1285                                 if (list == NULL)
1286                                         target_list = new_item;
1287                                 else {
1288                                         while (list->link) {
1289                                                 list = list->link;
1290                                         }
1291                                         list = new_item;
1292                                 }
1293                                 list = list->link;
1294                         }
1295                         target_list = defn->autointerfaces;
1296 #else
1297
1298                         /* iface_down */
1299                         const llist_t *list = state_list;
1300                         while (list) {
1301                                 target_list = llist_add_to_end(target_list, strdup(list->data));
1302                                 list = list->link;
1303                         }
1304                         target_list = defn->autointerfaces;
1305 #endif
1306                 }
1307         } else {
1308                 target_list = llist_add_to_end(target_list, argv[optind]);
1309         }
1310
1311
1312         /* Update the interfaces */
1313         while (target_list) {
1314                 llist_t *iface_list;
1315                 struct interface_defn_t *currif;
1316                 char *iface;
1317                 char *liface;
1318                 char *pch;
1319                 int okay = 0;
1320                 int cmds_ret;
1321
1322                 iface = strdup(target_list->data);
1323                 target_list = target_list->link;
1324
1325                 pch = strchr(iface, '=');
1326                 if (pch) {
1327                         *pch = '\0';
1328                         liface = strdup(pch + 1);
1329                 } else {
1330                         liface = strdup(iface);
1331                 }
1332
1333                 if (!force) {
1334                         const llist_t *iface_state = find_iface_state(state_list, iface);
1335
1336                         if (cmds == iface_up) {
1337                                 /* ifup */
1338                                 if (iface_state) {
1339                                         bb_error_msg("interface %s already configured", iface);
1340                                         continue;
1341                                 }
1342                         } else {
1343                                 /* ifdown */
1344                                 if (iface_state) {
1345                                         bb_error_msg("interface %s not configured", iface);
1346                                         continue;
1347                                 }
1348                         }
1349                 }
1350
1351 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1352                 if ((cmds == iface_up) && run_mappings) {
1353                         struct mapping_defn_t *currmap;
1354
1355                         for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1356
1357                                 for (i = 0; i < currmap->n_matches; i++) {
1358                                         if (fnmatch(currmap->match[i], liface, 0) != 0)
1359                                                 continue;
1360                                         if (verbose) {
1361                                                 printf("Running mapping script %s on %s\n", currmap->script, liface);
1362                                         }
1363                                         liface = run_mapping(iface, currmap);
1364                                         break;
1365                                 }
1366                         }
1367                 }
1368 #endif
1369
1370
1371                 iface_list = defn->ifaces;
1372                 while (iface_list) {
1373                         currif = (struct interface_defn_t *) iface_list->data;
1374                         if (strcmp(liface, currif->iface) == 0) {
1375                                 char *oldiface = currif->iface;
1376
1377                                 okay = 1;
1378                                 currif->iface = iface;
1379
1380                                 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1381
1382                                 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1383                                 cmds_ret = cmds(currif);
1384                                 if (cmds_ret == -1) {
1385                                         bb_error_msg("Don't seem to have all the variables for %s/%s.",
1386                                                         liface, currif->address_family->name);
1387                                         any_failures += 1;
1388                                 } else if (cmds_ret == 0) {
1389                                         any_failures += 1;
1390                                 }
1391
1392                                 currif->iface = oldiface;
1393                         }
1394                         iface_list = iface_list->link;
1395                 }
1396                 if (verbose) {
1397                         printf("\n");
1398                 }
1399
1400                 if (!okay && !force) {
1401                         bb_error_msg("Ignoring unknown interface %s", liface);
1402                         any_failures += 1;
1403                 } else {
1404                         llist_t *iface_state = find_iface_state(state_list, iface);
1405
1406                         if (cmds == iface_up) {
1407                                 char *newiface = xmalloc(bb_strlen(iface) + 1 + bb_strlen(liface) + 1);
1408                                 sprintf(newiface, "%s=%s", iface, liface);
1409                                 if (iface_state == NULL) {
1410                                         state_list = llist_add_to_end(state_list, newiface);
1411                                 } else {
1412                                         free(iface_state->data);
1413                                         iface_state->data = newiface;
1414                                 }
1415                         } else if (cmds == iface_down) {
1416                                 /* Remove an interface from the linked list */
1417                                 if (iface_state) {
1418                                         /* This needs to be done better */
1419                                         free(iface_state->data);
1420                                         free(iface_state->link);
1421                                         if (iface_state->link) {
1422                                                 iface_state->data = iface_state->link->data;
1423                                                 iface_state->link = iface_state->link->link;
1424                                         } else {
1425                                                 iface_state->data = NULL;
1426                                                 iface_state->link = NULL;
1427                                         }
1428                                 }
1429                         }
1430                 }
1431         }
1432
1433         /* Actually write the new state */
1434         if (!no_act) {
1435
1436                 if (state_fp)
1437                         fclose(state_fp);
1438                 state_fp = bb_xfopen(statefile, "a+");
1439
1440                 if (ftruncate(fileno(state_fp), 0) < 0) {
1441                         bb_error_msg_and_die("failed to truncate statefile %s: %s", statefile, strerror(errno));
1442                 }
1443
1444                 rewind(state_fp);
1445
1446                 while (state_list) {
1447                         if (state_list->data) {
1448                                 fputs(state_list->data, state_fp);
1449                                 fputc('\n', state_fp);
1450                         }
1451                         state_list = state_list->link;
1452                 }
1453                 fflush(state_fp);
1454         }
1455
1456         /* Cleanup */
1457         if (state_fp != NULL) {
1458                 fclose(state_fp);
1459                 state_fp = NULL;
1460         }
1461
1462         if (any_failures)
1463                 return 1;
1464         return 0;
1465 }