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