3
0

ifplugd.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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"
  11. //config: default y
  12. //config: select PLATFORM_LINUX
  13. //config: help
  14. //config: Network interface plug detection daemon.
  15. //applet:IF_IFPLUGD(APPLET(ifplugd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  16. //kbuild:lib-$(CONFIG_IFPLUGD) += ifplugd.o
  17. //usage:#define ifplugd_trivial_usage
  18. //usage: "[OPTIONS]"
  19. //usage:#define ifplugd_full_usage "\n\n"
  20. //usage: "Network interface plug detection daemon\n"
  21. //usage: "\n -n Don't daemonize"
  22. //usage: "\n -s Don't log to syslog"
  23. //usage: "\n -i IFACE Interface"
  24. //usage: "\n -f/-F Treat link detection error as link down/link up"
  25. //usage: "\n (otherwise exit on error)"
  26. //usage: "\n -a Don't up interface at each link probe"
  27. //usage: "\n -M Monitor creation/destruction of interface"
  28. //usage: "\n (otherwise it must exist)"
  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, Do not enable interface automatically
  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. #if ENABLE_FEATURE_PIDFILE
  102. FLAG_KILL = 1 << 17, // -k, Kill a running daemon
  103. #endif
  104. };
  105. #if ENABLE_FEATURE_PIDFILE
  106. # define OPTION_STR "+ansfFi:r:It:+u:+d:+m:pqlx:Mk"
  107. #else
  108. # define OPTION_STR "+ansfFi:r:It:+u:+d:+m:pqlx:M"
  109. #endif
  110. enum { // interface status
  111. IFSTATUS_ERR = -1,
  112. IFSTATUS_DOWN = 0,
  113. IFSTATUS_UP = 1,
  114. };
  115. enum { // constant fds
  116. ioctl_fd = 3,
  117. netlink_fd = 4,
  118. };
  119. struct globals {
  120. smallint iface_last_status;
  121. smallint iface_prev_status;
  122. smallint iface_exists;
  123. smallint api_method_num;
  124. /* Used in getopt32, must have sizeof == sizeof(int) */
  125. unsigned poll_time;
  126. unsigned delay_up;
  127. unsigned delay_down;
  128. const char *iface;
  129. const char *api_mode;
  130. const char *script_name;
  131. const char *extra_arg;
  132. };
  133. #define G (*ptr_to_globals)
  134. #define INIT_G() do { \
  135. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  136. G.iface_last_status = -1; \
  137. G.iface_exists = 1; \
  138. G.poll_time = 1; \
  139. G.delay_down = 5; \
  140. G.iface = "eth0"; \
  141. G.api_mode = "a"; \
  142. G.script_name = "/etc/ifplugd/ifplugd.action"; \
  143. } while (0)
  144. /* Utility routines */
  145. static void set_ifreq_to_ifname(struct ifreq *ifreq)
  146. {
  147. memset(ifreq, 0, sizeof(struct ifreq));
  148. strncpy_IFNAMSIZ(ifreq->ifr_name, G.iface);
  149. }
  150. static int network_ioctl(int request, void* data, const char *errmsg)
  151. {
  152. int r = ioctl(ioctl_fd, request, data);
  153. if (r < 0 && errmsg)
  154. bb_perror_msg("%s failed", errmsg);
  155. return r;
  156. }
  157. /* Link detection routines and table */
  158. static smallint detect_link_mii(void)
  159. {
  160. /* char buffer instead of bona-fide struct avoids aliasing warning */
  161. char buf[sizeof(struct ifreq)];
  162. struct ifreq *const ifreq = (void *)buf;
  163. struct mii_ioctl_data *mii = (void *)&ifreq->ifr_data;
  164. set_ifreq_to_ifname(ifreq);
  165. if (network_ioctl(SIOCGMIIPHY, ifreq, "SIOCGMIIPHY") < 0) {
  166. return IFSTATUS_ERR;
  167. }
  168. mii->reg_num = 1;
  169. if (network_ioctl(SIOCGMIIREG, ifreq, "SIOCGMIIREG") < 0) {
  170. return IFSTATUS_ERR;
  171. }
  172. return (mii->val_out & 0x0004) ? IFSTATUS_UP : IFSTATUS_DOWN;
  173. }
  174. static smallint detect_link_priv(void)
  175. {
  176. /* char buffer instead of bona-fide struct avoids aliasing warning */
  177. char buf[sizeof(struct ifreq)];
  178. struct ifreq *const ifreq = (void *)buf;
  179. struct mii_ioctl_data *mii = (void *)&ifreq->ifr_data;
  180. set_ifreq_to_ifname(ifreq);
  181. if (network_ioctl(SIOCDEVPRIVATE, ifreq, "SIOCDEVPRIVATE") < 0) {
  182. return IFSTATUS_ERR;
  183. }
  184. mii->reg_num = 1;
  185. if (network_ioctl(SIOCDEVPRIVATE+1, ifreq, "SIOCDEVPRIVATE+1") < 0) {
  186. return IFSTATUS_ERR;
  187. }
  188. return (mii->val_out & 0x0004) ? IFSTATUS_UP : IFSTATUS_DOWN;
  189. }
  190. static smallint detect_link_ethtool(void)
  191. {
  192. struct ifreq ifreq;
  193. struct ethtool_value edata;
  194. set_ifreq_to_ifname(&ifreq);
  195. edata.cmd = ETHTOOL_GLINK;
  196. ifreq.ifr_data = (void*) &edata;
  197. if (network_ioctl(SIOCETHTOOL, &ifreq, "ETHTOOL_GLINK") < 0) {
  198. return IFSTATUS_ERR;
  199. }
  200. return edata.data ? IFSTATUS_UP : IFSTATUS_DOWN;
  201. }
  202. static smallint detect_link_iff(void)
  203. {
  204. struct ifreq ifreq;
  205. set_ifreq_to_ifname(&ifreq);
  206. if (network_ioctl(SIOCGIFFLAGS, &ifreq, "SIOCGIFFLAGS") < 0) {
  207. return IFSTATUS_ERR;
  208. }
  209. /* If IFF_UP is not set (interface is down), IFF_RUNNING is never set
  210. * regardless of link status. Simply continue to report last status -
  211. * no point in reporting spurious link downs if interface is disabled
  212. * by admin. When/if it will be brought up,
  213. * we'll report real link status.
  214. */
  215. if (!(ifreq.ifr_flags & IFF_UP) && G.iface_last_status != IFSTATUS_ERR)
  216. return G.iface_last_status;
  217. return (ifreq.ifr_flags & IFF_RUNNING) ? IFSTATUS_UP : IFSTATUS_DOWN;
  218. }
  219. static smallint detect_link_wlan(void)
  220. {
  221. int i;
  222. struct iwreq iwrequest;
  223. uint8_t mac[ETH_ALEN];
  224. memset(&iwrequest, 0, sizeof(iwrequest));
  225. strncpy_IFNAMSIZ(iwrequest.ifr_ifrn.ifrn_name, G.iface);
  226. if (network_ioctl(SIOCGIWAP, &iwrequest, "SIOCGIWAP") < 0) {
  227. return IFSTATUS_ERR;
  228. }
  229. memcpy(mac, &iwrequest.u.ap_addr.sa_data, ETH_ALEN);
  230. if (mac[0] == 0xFF || mac[0] == 0x44 || mac[0] == 0x00) {
  231. for (i = 1; i < ETH_ALEN; ++i) {
  232. if (mac[i] != mac[0])
  233. return IFSTATUS_UP;
  234. }
  235. return IFSTATUS_DOWN;
  236. }
  237. return IFSTATUS_UP;
  238. }
  239. enum { // api mode
  240. API_ETHTOOL, // 'e'
  241. API_MII, // 'm'
  242. API_PRIVATE, // 'p'
  243. API_WLAN, // 'w'
  244. API_IFF, // 'i'
  245. API_AUTO, // 'a'
  246. };
  247. static const char api_modes[] ALIGN1 = "empwia";
  248. static const struct {
  249. const char *name;
  250. smallint (*func)(void);
  251. } method_table[] = {
  252. { "SIOCETHTOOL" , &detect_link_ethtool },
  253. { "SIOCGMIIPHY" , &detect_link_mii },
  254. { "SIOCDEVPRIVATE" , &detect_link_priv },
  255. { "wireless extension", &detect_link_wlan },
  256. { "IFF_RUNNING" , &detect_link_iff },
  257. };
  258. static const char *strstatus(int status)
  259. {
  260. if (status == IFSTATUS_ERR)
  261. return "error";
  262. return "down\0up" + (status * 5);
  263. }
  264. static int run_script(const char *action)
  265. {
  266. char *env_PREVIOUS, *env_CURRENT;
  267. char *argv[5];
  268. int r;
  269. bb_error_msg("executing '%s %s %s'", G.script_name, G.iface, action);
  270. argv[0] = (char*) G.script_name;
  271. argv[1] = (char*) G.iface;
  272. argv[2] = (char*) action;
  273. argv[3] = (char*) G.extra_arg;
  274. argv[4] = NULL;
  275. env_PREVIOUS = xasprintf("%s=%s", IFPLUGD_ENV_PREVIOUS, strstatus(G.iface_prev_status));
  276. putenv(env_PREVIOUS);
  277. env_CURRENT = xasprintf("%s=%s", IFPLUGD_ENV_CURRENT, strstatus(G.iface_last_status));
  278. putenv(env_CURRENT);
  279. /* r < 0 - can't exec, 0 <= r < 0x180 - exited, >=0x180 - killed by sig (r-0x180) */
  280. r = spawn_and_wait(argv);
  281. unsetenv(IFPLUGD_ENV_PREVIOUS);
  282. unsetenv(IFPLUGD_ENV_CURRENT);
  283. free(env_PREVIOUS);
  284. free(env_CURRENT);
  285. bb_error_msg("exit code: %d", r & 0xff);
  286. return (option_mask32 & FLAG_IGNORE_RETVAL) ? 0 : r;
  287. }
  288. static void up_iface(void)
  289. {
  290. struct ifreq ifrequest;
  291. if (!G.iface_exists)
  292. return;
  293. set_ifreq_to_ifname(&ifrequest);
  294. if (network_ioctl(SIOCGIFFLAGS, &ifrequest, "getting interface flags") < 0) {
  295. G.iface_exists = 0;
  296. return;
  297. }
  298. if (!(ifrequest.ifr_flags & IFF_UP)) {
  299. ifrequest.ifr_flags |= IFF_UP;
  300. /* Let user know we mess up with interface */
  301. bb_error_msg("upping interface");
  302. if (network_ioctl(SIOCSIFFLAGS, &ifrequest, "setting interface flags") < 0) {
  303. if (errno != ENODEV)
  304. xfunc_die();
  305. G.iface_exists = 0;
  306. return;
  307. }
  308. }
  309. #if 0 /* why do we mess with IP addr? It's not our business */
  310. if (network_ioctl(SIOCGIFADDR, &ifrequest, "can't get interface address") < 0) {
  311. } else if (ifrequest.ifr_addr.sa_family != AF_INET) {
  312. bb_perror_msg("the interface is not IP-based");
  313. } else {
  314. ((struct sockaddr_in*)(&ifrequest.ifr_addr))->sin_addr.s_addr = INADDR_ANY;
  315. network_ioctl(SIOCSIFADDR, &ifrequest, "can't set interface address");
  316. }
  317. network_ioctl(SIOCGIFFLAGS, &ifrequest, "can't get interface flags");
  318. #endif
  319. }
  320. static void maybe_up_new_iface(void)
  321. {
  322. if (!(option_mask32 & FLAG_NO_AUTO))
  323. up_iface();
  324. #if 0 /* bloat */
  325. struct ifreq ifrequest;
  326. struct ethtool_drvinfo driver_info;
  327. set_ifreq_to_ifname(&ifrequest);
  328. driver_info.cmd = ETHTOOL_GDRVINFO;
  329. ifrequest.ifr_data = &driver_info;
  330. if (network_ioctl(SIOCETHTOOL, &ifrequest, NULL) == 0) {
  331. char buf[sizeof("/xx:xx:xx:xx:xx:xx")];
  332. /* Get MAC */
  333. buf[0] = '\0';
  334. set_ifreq_to_ifname(&ifrequest);
  335. if (network_ioctl(SIOCGIFHWADDR, &ifrequest, NULL) == 0) {
  336. sprintf(buf, "/%02X:%02X:%02X:%02X:%02X:%02X",
  337. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[0]),
  338. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[1]),
  339. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[2]),
  340. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[3]),
  341. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[4]),
  342. (uint8_t)(ifrequest.ifr_hwaddr.sa_data[5]));
  343. }
  344. bb_error_msg("using interface %s%s with driver<%s> (version: %s)",
  345. G.iface, buf, driver_info.driver, driver_info.version);
  346. }
  347. #endif
  348. if (G.api_mode[0] == 'a')
  349. G.api_method_num = API_AUTO;
  350. }
  351. static smallint detect_link(void)
  352. {
  353. smallint status;
  354. if (!G.iface_exists)
  355. return (option_mask32 & FLAG_MONITOR) ? IFSTATUS_DOWN : IFSTATUS_ERR;
  356. /* Some drivers can't detect link status when the interface is down.
  357. * I imagine detect_link_iff() is the most vulnerable.
  358. * That's why -a "noauto" in an option, not a hardwired behavior.
  359. */
  360. if (!(option_mask32 & FLAG_NO_AUTO))
  361. up_iface();
  362. if (G.api_method_num == API_AUTO) {
  363. int i;
  364. smallint sv_logmode;
  365. sv_logmode = logmode;
  366. for (i = 0; i < ARRAY_SIZE(method_table); i++) {
  367. logmode = LOGMODE_NONE;
  368. status = method_table[i].func();
  369. logmode = sv_logmode;
  370. if (status != IFSTATUS_ERR) {
  371. G.api_method_num = i;
  372. bb_error_msg("using %s detection mode", method_table[i].name);
  373. break;
  374. }
  375. }
  376. } else {
  377. status = method_table[G.api_method_num].func();
  378. }
  379. if (status == IFSTATUS_ERR) {
  380. if (option_mask32 & FLAG_IGNORE_FAIL)
  381. status = IFSTATUS_DOWN;
  382. else if (option_mask32 & FLAG_IGNORE_FAIL_POSITIVE)
  383. status = IFSTATUS_UP;
  384. else if (G.api_mode[0] == 'a')
  385. bb_error_msg("can't detect link status");
  386. }
  387. if (status != G.iface_last_status) {
  388. G.iface_prev_status = G.iface_last_status;
  389. G.iface_last_status = status;
  390. }
  391. return status;
  392. }
  393. static NOINLINE int check_existence_through_netlink(void)
  394. {
  395. int iface_len;
  396. /* Buffer was 1K, but on linux-3.9.9 it was reported to be too small.
  397. * netlink.h: "limit to 8K to avoid MSG_TRUNC when PAGE_SIZE is very large".
  398. * Note: on error returns (-1) we exit, no need to free replybuf.
  399. */
  400. enum { BUF_SIZE = 8 * 1024 };
  401. char *replybuf = xmalloc(BUF_SIZE);
  402. iface_len = strlen(G.iface);
  403. while (1) {
  404. struct nlmsghdr *mhdr;
  405. ssize_t bytes;
  406. bytes = recv(netlink_fd, replybuf, BUF_SIZE, MSG_DONTWAIT);
  407. if (bytes < 0) {
  408. if (errno == EAGAIN)
  409. goto ret;
  410. if (errno == EINTR)
  411. continue;
  412. bb_perror_msg("netlink: recv");
  413. return -1;
  414. }
  415. mhdr = (struct nlmsghdr*)replybuf;
  416. while (bytes > 0) {
  417. if (!NLMSG_OK(mhdr, bytes)) {
  418. bb_error_msg("netlink packet too small or truncated");
  419. return -1;
  420. }
  421. if (mhdr->nlmsg_type == RTM_NEWLINK || mhdr->nlmsg_type == RTM_DELLINK) {
  422. struct rtattr *attr;
  423. int attr_len;
  424. if (mhdr->nlmsg_len < NLMSG_LENGTH(sizeof(struct ifinfomsg))) {
  425. bb_error_msg("netlink packet too small or truncated");
  426. return -1;
  427. }
  428. attr = IFLA_RTA(NLMSG_DATA(mhdr));
  429. attr_len = IFLA_PAYLOAD(mhdr);
  430. while (RTA_OK(attr, attr_len)) {
  431. if (attr->rta_type == IFLA_IFNAME) {
  432. int len = RTA_PAYLOAD(attr);
  433. if (len > IFNAMSIZ)
  434. len = IFNAMSIZ;
  435. if (iface_len <= len
  436. && strncmp(G.iface, RTA_DATA(attr), len) == 0
  437. ) {
  438. G.iface_exists = (mhdr->nlmsg_type == RTM_NEWLINK);
  439. }
  440. }
  441. attr = RTA_NEXT(attr, attr_len);
  442. }
  443. }
  444. mhdr = NLMSG_NEXT(mhdr, bytes);
  445. }
  446. }
  447. ret:
  448. free(replybuf);
  449. return G.iface_exists;
  450. }
  451. #if ENABLE_FEATURE_PIDFILE
  452. static NOINLINE pid_t read_pid(const char *filename)
  453. {
  454. int len;
  455. char buf[128];
  456. len = open_read_close(filename, buf, 127);
  457. if (len > 0) {
  458. buf[len] = '\0';
  459. /* returns ULONG_MAX on error => -1 */
  460. return bb_strtoul(buf, NULL, 10);
  461. }
  462. return 0;
  463. }
  464. #endif
  465. int ifplugd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  466. int ifplugd_main(int argc UNUSED_PARAM, char **argv)
  467. {
  468. int iface_status;
  469. int delay_time;
  470. const char *iface_status_str;
  471. struct pollfd netlink_pollfd[1];
  472. unsigned opts;
  473. const char *api_mode_found;
  474. #if ENABLE_FEATURE_PIDFILE
  475. char *pidfile_name;
  476. pid_t pid_from_pidfile;
  477. #endif
  478. INIT_G();
  479. opts = getopt32(argv, OPTION_STR,
  480. &G.iface, &G.script_name, &G.poll_time, &G.delay_up,
  481. &G.delay_down, &G.api_mode, &G.extra_arg);
  482. G.poll_time *= 1000;
  483. applet_name = xasprintf("ifplugd(%s)", G.iface);
  484. #if ENABLE_FEATURE_PIDFILE
  485. pidfile_name = xasprintf(CONFIG_PID_FILE_PATH "/ifplugd.%s.pid", G.iface);
  486. pid_from_pidfile = read_pid(pidfile_name);
  487. if (opts & FLAG_KILL) {
  488. if (pid_from_pidfile > 0)
  489. /* Upstream tool use SIGINT for -k */
  490. kill(pid_from_pidfile, SIGINT);
  491. return EXIT_SUCCESS;
  492. }
  493. if (pid_from_pidfile > 0 && kill(pid_from_pidfile, 0) == 0)
  494. bb_error_msg_and_die("daemon already running");
  495. #endif
  496. api_mode_found = strchr(api_modes, G.api_mode[0]);
  497. if (!api_mode_found)
  498. bb_error_msg_and_die("unknown API mode '%s'", G.api_mode);
  499. G.api_method_num = api_mode_found - api_modes;
  500. if (!(opts & FLAG_NO_DAEMON))
  501. bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
  502. xmove_fd(xsocket(AF_INET, SOCK_DGRAM, 0), ioctl_fd);
  503. if (opts & FLAG_MONITOR) {
  504. struct sockaddr_nl addr;
  505. int fd = xsocket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  506. memset(&addr, 0, sizeof(addr));
  507. addr.nl_family = AF_NETLINK;
  508. addr.nl_groups = RTMGRP_LINK;
  509. addr.nl_pid = getpid();
  510. xbind(fd, (struct sockaddr*)&addr, sizeof(addr));
  511. xmove_fd(fd, netlink_fd);
  512. }
  513. write_pidfile(pidfile_name);
  514. /* this can't be moved before socket creation */
  515. if (!(opts & FLAG_NO_SYSLOG)) {
  516. openlog(applet_name, 0, LOG_DAEMON);
  517. logmode |= LOGMODE_SYSLOG;
  518. }
  519. bb_signals(0
  520. | (1 << SIGINT )
  521. | (1 << SIGTERM)
  522. | (1 << SIGQUIT)
  523. | (1 << SIGHUP ) /* why we ignore it? */
  524. /* | (1 << SIGCHLD) - run_script does not use it anymore */
  525. , record_signo);
  526. bb_error_msg("started: %s", bb_banner);
  527. if (opts & FLAG_MONITOR) {
  528. struct ifreq ifrequest;
  529. set_ifreq_to_ifname(&ifrequest);
  530. G.iface_exists = (network_ioctl(SIOCGIFINDEX, &ifrequest, NULL) == 0);
  531. }
  532. if (G.iface_exists)
  533. maybe_up_new_iface();
  534. iface_status = detect_link();
  535. if (iface_status == IFSTATUS_ERR)
  536. goto exiting;
  537. iface_status_str = strstatus(iface_status);
  538. if (opts & FLAG_MONITOR) {
  539. bb_error_msg("interface %s",
  540. G.iface_exists ? "exists"
  541. : "doesn't exist, waiting");
  542. }
  543. /* else we assume it always exists, but don't mislead user
  544. * by potentially lying that it really exists */
  545. if (G.iface_exists) {
  546. bb_error_msg("link is %s", iface_status_str);
  547. }
  548. if ((!(opts & FLAG_NO_STARTUP)
  549. && iface_status == IFSTATUS_UP
  550. )
  551. || (opts & FLAG_INITIAL_DOWN)
  552. ) {
  553. if (run_script(iface_status_str) != 0)
  554. goto exiting;
  555. }
  556. /* Main loop */
  557. netlink_pollfd[0].fd = netlink_fd;
  558. netlink_pollfd[0].events = POLLIN;
  559. delay_time = 0;
  560. while (1) {
  561. int iface_status_old;
  562. switch (bb_got_signal) {
  563. case SIGINT:
  564. case SIGTERM:
  565. bb_got_signal = 0;
  566. goto cleanup;
  567. case SIGQUIT:
  568. bb_got_signal = 0;
  569. goto exiting;
  570. default:
  571. bb_got_signal = 0;
  572. break;
  573. }
  574. if (poll(netlink_pollfd,
  575. (opts & FLAG_MONITOR) ? 1 : 0,
  576. G.poll_time
  577. ) < 0
  578. ) {
  579. if (errno == EINTR)
  580. continue;
  581. bb_perror_msg("poll");
  582. goto exiting;
  583. }
  584. if ((opts & FLAG_MONITOR)
  585. && (netlink_pollfd[0].revents & POLLIN)
  586. ) {
  587. int iface_exists_old;
  588. iface_exists_old = G.iface_exists;
  589. G.iface_exists = check_existence_through_netlink();
  590. if (G.iface_exists < 0) /* error */
  591. goto exiting;
  592. if (iface_exists_old != G.iface_exists) {
  593. bb_error_msg("interface %sappeared",
  594. G.iface_exists ? "" : "dis");
  595. if (G.iface_exists)
  596. maybe_up_new_iface();
  597. }
  598. }
  599. /* note: if !G.iface_exists, returns DOWN */
  600. iface_status_old = iface_status;
  601. iface_status = detect_link();
  602. if (iface_status == IFSTATUS_ERR) {
  603. if (!(opts & FLAG_MONITOR))
  604. goto exiting;
  605. iface_status = IFSTATUS_DOWN;
  606. }
  607. iface_status_str = strstatus(iface_status);
  608. if (iface_status_old != iface_status) {
  609. bb_error_msg("link is %s", iface_status_str);
  610. if (delay_time) {
  611. /* link restored its old status before
  612. * we ran script. don't run the script: */
  613. delay_time = 0;
  614. } else {
  615. delay_time = monotonic_sec();
  616. if (iface_status == IFSTATUS_UP)
  617. delay_time += G.delay_up;
  618. if (iface_status == IFSTATUS_DOWN)
  619. delay_time += G.delay_down;
  620. #if 0 /* if you are back in 1970... */
  621. if (delay_time == 0) {
  622. sleep(1);
  623. delay_time = 1;
  624. }
  625. #endif
  626. }
  627. }
  628. if (delay_time && (int)(monotonic_sec() - delay_time) >= 0) {
  629. if (run_script(iface_status_str) != 0)
  630. goto exiting;
  631. delay_time = 0;
  632. }
  633. } /* while (1) */
  634. cleanup:
  635. if (!(opts & FLAG_NO_SHUTDOWN)
  636. && (iface_status == IFSTATUS_UP
  637. || (iface_status == IFSTATUS_DOWN && delay_time)
  638. )
  639. ) {
  640. setenv(IFPLUGD_ENV_PREVIOUS, strstatus(iface_status), 1);
  641. setenv(IFPLUGD_ENV_CURRENT, strstatus(-1), 1);
  642. run_script("down\0up"); /* reusing string */
  643. }
  644. exiting:
  645. remove_pidfile(pidfile_name);
  646. bb_error_msg_and_die("exiting");
  647. }