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