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