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