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