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