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