ifplugd.c 20 KB

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