3
0

ifplugd.c 20 KB

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