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