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