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