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