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