ifplugd.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ifplugd for busybox, based on ifplugd 0.28 (written by Lennart Poettering).
  4. *
  5. * Copyright (C) 2009 Maksym Kryzhanovskyy <xmaks@email.cz>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. //config:config IFPLUGD
  10. //config: bool "ifplugd (10 kb)"
  11. //config: default y
  12. //config: help
  13. //config: Network interface plug detection daemon.
  14. //applet:IF_IFPLUGD(APPLET(ifplugd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  15. //kbuild:lib-$(CONFIG_IFPLUGD) += ifplugd.o
  16. //usage:#define ifplugd_trivial_usage
  17. //usage: "[OPTIONS]"
  18. //usage:#define ifplugd_full_usage "\n\n"
  19. //usage: "Network interface plug detection daemon\n"
  20. //usage: "\n -n Run in foreground"
  21. //usage: "\n -s Don't log to syslog"
  22. //usage: "\n -i IFACE Interface"
  23. //usage: "\n -f/-F Treat link detection error as link down/link up"
  24. //usage: "\n (otherwise exit on error)"
  25. //usage: "\n -a Don't up interface at each link probe"
  26. //usage: "\n -M Monitor creation/destruction of interface"
  27. //usage: "\n (otherwise it must exist)"
  28. //usage: "\n -A Don't up newly appeared interface"
  29. //usage: "\n -r PROG Script to run"
  30. //usage: "\n -x ARG Extra argument for script"
  31. //usage: "\n -I Don't exit on nonzero exit code from script"
  32. //usage: "\n -p Don't run \"up\" script on startup"
  33. //usage: "\n -q Don't run \"down\" script on exit"
  34. //usage: "\n -l Always run script on startup"
  35. //usage: "\n -t SECS Poll time in seconds"
  36. //usage: "\n -u SECS Delay before running script after link up"
  37. //usage: "\n -d SECS Delay after link down"
  38. //usage: "\n -m MODE API mode (mii, priv, ethtool, wlan, iff, auto)"
  39. //usage: "\n -k Kill running daemon"
  40. #include "libbb.h"
  41. #include "fix_u32.h"
  42. #include <linux/if.h>
  43. #include <linux/mii.h>
  44. #include <linux/ethtool.h>
  45. #ifdef HAVE_NET_ETHERNET_H
  46. /* musl breakage:
  47. * In file included from /usr/include/net/ethernet.h:10,
  48. * from networking/ifplugd.c:41:
  49. * /usr/include/netinet/if_ether.h:96: error: redefinition of 'struct ethhdr'
  50. *
  51. * Build succeeds without it on musl. Commented it out.
  52. * If on your system you need it, consider removing <linux/ethtool.h>
  53. * and copy-pasting its definitions here (<linux/ethtool.h> is what pulls in
  54. * conflicting definition of struct ethhdr on musl).
  55. */
  56. /* # include <net/ethernet.h> */
  57. #endif
  58. #include <linux/netlink.h>
  59. #include <linux/rtnetlink.h>
  60. #include <linux/sockios.h>
  61. #include <syslog.h>
  62. #define __user
  63. #include <linux/wireless.h>
  64. #ifndef ETH_ALEN
  65. # define ETH_ALEN 6
  66. #endif
  67. /*
  68. From initial port to busybox, removed most of the redundancy by
  69. converting implementation of a polymorphic interface to the strict
  70. functional style. The main role is run a script when link state
  71. changed, other activities like audio signal or detailed reports
  72. are on the script itself.
  73. One questionable point of the design is netlink usage:
  74. We have 1 second timeout by default to poll the link status,
  75. it is short enough so that there are no real benefits in
  76. using netlink to get "instantaneous" interface creation/deletion
  77. notifications. We can check for interface existence by just
  78. doing some fast ioctl using its name.
  79. Netlink code then can be just dropped (1k or more?)
  80. */
  81. #define IFPLUGD_ENV_PREVIOUS "IFPLUGD_PREVIOUS"
  82. #define IFPLUGD_ENV_CURRENT "IFPLUGD_CURRENT"
  83. enum {
  84. FLAG_NO_AUTO = 1 << 0, // -a, Don't up interface at each link probe
  85. FLAG_NO_DAEMON = 1 << 1, // -n, Do not daemonize
  86. FLAG_NO_SYSLOG = 1 << 2, // -s, Do not use syslog, use stderr instead
  87. FLAG_IGNORE_FAIL = 1 << 3, // -f, Ignore detection failure, retry instead (failure is treated as DOWN)
  88. FLAG_IGNORE_FAIL_POSITIVE = 1 << 4, // -F, Ignore detection failure, retry instead (failure is treated as UP)
  89. FLAG_IFACE = 1 << 5, // -i, Specify ethernet interface
  90. FLAG_RUN = 1 << 6, // -r, Specify program to execute
  91. FLAG_IGNORE_RETVAL = 1 << 7, // -I, Don't exit on nonzero return value of program executed
  92. FLAG_POLL_TIME = 1 << 8, // -t, Specify poll time in seconds
  93. FLAG_DELAY_UP = 1 << 9, // -u, Specify delay for configuring interface
  94. FLAG_DELAY_DOWN = 1 << 10, // -d, Specify delay for deconfiguring interface
  95. FLAG_API_MODE = 1 << 11, // -m, Force API mode (mii, priv, ethtool, wlan, auto)
  96. FLAG_NO_STARTUP = 1 << 12, // -p, Don't run script on daemon startup
  97. FLAG_NO_SHUTDOWN = 1 << 13, // -q, Don't run script on daemon quit
  98. FLAG_INITIAL_DOWN = 1 << 14, // -l, Run "down" script on startup if no cable is detected
  99. FLAG_EXTRA_ARG = 1 << 15, // -x, Specify an extra argument for action script
  100. FLAG_MONITOR = 1 << 16, // -M, Use interface monitoring
  101. FLAG_NO_UP_NEW_IFACE = 1 << 17, // -A, Don't up newly appeared interface
  102. #if ENABLE_FEATURE_PIDFILE
  103. FLAG_KILL = 1 << 18, // -k, Kill a running daemon
  104. #endif
  105. };
  106. #if ENABLE_FEATURE_PIDFILE
  107. # define OPTION_STR "+ansfFi:r:It:+u:+d:+m:pqlx:MAk"
  108. #else
  109. # define OPTION_STR "+ansfFi:r:It:+u:+d:+m:pqlx:MA"
  110. #endif
  111. enum { // interface status
  112. IFSTATUS_ERR = -1,
  113. IFSTATUS_DOWN = 0,
  114. IFSTATUS_UP = 1,
  115. };
  116. enum { // constant fds
  117. ioctl_fd = 3,
  118. netlink_fd = 4,
  119. };
  120. struct globals {
  121. smallint iface_last_status;
  122. smallint iface_prev_status;
  123. smallint iface_exists;
  124. smallint api_method_num;
  125. /* Used in getopt32, must have sizeof == sizeof(int) */
  126. unsigned poll_time;
  127. unsigned delay_up;
  128. unsigned delay_down;
  129. const char *iface;
  130. const char *api_mode;
  131. const char *script_name;
  132. const char *extra_arg;
  133. };
  134. #define G (*ptr_to_globals)
  135. #define INIT_G() do { \
  136. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  137. G.iface_last_status = -1; \
  138. G.iface_exists = 1; \
  139. G.poll_time = 1; \
  140. G.delay_down = 5; \
  141. G.iface = "eth0"; \
  142. G.api_mode = "a"; \
  143. G.script_name = "/etc/ifplugd/ifplugd.action"; \
  144. } while (0)
  145. /* Utility routines */
  146. static void set_ifreq_to_ifname(struct ifreq *ifreq)
  147. {
  148. memset(ifreq, 0, sizeof(struct ifreq));
  149. strncpy_IFNAMSIZ(ifreq->ifr_name, G.iface);
  150. }
  151. static int network_ioctl(int request, void* data, const char *errmsg)
  152. {
  153. int r = ioctl(ioctl_fd, request, data);
  154. if (r < 0 && errmsg)
  155. bb_perror_msg("%s failed", errmsg);
  156. return r;
  157. }
  158. /* Link detection routines and table */
  159. static smallint detect_link_mii(void)
  160. {
  161. /* char buffer instead of bona-fide struct avoids aliasing warning */
  162. char buf[sizeof(struct ifreq)];
  163. struct ifreq *const ifreq = (void *)buf;
  164. struct mii_ioctl_data *mii = (void *)&ifreq->ifr_data;
  165. set_ifreq_to_ifname(ifreq);
  166. if (network_ioctl(SIOCGMIIPHY, ifreq, "SIOCGMIIPHY") < 0) {
  167. return IFSTATUS_ERR;
  168. }
  169. mii->reg_num = 1;
  170. if (network_ioctl(SIOCGMIIREG, ifreq, "SIOCGMIIREG") < 0) {
  171. return IFSTATUS_ERR;
  172. }
  173. return (mii->val_out & 0x0004) ? IFSTATUS_UP : IFSTATUS_DOWN;
  174. }
  175. static smallint detect_link_priv(void)
  176. {
  177. /* char buffer instead of bona-fide struct avoids aliasing warning */
  178. char buf[sizeof(struct ifreq)];
  179. struct ifreq *const ifreq = (void *)buf;
  180. struct mii_ioctl_data *mii = (void *)&ifreq->ifr_data;
  181. set_ifreq_to_ifname(ifreq);
  182. if (network_ioctl(SIOCDEVPRIVATE, ifreq, "SIOCDEVPRIVATE") < 0) {
  183. return IFSTATUS_ERR;
  184. }
  185. mii->reg_num = 1;
  186. if (network_ioctl(SIOCDEVPRIVATE+1, ifreq, "SIOCDEVPRIVATE+1") < 0) {
  187. return IFSTATUS_ERR;
  188. }
  189. return (mii->val_out & 0x0004) ? IFSTATUS_UP : IFSTATUS_DOWN;
  190. }
  191. static smallint detect_link_ethtool(void)
  192. {
  193. struct ifreq ifreq;
  194. struct ethtool_value edata;
  195. set_ifreq_to_ifname(&ifreq);
  196. edata.cmd = ETHTOOL_GLINK;
  197. ifreq.ifr_data = (void*) &edata;
  198. if (network_ioctl(SIOCETHTOOL, &ifreq, "ETHTOOL_GLINK") < 0) {
  199. return IFSTATUS_ERR;
  200. }
  201. return edata.data ? IFSTATUS_UP : IFSTATUS_DOWN;
  202. }
  203. static smallint detect_link_iff(void)
  204. {
  205. struct ifreq ifreq;
  206. set_ifreq_to_ifname(&ifreq);
  207. if (network_ioctl(SIOCGIFFLAGS, &ifreq, "SIOCGIFFLAGS") < 0) {
  208. return IFSTATUS_ERR;
  209. }
  210. /* If IFF_UP is not set (interface is down), IFF_RUNNING is never set
  211. * regardless of link status. Simply continue to report last status -
  212. * no point in reporting spurious link downs if interface is disabled
  213. * by admin. When/if it will be brought up,
  214. * we'll report real link status.
  215. */
  216. if (!(ifreq.ifr_flags & IFF_UP) && G.iface_last_status != IFSTATUS_ERR)
  217. return G.iface_last_status;
  218. return (ifreq.ifr_flags & IFF_RUNNING) ? IFSTATUS_UP : IFSTATUS_DOWN;
  219. }
  220. static smallint detect_link_wlan(void)
  221. {
  222. int i;
  223. struct iwreq iwrequest;
  224. uint8_t mac[ETH_ALEN];
  225. memset(&iwrequest, 0, sizeof(iwrequest));
  226. strncpy_IFNAMSIZ(iwrequest.ifr_ifrn.ifrn_name, G.iface);
  227. if (network_ioctl(SIOCGIWAP, &iwrequest, "SIOCGIWAP") < 0) {
  228. return IFSTATUS_ERR;
  229. }
  230. memcpy(mac, &iwrequest.u.ap_addr.sa_data, ETH_ALEN);
  231. if (mac[0] == 0xFF || mac[0] == 0x44 || mac[0] == 0x00) {
  232. for (i = 1; i < ETH_ALEN; ++i) {
  233. if (mac[i] != mac[0])
  234. return IFSTATUS_UP;
  235. }
  236. return IFSTATUS_DOWN;
  237. }
  238. return IFSTATUS_UP;
  239. }
  240. enum { // api mode
  241. API_ETHTOOL, // 'e'
  242. API_MII, // 'm'
  243. API_PRIVATE, // 'p'
  244. API_WLAN, // 'w'
  245. API_IFF, // 'i'
  246. API_AUTO, // 'a'
  247. };
  248. static const char api_modes[] ALIGN1 = "empwia";
  249. static const struct {
  250. const char *name;
  251. smallint (*func)(void);
  252. } method_table[] ALIGN_PTR = {
  253. { "SIOCETHTOOL" , &detect_link_ethtool },
  254. { "SIOCGMIIPHY" , &detect_link_mii },
  255. { "SIOCDEVPRIVATE" , &detect_link_priv },
  256. { "wireless extension", &detect_link_wlan },
  257. { "IFF_RUNNING" , &detect_link_iff },
  258. };
  259. static const char *strstatus(int status)
  260. {
  261. if (status == IFSTATUS_ERR)
  262. return "error";
  263. return "down\0up" + (status * 5);
  264. }
  265. static int run_script(const char *action)
  266. {
  267. char *env_PREVIOUS, *env_CURRENT;
  268. char *argv[5];
  269. int r;
  270. bb_info_msg("executing '%s %s %s'", G.script_name, G.iface, action);
  271. argv[0] = (char*) G.script_name;
  272. argv[1] = (char*) G.iface;
  273. argv[2] = (char*) action;
  274. argv[3] = (char*) G.extra_arg;
  275. argv[4] = NULL;
  276. env_PREVIOUS = xasprintf("%s=%s", IFPLUGD_ENV_PREVIOUS, strstatus(G.iface_prev_status));
  277. putenv(env_PREVIOUS);
  278. env_CURRENT = xasprintf("%s=%s", IFPLUGD_ENV_CURRENT, strstatus(G.iface_last_status));
  279. putenv(env_CURRENT);
  280. /* r < 0 - can't exec, 0 <= r < 0x180 - exited, >=0x180 - killed by sig (r-0x180) */
  281. r = spawn_and_wait(argv);
  282. bb_unsetenv_and_free(env_PREVIOUS);
  283. bb_unsetenv_and_free(env_CURRENT);
  284. bb_info_msg("exit code: %d", r & 0xff);
  285. return (option_mask32 & FLAG_IGNORE_RETVAL) ? 0 : r;
  286. }
  287. static void up_iface(void)
  288. {
  289. struct ifreq ifrequest;
  290. if (!G.iface_exists)
  291. return;
  292. set_ifreq_to_ifname(&ifrequest);
  293. if (network_ioctl(SIOCGIFFLAGS, &ifrequest, "getting interface flags") < 0) {
  294. G.iface_exists = 0;
  295. return;
  296. }
  297. if (!(ifrequest.ifr_flags & IFF_UP)) {
  298. ifrequest.ifr_flags |= IFF_UP;
  299. /* Let user know we mess up with interface */
  300. bb_simple_info_msg("upping interface");
  301. if (network_ioctl(SIOCSIFFLAGS, &ifrequest, "setting interface flags") < 0) {
  302. if (errno != ENODEV && errno != EADDRNOTAVAIL)
  303. xfunc_die();
  304. G.iface_exists = 0;
  305. return;
  306. }
  307. }
  308. #if 0 /* why do we mess with IP addr? It's not our business */
  309. if (network_ioctl(SIOCGIFADDR, &ifrequest, "can't get interface address") < 0) {
  310. } else if (ifrequest.ifr_addr.sa_family != AF_INET) {
  311. bb_perror_msg("the interface is not IP-based");
  312. } else {
  313. ((struct sockaddr_in*)(&ifrequest.ifr_addr))->sin_addr.s_addr = INADDR_ANY;
  314. network_ioctl(SIOCSIFADDR, &ifrequest, "can't set interface address");
  315. }
  316. network_ioctl(SIOCGIFFLAGS, &ifrequest, "can't get interface flags");
  317. #endif
  318. }
  319. static void maybe_up_new_iface(void)
  320. {
  321. if (!(option_mask32 & FLAG_NO_UP_NEW_IFACE))
  322. up_iface();
  323. #if 0 /* bloat */
  324. struct ifreq ifrequest;
  325. struct ethtool_drvinfo driver_info;
  326. set_ifreq_to_ifname(&ifrequest);
  327. driver_info.cmd = ETHTOOL_GDRVINFO;
  328. ifrequest.ifr_data = &driver_info;
  329. if (network_ioctl(SIOCETHTOOL, &ifrequest, NULL) == 0) {
  330. char buf[sizeof("/xx:xx:xx:xx:xx:xx")];
  331. /* Get MAC */
  332. buf[0] = '\0';
  333. set_ifreq_to_ifname(&ifrequest);
  334. if (network_ioctl(SIOCGIFHWADDR, &ifrequest, NULL) == 0) {
  335. sprintf(buf, "/%02X:%02X:%02X:%02X:%02X:%02X",
  336. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[0]),
  337. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[1]),
  338. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[2]),
  339. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[3]),
  340. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[4]),
  341. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[5]));
  342. }
  343. bb_info_msg("using interface %s%s with driver<%s> (version: %s)",
  344. G.iface, buf, driver_info.driver, driver_info.version);
  345. }
  346. #endif
  347. if (G.api_mode[0] == 'a')
  348. G.api_method_num = API_AUTO;
  349. }
  350. static smallint detect_link(void)
  351. {
  352. smallint status;
  353. if (!G.iface_exists)
  354. return (option_mask32 & FLAG_MONITOR) ? IFSTATUS_DOWN : IFSTATUS_ERR;
  355. /* Some drivers can't detect link status when the interface is down.
  356. * I imagine detect_link_iff() is the most vulnerable.
  357. * That's why -a "noauto" in an option, not a hardwired behavior.
  358. */
  359. if (!(option_mask32 & FLAG_NO_AUTO))
  360. up_iface();
  361. if (G.api_method_num == API_AUTO) {
  362. int i;
  363. smallint sv_logmode;
  364. sv_logmode = logmode;
  365. for (i = 0; i < ARRAY_SIZE(method_table); i++) {
  366. logmode = LOGMODE_NONE;
  367. status = method_table[i].func();
  368. logmode = sv_logmode;
  369. if (status != IFSTATUS_ERR) {
  370. G.api_method_num = i;
  371. bb_info_msg("using %s detection mode", method_table[i].name);
  372. break;
  373. }
  374. }
  375. } else {
  376. status = method_table[G.api_method_num].func();
  377. }
  378. if (status == IFSTATUS_ERR) {
  379. if (option_mask32 & FLAG_IGNORE_FAIL)
  380. status = IFSTATUS_DOWN;
  381. else if (option_mask32 & FLAG_IGNORE_FAIL_POSITIVE)
  382. status = IFSTATUS_UP;
  383. else if (G.api_mode[0] == 'a')
  384. bb_simple_error_msg("can't detect link status");
  385. }
  386. if (status != G.iface_last_status) {
  387. G.iface_prev_status = G.iface_last_status;
  388. G.iface_last_status = status;
  389. }
  390. return status;
  391. }
  392. static NOINLINE int check_existence_through_netlink(void)
  393. {
  394. int iface_len;
  395. /* Buffer was 1K, but on linux-3.9.9 it was reported to be too small.
  396. * netlink.h: "limit to 8K to avoid MSG_TRUNC when PAGE_SIZE is very large".
  397. * Note: on error returns (-1) we exit, no need to free replybuf.
  398. */
  399. enum { BUF_SIZE = 8 * 1024 };
  400. char *replybuf = xmalloc(BUF_SIZE);
  401. iface_len = strlen(G.iface);
  402. while (1) {
  403. struct nlmsghdr *mhdr;
  404. ssize_t bytes;
  405. bytes = recv(netlink_fd, replybuf, BUF_SIZE, MSG_DONTWAIT);
  406. if (bytes < 0) {
  407. if (errno == EAGAIN)
  408. goto ret;
  409. if (errno == EINTR)
  410. continue;
  411. bb_simple_perror_msg("netlink: recv");
  412. return -1;
  413. }
  414. mhdr = (struct nlmsghdr*)replybuf;
  415. while (bytes > 0) {
  416. if (!NLMSG_OK(mhdr, bytes)) {
  417. bb_simple_error_msg("netlink packet too small or truncated");
  418. return -1;
  419. }
  420. if (mhdr->nlmsg_type == RTM_NEWLINK || mhdr->nlmsg_type == RTM_DELLINK) {
  421. struct rtattr *attr;
  422. int attr_len;
  423. if (mhdr->nlmsg_len < NLMSG_LENGTH(sizeof(struct ifinfomsg))) {
  424. bb_simple_error_msg("netlink packet too small or truncated");
  425. return -1;
  426. }
  427. attr = IFLA_RTA(NLMSG_DATA(mhdr));
  428. attr_len = IFLA_PAYLOAD(mhdr);
  429. while (RTA_OK(attr, attr_len)) {
  430. if (attr->rta_type == IFLA_IFNAME) {
  431. int len = RTA_PAYLOAD(attr);
  432. if (len > IFNAMSIZ)
  433. len = IFNAMSIZ;
  434. if (iface_len <= len
  435. && strncmp(G.iface, RTA_DATA(attr), len) == 0
  436. ) {
  437. G.iface_exists = (mhdr->nlmsg_type == RTM_NEWLINK);
  438. }
  439. }
  440. attr = RTA_NEXT(attr, attr_len);
  441. }
  442. }
  443. mhdr = NLMSG_NEXT(mhdr, bytes);
  444. }
  445. }
  446. ret:
  447. free(replybuf);
  448. return G.iface_exists;
  449. }
  450. #if ENABLE_FEATURE_PIDFILE
  451. static NOINLINE pid_t read_pid(const char *filename)
  452. {
  453. int len;
  454. char buf[128];
  455. len = open_read_close(filename, buf, 127);
  456. if (len > 0) {
  457. buf[len] = '\0';
  458. /* returns ULONG_MAX on error => -1 */
  459. return bb_strtoul(buf, NULL, 10);
  460. }
  461. return 0;
  462. }
  463. #endif
  464. int ifplugd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  465. int ifplugd_main(int argc UNUSED_PARAM, char **argv)
  466. {
  467. int iface_status;
  468. int delay_time;
  469. const char *iface_status_str;
  470. struct pollfd netlink_pollfd[1];
  471. unsigned opts;
  472. const char *api_mode_found;
  473. #if ENABLE_FEATURE_PIDFILE
  474. char *pidfile_name;
  475. pid_t pid_from_pidfile;
  476. #endif
  477. INIT_G();
  478. opts = getopt32(argv, OPTION_STR,
  479. &G.iface, &G.script_name, &G.poll_time, &G.delay_up,
  480. &G.delay_down, &G.api_mode, &G.extra_arg);
  481. G.poll_time *= 1000;
  482. applet_name = xasprintf("ifplugd(%s)", G.iface);
  483. #if ENABLE_FEATURE_PIDFILE
  484. pidfile_name = xasprintf(CONFIG_PID_FILE_PATH "/ifplugd.%s.pid", G.iface);
  485. pid_from_pidfile = read_pid(pidfile_name);
  486. if (opts & FLAG_KILL) {
  487. if (pid_from_pidfile > 0)
  488. /* Upstream tool use SIGINT for -k */
  489. kill(pid_from_pidfile, SIGINT);
  490. return EXIT_SUCCESS;
  491. }
  492. if (pid_from_pidfile > 0 && kill(pid_from_pidfile, 0) == 0)
  493. bb_simple_error_msg_and_die("daemon already running");
  494. #endif
  495. api_mode_found = strchr(api_modes, G.api_mode[0]);
  496. if (!api_mode_found)
  497. bb_error_msg_and_die("unknown API mode '%s'", G.api_mode);
  498. G.api_method_num = api_mode_found - api_modes;
  499. if (!(opts & FLAG_NO_DAEMON))
  500. bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
  501. xmove_fd(xsocket(AF_INET, SOCK_DGRAM, 0), ioctl_fd);
  502. if (opts & FLAG_MONITOR) {
  503. int fd = create_and_bind_to_netlink(NETLINK_ROUTE, RTMGRP_LINK, 0);
  504. xmove_fd(fd, netlink_fd);
  505. }
  506. write_pidfile(pidfile_name);
  507. /* this can't be moved before socket creation */
  508. if (!(opts & FLAG_NO_SYSLOG)) {
  509. openlog(applet_name, 0, LOG_DAEMON);
  510. logmode |= LOGMODE_SYSLOG;
  511. }
  512. bb_signals(0
  513. | (1 << SIGINT )
  514. | (1 << SIGTERM)
  515. | (1 << SIGQUIT)
  516. | (1 << SIGHUP ) /* why we ignore it? */
  517. /* | (1 << SIGCHLD) - run_script does not use it anymore */
  518. , record_signo);
  519. bb_info_msg("started: %s", bb_banner);
  520. if (opts & FLAG_MONITOR) {
  521. struct ifreq ifrequest;
  522. set_ifreq_to_ifname(&ifrequest);
  523. G.iface_exists = (network_ioctl(SIOCGIFINDEX, &ifrequest, NULL) == 0);
  524. }
  525. if (G.iface_exists)
  526. maybe_up_new_iface();
  527. iface_status = detect_link();
  528. if (iface_status == IFSTATUS_ERR)
  529. goto exiting;
  530. iface_status_str = strstatus(iface_status);
  531. if (opts & FLAG_MONITOR) {
  532. bb_info_msg("interface %s",
  533. G.iface_exists ? "exists"
  534. : "doesn't exist, waiting");
  535. }
  536. /* else we assume it always exists, but don't mislead user
  537. * by potentially lying that it really exists */
  538. if (G.iface_exists) {
  539. bb_info_msg("link is %s", iface_status_str);
  540. }
  541. if ((!(opts & FLAG_NO_STARTUP)
  542. && iface_status == IFSTATUS_UP
  543. )
  544. || (opts & FLAG_INITIAL_DOWN)
  545. ) {
  546. if (run_script(iface_status_str) != 0)
  547. goto exiting;
  548. }
  549. /* Main loop */
  550. netlink_pollfd[0].fd = netlink_fd;
  551. netlink_pollfd[0].events = POLLIN;
  552. delay_time = 0;
  553. while (1) {
  554. int iface_status_old;
  555. switch (bb_got_signal) {
  556. case SIGINT:
  557. case SIGTERM:
  558. bb_got_signal = 0;
  559. goto cleanup;
  560. case SIGQUIT:
  561. bb_got_signal = 0;
  562. goto exiting;
  563. default:
  564. bb_got_signal = 0;
  565. /* do not clear bb_got_signal if already 0, this can lose signals */
  566. case 0:
  567. break;
  568. }
  569. if (poll(netlink_pollfd,
  570. (opts & FLAG_MONITOR) ? 1 : 0,
  571. G.poll_time
  572. ) < 0
  573. ) {
  574. if (errno == EINTR)
  575. continue;
  576. bb_simple_perror_msg("poll");
  577. goto exiting;
  578. }
  579. if ((opts & FLAG_MONITOR)
  580. && (netlink_pollfd[0].revents & POLLIN)
  581. ) {
  582. int iface_exists_old;
  583. iface_exists_old = G.iface_exists;
  584. G.iface_exists = check_existence_through_netlink();
  585. if (G.iface_exists < 0) /* error */
  586. goto exiting;
  587. if (iface_exists_old != G.iface_exists) {
  588. bb_info_msg("interface %sappeared",
  589. G.iface_exists ? "" : "dis");
  590. if (G.iface_exists)
  591. maybe_up_new_iface();
  592. }
  593. }
  594. /* note: if !G.iface_exists, returns DOWN */
  595. iface_status_old = iface_status;
  596. iface_status = detect_link();
  597. if (iface_status == IFSTATUS_ERR) {
  598. if (!(opts & FLAG_MONITOR))
  599. goto exiting;
  600. iface_status = IFSTATUS_DOWN;
  601. }
  602. iface_status_str = strstatus(iface_status);
  603. if (iface_status_old != iface_status) {
  604. bb_info_msg("link is %s", iface_status_str);
  605. if (delay_time) {
  606. /* link restored its old status before
  607. * we ran script. don't run the script: */
  608. delay_time = 0;
  609. } else {
  610. delay_time = monotonic_sec();
  611. if (iface_status == IFSTATUS_UP)
  612. delay_time += G.delay_up;
  613. if (iface_status == IFSTATUS_DOWN)
  614. delay_time += G.delay_down;
  615. #if 0 /* if you are back in 1970... */
  616. if (delay_time == 0) {
  617. sleep1();
  618. delay_time = 1;
  619. }
  620. #endif
  621. }
  622. }
  623. if (delay_time && (int)(monotonic_sec() - delay_time) >= 0) {
  624. if (run_script(iface_status_str) != 0)
  625. goto exiting;
  626. delay_time = 0;
  627. }
  628. } /* while (1) */
  629. cleanup:
  630. if (!(opts & FLAG_NO_SHUTDOWN)
  631. && (iface_status == IFSTATUS_UP
  632. || (iface_status == IFSTATUS_DOWN && delay_time)
  633. )
  634. ) {
  635. setenv(IFPLUGD_ENV_PREVIOUS, strstatus(iface_status), 1);
  636. setenv(IFPLUGD_ENV_CURRENT, strstatus(-1), 1);
  637. run_script("down\0up"); /* reusing string */
  638. }
  639. exiting:
  640. remove_pidfile(pidfile_name);
  641. bb_simple_error_msg_and_die("exiting");
  642. }