ifplugd.c 19 KB

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