Only compile the files in this dir if the IP applet is enabled
[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 "busybox.h"
39 #include "config.h"
40
41 #define IFUPDOWN_VERSION "0.6.4"
42
43 typedef struct interface_defn interface_defn;
44
45 typedef int (execfn)(char *command);
46 typedef int (command_set)(interface_defn *ifd, execfn *e);
47
48 typedef struct method {
49         char *name;
50         command_set *up;
51         command_set *down;
52 } method;
53
54 typedef struct address_family {
55         char *name;
56         int n_methods;
57         method *method;
58 } address_family;
59
60 typedef struct mapping_defn {
61         struct mapping_defn *next;
62
63         int max_matches;
64         int n_matches;
65         char **match;
66
67         char *script;
68
69         int max_mappings;
70         int n_mappings;
71         char **mapping;
72 } mapping_defn;
73
74 typedef struct variable {
75         char *name;
76         char *value;
77 } variable;
78
79 struct interface_defn {
80         struct interface_defn *next;
81
82         char *iface;
83         address_family *address_family;
84         method *method;
85
86         int automatic;
87
88         int max_options;
89         int n_options;
90         variable *option;
91 };
92
93 typedef struct interfaces_file {
94         int max_autointerfaces;
95         int n_autointerfaces;
96         char **autointerfaces;
97
98         interface_defn *ifaces;
99         mapping_defn *mappings;
100 } interfaces_file;
101
102 #define MAX_OPT_DEPTH 10
103 #define EUNBALBRACK 10001
104 #define EUNDEFVAR   10002
105 #define MAX_VARNAME    32
106 #define EUNBALPER   10000
107
108 static int no_act = 0;
109 static int verbose = 0;
110 static char **environ = NULL;
111
112 static int execable(char *program)
113 {
114         struct stat buf;
115         if (0 == stat(program, &buf)) {
116                 if (S_ISREG(buf.st_mode) && (S_IXUSR & buf.st_mode)) {
117                         return(1);
118                 }
119         }
120         return(0);
121 }
122
123 static void addstr(char **buf, size_t *len, size_t *pos, char *str, size_t str_length)
124 {
125         if (*pos + str_length >= *len) {
126                 char *newbuf;
127
128                 newbuf = xrealloc(*buf, *len * 2 + str_length + 1);
129                 *buf = newbuf;
130                 *len = *len * 2 + str_length + 1;
131         }
132
133         while (str_length-- >= 1) {
134                 (*buf)[(*pos)++] = *str;
135                 str++;
136         }
137         (*buf)[*pos] = '\0';
138 }
139
140 static int strncmpz(char *l, char *r, size_t llen)
141 {
142         int i = strncmp(l, r, llen);
143
144         if (i == 0) {
145                 return(-r[llen]);
146         } else {
147                 return(i);
148         }
149 }
150
151 static char *get_var(char *id, size_t idlen, interface_defn *ifd)
152 {
153         int i;
154
155         if (strncmpz(id, "iface", idlen) == 0) {
156                 return (ifd->iface);
157         } else {
158                 for (i = 0; i < ifd->n_options; i++) {
159                         if (strncmpz(id, ifd->option[i].name, idlen) == 0) {
160                                 return (ifd->option[i].value);
161                         }
162                 }
163         }
164
165         return(NULL);
166 }
167
168 static char *parse(char *command, interface_defn *ifd)
169 {
170
171         char *result = NULL;
172         size_t pos = 0, len = 0;
173         size_t old_pos[MAX_OPT_DEPTH] = { 0 };
174         int okay[MAX_OPT_DEPTH] = { 1 };
175         int opt_depth = 1;
176
177         while (*command) {
178                 switch (*command) {
179
180                 default:
181                         addstr(&result, &len, &pos, command, 1);
182                         command++;
183                         break;
184                 case '\\':
185                         if (command[1]) {
186                                 addstr(&result, &len, &pos, command + 1, 1);
187                                 command += 2;
188                         } else {
189                                 addstr(&result, &len, &pos, command, 1);
190                                 command++;
191                         }
192                         break;
193                 case '[':
194                         if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
195                                 old_pos[opt_depth] = pos;
196                                 okay[opt_depth] = 1;
197                                 opt_depth++;
198                                 command += 2;
199                         } else {
200                                 addstr(&result, &len, &pos, "[", 1);
201                                 command++;
202                         }
203                         break;
204                 case ']':
205                         if (command[1] == ']' && opt_depth > 1) {
206                                 opt_depth--;
207                                 if (!okay[opt_depth]) {
208                                         pos = old_pos[opt_depth];
209                                         result[pos] = '\0';
210                                 }
211                                 command += 2;
212                         } else {
213                                 addstr(&result, &len, &pos, "]", 1);
214                                 command++;
215                         }
216                         break;
217                 case '%':
218                 {
219                         char *nextpercent;
220                         char *varvalue;
221
222                         command++;
223                         nextpercent = strchr(command, '%');
224                         if (!nextpercent) {
225                                 errno = EUNBALPER;
226                                 free(result);
227                                 return (NULL);
228                         }
229
230                         varvalue = get_var(command, nextpercent - command, ifd);
231
232                         if (varvalue) {
233                                 addstr(&result, &len, &pos, varvalue, xstrlen(varvalue));
234                         } else {
235                                 okay[opt_depth - 1] = 0;
236                         }
237
238                         command = nextpercent + 1;
239                 }
240                         break;
241                 }
242         }
243
244         if (opt_depth > 1) {
245                 errno = EUNBALBRACK;
246                 free(result);
247                 return(NULL);
248         }
249
250         if (!okay[0]) {
251                 errno = EUNDEFVAR;
252                 free(result);
253                 return(NULL);
254         }
255
256         return(result);
257 }
258
259 static int execute(char *command, interface_defn *ifd, execfn *exec)
260 {
261         char *out;
262         int ret;
263
264         out = parse(command, ifd);
265         if (!out) {
266                 return(0);
267         }
268
269         ret = (*exec) (out);
270
271         free(out);
272         return(ret);
273 }
274
275 #ifdef CONFIG_FEATURE_IFUPDOWN_IPX
276 static int static_up_ipx(interface_defn *ifd, execfn *exec)
277 {
278         if (!execute("ipx_interface add %iface% %frame% %netnum%", ifd, exec)) {
279                 return(0);
280         }
281         return(1);
282 }
283
284 static int static_down_ipx(interface_defn *ifd, execfn *exec)
285 {
286         if (!execute("ipx_interface del %iface% %frame%", ifd, exec)) {
287                 return(0);
288         }
289         return(1);
290 }
291
292 static int dynamic_up(interface_defn *ifd, execfn *exec)
293 {
294         if (!execute("ipx_interface add %iface% %frame%", ifd, exec)) {
295                 return(0);
296         }
297         return(1);
298 }
299
300 static int dynamic_down(interface_defn *ifd, execfn *exec)
301 {
302         if (!execute("ipx_interface del %iface% %frame%", ifd, exec)) {
303                 return(0);
304         }
305         return(1);
306 }
307
308 static method methods_ipx[] = {
309         { "dynamic", dynamic_up, dynamic_down, },
310         { "static", static_up_ipx, static_down_ipx, },
311 };
312
313 address_family addr_ipx = {
314         "ipx",
315         sizeof(methods_ipx) / sizeof(struct method),
316         methods_ipx
317 };
318 #endif /* IFUP_FEATURE_IPX */
319
320 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV6
321 static int loopback_up6(interface_defn *ifd, execfn *exec)
322 {
323         if (!execute("ifconfig %iface% add ::1", ifd, exec)) {
324                 return(0);
325         }
326         return(1);
327 }
328
329 static int loopback_down6(interface_defn *ifd, execfn *exec)
330 {
331         if (!execute("ifconfig %iface% del ::1", ifd, exec))
332                 return(0);
333         }
334         return(1);
335 }
336
337 static int static_up6(interface_defn *ifd, execfn *exec)
338 {
339         if (!execute("ifconfig %iface% [[media %media%]] [[hw %hwaddress%]] [[mtu %mtu%]] up", ifd, exec)) {
340                 return(0);
341         }
342         if (!execute("ifconfig %iface% add %address%/%netmask%", ifd, exec)) {
343                 return(0);
344         }
345         if (!execute("[[ route -A inet6 add ::/0 gw %gateway% ]]", ifd, exec)) {
346                 return(0);
347         }
348         return(1);
349 }
350
351 static int static_down6(interface_defn *ifd, execfn *exec)
352 {
353         if (!execute("ifconfig %iface% down", ifd, exec)) {
354                 return(0);
355         }
356         return(1);
357 }
358
359 static int v4tunnel_up(interface_defn *ifd, execfn *exec)
360 {
361         if (!execute("ip tunnel add %iface% mode sit remote %endpoint% [[local %local%]] [[ttl %ttl%]]", ifd, exec)) {
362                 return(0);
363         }
364         if (!execute("ip link set %iface% up", ifd, exec)) {
365                 return(0);
366         }
367         if (!execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec)) {
368                 return(0);
369         }
370         if (!execute("[[ ip route add ::/0 via %gateway% ]]", ifd, exec)) {
371                 return(0);
372         }
373         return(1);
374 }
375
376 static int v4tunnel_down(interface_defn * ifd, execfn * exec)
377 {
378         if (!execute("ip tunnel del %iface%", ifd, exec)) {
379                 return(0);
380         }
381         return(1);
382 }
383
384 static method methods6[] = {
385         { "v4tunnel", v4tunnel_up, v4tunnel_down, },
386         { "static", static_up6, static_down6, },
387         { "loopback", loopback_up6, loopback_down6, },
388 };
389
390 address_family addr_inet6 = {
391         "inet6",
392         sizeof(methods6) / sizeof(struct method),
393         methods6
394 };
395 #endif /* CONFIG_FEATURE_IFUPDOWN_IPV6 */
396
397 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV4
398 static int loopback_up(interface_defn *ifd, execfn *exec)
399 {
400         if (!execute("ifconfig %iface% 127.0.0.1 up", ifd, exec)) {
401                 return(0);
402         }
403         return(1);
404 }
405
406 static int loopback_down(interface_defn *ifd, execfn *exec)
407 {
408         if (!execute("ifconfig %iface% down", ifd, exec)) {
409                 return(0);
410         }
411         return(1);
412 }
413
414 static int static_up(interface_defn *ifd, execfn *exec)
415 {
416         if (!execute("ifconfig %iface% %address% netmask %netmask% [[broadcast %broadcast%]]    [[pointopoint %pointopoint%]] [[media %media%]] [[mtu %mtu%]]   [[hw %hwaddress%]] up",
417                  ifd, exec)) {
418                 return(0);
419         }
420         if (!execute("[[ route add default gw %gateway% %iface% ]]", ifd, exec)) {
421                 return(0);
422         }
423         return(1);
424 }
425
426 static int static_down(interface_defn *ifd, execfn *exec)
427 {
428         if (!execute("[[ route del default gw %gateway% %iface% ]]", ifd, exec)) {
429                 return(0);
430         }
431         if (!execute("ifconfig %iface% down", ifd, exec)) {
432                 return(0);
433         }
434         return(1);
435 }
436
437 static int dhcp_up(interface_defn *ifd, execfn *exec)
438 {
439         if (execable("/sbin/dhclient")) {
440                 if (!execute("dhclient -pf /var/run/dhclient.%iface%.pid %iface%", ifd, exec)) {
441                         return(0);
442                 }
443         } else if (execable("/sbin/pump")) {
444                 if (!execute("pump -i %iface% [[-h %hostname%]] [[-l %leasehours%]]", ifd, exec)) {
445                         return(0);
446                 }
447         } else if (execable("/sbin/udhcpc")) {
448                 if (!execute("udhcpc -n -p /var/run/udhcpc.%iface%.pid -i %iface% [[-H %hostname%]] [[-c %clientid%]]", ifd, exec)) {
449                         return 0;
450                 }
451         } else if (execable("/sbin/dhcpcd")) {
452                 if (!execute("dhcpcd [[-h %hostname%]] [[-i %vendor%]] [[-I %clientid%]] [[-l %leasetime%]] %iface%", ifd, exec)) {
453                         return(0);
454                 }
455         }
456         return(1);
457 }
458
459 static int dhcp_down(interface_defn *ifd, execfn *exec)
460 {
461         if (execable("/sbin/dhclient")) {
462                 if (!execute("cat /var/run/dhclient.%iface%.pid | xargs -i kill -TERM {}", ifd, exec)) {
463                         return(0);
464                 }
465         } else if (execable("/sbin/pump")) {
466                 if (!execute("pump -i %iface% -k", ifd, exec)) {
467                         return(0);
468                 }
469         } else if (execable("/sbin/udhcpc")) {
470                 if (!execute("cat /var/run/udhcpc.%iface%.pid | xargs -i kill -TERM {}", ifd, exec)) {
471                         return(0);
472                 }
473         } else if (execable("/sbin/dhcpcd")) {
474                 if (!execute("dhcpcd -k %iface%", ifd, exec)) {
475                         return(0);
476                 }
477         }
478         if (!execute("ifconfig %iface% down", ifd, exec)) {
479                 return(0);
480         }
481         return(1);
482 }
483
484 static int bootp_up(interface_defn *ifd, execfn *exec)
485 {
486         if (!execute("bootpc [[--bootfile %bootfile%]] --dev %iface% [[--server %server%]]            [[--hwaddr %hwaddr%]] --returniffail --serverbcast", ifd, exec)) {
487                 return 0;
488         }
489         return 1;
490 }
491
492 static int bootp_down(interface_defn *ifd, execfn *exec)
493 {
494         if (!execute("ifconfig down %iface%", ifd, exec)) {
495                 return 0;
496         }
497         return 1;
498 }
499
500 static int ppp_up(interface_defn *ifd, execfn *exec)
501 {
502         if (!execute("pon [[%provider%]]", ifd, exec)) {
503                 return 0;
504         }
505         return 1;
506 }
507
508 static int ppp_down(interface_defn *ifd, execfn *exec)
509 {
510         if (!execute("poff [[%provider%]]", ifd, exec)) {
511                 return 0;
512         }
513         return 1;
514 }
515
516 static int wvdial_up(interface_defn *ifd, execfn *exec)
517 {
518         if (!execute("/sbin/start-stop-daemon --start -x /usr/bin/wvdial -p /var/run/wvdial.%iface% -b -m -- [[ %provider% ]]", ifd, exec)) {
519                 return 0;
520         }
521         return 1;
522 }
523
524 static int wvdial_down(interface_defn *ifd, execfn *exec)
525 {
526         if (!execute ("/sbin/start-stop-daemon --stop -x /usr/bin/wvdial -p /var/run/wvdial.%iface% -s 2", ifd, exec)) {
527                 return 0;
528         }
529         return 1;
530 }
531
532 static method methods[] = {
533         { "wvdial", wvdial_up, wvdial_down, },
534         { "ppp", ppp_up, ppp_down, },
535         { "static", static_up, static_down, },
536         { "bootp", bootp_up, bootp_down, },
537         { "dhcp", dhcp_up, dhcp_down, },
538         { "loopback", loopback_up, loopback_down, },
539 };
540
541 address_family addr_inet = {
542         "inet",
543         sizeof(methods) / sizeof(struct method),
544         methods
545 };
546
547 #endif  /* ifdef CONFIG_FEATURE_IFUPDOWN_IPV4 */
548
549 static char *next_word(char *buf, char *word, int maxlen)
550 {
551         if (!buf)
552                 return NULL;
553         if (!*buf)
554                 return NULL;
555
556         while (!isspace(*buf) && *buf) {
557                 if (maxlen-- > 1)
558                         *word++ = *buf;
559                 buf++;
560         }
561         if (maxlen > 0) {
562                 *word = '\0';
563         }
564
565         while (isspace(*buf) && *buf) {
566                 buf++;
567         }
568
569         return buf;
570 }
571
572 static address_family *get_address_family(address_family *af[], char *name)
573 {
574         int i;
575
576         for (i = 0; af[i]; i++) {
577                 if (strcmp(af[i]->name, name) == 0) {
578                         return af[i];
579                 }
580         }
581         return NULL;
582 }
583
584 static method *get_method(address_family *af, char *name)
585 {
586         int i;
587
588         for (i = 0; i < af->n_methods; i++) {
589                 if (strcmp(af->method[i].name, name) == 0) {
590                         return &af->method[i];
591                 }
592         }
593         return(NULL);
594 }
595
596 static int duplicate_if(interface_defn *ifa, interface_defn *ifb)
597 {
598         if (strcmp(ifa->iface, ifb->iface) != 0) {
599                 return(0);
600         }
601         if (ifa->address_family != ifb->address_family) {
602                 return(0);
603         }
604         return(1);
605 }
606
607 static int get_line(char **result, size_t * result_len, FILE * f, int *line)
608 {
609         size_t pos;
610
611         do {
612                 pos = 0;
613                 do {
614                         if (*result_len - pos < 10) {
615                                 char *newstr = xrealloc(*result, *result_len * 2 + 80);
616                                 *result = newstr;
617                                 *result_len = *result_len * 2 + 80;
618                         }
619
620                         if (!fgets(*result + pos, *result_len - pos, f)) {
621                                 if (ferror(f) == 0 && pos == 0)
622                                         return 0;
623                                 if (ferror(f) != 0)
624                                         return 0;
625                         }
626                         pos += xstrlen(*result + pos);
627                 } while (pos == *result_len - 1 && (*result)[pos - 1] != '\n');
628
629                 if (pos != 0 && (*result)[pos - 1] == '\n') {
630                         (*result)[--pos] = '\0';
631                 }
632
633                 (*line)++;
634                 {
635                         int first = 0;
636
637                         while (isspace((*result)[first]) && (*result)[first]) {
638                                 first++;
639                         }
640
641                         memmove(*result, *result + first, pos - first + 1);
642                         pos -= first;
643                 }
644         } while ((*result)[0] == '#');
645
646         while ((*result)[pos - 1] == '\\') {
647                 (*result)[--pos] = '\0';
648                 do {
649                         if (*result_len - pos < 10) {
650                                 char *newstr = xrealloc(*result, *result_len * 2 + 80);
651                                 *result = newstr;
652                                 *result_len = *result_len * 2 + 80;
653                         }
654
655                         if (!fgets(*result + pos, *result_len - pos, f)) {
656                                 if (ferror(f) == 0 && pos == 0)
657                                         return 0;
658                                 if (ferror(f) != 0)
659                                         return 0;
660                         }
661                         pos += xstrlen(*result + pos);
662                 } while (pos == *result_len - 1 && (*result)[pos - 1] != '\n');
663
664                 if (pos != 0 && (*result)[pos - 1] == '\n') {
665                         (*result)[--pos] = '\0';
666                 }
667                 (*line)++;
668         }
669
670         while (isspace((*result)[pos - 1])) {   /* remove trailing whitespace */
671                 pos--;
672         }
673         (*result)[pos] = '\0';
674
675         return 1;
676 }
677
678 static interfaces_file *read_interfaces(char *filename)
679 {
680         interface_defn *currif = NULL;
681         interfaces_file *defn;
682         mapping_defn *currmap = NULL;
683         FILE *f;
684         char firstword[80];
685         char *buf = NULL;
686         char *rest;
687         int line;
688         size_t buf_len = 0;
689
690         enum { NONE, IFACE, MAPPING } currently_processing = NONE;
691
692         defn = xmalloc(sizeof(interfaces_file));
693         defn->max_autointerfaces = defn->n_autointerfaces = 0;
694         defn->autointerfaces = NULL;
695         defn->mappings = NULL;
696         defn->ifaces = NULL;
697         f = fopen(filename, "r");
698         if (f == NULL) {
699                 return NULL;
700         }
701         line = 0;
702
703         while (get_line(&buf, &buf_len, f, &line)) {
704                 rest = next_word(buf, firstword, 80);
705                 if (rest == NULL) {
706                         continue;       /* blank line */
707                 }
708
709                 if (strcmp(firstword, "mapping") == 0) {
710
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, char *opt)
1010 {
1011         int i;
1012         char buf[100];
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         sprintf(buf, "run-parts /etc/network/if-%s.d", opt);
1023         (*exec) (buf);
1024
1025         return (1);
1026 }
1027
1028 static int iface_up(interface_defn *iface)
1029 {
1030         if (!iface->method->up(iface, check)) {
1031                 return (-1);
1032         }
1033
1034         set_environ(iface, "start");
1035         if (!execute_all(iface, doit, "pre-up")) {
1036                 return (0);
1037         }
1038         if (!iface->method->up(iface, doit)) {
1039                 return (0);
1040         }
1041         if (!execute_all(iface, doit, "up")) {
1042                 return (0);
1043         }
1044
1045         return (1);
1046 }
1047
1048 static int iface_down(interface_defn *iface)
1049 {
1050         if (!iface->method->down(iface, check)) {
1051                 return (-1);
1052         }
1053         set_environ(iface, "stop");
1054         if (!execute_all(iface, doit, "down")) {
1055                 return (0);
1056         }
1057         if (!iface->method->down(iface, doit)) {
1058                 return (0);
1059         }
1060         if (!execute_all(iface, doit, "post-down")) {
1061                 return (0);
1062         }
1063         return (1);
1064 }
1065
1066 static int popen2(FILE **in, FILE **out, char *command, ...)
1067 {
1068         va_list ap;
1069         char *argv[11] = { command };
1070         int argc;
1071         int infd[2], outfd[2];
1072         pid_t pid;
1073
1074         argc = 1;
1075         va_start(ap, command);
1076         while ((argc < 10) && (argv[argc] = va_arg(ap, char *))) {
1077                 argc++;
1078         }
1079         argv[argc] = NULL;      /* make sure */
1080         va_end(ap);
1081
1082         if (pipe(infd) != 0) {
1083                 return 0;
1084         }
1085
1086         if (pipe(outfd) != 0) {
1087                 close(infd[0]);
1088                 close(infd[1]);
1089                 return 0;
1090         }
1091
1092         fflush(NULL);
1093         switch (pid = fork()) {
1094         case -1:                        /* failure */
1095                 close(infd[0]);
1096                 close(infd[1]);
1097                 close(outfd[0]);
1098                 close(outfd[1]);
1099                 return 0;
1100         case 0:                 /* child */
1101                 dup2(infd[0], 0);
1102                 dup2(outfd[1], 1);
1103                 close(infd[0]);
1104                 close(infd[1]);
1105                 close(outfd[0]);
1106                 close(outfd[1]);
1107                 execvp(command, argv);
1108                 exit(127);
1109         default:                        /* parent */
1110                 *in = fdopen(infd[1], "w");
1111                 *out = fdopen(outfd[0], "r");
1112                 close(infd[0]);
1113                 close(outfd[1]);
1114                 return pid;
1115         }
1116         /* unreached */
1117 }
1118
1119 static int run_mapping(char *physical, char *logical, int len, mapping_defn * map)
1120 {
1121         FILE *in, *out;
1122         int i, status;
1123         pid_t pid;
1124
1125
1126         pid = popen2(&in, &out, map->script, physical, NULL);
1127         if (pid == 0) {
1128                 return 0;
1129         }
1130         for (i = 0; i < map->n_mappings; i++) {
1131                 fprintf(in, "%s\n", map->mapping[i]);
1132         }
1133         fclose(in);
1134         waitpid(pid, &status, 0);
1135         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1136                 if (fgets(logical, len, out)) {
1137                         char *pch = logical + xstrlen(logical) - 1;
1138
1139                         while (pch >= logical && isspace(*pch))
1140                                 *(pch--) = '\0';
1141                 }
1142         }
1143         fclose(out);
1144
1145         return 1;
1146 }
1147
1148 static int lookfor_iface(char **ifaces, int n_ifaces, char *iface)
1149 {
1150         int i;
1151
1152         for (i = 0; i < n_ifaces; i++) {
1153                 if (strncmp(iface, ifaces[i], xstrlen(iface)) == 0) {
1154                         if (ifaces[i][xstrlen(iface)] == '=') {
1155                                 return i;
1156                         }
1157                 }
1158         }
1159
1160         return(-1);
1161 }
1162
1163 static void add_to_state(char ***ifaces, int *n_ifaces, int *max_ifaces, char *new_iface)
1164 {
1165         if (*max_ifaces == *n_ifaces) {
1166                 *max_ifaces = (*max_ifaces * 2) + 1;
1167                 *ifaces = xrealloc(*ifaces, sizeof(**ifaces) * *max_ifaces);
1168         }
1169
1170         (*ifaces)[(*n_ifaces)++] = new_iface;
1171 }
1172
1173 extern int ifupdown_main(int argc, char **argv)
1174 {
1175         int (*cmds) (interface_defn *) = NULL;
1176         struct option long_opts[] = {
1177                 {"help", no_argument, NULL, 'h'},
1178                 {"verbose", no_argument, NULL, 'v'},
1179                 {"all", no_argument, NULL, 'a'},
1180                 {"interfaces", required_argument, NULL, 'i'},
1181                 {"no-act", no_argument, NULL, 'n'},
1182                 {"no-mappings", no_argument, NULL, 1},
1183                 {"force", no_argument, NULL, 2},
1184                 {0, 0, 0, 0}
1185         };
1186         interfaces_file *defn;
1187         FILE *state_fp = NULL;
1188         char **target_iface = NULL;
1189         char **state = NULL;    /* list of iface=liface */
1190         char *interfaces = "/etc/network/interfaces";
1191         char *statefile = "/etc/network/ifstate";
1192
1193         int do_all = 0;
1194         int run_mappings = 1;
1195         int force = 0;
1196         int n_target_ifaces = 0;
1197         int n_state = 0;
1198         int max_state = 0;
1199         int i;
1200
1201         if (applet_name[2] == 'u') {
1202                 /* ifup command */
1203                 cmds = iface_up;
1204         } else {
1205                 /* ifdown command */
1206                 cmds = iface_down;
1207         }
1208
1209         while ((i = getopt_long(argc, argv, "i:hvna", long_opts, NULL)) != EOF) {
1210                 switch (i) {
1211                 case 'i':
1212                         interfaces = xstrdup(optarg);
1213                         break;
1214                 case 'v':
1215                         verbose = 1;
1216                         break;
1217                 case 'a':
1218                         do_all = 1;
1219                         break;
1220                 case 'n':
1221                         no_act = 1;
1222                         break;
1223                 case 1:
1224                         run_mappings = 0;
1225                         break;
1226                 case 2:
1227                         force = 1;
1228                         break;
1229                 default:
1230                         show_usage();
1231                         break;
1232                 }
1233         }
1234
1235         if (argc - optind > 0) {
1236                 if (do_all) {
1237                         show_usage();
1238                 }
1239         } else {
1240                 if (!do_all) {
1241                         show_usage();
1242                 }
1243         }                       
1244
1245         defn = read_interfaces(interfaces);
1246         if (!defn) {
1247                 error_msg_and_die("couldn't read interfaces file \"%s\"", interfaces);
1248         }
1249
1250         state_fp = fopen(statefile, no_act ? "r" : "a+");
1251         if (state_fp == NULL && !no_act) {
1252                 perror_msg_and_die("failed to open statefile %s", statefile);
1253         }
1254
1255         if (state_fp != NULL) {
1256                 char buf[80];
1257                 char *p;
1258
1259                 if (!no_act) {
1260                         int flags;
1261                         struct flock lock;
1262                         const int state_fd = fileno(state_fp);
1263                         
1264                         flags = fcntl(state_fd, F_GETFD);
1265                         if ((flags < 0) || (fcntl(state_fd, F_SETFD, flags | FD_CLOEXEC) < 0)) {
1266                                 perror_msg_and_die("failed to set FD_CLOEXEC on statefile %s", statefile);
1267                         }
1268
1269                         lock.l_type = F_WRLCK;
1270                         lock.l_whence = SEEK_SET;
1271                         lock.l_start = 0;
1272                         lock.l_len = 0;
1273
1274                         if (fcntl(state_fd, F_SETLKW, &lock) < 0) {
1275                                 perror_msg_and_die("failed to lock statefile %s", statefile);
1276                         }
1277                 }
1278
1279                 rewind(state_fp);
1280                 while ((p = fgets(buf, sizeof buf, state_fp)) != NULL) {
1281                         char *pch;
1282
1283                         pch = buf + xstrlen(buf) - 1;
1284                         while (pch > buf && isspace(*pch)) {
1285                                 pch--;
1286                         }
1287                         *(pch + 1) = '\0';
1288
1289                         pch = buf;
1290                         while (isspace(*pch)) {
1291                                 pch++;
1292                         }
1293
1294                         add_to_state(&state, &n_state, &max_state, xstrdup(pch));
1295                 }
1296         }
1297
1298         if (do_all) {
1299                 if (cmds == iface_up) {
1300                         target_iface = defn->autointerfaces;
1301                         n_target_ifaces = defn->n_autointerfaces;
1302                 } else if (cmds == iface_down) {
1303                         target_iface = state;
1304                         n_target_ifaces = n_state;
1305                 }
1306         } else {
1307                 target_iface = argv + optind;
1308                 n_target_ifaces = argc - optind;
1309         }
1310
1311
1312         for (i = 0; i < n_target_ifaces; i++) {
1313                 interface_defn *currif;
1314                 char iface[80];
1315                 char liface[80];
1316                 char *pch;
1317                 int okay = 0;
1318
1319                 strncpy(iface, target_iface[i], sizeof(iface));
1320                 iface[sizeof(iface) - 1] = '\0';
1321
1322                 if ((pch = strchr(iface, '='))) {
1323                         *pch = '\0';
1324                         strncpy(liface, pch + 1, sizeof(liface));
1325                         liface[sizeof(liface) - 1] = '\0';
1326                 } else {
1327                         strncpy(liface, iface, sizeof(liface));
1328                         liface[sizeof(liface) - 1] = '\0';
1329                 }
1330                 if (!force) {
1331                         int already_up = lookfor_iface(state, n_state, iface);;
1332
1333                         if (cmds == iface_up) {
1334                                 /* ifup */
1335                                 if (already_up != -1) {
1336                                         error_msg("interface %s already configured", iface);
1337                                         continue;
1338                                 }
1339                         } else {
1340                                 /* ifdown */
1341                                 if (already_up == -1) {
1342                                         error_msg("interface %s not configured", iface);
1343                                         continue;
1344                                 }
1345                                 strncpy(liface, strchr(state[already_up], '=') + 1, 80);
1346                                 liface[79] = 0;
1347                         }
1348                 }
1349
1350                 if ((cmds == iface_up) && run_mappings) {
1351                         mapping_defn *currmap;
1352
1353                         for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1354
1355                                 for (i = 0; i < currmap->n_matches; i++) {
1356                                         if (fnmatch(currmap->match[i], liface, 0) != 0)
1357                                                 continue;
1358                                         if (verbose) {
1359                                                 error_msg("Running mapping script %s on %s", currmap->script, liface);
1360                                         }
1361                                         run_mapping(iface, liface, sizeof(liface), currmap);
1362                                         break;
1363                                 }
1364                         }
1365                 }
1366
1367
1368                 for (currif = defn->ifaces; currif; currif = currif->next) {
1369                         if (strcmp(liface, currif->iface) == 0) {
1370                                 char *oldiface = currif->iface;
1371
1372                                 okay = 1;
1373
1374                                 currif->iface = iface;
1375
1376                                 if (verbose) {
1377                                         error_msg("Configuring interface %s=%s (%s)", iface, liface, currif->address_family->name);
1378                                 }
1379
1380                                 switch (cmds(currif)) {
1381                                 case -1:
1382                                         printf
1383                                                 ("Don't seem to be have all the variables for %s/%s.\n",
1384                                                  liface, currif->address_family->name);
1385                                         break;
1386                                 case 0:
1387                                         /* this wasn't entirely successful, should it be added to
1388                                          *      the state file?
1389                                          */
1390                                 case 1:
1391                                         /* successful */
1392                                 }
1393                                 currif->iface = oldiface;
1394                         }
1395                 }
1396
1397                 if (!okay && !force) {
1398                         error_msg("Ignoring unknown interface %s=%s.", iface, liface);
1399                 } else {
1400                         int already_up = lookfor_iface(state, n_state, iface);
1401
1402                         if (cmds == iface_up) {
1403                                 char *newiface = xmalloc(xstrlen(iface) + 1 + xstrlen(liface) + 1);
1404                                 sprintf(newiface, "%s=%s", iface, liface);
1405                                 if (already_up == -1) {
1406                                         add_to_state(&state, &n_state, &max_state, newiface);
1407                                 } else {
1408                                         free(state[already_up]);
1409                                         state[already_up] = newiface;
1410                                 }
1411                         } else if (cmds == iface_down) {
1412                                 if (already_up != -1) {
1413                                         state[already_up] = state[--n_state];
1414                                 }
1415                         }
1416                 }
1417                 if (state_fp != NULL && !no_act) {
1418                         if (ftruncate(fileno(state_fp), 0) < 0) {
1419                                 error_msg_and_die("failed to truncate statefile %s: %s", statefile, strerror(errno));
1420                         }
1421
1422                         rewind(state_fp);
1423                         for (i = 0; i < n_state; i++) {
1424                                 fputs(state[i], state_fp);
1425                                 fputc('\n', state_fp);
1426                         }
1427                         fflush(state_fp);
1428                 }
1429         }
1430
1431         if (state_fp != NULL) {
1432                 fclose(state_fp);
1433                 state_fp = NULL;
1434         }
1435
1436         return 0;
1437 }