fedae8dd6a282419a2b83d33657226283a6b7547
[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         **buf = '\0';
634         (*buf)++;
635
636         return word;
637 }
638
639 static struct address_family_t *get_address_family(struct address_family_t *af[], char *name)
640 {
641         int i;
642
643         for (i = 0; af[i]; i++) {
644                 if (strcmp(af[i]->name, name) == 0) {
645                         return af[i];
646                 }
647         }
648         return NULL;
649 }
650
651 static struct method_t *get_method(struct address_family_t *af, char *name)
652 {
653         int i;
654
655         for (i = 0; i < af->n_methods; i++) {
656                 if (strcmp(af->method[i].name, name) == 0) {
657                         return &af->method[i];
658                 }
659         }
660         return(NULL);
661 }
662
663 static int duplicate_if(struct interface_defn_t *ifa, struct interface_defn_t *ifb)
664 {
665         if (strcmp(ifa->iface, ifb->iface) != 0) {
666                 return(0);
667         }
668         if (ifa->address_family != ifb->address_family) {
669                 return(0);
670         }
671         return(1);
672 }
673
674 static const llist_t *find_list_string(const llist_t *list, const char *string)
675 {
676         while (list) {
677                 if (strcmp(list->data, string) == 0) {
678                         return(list);
679                 }
680                 list = list->link;
681         }
682         return(NULL);
683 }
684
685 static struct interfaces_file_t *read_interfaces(char *filename)
686 {
687 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
688         struct mapping_defn_t *currmap = NULL;
689 #endif
690         struct interface_defn_t *currif = NULL;
691         struct interfaces_file_t *defn;
692         FILE *f;
693         char *firstword;
694         char *buf;
695
696         enum { NONE, IFACE, MAPPING } currently_processing = NONE;
697
698         defn = xmalloc(sizeof(struct interfaces_file_t));
699         defn->autointerfaces = NULL;
700         defn->mappings = NULL;
701         defn->ifaces = NULL;
702
703         f = bb_xfopen(filename, "r");
704
705         while ((buf = bb_get_chomped_line_from_file(f)) != NULL) {
706                 char *buf_ptr = buf;
707
708                 /* Ignore comments */
709                 if (buf[0] == '#') {
710                         continue;
711                 }
712
713                 firstword = next_word(&buf_ptr);
714                 if (firstword == NULL) {
715                         continue;       /* blank line */
716                 }
717
718                 if (strcmp(firstword, "mapping") == 0) {
719 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
720                         currmap = xmalloc(sizeof(struct mapping_defn_t));
721                         currmap->max_matches = 0;
722                         currmap->n_matches = 0;
723                         currmap->match = NULL;
724
725                         while ((firstword = next_word(&buf_ptr)) != NULL) {
726                                 if (currmap->max_matches == currmap->n_matches) {
727                                         currmap->max_matches = currmap->max_matches * 2 + 1;
728                                         currmap->match = xrealloc(currmap->match, sizeof(currmap->match) * currmap->max_matches);
729                                 }
730
731                                 currmap->match[currmap->n_matches++] = bb_xstrdup(firstword);
732                         }
733                         currmap->max_mappings = 0;
734                         currmap->n_mappings = 0;
735                         currmap->mapping = NULL;
736                         currmap->script = NULL;
737                         {
738                                 struct mapping_defn_t **where = &defn->mappings;
739                                 while (*where != NULL) {
740                                         where = &(*where)->next;
741                                 }
742                                 *where = currmap;
743                                 currmap->next = NULL;
744                         }
745                         debug_noise("Added mapping\n");
746 #endif
747                         currently_processing = MAPPING;
748                 } else if (strcmp(firstword, "iface") == 0) {
749                         {
750                                 char *iface_name;
751                                 char *address_family_name;
752                                 char *method_name;
753                                 struct address_family_t *addr_fams[] = {
754 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV4
755                                         &addr_inet,
756 #endif
757 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV6
758                                         &addr_inet6,
759 #endif
760 #ifdef CONFIG_FEATURE_IFUPDOWN_IPX
761                                         &addr_ipx,
762 #endif
763                                         NULL
764                                 };
765
766                                 currif = xmalloc(sizeof(struct interface_defn_t));
767                                 iface_name = next_word(&buf_ptr);
768                                 address_family_name = next_word(&buf_ptr);
769                                 method_name = next_word(&buf_ptr);
770
771                                 if (buf_ptr == NULL) {
772                                         bb_error_msg("too few parameters for line \"%s\"", buf);
773                                         return NULL;
774                                 }
775
776                                 if (buf_ptr[0] != '\0') {
777                                         bb_error_msg("too many parameters \"%s\"", buf);
778                                         return NULL;
779                                 }
780
781                                 currif->iface = bb_xstrdup(iface_name);
782
783                                 currif->address_family = get_address_family(addr_fams, address_family_name);
784                                 if (!currif->address_family) {
785                                         bb_error_msg("unknown address type \"%s\"", buf);
786                                         return NULL;
787                                 }
788
789                                 currif->method = get_method(currif->address_family, method_name);
790                                 if (!currif->method) {
791                                         bb_error_msg("unknown method \"%s\"", buf);
792                                         return NULL;
793                                 }
794
795                                 currif->automatic = 1;
796                                 currif->max_options = 0;
797                                 currif->n_options = 0;
798                                 currif->option = NULL;
799
800                                 {
801                                         struct interface_defn_t *tmp;
802                                         llist_t *iface_list;
803                                         iface_list = defn->ifaces;
804                                         while (iface_list) {
805                                                 tmp = (struct interface_defn_t *) iface_list->data;
806                                                 if (duplicate_if(tmp, currif)) {
807                                                         bb_error_msg("duplicate interface \"%s\"", tmp->iface);
808                                                         return NULL;
809                                                 }
810                                                 iface_list = iface_list->link;
811                                         }
812
813                                         defn->ifaces = llist_add_to_end(defn->ifaces, (char*)currif);
814                                 }
815                                 debug_noise("iface %s %s %s\n", currif->iface, address_family_name, method_name);
816                         }
817                         currently_processing = IFACE;
818                 } else if (strcmp(firstword, "auto") == 0) {
819                         while ((firstword = next_word(&buf_ptr)) != NULL) {
820
821                                 /* Check the interface isnt already listed */
822                                 if (find_list_string(defn->autointerfaces, firstword)) {
823                                         bb_perror_msg_and_die("interface declared auto twice \"%s\"", buf);
824                                 }
825
826                                 /* Add the interface to the list */
827                                 defn->autointerfaces = llist_add_to_end(defn->autointerfaces, strdup(firstword));
828                                 debug_noise("\nauto %s\n", firstword);
829                         }
830                         currently_processing = NONE;
831                 } else {
832                         switch (currently_processing) {
833                                 case IFACE:
834                                         {
835                                                 int i;
836
837                                                 if (bb_strlen(buf_ptr) == 0) {
838                                                         bb_error_msg("option with empty value \"%s\"", buf);
839                                                         return NULL;
840                                                 }
841
842                                                 if (strcmp(firstword, "up") != 0
843                                                                 && strcmp(firstword, "down") != 0
844                                                                 && strcmp(firstword, "pre-up") != 0
845                                                                 && strcmp(firstword, "post-down") != 0) {
846                                                         for (i = 0; i < currif->n_options; i++) {
847                                                                 if (strcmp(currif->option[i].name, firstword) == 0) {
848                                                                         bb_error_msg("duplicate option \"%s\"", buf);
849                                                                         return NULL;
850                                                                 }
851                                                         }
852                                                 }
853                                         }
854                                         if (currif->n_options >= currif->max_options) {
855                                                 struct variable_t *opt;
856
857                                                 currif->max_options = currif->max_options + 10;
858                                                 opt = xrealloc(currif->option, sizeof(*opt) * currif->max_options);
859                                                 currif->option = opt;
860                                         }
861                                         currif->option[currif->n_options].name = bb_xstrdup(firstword);
862                                         currif->option[currif->n_options].value = bb_xstrdup(buf_ptr);
863                                         if (!currif->option[currif->n_options].name) {
864                                                 perror(filename);
865                                                 return NULL;
866                                         }
867                                         if (!currif->option[currif->n_options].value) {
868                                                 perror(filename);
869                                                 return NULL;
870                                         }
871                                         debug_noise("\t%s=%s\n", currif->option[currif->n_options].name, 
872                                                         currif->option[currif->n_options].value);
873                                         currif->n_options++;
874                                         break;
875                                 case MAPPING:
876 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
877                                         if (strcmp(firstword, "script") == 0) {
878                                                 if (currmap->script != NULL) {
879                                                         bb_error_msg("duplicate script in mapping \"%s\"", buf);
880                                                         return NULL;
881                                                 } else {
882                                                         currmap->script = bb_xstrdup(next_word(&buf_ptr));
883                                                 }
884                                         } else if (strcmp(firstword, "map") == 0) {
885                                                 if (currmap->max_mappings == currmap->n_mappings) {
886                                                         currmap->max_mappings = currmap->max_mappings * 2 + 1;
887                                                         currmap->mapping = xrealloc(currmap->mapping, sizeof(char *) * currmap->max_mappings);
888                                                 }
889                                                 currmap->mapping[currmap->n_mappings] = bb_xstrdup(next_word(&buf_ptr));
890                                                 currmap->n_mappings++;
891                                         } else {
892                                                 bb_error_msg("misplaced option \"%s\"", buf);
893                                                 return NULL;
894                                         }
895 #endif
896                                         break;
897                                 case NONE:
898                                 default:
899                                         bb_error_msg("misplaced option \"%s\"", buf);
900                                         return NULL;
901                         }
902                 }
903                 free(buf);
904         }
905         if (ferror(f) != 0) {
906                 bb_perror_msg_and_die("%s", filename);
907         }
908         fclose(f);
909
910         return defn;
911 }
912
913 static char *setlocalenv(char *format, char *name, char *value)
914 {
915         char *result;
916         char *here;
917         char *there;
918
919         result = xmalloc(bb_strlen(format) + bb_strlen(name) + bb_strlen(value) + 1);
920
921         sprintf(result, format, name, value);
922
923         for (here = there = result; *there != '=' && *there; there++) {
924                 if (*there == '-')
925                         *there = '_';
926                 if (isalpha(*there))
927                         *there = toupper(*there);
928
929                 if (isalnum(*there) || *there == '_') {
930                         *here = *there;
931                         here++;
932                 }
933         }
934         memmove(here, there, bb_strlen(there) + 1);
935
936         return result;
937 }
938
939 static void set_environ(struct interface_defn_t *iface, char *mode)
940 {
941         char **environend;
942         int i;
943         const int n_env_entries = iface->n_options + 5;
944         char **ppch;
945
946         if (environ != NULL) {
947                 for (ppch = environ; *ppch; ppch++) {
948                         free(*ppch);
949                         *ppch = NULL;
950                 }
951                 free(environ);
952                 environ = NULL;
953         }
954         environ = xmalloc(sizeof(char *) * (n_env_entries + 1 /* for final NULL */ ));
955         environend = environ;
956         *environend = NULL;
957
958         for (i = 0; i < iface->n_options; i++) {
959                 if (strcmp(iface->option[i].name, "up") == 0
960                                 || strcmp(iface->option[i].name, "down") == 0
961                                 || strcmp(iface->option[i].name, "pre-up") == 0
962                                 || strcmp(iface->option[i].name, "post-down") == 0) {
963                         continue;
964                 }
965                 *(environend++) = setlocalenv("IF_%s=%s", iface->option[i].name, iface->option[i].value);
966                 *environend = NULL;
967         }
968
969         *(environend++) = setlocalenv("%s=%s", "IFACE", iface->iface);
970         *environend = NULL;
971         *(environend++) = setlocalenv("%s=%s", "ADDRFAM", iface->address_family->name);
972         *environend = NULL;
973         *(environend++) = setlocalenv("%s=%s", "METHOD", iface->method->name);
974         *environend = NULL;
975         *(environend++) = setlocalenv("%s=%s", "MODE", mode);
976         *environend = NULL;
977         *(environend++) = setlocalenv("%s=%s", "PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
978         *environend = NULL;
979 }
980
981 static int doit(char *str)
982 {
983         if (verbose || no_act) {
984                 printf("%s\n", str);
985         }
986         if (!no_act) {
987                 pid_t child;
988                 int status;
989
990                 fflush(NULL);
991                 switch (child = fork()) {
992                         case -1:                /* failure */
993                                 return 0;
994                         case 0:         /* child */
995                                 execle("/bin/sh", "/bin/sh", "-c", str, NULL, environ);
996                                 exit(127);
997                 }
998                 waitpid(child, &status, 0);
999                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1000                         return 0;
1001                 }
1002         }
1003         return (1);
1004 }
1005
1006 static int execute_all(struct interface_defn_t *ifd, execfn *exec, const char *opt)
1007 {
1008         int i;
1009         char *buf;
1010
1011         for (i = 0; i < ifd->n_options; i++) {
1012                 if (strcmp(ifd->option[i].name, opt) == 0) {
1013                         if (!(*exec) (ifd->option[i].value)) {
1014                                 return 0;
1015                         }
1016                 }
1017         }
1018
1019         buf = xmalloc(bb_strlen(opt) + 19);
1020         sprintf(buf, "/etc/network/if-%s.d", opt);
1021         run_parts(&buf, 2);
1022         free(buf);
1023         return (1);
1024 }
1025
1026 static int check(char *str) {
1027         return str != NULL;
1028 }
1029
1030 static int iface_up(struct interface_defn_t *iface)
1031 {
1032         int result;
1033         if (!iface->method->up(iface,check)) return -1;
1034         set_environ(iface, "start");
1035         result = execute_all(iface, doit, "pre-up");
1036         result += iface->method->up(iface, doit);
1037         result += execute_all(iface, doit, "up");
1038         return(result);
1039 }
1040
1041 static int iface_down(struct interface_defn_t *iface)
1042 {
1043         int result;
1044         if (!iface->method->down(iface,check)) return -1;
1045         set_environ(iface, "stop");
1046         result = execute_all(iface, doit, "down");
1047         result += iface->method->down(iface, doit);
1048         result += execute_all(iface, doit, "post-down");
1049         return(result);
1050 }
1051
1052 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1053 static int popen2(FILE **in, FILE **out, char *command, ...)
1054 {
1055         va_list ap;
1056         char *argv[11] = { command };
1057         int argc;
1058         int infd[2], outfd[2];
1059         pid_t pid;
1060
1061         argc = 1;
1062         va_start(ap, command);
1063         while ((argc < 10) && (argv[argc] = va_arg(ap, char *))) {
1064                 argc++;
1065         }
1066         argv[argc] = NULL;      /* make sure */
1067         va_end(ap);
1068
1069         if (pipe(infd) != 0) {
1070                 return 0;
1071         }
1072
1073         if (pipe(outfd) != 0) {
1074                 close(infd[0]);
1075                 close(infd[1]);
1076                 return 0;
1077         }
1078
1079         fflush(NULL);
1080         switch (pid = fork()) {
1081                 case -1:                        /* failure */
1082                         close(infd[0]);
1083                         close(infd[1]);
1084                         close(outfd[0]);
1085                         close(outfd[1]);
1086                         return 0;
1087                 case 0:                 /* child */
1088                         dup2(infd[0], 0);
1089                         dup2(outfd[1], 1);
1090                         close(infd[0]);
1091                         close(infd[1]);
1092                         close(outfd[0]);
1093                         close(outfd[1]);
1094                         execvp(command, argv);
1095                         exit(127);
1096                 default:                        /* parent */
1097                         *in = fdopen(infd[1], "w");
1098                         *out = fdopen(outfd[0], "r");
1099                         close(infd[0]);
1100                         close(outfd[1]);
1101                         return pid;
1102         }
1103         /* unreached */
1104 }
1105
1106 static int run_mapping(char *physical, char *logical, int len, struct mapping_defn_t * map)
1107 {
1108         FILE *in, *out;
1109         int i, status;
1110         pid_t pid;
1111
1112
1113         pid = popen2(&in, &out, map->script, physical, NULL);
1114         if (pid == 0) {
1115                 return 0;
1116         }
1117         for (i = 0; i < map->n_mappings; i++) {
1118                 fprintf(in, "%s\n", map->mapping[i]);
1119         }
1120         fclose(in);
1121         waitpid(pid, &status, 0);
1122         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1123                 if (fgets(logical, len, out)) {
1124                         char *pch = logical + bb_strlen(logical) - 1;
1125
1126                         while (pch >= logical && isspace(*pch))
1127                                 *(pch--) = '\0';
1128                 }
1129         }
1130         fclose(out);
1131
1132         return 1;
1133 }
1134 #endif /* CONFIG_FEATURE_IFUPDOWN_IPV6 */
1135
1136 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1137 {
1138         unsigned short iface_len = bb_strlen(iface);
1139         llist_t *search = state_list;
1140
1141         while (search) {
1142                 if ((strncmp(search->data, iface, iface_len) == 0) &&
1143                                 (search->data[iface_len] == '=')) {
1144                         return(search);
1145                 }
1146                 search = search->link;
1147         }
1148         return(NULL);
1149 }
1150
1151 extern int ifupdown_main(int argc, char **argv)
1152 {
1153         int (*cmds) (struct interface_defn_t *) = NULL;
1154         struct interfaces_file_t *defn;
1155         FILE *state_fp = NULL;
1156         llist_t *state_list = NULL;
1157         llist_t *target_list = NULL;
1158         char *interfaces = "/etc/network/interfaces";
1159         const char *statefile = "/var/run/ifstate";
1160
1161 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1162         int run_mappings = 1;
1163 #endif
1164         int do_all = 0;
1165         int force = 0;
1166         int i;
1167
1168         if (bb_applet_name[2] == 'u') {
1169                 /* ifup command */
1170                 cmds = iface_up;
1171         } else {
1172                 /* ifdown command */
1173                 cmds = iface_down;
1174         }
1175
1176 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1177         while ((i = getopt(argc, argv, "i:hvnamf")) != -1)
1178 #else
1179                 while ((i = getopt(argc, argv, "i:hvnaf")) != -1) 
1180 #endif
1181                 {
1182                         switch (i) {
1183                                 case 'i':       /* interfaces */
1184                                         interfaces = bb_xstrdup(optarg);
1185                                         break;
1186                                 case 'v':       /* verbose */
1187                                         verbose = 1;
1188                                         break;
1189                                 case 'a':       /* all */
1190                                         do_all = 1;
1191                                         break;
1192                                 case 'n':       /* no-act */
1193                                         no_act = 1;
1194                                         break;
1195 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1196                                 case 'm':       /* no-mappings */
1197                                         run_mappings = 0;
1198                                         break;
1199 #endif
1200                                 case 'f':       /* force */
1201                                         force = 1;
1202                                         break;
1203                                 default:
1204                                         bb_show_usage();
1205                                         break;
1206                         }
1207                 }
1208
1209         if (argc - optind > 0) {
1210                 if (do_all) {
1211                         bb_show_usage();
1212                 }
1213         } else {
1214                 if (!do_all) {
1215                         bb_show_usage();
1216                 }
1217         }                       
1218
1219         debug_noise("reading %s file:\n", interfaces);
1220         defn = read_interfaces(interfaces);
1221         debug_noise("\ndone reading %s\n\n", interfaces);
1222
1223         if (no_act) {
1224                 state_fp = fopen(statefile, "r");
1225         }
1226
1227         /* Create a list of interfaces to work on */
1228         if (do_all) {
1229                 if (cmds == iface_up) {
1230                         target_list = defn->autointerfaces;
1231                 } else {
1232 #if 0
1233                         /* iface_down */
1234                         llist_t *new_item;
1235                         const llist_t *list = state_list;
1236                         while (list) {
1237                                 new_item = xmalloc(sizeof(llist_t));
1238                                 new_item->data = strdup(list->data);
1239                                 new_item->link = NULL;
1240                                 list = target_list;
1241                                 if (list == NULL)
1242                                         target_list = new_item;
1243                                 else {
1244                                         while (list->link) {
1245                                                 list = list->link;
1246                                         }
1247                                         list = new_item;
1248                                 }
1249                                 list = list->link;
1250                         }
1251                         target_list = defn->autointerfaces;
1252 #else
1253
1254                         /* iface_down */
1255                         const llist_t *list = state_list;
1256                         while (list) {
1257                                 target_list = llist_add_to_end(target_list, strdup(list->data));
1258                                 list = list->link;
1259                         }
1260                         target_list = defn->autointerfaces;
1261 #endif  
1262                 } 
1263         } else {
1264                 target_list = llist_add_to_end(target_list, argv[optind]);
1265         }
1266
1267
1268         /* Update the interfaces */
1269         while (target_list) {
1270                 llist_t *iface_list;
1271                 struct interface_defn_t *currif;
1272                 char *iface;
1273                 char *liface;
1274                 char *pch;
1275                 int okay = 0;
1276
1277                 iface = strdup(target_list->data);
1278                 target_list = target_list->link;
1279
1280                 pch = strchr(iface, '=');
1281                 if (pch) {
1282                         *pch = '\0';
1283                         liface = strdup(pch + 1);
1284                 } else {
1285                         liface = strdup(iface);
1286                 }
1287
1288                 if (!force) {
1289                         const llist_t *iface_state = find_iface_state(state_list, iface);
1290
1291                         if (cmds == iface_up) {
1292                                 /* ifup */
1293                                 if (iface_state) {
1294                                         bb_error_msg("interface %s already configured", iface);
1295                                         continue;
1296                                 }
1297                         } else {
1298                                 /* ifdown */
1299                                 if (iface_state) {
1300                                         bb_error_msg("interface %s not configured", iface);
1301                                         continue;
1302                                 }
1303                         }
1304                 }
1305
1306 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1307                 if ((cmds == iface_up) && run_mappings) {
1308                         struct mapping_defn_t *currmap;
1309
1310                         for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1311
1312                                 for (i = 0; i < currmap->n_matches; i++) {
1313                                         if (fnmatch(currmap->match[i], liface, 0) != 0)
1314                                                 continue;
1315                                         if (verbose) {
1316                                                 printf("Running mapping script %s on %s\n", currmap->script, liface);
1317                                         }
1318                                         run_mapping(iface, liface, sizeof(liface), currmap);
1319                                         break;
1320                                 }
1321                         }
1322                 }
1323 #endif
1324
1325
1326                 iface_list = defn->ifaces;
1327                 while (iface_list) {
1328                         currif = (struct interface_defn_t *) iface_list->data;
1329                         if (strcmp(liface, currif->iface) == 0) {
1330                                 char *oldiface = currif->iface;
1331
1332                                 okay = 1;
1333                                 currif->iface = iface;
1334
1335                                 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1336
1337                                 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1338                                 if (cmds(currif) == -1) {
1339                                         bb_error_msg("Don't seem to be have all the variables for %s/%s.",
1340                                                         liface, currif->address_family->name);
1341                                 }
1342
1343                                 currif->iface = oldiface;
1344                         }
1345                         iface_list = iface_list->link;
1346                 }
1347                 if (verbose) {
1348                         printf("\n");
1349                 }
1350
1351                 if (!okay && !force) {
1352                         bb_error_msg("Ignoring unknown interface %s", liface);
1353                 } else {
1354                         llist_t *iface_state = find_iface_state(state_list, iface);
1355
1356                         if (cmds == iface_up) {
1357                                 char *newiface = xmalloc(bb_strlen(iface) + 1 + bb_strlen(liface) + 1);
1358                                 sprintf(newiface, "%s=%s", iface, liface);
1359                                 if (iface_state == NULL) {
1360                                         state_list = llist_add_to_end(state_list, newiface);
1361                                 } else {
1362                                         free(iface_state->data);
1363                                         iface_state->data = newiface;
1364                                 }
1365                         } else if (cmds == iface_down) {
1366                                 /* Remove an interface from the linked list */
1367                                 if (iface_state) {
1368                                         /* This needs to be done better */
1369                                         free(iface_state->data);
1370                                         free(iface_state->link);
1371                                         if (iface_state->link) {
1372                                                 iface_state->data = iface_state->link->data;
1373                                                 iface_state->link = iface_state->link->link;
1374                                         } else {
1375                                                 iface_state->data = NULL;
1376                                                 iface_state->link = NULL;
1377                                         }                                               
1378                                 }
1379                         }
1380                 }
1381         }
1382
1383         /* Actually write the new state */
1384         if (!no_act) {
1385
1386                 if (state_fp)
1387                         fclose(state_fp);
1388                 state_fp = bb_xfopen(statefile, "a+");
1389
1390                 if (ftruncate(fileno(state_fp), 0) < 0) {
1391                         bb_error_msg_and_die("failed to truncate statefile %s: %s", statefile, strerror(errno));
1392                 }
1393
1394                 rewind(state_fp);
1395
1396                 while (state_list) {
1397                         if (state_list->data) {
1398                                 fputs(state_list->data, state_fp);
1399                                 fputc('\n', state_fp);
1400                         }
1401                         state_list = state_list->link;
1402                 }
1403                 fflush(state_fp);
1404         }
1405
1406         /* Cleanup */
1407         if (state_fp != NULL) {
1408                 fclose(state_fp);
1409                 state_fp = NULL;
1410         }
1411
1412         return 0;
1413 }