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