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