ifupdown.c 42 KB

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