Patch from Felipe Kellermann, remove some unnecessary dups, i declared a few extra...
[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 dhcp_down(struct interface_defn_t *ifd, execfn *exec)
555 {
556         int result = 0;
557         if (execable("/sbin/udhcpc")) {
558                 /* SIGUSR2 forces udhcpc to release the current lease and go inactive,
559                  * and SIGTERM causes udhcpc to exit.  Signals are queued and processed
560                  * sequentially so we don't need to sleep */
561                 result = execute("kill -USR2 `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
562                 result += execute("kill -TERM `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
563         } else if (execable("/sbin/pump")) {
564                 result = execute("pump -i %iface% -k", ifd, exec);
565         } else if (execable("/sbin/dhclient")) {
566                 result = execute("kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null", ifd, exec);
567         } else if (execable("/sbin/dhcpcd")) {
568                 result = execute("dhcpcd -k %iface%", ifd, exec);
569         }
570         return (result || static_down(ifd, exec));
571 }
572
573 static int bootp_up(struct interface_defn_t *ifd, execfn *exec)
574 {
575         return( execute("bootpc [[--bootfile %bootfile%]] --dev %iface% "
576                                 "[[--server %server%]] [[--hwaddr %hwaddr%]] "
577                                 "--returniffail --serverbcast", ifd, exec));
578 }
579
580 static int ppp_up(struct interface_defn_t *ifd, execfn *exec)
581 {
582         return( execute("pon [[%provider%]]", ifd, exec));
583 }
584
585 static int ppp_down(struct interface_defn_t *ifd, execfn *exec)
586 {
587         return( execute("poff [[%provider%]]", ifd, exec));
588 }
589
590 static int wvdial_up(struct interface_defn_t *ifd, execfn *exec)
591 {
592         return( execute("/sbin/start-stop-daemon --start -x /usr/bin/wvdial "
593                                 "-p /var/run/wvdial.%iface% -b -m -- [[ %provider% ]]", ifd, exec));
594 }
595
596 static int wvdial_down(struct interface_defn_t *ifd, execfn *exec)
597 {
598         return( execute("/sbin/start-stop-daemon --stop -x /usr/bin/wvdial "
599                                 "-p /var/run/wvdial.%iface% -s 2", ifd, exec));
600 }
601
602 static struct method_t methods[] =
603 {
604         { "wvdial", wvdial_up, wvdial_down, },
605         { "ppp", ppp_up, ppp_down, },
606         { "static", static_up, static_down, },
607         { "bootp", bootp_up, static_down, },
608         { "dhcp", dhcp_up, dhcp_down, },
609         { "loopback", loopback_up, loopback_down, },
610 };
611
612 struct address_family_t addr_inet =
613 {
614         "inet",
615         sizeof(methods) / sizeof(struct method_t),
616         methods
617 };
618
619 #endif  /* ifdef CONFIG_FEATURE_IFUPDOWN_IPV4 */
620
621 static char *next_word(char **buf)
622 {
623         unsigned short length;
624         char *word;
625
626         if ((buf == NULL) || (*buf == NULL) || (**buf == '\0')) {
627                 return NULL;
628         }
629
630         /* Skip over leading whitespace */
631         word = *buf;
632         while (isspace(*word)) {
633                 ++word;
634         }
635
636         /* Skip over comments */
637         if (*word == '#') {
638                 return(NULL);
639         }
640
641         /* Find the length of this word */
642         length = strcspn(word, " \t\n");
643         if (length == 0) {
644                 return(NULL);
645         }
646         *buf = word + length;
647         /*DBU:[dave@cray.com] if we are already at EOL dont't increment beyond it */
648         if (**buf) {
649                 **buf = '\0';
650                 (*buf)++;
651         }
652
653         return word;
654 }
655
656 static struct address_family_t *get_address_family(struct address_family_t *af[], char *name)
657 {
658         int i;
659
660         for (i = 0; af[i]; i++) {
661                 if (strcmp(af[i]->name, name) == 0) {
662                         return af[i];
663                 }
664         }
665         return NULL;
666 }
667
668 static struct method_t *get_method(struct address_family_t *af, char *name)
669 {
670         int i;
671
672         for (i = 0; i < af->n_methods; i++) {
673                 if (strcmp(af->method[i].name, name) == 0) {
674                         return &af->method[i];
675                 }
676         }
677         return(NULL);
678 }
679
680 static int duplicate_if(struct interface_defn_t *ifa, struct interface_defn_t *ifb)
681 {
682         if (strcmp(ifa->iface, ifb->iface) != 0) {
683                 return(0);
684         }
685         if (ifa->address_family != ifb->address_family) {
686                 return(0);
687         }
688         return(1);
689 }
690
691 static const llist_t *find_list_string(const llist_t *list, const char *string)
692 {
693         while (list) {
694                 if (strcmp(list->data, string) == 0) {
695                         return(list);
696                 }
697                 list = list->link;
698         }
699         return(NULL);
700 }
701
702 static struct interfaces_file_t *read_interfaces(const char *filename)
703 {
704 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
705         struct mapping_defn_t *currmap = NULL;
706 #endif
707         struct interface_defn_t *currif = NULL;
708         struct interfaces_file_t *defn;
709         FILE *f;
710         char *firstword;
711         char *buf;
712
713         enum { NONE, IFACE, MAPPING } currently_processing = NONE;
714
715         defn = xmalloc(sizeof(struct interfaces_file_t));
716         defn->autointerfaces = NULL;
717         defn->mappings = NULL;
718         defn->ifaces = NULL;
719
720         f = bb_xfopen(filename, "r");
721
722         while ((buf = bb_get_chomped_line_from_file(f)) != NULL) {
723                 char *buf_ptr = buf;
724
725                 firstword = next_word(&buf_ptr);
726                 if (firstword == NULL) {
727                         free(buf);
728                         continue;       /* blank line */
729                 }
730
731                 if (strcmp(firstword, "mapping") == 0) {
732 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
733                         currmap = xmalloc(sizeof(struct mapping_defn_t));
734                         currmap->max_matches = 0;
735                         currmap->n_matches = 0;
736                         currmap->match = NULL;
737
738                         while ((firstword = next_word(&buf_ptr)) != NULL) {
739                                 if (currmap->max_matches == currmap->n_matches) {
740                                         currmap->max_matches = currmap->max_matches * 2 + 1;
741                                         currmap->match = xrealloc(currmap->match, sizeof(currmap->match) * currmap->max_matches);
742                                 }
743
744                                 currmap->match[currmap->n_matches++] = bb_xstrdup(firstword);
745                         }
746                         currmap->max_mappings = 0;
747                         currmap->n_mappings = 0;
748                         currmap->mapping = NULL;
749                         currmap->script = NULL;
750                         {
751                                 struct mapping_defn_t **where = &defn->mappings;
752                                 while (*where != NULL) {
753                                         where = &(*where)->next;
754                                 }
755                                 *where = currmap;
756                                 currmap->next = NULL;
757                         }
758                         debug_noise("Added mapping\n");
759 #endif
760                         currently_processing = MAPPING;
761                 } else if (strcmp(firstword, "iface") == 0) {
762                         {
763                                 char *iface_name;
764                                 char *address_family_name;
765                                 char *method_name;
766                                 struct address_family_t *addr_fams[] = {
767 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV4
768                                         &addr_inet,
769 #endif
770 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV6
771                                         &addr_inet6,
772 #endif
773 #ifdef CONFIG_FEATURE_IFUPDOWN_IPX
774                                         &addr_ipx,
775 #endif
776                                         NULL
777                                 };
778
779                                 currif = xmalloc(sizeof(struct interface_defn_t));
780                                 iface_name = next_word(&buf_ptr);
781                                 address_family_name = next_word(&buf_ptr);
782                                 method_name = next_word(&buf_ptr);
783
784                                 if (buf_ptr == NULL) {
785                                         bb_error_msg("too few parameters for line \"%s\"", buf);
786                                         return NULL;
787                                 }
788
789                                 /* ship any trailing whitespace */
790                                 while (isspace(*buf_ptr)) {
791                                         ++buf_ptr;
792                                 }
793
794                                 if (buf_ptr[0] != '\0') {
795                                         bb_error_msg("too many parameters \"%s\"", buf);
796                                         return NULL;
797                                 }
798
799                                 currif->iface = bb_xstrdup(iface_name);
800
801                                 currif->address_family = get_address_family(addr_fams, address_family_name);
802                                 if (!currif->address_family) {
803                                         bb_error_msg("unknown address type \"%s\"", address_family_name);
804                                         return NULL;
805                                 }
806
807                                 currif->method = get_method(currif->address_family, method_name);
808                                 if (!currif->method) {
809                                         bb_error_msg("unknown method \"%s\"", method_name);
810                                         return NULL;
811                                 }
812
813                                 currif->automatic = 1;
814                                 currif->max_options = 0;
815                                 currif->n_options = 0;
816                                 currif->option = NULL;
817
818                                 {
819                                         struct interface_defn_t *tmp;
820                                         llist_t *iface_list;
821                                         iface_list = defn->ifaces;
822                                         while (iface_list) {
823                                                 tmp = (struct interface_defn_t *) iface_list->data;
824                                                 if (duplicate_if(tmp, currif)) {
825                                                         bb_error_msg("duplicate interface \"%s\"", tmp->iface);
826                                                         return NULL;
827                                                 }
828                                                 iface_list = iface_list->link;
829                                         }
830
831                                         defn->ifaces = llist_add_to_end(defn->ifaces, (char*)currif);
832                                 }
833                                 debug_noise("iface %s %s %s\n", currif->iface, address_family_name, method_name);
834                         }
835                         currently_processing = IFACE;
836                 } else if (strcmp(firstword, "auto") == 0) {
837                         while ((firstword = next_word(&buf_ptr)) != NULL) {
838
839                                 /* Check the interface isnt already listed */
840                                 if (find_list_string(defn->autointerfaces, firstword)) {
841                                         bb_perror_msg_and_die("interface declared auto twice \"%s\"", buf);
842                                 }
843
844                                 /* Add the interface to the list */
845                                 defn->autointerfaces = llist_add_to_end(defn->autointerfaces, strdup(firstword));
846                                 debug_noise("\nauto %s\n", firstword);
847                         }
848                         currently_processing = NONE;
849                 } else {
850                         switch (currently_processing) {
851                                 case IFACE:
852                                         {
853                                                 int i;
854
855                                                 if (bb_strlen(buf_ptr) == 0) {
856                                                         bb_error_msg("option with empty value \"%s\"", buf);
857                                                         return NULL;
858                                                 }
859
860                                                 if (strcmp(firstword, "up") != 0
861                                                                 && strcmp(firstword, "down") != 0
862                                                                 && strcmp(firstword, "pre-up") != 0
863                                                                 && strcmp(firstword, "post-down") != 0) {
864                                                         for (i = 0; i < currif->n_options; i++) {
865                                                                 if (strcmp(currif->option[i].name, firstword) == 0) {
866                                                                         bb_error_msg("duplicate option \"%s\"", buf);
867                                                                         return NULL;
868                                                                 }
869                                                         }
870                                                 }
871                                         }
872                                         if (currif->n_options >= currif->max_options) {
873                                                 struct variable_t *opt;
874
875                                                 currif->max_options = currif->max_options + 10;
876                                                 opt = xrealloc(currif->option, sizeof(*opt) * currif->max_options);
877                                                 currif->option = opt;
878                                         }
879                                         currif->option[currif->n_options].name = bb_xstrdup(firstword);
880                                         currif->option[currif->n_options].value = bb_xstrdup(buf_ptr);
881                                         if (!currif->option[currif->n_options].name) {
882                                                 perror(filename);
883                                                 return NULL;
884                                         }
885                                         if (!currif->option[currif->n_options].value) {
886                                                 perror(filename);
887                                                 return NULL;
888                                         }
889                                         debug_noise("\t%s=%s\n", currif->option[currif->n_options].name,
890                                                         currif->option[currif->n_options].value);
891                                         currif->n_options++;
892                                         break;
893                                 case MAPPING:
894 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
895                                         if (strcmp(firstword, "script") == 0) {
896                                                 if (currmap->script != NULL) {
897                                                         bb_error_msg("duplicate script in mapping \"%s\"", buf);
898                                                         return NULL;
899                                                 } else {
900                                                         currmap->script = bb_xstrdup(next_word(&buf_ptr));
901                                                 }
902                                         } else if (strcmp(firstword, "map") == 0) {
903                                                 if (currmap->max_mappings == currmap->n_mappings) {
904                                                         currmap->max_mappings = currmap->max_mappings * 2 + 1;
905                                                         currmap->mapping = xrealloc(currmap->mapping, sizeof(char *) * currmap->max_mappings);
906                                                 }
907                                                 currmap->mapping[currmap->n_mappings] = bb_xstrdup(next_word(&buf_ptr));
908                                                 currmap->n_mappings++;
909                                         } else {
910                                                 bb_error_msg("misplaced option \"%s\"", buf);
911                                                 return NULL;
912                                         }
913 #endif
914                                         break;
915                                 case NONE:
916                                 default:
917                                         bb_error_msg("misplaced option \"%s\"", buf);
918                                         return NULL;
919                         }
920                 }
921                 free(buf);
922         }
923         if (ferror(f) != 0) {
924                 bb_perror_msg_and_die("%s", filename);
925         }
926         fclose(f);
927
928         return defn;
929 }
930
931 static char *setlocalenv(char *format, char *name, char *value)
932 {
933         char *result;
934         char *here;
935         char *there;
936
937         result = xmalloc(bb_strlen(format) + bb_strlen(name) + bb_strlen(value) + 1);
938
939         sprintf(result, format, name, value);
940
941         for (here = there = result; *there != '=' && *there; there++) {
942                 if (*there == '-')
943                         *there = '_';
944                 if (isalpha(*there))
945                         *there = toupper(*there);
946
947                 if (isalnum(*there) || *there == '_') {
948                         *here = *there;
949                         here++;
950                 }
951         }
952         memmove(here, there, bb_strlen(there) + 1);
953
954         return result;
955 }
956
957 static void set_environ(struct interface_defn_t *iface, char *mode)
958 {
959         char **environend;
960         int i;
961         const int n_env_entries = iface->n_options + 5;
962         char **ppch;
963
964         if (environ != NULL) {
965                 for (ppch = environ; *ppch; ppch++) {
966                         free(*ppch);
967                         *ppch = NULL;
968                 }
969                 free(environ);
970                 environ = NULL;
971         }
972         environ = xmalloc(sizeof(char *) * (n_env_entries + 1 /* for final NULL */ ));
973         environend = environ;
974         *environend = NULL;
975
976         for (i = 0; i < iface->n_options; i++) {
977                 if (strcmp(iface->option[i].name, "up") == 0
978                                 || strcmp(iface->option[i].name, "down") == 0
979                                 || strcmp(iface->option[i].name, "pre-up") == 0
980                                 || strcmp(iface->option[i].name, "post-down") == 0) {
981                         continue;
982                 }
983                 *(environend++) = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
984                 *environend = NULL;
985         }
986
987         *(environend++) = setlocalenv("%s=%s", "IFACE", iface->iface);
988         *environend = NULL;
989         *(environend++) = setlocalenv("%s=%s", "ADDRFAM", iface->address_family->name);
990         *environend = NULL;
991         *(environend++) = setlocalenv("%s=%s", "METHOD", iface->method->name);
992         *environend = NULL;
993         *(environend++) = setlocalenv("%s=%s", "MODE", mode);
994         *environend = NULL;
995         *(environend++) = setlocalenv("%s=%s", "PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
996         *environend = NULL;
997 }
998
999 static int doit(char *str)
1000 {
1001         if (verbose || no_act) {
1002                 printf("%s\n", str);
1003         }
1004         if (!no_act) {
1005                 pid_t child;
1006                 int status;
1007
1008                 fflush(NULL);
1009                 switch (child = fork()) {
1010                         case -1:                /* failure */
1011                                 return 0;
1012                         case 0:         /* child */
1013                                 execle(DEFAULT_SHELL, DEFAULT_SHELL, "-c", str, NULL, environ);
1014                                 exit(127);
1015                 }
1016                 waitpid(child, &status, 0);
1017                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1018                         return 0;
1019                 }
1020         }
1021         return (1);
1022 }
1023
1024 static int execute_all(struct interface_defn_t *ifd, execfn *exec, const char *opt)
1025 {
1026         int i;
1027         char *buf;
1028         for (i = 0; i < ifd->n_options; i++) {
1029                 if (strcmp(ifd->option[i].name, opt) == 0) {
1030                         if (!(*exec) (ifd->option[i].value)) {
1031                                 return 0;
1032                         }
1033                 }
1034         }
1035
1036         bb_xasprintf(&buf, "run-parts /etc/network/if-%s.d", opt);
1037         if ((*exec)(buf) != 1) {
1038                 return 0;
1039         }
1040         return 1;
1041 }
1042
1043 static int check(char *str) {
1044         return str != NULL;
1045 }
1046
1047 static int iface_up(struct interface_defn_t *iface)
1048 {
1049         if (!iface->method->up(iface,check)) return -1;
1050         set_environ(iface, "start");
1051         if (!execute_all(iface, doit, "pre-up")) return 0;
1052         if (!iface->method->up(iface, doit)) return 0;
1053         if (!execute_all(iface, doit, "up")) return 0;
1054         return 1;
1055 }
1056
1057 static int iface_down(struct interface_defn_t *iface)
1058 {
1059         if (!iface->method->down(iface,check)) return -1;
1060         set_environ(iface, "stop");
1061         if (!execute_all(iface, doit, "down")) return 0;
1062         if (!iface->method->down(iface, doit)) return 0;
1063         if (!execute_all(iface, doit, "post-down")) return 0;
1064         return 1;
1065 }
1066
1067 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1068 static int popen2(FILE **in, FILE **out, char *command, ...)
1069 {
1070         va_list ap;
1071         char *argv[11] = { command };
1072         int argc;
1073         int infd[2], outfd[2];
1074         pid_t pid;
1075
1076         argc = 1;
1077         va_start(ap, command);
1078         while ((argc < 10) && (argv[argc] = va_arg(ap, char *))) {
1079                 argc++;
1080         }
1081         argv[argc] = NULL;      /* make sure */
1082         va_end(ap);
1083
1084         if (pipe(infd) != 0) {
1085                 return 0;
1086         }
1087
1088         if (pipe(outfd) != 0) {
1089                 close(infd[0]);
1090                 close(infd[1]);
1091                 return 0;
1092         }
1093
1094         fflush(NULL);
1095         switch (pid = fork()) {
1096                 case -1:                        /* failure */
1097                         close(infd[0]);
1098                         close(infd[1]);
1099                         close(outfd[0]);
1100                         close(outfd[1]);
1101                         return 0;
1102                 case 0:                 /* child */
1103                         dup2(infd[0], 0);
1104                         dup2(outfd[1], 1);
1105                         close(infd[0]);
1106                         close(infd[1]);
1107                         close(outfd[0]);
1108                         close(outfd[1]);
1109                         execvp(command, argv);
1110                         exit(127);
1111                 default:                        /* parent */
1112                         *in = fdopen(infd[1], "w");
1113                         *out = fdopen(outfd[0], "r");
1114                         close(infd[0]);
1115                         close(outfd[1]);
1116                         return pid;
1117         }
1118         /* unreached */
1119 }
1120
1121 static char *run_mapping(char *physical, struct mapping_defn_t * map)
1122 {
1123         FILE *in, *out;
1124         int i, status;
1125         pid_t pid;
1126
1127         char *logical = bb_xstrdup(physical);
1128
1129         /* Run the mapping script. */
1130         pid = popen2(&in, &out, map->script, physical, NULL);
1131
1132         /* popen2() returns 0 on failure. */
1133         if (pid == 0)
1134                 return logical;
1135
1136         /* Write mappings to stdin of mapping script. */
1137         for (i = 0; i < map->n_mappings; i++) {
1138                 fprintf(in, "%s\n", map->mapping[i]);
1139         }
1140         fclose(in);
1141         waitpid(pid, &status, 0);
1142
1143         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1144                 /* If the mapping script exited successfully, try to
1145                  * grab a line of output and use that as the name of the
1146                  * logical interface. */
1147                 char *new_logical = (char *)xmalloc(MAX_INTERFACE_LENGTH);
1148
1149                 if (fgets(new_logical, MAX_INTERFACE_LENGTH, out)) {
1150                         /* If we are able to read a line of output from the script,
1151                          * remove any trailing whitespace and use this value
1152                          * as the name of the logical interface. */
1153                         char *pch = new_logical + bb_strlen(new_logical) - 1;
1154
1155                         while (pch >= new_logical && isspace(*pch))
1156                                 *(pch--) = '\0';
1157
1158                         free(logical);
1159                         logical = new_logical;
1160                 } else {
1161                         /* If we are UNABLE to read a line of output, discard are
1162                          * freshly allocated memory. */
1163                         free(new_logical);
1164                 }
1165         }
1166
1167         fclose(out);
1168
1169         return logical;
1170 }
1171 #endif /* CONFIG_FEATURE_IFUPDOWN_MAPPING */
1172
1173 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1174 {
1175         unsigned short iface_len = bb_strlen(iface);
1176         llist_t *search = state_list;
1177
1178         while (search) {
1179                 if ((strncmp(search->data, iface, iface_len) == 0) &&
1180                                 (search->data[iface_len] == '=')) {
1181                         return(search);
1182                 }
1183                 search = search->link;
1184         }
1185         return(NULL);
1186 }
1187
1188 extern int ifupdown_main(int argc, char **argv)
1189 {
1190         int (*cmds) (struct interface_defn_t *) = NULL;
1191         struct interfaces_file_t *defn;
1192         FILE *state_fp = NULL;
1193         llist_t *state_list = NULL;
1194         llist_t *target_list = NULL;
1195         const char *interfaces = "/etc/network/interfaces";
1196         const char *statefile = "/var/run/ifstate";
1197
1198 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1199         int run_mappings = 1;
1200 #endif
1201         int do_all = 0;
1202         int force = 0;
1203         int any_failures = 0;
1204         int i;
1205
1206         if (bb_applet_name[2] == 'u') {
1207                 /* ifup command */
1208                 cmds = iface_up;
1209         } else {
1210                 /* ifdown command */
1211                 cmds = iface_down;
1212         }
1213
1214 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1215         while ((i = getopt(argc, argv, "i:hvnamf")) != -1)
1216 #else
1217                 while ((i = getopt(argc, argv, "i:hvnaf")) != -1)
1218 #endif
1219                 {
1220                         switch (i) {
1221                                 case 'i':       /* interfaces */
1222                                         interfaces = optarg;
1223                                         break;
1224                                 case 'v':       /* verbose */
1225                                         verbose = 1;
1226                                         break;
1227                                 case 'a':       /* all */
1228                                         do_all = 1;
1229                                         break;
1230                                 case 'n':       /* no-act */
1231                                         no_act = 1;
1232                                         break;
1233 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1234                                 case 'm':       /* no-mappings */
1235                                         run_mappings = 0;
1236                                         break;
1237 #endif
1238                                 case 'f':       /* force */
1239                                         force = 1;
1240                                         break;
1241                                 default:
1242                                         bb_show_usage();
1243                                         break;
1244                         }
1245                 }
1246
1247         if (argc - optind > 0) {
1248                 if (do_all) {
1249                         bb_show_usage();
1250                 }
1251         } else {
1252                 if (!do_all) {
1253                         bb_show_usage();
1254                 }
1255         }
1256
1257         debug_noise("reading %s file:\n", interfaces);
1258         defn = read_interfaces(interfaces);
1259         debug_noise("\ndone reading %s\n\n", interfaces);
1260
1261         if (!defn) {
1262                 exit(EXIT_FAILURE);
1263         }
1264
1265         if (no_act) {
1266                 state_fp = fopen(statefile, "r");
1267         }
1268
1269         /* Create a list of interfaces to work on */
1270         if (do_all) {
1271                 if (cmds == iface_up) {
1272                         target_list = defn->autointerfaces;
1273                 } else {
1274 #if 0
1275                         /* iface_down */
1276                         llist_t *new_item;
1277                         const llist_t *list = state_list;
1278                         while (list) {
1279                                 new_item = xmalloc(sizeof(llist_t));
1280                                 new_item->data = strdup(list->data);
1281                                 new_item->link = NULL;
1282                                 list = target_list;
1283                                 if (list == NULL)
1284                                         target_list = new_item;
1285                                 else {
1286                                         while (list->link) {
1287                                                 list = list->link;
1288                                         }
1289                                         list = new_item;
1290                                 }
1291                                 list = list->link;
1292                         }
1293                         target_list = defn->autointerfaces;
1294 #else
1295
1296                         /* iface_down */
1297                         const llist_t *list = state_list;
1298                         while (list) {
1299                                 target_list = llist_add_to_end(target_list, strdup(list->data));
1300                                 list = list->link;
1301                         }
1302                         target_list = defn->autointerfaces;
1303 #endif
1304                 }
1305         } else {
1306                 target_list = llist_add_to_end(target_list, argv[optind]);
1307         }
1308
1309
1310         /* Update the interfaces */
1311         while (target_list) {
1312                 llist_t *iface_list;
1313                 struct interface_defn_t *currif;
1314                 char *iface;
1315                 char *liface;
1316                 char *pch;
1317                 int okay = 0;
1318                 int cmds_ret;
1319
1320                 iface = strdup(target_list->data);
1321                 target_list = target_list->link;
1322
1323                 pch = strchr(iface, '=');
1324                 if (pch) {
1325                         *pch = '\0';
1326                         liface = strdup(pch + 1);
1327                 } else {
1328                         liface = strdup(iface);
1329                 }
1330
1331                 if (!force) {
1332                         const llist_t *iface_state = find_iface_state(state_list, iface);
1333
1334                         if (cmds == iface_up) {
1335                                 /* ifup */
1336                                 if (iface_state) {
1337                                         bb_error_msg("interface %s already configured", iface);
1338                                         continue;
1339                                 }
1340                         } else {
1341                                 /* ifdown */
1342                                 if (iface_state) {
1343                                         bb_error_msg("interface %s not configured", iface);
1344                                         continue;
1345                                 }
1346                         }
1347                 }
1348
1349 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1350                 if ((cmds == iface_up) && run_mappings) {
1351                         struct mapping_defn_t *currmap;
1352
1353                         for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1354
1355                                 for (i = 0; i < currmap->n_matches; i++) {
1356                                         if (fnmatch(currmap->match[i], liface, 0) != 0)
1357                                                 continue;
1358                                         if (verbose) {
1359                                                 printf("Running mapping script %s on %s\n", currmap->script, liface);
1360                                         }
1361                                         liface = run_mapping(iface, currmap);
1362                                         break;
1363                                 }
1364                         }
1365                 }
1366 #endif
1367
1368
1369                 iface_list = defn->ifaces;
1370                 while (iface_list) {
1371                         currif = (struct interface_defn_t *) iface_list->data;
1372                         if (strcmp(liface, currif->iface) == 0) {
1373                                 char *oldiface = currif->iface;
1374
1375                                 okay = 1;
1376                                 currif->iface = iface;
1377
1378                                 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1379
1380                                 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1381                                 cmds_ret = cmds(currif);
1382                                 if (cmds_ret == -1) {
1383                                         bb_error_msg("Don't seem to have all the variables for %s/%s.",
1384                                                         liface, currif->address_family->name);
1385                                         any_failures += 1;
1386                                 } else if (cmds_ret == 0) {
1387                                         any_failures += 1;
1388                                 }
1389
1390                                 currif->iface = oldiface;
1391                         }
1392                         iface_list = iface_list->link;
1393                 }
1394                 if (verbose) {
1395                         printf("\n");
1396                 }
1397
1398                 if (!okay && !force) {
1399                         bb_error_msg("Ignoring unknown interface %s", liface);
1400                         any_failures += 1;
1401                 } else {
1402                         llist_t *iface_state = find_iface_state(state_list, iface);
1403
1404                         if (cmds == iface_up) {
1405                                 char *newiface = xmalloc(bb_strlen(iface) + 1 + bb_strlen(liface) + 1);
1406                                 sprintf(newiface, "%s=%s", iface, liface);
1407                                 if (iface_state == NULL) {
1408                                         state_list = llist_add_to_end(state_list, newiface);
1409                                 } else {
1410                                         free(iface_state->data);
1411                                         iface_state->data = newiface;
1412                                 }
1413                         } else if (cmds == iface_down) {
1414                                 /* Remove an interface from the linked list */
1415                                 if (iface_state) {
1416                                         /* This needs to be done better */
1417                                         free(iface_state->data);
1418                                         free(iface_state->link);
1419                                         if (iface_state->link) {
1420                                                 iface_state->data = iface_state->link->data;
1421                                                 iface_state->link = iface_state->link->link;
1422                                         } else {
1423                                                 iface_state->data = NULL;
1424                                                 iface_state->link = NULL;
1425                                         }
1426                                 }
1427                         }
1428                 }
1429         }
1430
1431         /* Actually write the new state */
1432         if (!no_act) {
1433
1434                 if (state_fp)
1435                         fclose(state_fp);
1436                 state_fp = bb_xfopen(statefile, "a+");
1437
1438                 if (ftruncate(fileno(state_fp), 0) < 0) {
1439                         bb_error_msg_and_die("failed to truncate statefile %s: %s", statefile, strerror(errno));
1440                 }
1441
1442                 rewind(state_fp);
1443
1444                 while (state_list) {
1445                         if (state_list->data) {
1446                                 fputs(state_list->data, state_fp);
1447                                 fputc('\n', state_fp);
1448                         }
1449                         state_list = state_list->link;
1450                 }
1451                 fflush(state_fp);
1452         }
1453
1454         /* Cleanup */
1455         if (state_fp != NULL) {
1456                 fclose(state_fp);
1457                 state_fp = NULL;
1458         }
1459
1460         if (any_failures)
1461                 return 1;
1462         return 0;
1463 }