ifupdown: style cleanup, no code changes
[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 static unsigned option_mask;
93 #define OPTION_STR "anvf" USE_FEATURE_IFUPDOWN_MAPPING("m") "i:"
94 enum {
95         OPT_do_all = 0x1,
96         OPT_no_act = 0x2,
97         OPT_verbose = 0x4,
98         OPT_force = 0x8,
99         OPT_no_mappings = 0x10,
100 };
101 #define DO_ALL (option_mask & OPT_do_all)
102 #define NO_ACT (option_mask & OPT_no_act)
103 #define VERBOSE (option_mask & OPT_verbose)
104 #define FORCE (option_mask & OPT_force)
105 #define NO_MAPPINGS (option_mask & OPT_no_mappings)
106
107 static char **__myenviron;
108
109 #if ENABLE_FEATURE_IFUPDOWN_IPV4 || ENABLE_FEATURE_IFUPDOWN_IPV6
110
111 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
112
113 static unsigned int count_bits(unsigned int a)
114 {
115         unsigned int result;
116         result = (a & 0x55) + ((a >> 1) & 0x55);
117         result = (result & 0x33) + ((result >> 2) & 0x33);
118         return ((result & 0x0F) + ((result >> 4) & 0x0F));
119 }
120
121 static int count_netmask_bits(char *dotted_quad)
122 {
123         unsigned int result, a, b, c, d;
124         /* Found a netmask...  Check if it is dotted quad */
125         if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
126                 return -1;
127         result = count_bits(a);
128         result += count_bits(b);
129         result += count_bits(c);
130         result += count_bits(d);
131         return (int)result;
132 }
133 #endif
134
135 static void addstr(char **buf, size_t *len, size_t *pos, char *str, size_t str_length)
136 {
137         if (*pos + str_length >= *len) {
138                 char *newbuf;
139
140                 newbuf = xrealloc(*buf, *len * 2 + str_length + 1);
141                 *buf = newbuf;
142                 *len = *len * 2 + str_length + 1;
143         }
144
145         while (str_length-- >= 1) {
146                 (*buf)[(*pos)++] = *str;
147                 str++;
148         }
149         (*buf)[*pos] = '\0';
150 }
151
152 static int strncmpz(char *l, char *r, size_t llen)
153 {
154         int i = strncmp(l, r, llen);
155
156         if (i == 0) {
157                 return -r[llen];
158         } else {
159                 return i;
160         }
161 }
162
163 static char *get_var(char *id, size_t idlen, struct interface_defn_t *ifd)
164 {
165         int i;
166
167         if (strncmpz(id, "iface", idlen) == 0) {
168                 char *result;
169                 static char label_buf[20];
170                 strncpy(label_buf, ifd->iface, 19);
171                 label_buf[19]=0;
172                 result = strchr(label_buf, ':');
173                 if (result) {
174                         *result=0;
175                 }
176                 return label_buf;
177         } else if (strncmpz(id, "label", idlen) == 0) {
178                 return ifd->iface;
179         } else {
180                 for (i = 0; i < ifd->n_options; i++) {
181                         if (strncmpz(id, ifd->option[i].name, idlen) == 0) {
182                                 return ifd->option[i].value;
183                         }
184                 }
185         }
186
187         return NULL;
188 }
189
190 static char *parse(char *command, struct interface_defn_t *ifd)
191 {
192
193         char *result = NULL;
194         size_t pos = 0, len = 0;
195         size_t old_pos[MAX_OPT_DEPTH] = { 0 };
196         int okay[MAX_OPT_DEPTH] = { 1 };
197         int opt_depth = 1;
198
199         while (*command) {
200                 switch (*command) {
201                 default:
202                         addstr(&result, &len, &pos, command, 1);
203                         command++;
204                         break;
205                 case '\\':
206                         if (command[1]) {
207                                 addstr(&result, &len, &pos, command + 1, 1);
208                                 command += 2;
209                         } else {
210                                 addstr(&result, &len, &pos, command, 1);
211                                 command++;
212                         }
213                         break;
214                 case '[':
215                         if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
216                                 old_pos[opt_depth] = pos;
217                                 okay[opt_depth] = 1;
218                                 opt_depth++;
219                                 command += 2;
220                         } else {
221                                 addstr(&result, &len, &pos, "[", 1);
222                                 command++;
223                         }
224                         break;
225                 case ']':
226                         if (command[1] == ']' && opt_depth > 1) {
227                                 opt_depth--;
228                                 if (!okay[opt_depth]) {
229                                         pos = old_pos[opt_depth];
230                                         result[pos] = '\0';
231                                 }
232                                 command += 2;
233                         } else {
234                                 addstr(&result, &len, &pos, "]", 1);
235                                 command++;
236                         }
237                         break;
238                 case '%':
239                         {
240                                 char *nextpercent;
241                                 char *varvalue;
242
243                                 command++;
244                                 nextpercent = strchr(command, '%');
245                                 if (!nextpercent) {
246                                         errno = EUNBALPER;
247                                         free(result);
248                                         return NULL;
249                                 }
250
251                                 varvalue = get_var(command, nextpercent - command, ifd);
252
253                                 if (varvalue) {
254                                         addstr(&result, &len, &pos, varvalue, strlen(varvalue));
255                                 } else {
256 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
257                                         /* Sigh...  Add a special case for 'ip' to convert from
258                                          * dotted quad to bit count style netmasks.  */
259                                         if (strncmp(command, "bnmask", 6)==0) {
260                                                 int res;
261                                                 varvalue = get_var("netmask", 7, ifd);
262                                                 if (varvalue && (res=count_netmask_bits(varvalue)) > 0) {
263                                                         char argument[255];
264                                                         sprintf(argument, "%d", res);
265                                                         addstr(&result, &len, &pos, argument, strlen(argument));
266                                                         command = nextpercent + 1;
267                                                         break;
268                                                 }
269                                         }
270 #endif
271                                         okay[opt_depth - 1] = 0;
272                                 }
273
274                                 command = nextpercent + 1;
275                         }
276                         break;
277                 }
278         }
279
280         if (opt_depth > 1) {
281                 errno = EUNBALBRACK;
282                 free(result);
283                 return NULL;
284         }
285
286         if (!okay[0]) {
287                 errno = EUNDEFVAR;
288                 free(result);
289                 return NULL;
290         }
291
292         return result;
293 }
294
295 /* execute() returns 1 for success and 0 for failure */
296 static int execute(char *command, struct interface_defn_t *ifd, execfn *exec)
297 {
298         char *out;
299         int ret;
300
301         out = parse(command, ifd);
302         if (!out) {
303                 return 0;
304         }
305         ret = (*exec)(out);
306
307         free(out);
308         if (ret != 1) {
309                 return 0;
310         }
311         return 1;
312 }
313 #endif
314
315 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV6
316 static int loopback_up6(struct interface_defn_t *ifd, execfn *exec)
317 {
318 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
319         int result;
320         result = execute("ip addr add ::1 dev %iface%", ifd, exec);
321         result += execute("ip link set %iface% up", ifd, exec);
322         return ((result == 2) ? 2 : 0);
323 #else
324         return execute("ifconfig %iface% add ::1", ifd, exec);
325 #endif
326 }
327
328 static int loopback_down6(struct interface_defn_t *ifd, execfn *exec)
329 {
330 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
331         return execute("ip link set %iface% down", ifd, exec);
332 #else
333         return execute("ifconfig %iface% del ::1", ifd, exec);
334 #endif
335 }
336
337 static int static_up6(struct interface_defn_t *ifd, execfn *exec)
338 {
339         int result;
340 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
341         result = execute("ip addr add %address%/%netmask% dev %iface% [[label %label%]]", ifd, exec);
342         result += execute("ip link set [[mtu %mtu%]] [[address %hwaddress%]] %iface% up", ifd, exec);
343         result += execute("[[ ip route add ::/0 via %gateway% ]]", ifd, exec);
344 #else
345         result = execute("ifconfig %iface% [[media %media%]] [[hw %hwaddress%]] [[mtu %mtu%]] up", ifd, exec);
346         result += execute("ifconfig %iface% add %address%/%netmask%", ifd, exec);
347         result += execute("[[ route -A inet6 add ::/0 gw %gateway% ]]", ifd, exec);
348 #endif
349         return ((result == 3) ? 3 : 0);
350 }
351
352 static int static_down6(struct interface_defn_t *ifd, execfn *exec)
353 {
354 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
355         return execute("ip link set %iface% down", ifd, exec);
356 #else
357         return execute("ifconfig %iface% down", ifd, exec);
358 #endif
359 }
360
361 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
362 static int v4tunnel_up(struct interface_defn_t *ifd, execfn *exec)
363 {
364         int result;
365         result = execute("ip tunnel add %iface% mode sit remote "
366                         "%endpoint% [[local %local%]] [[ttl %ttl%]]", ifd, exec);
367         result += execute("ip link set %iface% up", ifd, exec);
368         result += execute("ip addr add %address%/%netmask% dev %iface%", ifd, exec);
369         result += execute("[[ ip route add ::/0 via %gateway% ]]", ifd, exec);
370         return ((result == 4) ? 4 : 0);
371 }
372
373 static int v4tunnel_down(struct interface_defn_t * ifd, execfn * exec)
374 {
375         return execute("ip tunnel del %iface%", ifd, exec);
376 }
377 #endif
378
379 static const struct method_t methods6[] = {
380 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
381         { "v4tunnel", v4tunnel_up, v4tunnel_down, },
382 #endif
383         { "static", static_up6, static_down6, },
384         { "loopback", loopback_up6, loopback_down6, },
385 };
386
387 static const struct address_family_t addr_inet6 = {
388         "inet6",
389         sizeof(methods6) / sizeof(struct method_t),
390         methods6
391 };
392 #endif /* CONFIG_FEATURE_IFUPDOWN_IPV6 */
393
394 #ifdef CONFIG_FEATURE_IFUPDOWN_IPV4
395 static int loopback_up(struct interface_defn_t *ifd, execfn *exec)
396 {
397 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
398         int result;
399         result = execute("ip addr add 127.0.0.1/8 dev %iface%", ifd, exec);
400         result += execute("ip link set %iface% up", ifd, exec);
401         return ((result == 2) ? 2 : 0);
402 #else
403         return execute("ifconfig %iface% 127.0.0.1 up", ifd, exec);
404 #endif
405 }
406
407 static int loopback_down(struct interface_defn_t *ifd, execfn *exec)
408 {
409 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
410         int result;
411         result = execute("ip addr flush dev %iface%", ifd, exec);
412         result += execute("ip link set %iface% down", ifd, exec);
413         return ((result == 2) ? 2 : 0);
414 #else
415         return execute("ifconfig %iface% 127.0.0.1 down", ifd, exec);
416 #endif
417 }
418
419 static int static_up(struct interface_defn_t *ifd, execfn *exec)
420 {
421         int result;
422 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
423         result = execute("ip addr add %address%/%bnmask% [[broadcast %broadcast%]] "
424                         "dev %iface% [[peer %pointopoint%]] [[label %label%]]", ifd, exec);
425         result += execute("ip link set [[mtu %mtu%]] [[address %hwaddress%]] %iface% up", ifd, exec);
426         result += execute("[[ ip route add default via %gateway% dev %iface% ]]", ifd, exec);
427         return ((result == 3) ? 3 : 0);
428 #else
429         result = execute("ifconfig %iface% %address% netmask %netmask% "
430                         "[[broadcast %broadcast%]] [[pointopoint %pointopoint%]] "
431                         "[[media %media%]] [[mtu %mtu%]] [[hw %hwaddress%]] up",
432                         ifd, exec);
433         result += execute("[[ route add default gw %gateway% %iface% ]]", ifd, exec);
434         return ((result == 2) ? 2 : 0);
435 #endif
436 }
437
438 static int static_down(struct interface_defn_t *ifd, execfn *exec)
439 {
440         int result;
441 #ifdef CONFIG_FEATURE_IFUPDOWN_IP
442         result = execute("ip addr flush dev %iface%", ifd, exec);
443         result += execute("ip link set %iface% down", ifd, exec);
444 #else
445         result = execute("[[ route del default gw %gateway% %iface% ]]", ifd, exec);
446         result += execute("ifconfig %iface% down", ifd, exec);
447 #endif
448         return ((result == 2) ? 2 : 0);
449 }
450
451 static int execable(char *program)
452 {
453         struct stat buf;
454         if (0 == stat(program, &buf)) {
455                 if (S_ISREG(buf.st_mode) && (S_IXUSR & buf.st_mode)) {
456                         return(1);
457                 }
458         }
459         return(0);
460 }
461
462 static int dhcp_up(struct interface_defn_t *ifd, execfn *exec)
463 {
464         if (execable("/sbin/udhcpc")) {
465                 return( execute("udhcpc -n -p /var/run/udhcpc.%iface%.pid -i "
466                                         "%iface% [[-H %hostname%]] [[-c %clientid%]]", ifd, exec));
467         } else if (execable("/sbin/pump")) {
468                 return( execute("pump -i %iface% [[-h %hostname%]] [[-l %leasehours%]]", ifd, exec));
469         } else if (execable("/sbin/dhclient")) {
470                 return( execute("dhclient -pf /var/run/dhclient.%iface%.pid %iface%", ifd, exec));
471         } else if (execable("/sbin/dhcpcd")) {
472                 return( execute("dhcpcd [[-h %hostname%]] [[-i %vendor%]] [[-I %clientid%]] "
473                                         "[[-l %leasetime%]] %iface%", ifd, exec));
474         }
475         return(0);
476 }
477
478 static int dhcp_down(struct interface_defn_t *ifd, execfn *exec)
479 {
480         int result = 0;
481         if (execable("/sbin/udhcpc")) {
482                 /* SIGUSR2 forces udhcpc to release the current lease and go inactive,
483                  * and SIGTERM causes udhcpc to exit.  Signals are queued and processed
484                  * sequentially so we don't need to sleep */
485                 result = execute("kill -USR2 `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
486                 result += execute("kill -TERM `cat /var/run/udhcpc.%iface%.pid` 2>/dev/null", ifd, exec);
487         } else if (execable("/sbin/pump")) {
488                 result = execute("pump -i %iface% -k", ifd, exec);
489         } else if (execable("/sbin/dhclient")) {
490                 result = execute("kill -9 `cat /var/run/dhclient.%iface%.pid` 2>/dev/null", ifd, exec);
491         } else if (execable("/sbin/dhcpcd")) {
492                 result = execute("dhcpcd -k %iface%", ifd, exec);
493         }
494         return (result || static_down(ifd, exec));
495 }
496
497 static int bootp_up(struct interface_defn_t *ifd, execfn *exec)
498 {
499         return execute("bootpc [[--bootfile %bootfile%]] --dev %iface% "
500                         "[[--server %server%]] [[--hwaddr %hwaddr%]] "
501                         "--returniffail --serverbcast", ifd, exec);
502 }
503
504 static int ppp_up(struct interface_defn_t *ifd, execfn *exec)
505 {
506         return execute("pon [[%provider%]]", ifd, exec);
507 }
508
509 static int ppp_down(struct interface_defn_t *ifd, execfn *exec)
510 {
511         return execute("poff [[%provider%]]", ifd, exec);
512 }
513
514 static int wvdial_up(struct interface_defn_t *ifd, execfn *exec)
515 {
516         return execute("/sbin/start-stop-daemon --start -x /usr/bin/wvdial "
517                 "-p /var/run/wvdial.%iface% -b -m -- [[ %provider% ]]", ifd, exec);
518 }
519
520 static int wvdial_down(struct interface_defn_t *ifd, execfn *exec)
521 {
522         return execute("/sbin/start-stop-daemon --stop -x /usr/bin/wvdial "
523                         "-p /var/run/wvdial.%iface% -s 2", ifd, exec);
524 }
525
526 static const struct method_t methods[] = {
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         /* FIXME: we must not impose our own PATH, it is admin's job!
879            Use PATH from parent env */
880         *(environend++) = setlocalenv("%s=%s", "PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
881 }
882
883 static int doit(char *str)
884 {
885         if (option_mask & (OPT_no_act|OPT_verbose)) {
886                 puts(str);
887         }
888         if (!(option_mask & OPT_no_act)) {
889                 pid_t child;
890                 int status;
891
892                 fflush(NULL);
893                 switch (child = fork()) {
894                 case -1:                /* failure */
895                         return 0;
896                 case 0:         /* child */
897                         execle(DEFAULT_SHELL, DEFAULT_SHELL, "-c", str, NULL, __myenviron);
898                         exit(127);
899                 }
900                 waitpid(child, &status, 0);
901                 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
902                         return 0;
903                 }
904         }
905         return 1;
906 }
907
908 static int execute_all(struct interface_defn_t *ifd, const char *opt)
909 {
910         int i;
911         char *buf;
912         for (i = 0; i < ifd->n_options; i++) {
913                 if (strcmp(ifd->option[i].name, opt) == 0) {
914                         if (!doit(ifd->option[i].value)) {
915                                 return 0;
916                         }
917                 }
918         }
919
920         buf = xasprintf("run-parts /etc/network/if-%s.d", opt);
921         if (doit(buf) != 1) {
922                 return 0;
923         }
924         return 1;
925 }
926
927 static int check(char *str) {
928         return str != NULL;
929 }
930
931 static int iface_up(struct interface_defn_t *iface)
932 {
933         if (!iface->method->up(iface,check)) return -1;
934         set_environ(iface, "start");
935         if (!execute_all(iface, "pre-up")) return 0;
936         if (!iface->method->up(iface, doit)) return 0;
937         if (!execute_all(iface, "up")) return 0;
938         return 1;
939 }
940
941 static int iface_down(struct interface_defn_t *iface)
942 {
943         if (!iface->method->down(iface,check)) return -1;
944         set_environ(iface, "stop");
945         if (!execute_all(iface, "down")) return 0;
946         if (!iface->method->down(iface, doit)) return 0;
947         if (!execute_all(iface, "post-down")) return 0;
948         return 1;
949 }
950
951 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
952 static int popen2(FILE **in, FILE **out, char *command, ...)
953 {
954         va_list ap;
955         char *argv[11] = { command };
956         int argc;
957         int infd[2], outfd[2];
958         pid_t pid;
959
960         argc = 1;
961         va_start(ap, command);
962         while ((argc < 10) && (argv[argc] = va_arg(ap, char *))) {
963                 argc++;
964         }
965         argv[argc] = NULL;      /* make sure */
966         va_end(ap);
967
968         if (pipe(infd) != 0) {
969                 return 0;
970         }
971
972         if (pipe(outfd) != 0) {
973                 close(infd[0]);
974                 close(infd[1]);
975                 return 0;
976         }
977
978         fflush(NULL);
979         switch (pid = fork()) {
980         case -1:                        /* failure */
981                 close(infd[0]);
982                 close(infd[1]);
983                 close(outfd[0]);
984                 close(outfd[1]);
985                 return 0;
986         case 0:                 /* child */
987                 dup2(infd[0], 0);
988                 dup2(outfd[1], 1);
989                 close(infd[0]);
990                 close(infd[1]);
991                 close(outfd[0]);
992                 close(outfd[1]);
993                 execvp(command, argv);
994                 exit(127);
995         default:                        /* parent */
996                 *in = fdopen(infd[1], "w");
997                 *out = fdopen(outfd[0], "r");
998                 close(infd[0]);
999                 close(outfd[1]);
1000                 return pid;
1001         }
1002         /* unreached */
1003 }
1004
1005 static char *run_mapping(char *physical, struct mapping_defn_t * map)
1006 {
1007         FILE *in, *out;
1008         int i, status;
1009         pid_t pid;
1010
1011         char *logical = xstrdup(physical);
1012
1013         /* Run the mapping script. */
1014         pid = popen2(&in, &out, map->script, physical, NULL);
1015
1016         /* popen2() returns 0 on failure. */
1017         if (pid == 0)
1018                 return logical;
1019
1020         /* Write mappings to stdin of mapping script. */
1021         for (i = 0; i < map->n_mappings; i++) {
1022                 fprintf(in, "%s\n", map->mapping[i]);
1023         }
1024         fclose(in);
1025         waitpid(pid, &status, 0);
1026
1027         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1028                 /* If the mapping script exited successfully, try to
1029                  * grab a line of output and use that as the name of the
1030                  * logical interface. */
1031                 char *new_logical = (char *)xmalloc(MAX_INTERFACE_LENGTH);
1032
1033                 if (fgets(new_logical, MAX_INTERFACE_LENGTH, out)) {
1034                         /* If we are able to read a line of output from the script,
1035                          * remove any trailing whitespace and use this value
1036                          * as the name of the logical interface. */
1037                         char *pch = new_logical + strlen(new_logical) - 1;
1038
1039                         while (pch >= new_logical && isspace(*pch))
1040                                 *(pch--) = '\0';
1041
1042                         free(logical);
1043                         logical = new_logical;
1044                 } else {
1045                         /* If we are UNABLE to read a line of output, discard our
1046                          * freshly allocated memory. */
1047                         free(new_logical);
1048                 }
1049         }
1050
1051         fclose(out);
1052
1053         return logical;
1054 }
1055 #endif /* CONFIG_FEATURE_IFUPDOWN_MAPPING */
1056
1057 static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1058 {
1059         unsigned short iface_len = strlen(iface);
1060         llist_t *search = state_list;
1061
1062         while (search) {
1063                 if ((strncmp(search->data, iface, iface_len) == 0) &&
1064                                 (search->data[iface_len] == '=')) {
1065                         return search;
1066                 }
1067                 search = search->link;
1068         }
1069         return NULL;
1070 }
1071
1072 int ifupdown_main(int argc, char **argv)
1073 {
1074         static const char statefile[] = "/var/run/ifstate";
1075
1076         int (*cmds)(struct interface_defn_t *) = NULL;
1077         struct interfaces_file_t *defn;
1078         llist_t *state_list = NULL;
1079         llist_t *target_list = NULL;
1080         const char *interfaces = "/etc/network/interfaces";
1081         int any_failures = 0;
1082         int i;
1083
1084         if (bb_applet_name[2] == 'u') {
1085                 /* ifup command */
1086                 cmds = iface_up;
1087         } else {
1088                 /* ifdown command */
1089                 cmds = iface_down;
1090         }
1091
1092         option_mask = bb_getopt_ulflags(argc, argv, OPTION_STR, &interfaces);
1093         if (argc - optind > 0) {
1094                 if (DO_ALL) bb_show_usage();
1095         } else
1096                 if (!DO_ALL) bb_show_usage();
1097
1098         debug_noise("reading %s file:\n", interfaces);
1099         defn = read_interfaces(interfaces);
1100         debug_noise("\ndone reading %s\n\n", interfaces);
1101
1102         if (!defn) {
1103                 exit(EXIT_FAILURE);
1104         }
1105
1106         /* Create a list of interfaces to work on */
1107         if (DO_ALL) {
1108                 if (cmds == iface_up) {
1109                         target_list = defn->autointerfaces;
1110                 } else {
1111                         /* iface_down */
1112                         const llist_t *list = state_list;
1113                         while (list) {
1114                                 llist_add_to_end(&target_list, xstrdup(list->data));
1115                                 list = list->link;
1116                         }
1117                         target_list = defn->autointerfaces;
1118                 }
1119         } else {
1120                 llist_add_to_end(&target_list, argv[optind]);
1121         }
1122
1123
1124         /* Update the interfaces */
1125         while (target_list) {
1126                 llist_t *iface_list;
1127                 struct interface_defn_t *currif;
1128                 char *iface;
1129                 char *liface;
1130                 char *pch;
1131                 int okay = 0;
1132                 int cmds_ret;
1133
1134                 iface = xstrdup(target_list->data);
1135                 target_list = target_list->link;
1136
1137                 pch = strchr(iface, '=');
1138                 if (pch) {
1139                         *pch = '\0';
1140                         liface = xstrdup(pch + 1);
1141                 } else {
1142                         liface = xstrdup(iface);
1143                 }
1144
1145                 if (!FORCE) {
1146                         const llist_t *iface_state = find_iface_state(state_list, iface);
1147
1148                         if (cmds == iface_up) {
1149                                 /* ifup */
1150                                 if (iface_state) {
1151                                         bb_error_msg("interface %s already configured", iface);
1152                                         continue;
1153                                 }
1154                         } else {
1155                                 /* ifdown */
1156                                 if (iface_state) {
1157                                         bb_error_msg("interface %s not configured", iface);
1158                                         continue;
1159                                 }
1160                         }
1161                 }
1162
1163 #ifdef CONFIG_FEATURE_IFUPDOWN_MAPPING
1164                 if ((cmds == iface_up) && !NO_MAPPINGS) {
1165                         struct mapping_defn_t *currmap;
1166
1167                         for (currmap = defn->mappings; currmap; currmap = currmap->next) {
1168                                 for (i = 0; i < currmap->n_matches; i++) {
1169                                         if (fnmatch(currmap->match[i], liface, 0) != 0)
1170                                                 continue;
1171                                         if (VERBOSE) {
1172                                                 printf("Running mapping script %s on %s\n", currmap->script, liface);
1173                                         }
1174                                         liface = run_mapping(iface, currmap);
1175                                         break;
1176                                 }
1177                         }
1178                 }
1179 #endif
1180
1181
1182                 iface_list = defn->ifaces;
1183                 while (iface_list) {
1184                         currif = (struct interface_defn_t *) iface_list->data;
1185                         if (strcmp(liface, currif->iface) == 0) {
1186                                 char *oldiface = currif->iface;
1187
1188                                 okay = 1;
1189                                 currif->iface = iface;
1190
1191                                 debug_noise("\nConfiguring interface %s (%s)\n", liface, currif->address_family->name);
1192
1193                                 /* Call the cmds function pointer, does either iface_up() or iface_down() */
1194                                 cmds_ret = cmds(currif);
1195                                 if (cmds_ret == -1) {
1196                                         bb_error_msg("don't seem to have all the variables for %s/%s",
1197                                                         liface, currif->address_family->name);
1198                                         any_failures += 1;
1199                                 } else if (cmds_ret == 0) {
1200                                         any_failures += 1;
1201                                 }
1202
1203                                 currif->iface = oldiface;
1204                         }
1205                         iface_list = iface_list->link;
1206                 }
1207                 if (VERBOSE) {
1208                         puts("");
1209                 }
1210
1211                 if (!okay && !FORCE) {
1212                         bb_error_msg("ignoring unknown interface %s", liface);
1213                         any_failures += 1;
1214                 } else {
1215                         llist_t *iface_state = find_iface_state(state_list, iface);
1216
1217                         if (cmds == iface_up) {
1218                                 char *newiface = xasprintf("%s=%s", iface, liface);
1219                                 if (iface_state == NULL) {
1220                                         llist_add_to_end(&state_list, newiface);
1221                                 } else {
1222                                         free(iface_state->data);
1223                                         iface_state->data = newiface;
1224                                 }
1225                         } else {
1226                                 /* Remove an interface from the linked list */
1227                                 free(llist_pop(&iface_state));
1228                         }
1229                 }
1230         }
1231
1232         /* Actually write the new state */
1233         if (!NO_ACT) {
1234                 FILE *state_fp = NULL;
1235
1236                 state_fp = xfopen(statefile, "w");
1237                 while (state_list) {
1238                         if (state_list->data) {
1239                                 fputs(state_list->data, state_fp);
1240                                 fputc('\n', state_fp);
1241                         }
1242                         state_list = state_list->link;
1243                 }
1244                 fclose(state_fp);
1245         }
1246
1247         if (any_failures)
1248                 return 1;
1249         return 0;
1250 }