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