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