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