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