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