3
0

ifupdown.c 42 KB

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