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