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