gluon-radv-filterd.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. /*
  2. Copyright (c) 2016 Jan-Philipp Litza <janphilipp@litza.de>
  3. Copyright (c) 2017 Sven Eckelmann <sven@narfation.org>
  4. All rights reserved.
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are met:
  7. 1. Redistributions of source code must retain the above copyright notice,
  8. this list of conditions and the following disclaimer.
  9. 2. Redistributions in binary form must reproduce the above copyright notice,
  10. this list of conditions and the following disclaimer in the documentation
  11. and/or other materials provided with the distribution.
  12. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  13. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  16. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  17. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  18. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  19. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  20. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  21. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. #include <errno.h>
  24. #include <signal.h>
  25. #include <stdarg.h>
  26. #include <stdbool.h>
  27. #include <stddef.h>
  28. #include <stdio.h>
  29. #include <stdint.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <time.h>
  33. #include <unistd.h>
  34. #include <sys/socket.h>
  35. #include <sys/select.h>
  36. #include <sys/types.h>
  37. #include <sys/wait.h>
  38. #include <net/ethernet.h>
  39. #include <net/if.h>
  40. #include <linux/filter.h>
  41. #include <linux/if_packet.h>
  42. #include <linux/limits.h>
  43. #include <netinet/icmp6.h>
  44. #include <netinet/in.h>
  45. #include <netinet/ip6.h>
  46. #include <netlink/netlink.h>
  47. #include <netlink/genl/genl.h>
  48. #include <netlink/genl/ctrl.h>
  49. #include <batadv-genl.h>
  50. #include "mac.h"
  51. // Recheck TQs after this time even if no RA was received
  52. #define MAX_INTERVAL 60
  53. // Recheck TQs at most this often, even if new RAs were received (they won't
  54. // become the preferred routers until the TQs have been rechecked)
  55. // Also, the first update will take at least this long
  56. #define MIN_INTERVAL 15
  57. // max execution time of a single ebtables call in nanoseconds
  58. #define EBTABLES_TIMEOUT 500000000 // 500ms
  59. // TQ value assigned to local routers
  60. #define LOCAL_TQ 512
  61. #define BUFSIZE 1500
  62. #ifdef DEBUG
  63. #define CHECK(stmt) \
  64. if(!(stmt)) { \
  65. fprintf(stderr, "check failed: " #stmt "\n"); \
  66. goto check_failed; \
  67. }
  68. #define DEBUG_MSG(msg, ...) fprintf(stderr, msg "\n", ##__VA_ARGS__)
  69. #else
  70. #define CHECK(stmt) if(!(stmt)) goto check_failed;
  71. #define DEBUG_MSG(msg, ...) do {} while(0)
  72. #endif
  73. #ifndef ARRAY_SIZE
  74. #define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))
  75. #endif
  76. #define foreach(item, list) \
  77. for((item) = (list); (item) != NULL; (item) = (item)->next)
  78. #define foreach_safe(item, safe, list) \
  79. for ((item) = (list); \
  80. (item) && (((safe) = item->next) || 1); \
  81. (item) = (safe))
  82. struct router {
  83. struct router *next;
  84. struct ether_addr src;
  85. struct timespec eol;
  86. struct ether_addr originator;
  87. uint16_t tq;
  88. };
  89. static struct global {
  90. int sock;
  91. struct router *routers;
  92. const char *mesh_iface;
  93. const char *chain;
  94. uint16_t max_tq;
  95. uint16_t hysteresis_thresh;
  96. struct router *best_router;
  97. volatile sig_atomic_t stop_daemon;
  98. } G = {
  99. .mesh_iface = "bat0",
  100. };
  101. static int fork_execvp_timeout(struct timespec *timeout, const char *file,
  102. const char *const argv[]);
  103. static void error_message(int status, int errnum, char *message, ...) {
  104. va_list ap;
  105. va_start(ap, message);
  106. fflush(stdout);
  107. vfprintf(stderr, message, ap);
  108. va_end(ap);
  109. if (errnum)
  110. fprintf(stderr, ": %s", strerror(errnum));
  111. fprintf(stderr, "\n");
  112. if (status)
  113. exit(status);
  114. }
  115. static int timespec_diff(struct timespec *tv1, struct timespec *tv2,
  116. struct timespec *tvdiff)
  117. {
  118. tvdiff->tv_sec = tv1->tv_sec - tv2->tv_sec;
  119. if (tv1->tv_nsec < tv2->tv_nsec) {
  120. tvdiff->tv_nsec = 1000000000 + tv1->tv_nsec - tv2->tv_nsec;
  121. tvdiff->tv_sec -= 1;
  122. } else {
  123. tvdiff->tv_nsec = tv1->tv_nsec - tv2->tv_nsec;
  124. }
  125. return (tvdiff->tv_sec >= 0);
  126. }
  127. static void cleanup(void) {
  128. struct router *router;
  129. struct timespec timeout = {
  130. .tv_nsec = EBTABLES_TIMEOUT,
  131. };
  132. close(G.sock);
  133. while (G.routers != NULL) {
  134. router = G.routers;
  135. G.routers = router->next;
  136. free(router);
  137. }
  138. if (G.chain) {
  139. /* Reset chain to accept everything again */
  140. if (fork_execvp_timeout(&timeout, "ebtables", (const char *[])
  141. { "ebtables", "--concurrent", "-F", G.chain, NULL }))
  142. DEBUG_MSG("warning: flushing ebtables chain %s failed, not adding a new rule", G.chain);
  143. if (fork_execvp_timeout(&timeout, "ebtables", (const char *[])
  144. { "ebtables", "--concurrent", "-A", G.chain, "-j", "ACCEPT", NULL }))
  145. DEBUG_MSG("warning: adding new rule to ebtables chain %s failed", G.chain);
  146. }
  147. }
  148. static void usage(const char *msg) {
  149. if (msg != NULL && *msg != '\0') {
  150. fprintf(stderr, "ERROR: %s\n\n", msg);
  151. }
  152. fprintf(stderr,
  153. "Usage: %s [-m <mesh_iface>] [-t <thresh>] -c <chain> -i <iface>\n\n"
  154. " -m <mesh_iface> B.A.T.M.A.N. advanced mesh interface used to get metric\n"
  155. " information (\"TQ\") for the available gateways. Default: bat0\n"
  156. " -t <thresh> Minimum TQ difference required to switch the gateway.\n"
  157. " Default: 0\n"
  158. " -c <chain> ebtables chain that should be managed by the daemon. The\n"
  159. " chain already has to exist on program invocation and should\n"
  160. " have a DROP policy. It will be flushed by the program!\n"
  161. " -i <iface> Interface to listen on for router advertisements. Should be\n"
  162. " <mesh_iface> or a bridge on top of it, as no metric\n"
  163. " information will be available for hosts on other interfaces.\n\n",
  164. program_invocation_short_name);
  165. cleanup();
  166. if (msg == NULL)
  167. exit(EXIT_SUCCESS);
  168. else
  169. exit(EXIT_FAILURE);
  170. }
  171. #define exit_errmsg(message, ...) { \
  172. fprintf(stderr, message "\n", ##__VA_ARGS__); \
  173. cleanup(); \
  174. exit(1); \
  175. }
  176. static inline void exit_errno(const char *message) {
  177. cleanup();
  178. error_message(1, errno, "error: %s", message);
  179. }
  180. static inline void warn_errno(const char *message) {
  181. error_message(0, errno, "warning: %s", message);
  182. }
  183. static int init_packet_socket(unsigned int ifindex) {
  184. struct sock_filter radv_filter_code[] = {
  185. // check that this is an ICMPv6 packet
  186. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, offsetof(struct ip6_hdr, ip6_nxt)),
  187. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_ICMPV6, 0, 7),
  188. // check that this is a router advertisement
  189. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, sizeof(struct ip6_hdr) + offsetof(struct icmp6_hdr, icmp6_type)),
  190. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ND_ROUTER_ADVERT, 0, 5),
  191. // check that the code field in the ICMPv6 header is 0
  192. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, sizeof(struct ip6_hdr) + offsetof(struct nd_router_advert, nd_ra_code)),
  193. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0, 0, 3),
  194. // check that this is a default route (lifetime > 0)
  195. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, sizeof(struct ip6_hdr) + offsetof(struct nd_router_advert, nd_ra_router_lifetime)),
  196. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0, 1, 0),
  197. // return true
  198. BPF_STMT(BPF_RET|BPF_K, 0xffffffff),
  199. // return false
  200. BPF_STMT(BPF_RET|BPF_K, 0),
  201. };
  202. struct sock_fprog radv_filter = {
  203. .len = ARRAY_SIZE(radv_filter_code),
  204. .filter = radv_filter_code,
  205. };
  206. int sock = socket(AF_PACKET, SOCK_DGRAM|SOCK_CLOEXEC, htons(ETH_P_IPV6));
  207. if (sock < 0)
  208. exit_errno("can't open packet socket");
  209. int ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &radv_filter, sizeof(radv_filter));
  210. if (ret < 0)
  211. exit_errno("can't attach socket filter");
  212. struct sockaddr_ll bind_iface = {
  213. .sll_family = AF_PACKET,
  214. .sll_protocol = htons(ETH_P_IPV6),
  215. .sll_ifindex = ifindex,
  216. };
  217. ret = bind(sock, (struct sockaddr *)&bind_iface, sizeof(bind_iface));
  218. if (ret < 0)
  219. exit_errno("can't bind socket");
  220. return sock;
  221. }
  222. static void parse_cmdline(int argc, char *argv[]) {
  223. int c;
  224. unsigned int ifindex;
  225. unsigned long int threshold;
  226. char *endptr;
  227. while ((c = getopt(argc, argv, "c:hi:m:t:")) != -1) {
  228. switch (c) {
  229. case 'i':
  230. if (G.sock >= 0)
  231. usage("-i given more than once");
  232. ifindex = if_nametoindex(optarg);
  233. if (ifindex == 0)
  234. exit_errmsg("Unknown interface: %s", optarg);
  235. G.sock = init_packet_socket(ifindex);
  236. break;
  237. case 'm':
  238. G.mesh_iface = optarg;
  239. break;
  240. case 'c':
  241. G.chain = optarg;
  242. break;
  243. case 't':
  244. threshold = strtoul(optarg, &endptr, 10);
  245. if (*endptr != '\0')
  246. exit_errmsg("Threshold must be a number: %s", optarg);
  247. if (threshold >= LOCAL_TQ)
  248. exit_errmsg("Threshold too large: %ld (max is %d)", threshold, LOCAL_TQ);
  249. G.hysteresis_thresh = (uint16_t) threshold;
  250. break;
  251. case 'h':
  252. usage(NULL);
  253. break;
  254. default:
  255. usage("");
  256. break;
  257. }
  258. }
  259. }
  260. static struct router *router_find_src(const struct ether_addr *src) {
  261. struct router *router;
  262. foreach(router, G.routers) {
  263. if (ether_addr_equal(router->src, *src))
  264. return router;
  265. }
  266. return NULL;
  267. }
  268. static struct router *router_find_orig(const struct ether_addr *orig) {
  269. struct router *router;
  270. foreach(router, G.routers) {
  271. if (ether_addr_equal(router->originator, *orig))
  272. return router;
  273. }
  274. return NULL;
  275. }
  276. static struct router *router_add(const struct ether_addr *mac) {
  277. struct router *router;
  278. router = malloc(sizeof(*router));
  279. if (!router)
  280. return NULL;
  281. router->src = *mac;
  282. router->next = G.routers;
  283. G.routers = router;
  284. router->eol.tv_sec = 0;
  285. router->eol.tv_nsec = 0;
  286. memset(&router->originator, 0, sizeof(router->originator));
  287. return router;
  288. }
  289. static void router_update(const struct ether_addr *mac, uint16_t timeout) {
  290. struct router *router;
  291. router = router_find_src(mac);
  292. if (!router)
  293. router = router_add(mac);
  294. if (!router)
  295. return;
  296. clock_gettime(CLOCK_MONOTONIC, &router->eol);
  297. router->eol.tv_sec += timeout;
  298. }
  299. static void handle_ra(int sock) {
  300. struct sockaddr_ll src;
  301. struct ether_addr mac;
  302. socklen_t addr_size = sizeof(src);
  303. ssize_t len;
  304. struct {
  305. struct ip6_hdr ip6;
  306. struct nd_router_advert ra;
  307. } pkt;
  308. len = recvfrom(sock, &pkt, sizeof(pkt), 0, (struct sockaddr *)&src, &addr_size);
  309. CHECK(len >= 0);
  310. // BPF already checked that this is an ICMPv6 RA of a default router
  311. CHECK((size_t)len >= sizeof(pkt));
  312. CHECK(ntohs(pkt.ip6.ip6_plen) + sizeof(struct ip6_hdr) >= sizeof(pkt));
  313. memcpy(&mac, src.sll_addr, sizeof(mac));
  314. DEBUG_MSG("received valid RA from " F_MAC, F_MAC_VAR(mac));
  315. router_update(&mac, ntohs(pkt.ra.nd_ra_router_lifetime));
  316. check_failed:
  317. return;
  318. }
  319. static void expire_routers(void) {
  320. struct router **prev_ptr = &G.routers;
  321. struct router *router;
  322. struct router *safe;
  323. struct timespec now;
  324. struct timespec diff;
  325. clock_gettime(CLOCK_MONOTONIC, &now);
  326. foreach_safe(router, safe, G.routers) {
  327. if (timespec_diff(&now, &router->eol, &diff)) {
  328. DEBUG_MSG("router " F_MAC " expired", F_MAC_VAR(router->src));
  329. *prev_ptr = router->next;
  330. if (G.best_router == router)
  331. G.best_router = NULL;
  332. free(router);
  333. } else {
  334. prev_ptr = &router->next;
  335. }
  336. }
  337. }
  338. static int parse_tt_global(struct nl_msg *msg,
  339. void *arg __attribute__((unused)))
  340. {
  341. static const enum batadv_nl_attrs mandatory[] = {
  342. BATADV_ATTR_TT_ADDRESS,
  343. BATADV_ATTR_ORIG_ADDRESS,
  344. };
  345. struct nlattr *attrs[BATADV_ATTR_MAX + 1];
  346. struct nlmsghdr *nlh = nlmsg_hdr(msg);
  347. struct ether_addr mac_a, mac_b;
  348. struct genlmsghdr *ghdr;
  349. struct router *router;
  350. uint8_t *addr;
  351. uint8_t *orig;
  352. // parse netlink entry
  353. if (!genlmsg_valid_hdr(nlh, 0))
  354. return NL_OK;
  355. ghdr = nlmsg_data(nlh);
  356. if (ghdr->cmd != BATADV_CMD_GET_TRANSTABLE_GLOBAL)
  357. return NL_OK;
  358. if (nla_parse(attrs, BATADV_ATTR_MAX, genlmsg_attrdata(ghdr, 0),
  359. genlmsg_len(ghdr), batadv_genl_policy)) {
  360. return NL_OK;
  361. }
  362. if (batadv_genl_missing_attrs(attrs, mandatory, ARRAY_SIZE(mandatory)))
  363. return NL_OK;
  364. addr = nla_data(attrs[BATADV_ATTR_TT_ADDRESS]);
  365. orig = nla_data(attrs[BATADV_ATTR_ORIG_ADDRESS]);
  366. if (!attrs[BATADV_ATTR_FLAG_BEST])
  367. return NL_OK;
  368. MAC2ETHER(mac_a, addr);
  369. MAC2ETHER(mac_b, orig);
  370. // update router
  371. router = router_find_src(&mac_a);
  372. if (!router)
  373. return NL_OK;
  374. DEBUG_MSG("Found originator for " F_MAC ", it's " F_MAC,
  375. F_MAC_VAR(router->src), F_MAC_VAR(mac_b));
  376. router->originator = mac_b;
  377. return NL_OK;
  378. }
  379. static int parse_originator(struct nl_msg *msg,
  380. void *arg __attribute__((unused)))
  381. {
  382. static const enum batadv_nl_attrs mandatory[] = {
  383. BATADV_ATTR_ORIG_ADDRESS,
  384. BATADV_ATTR_TQ,
  385. };
  386. struct nlattr *attrs[BATADV_ATTR_MAX + 1];
  387. struct nlmsghdr *nlh = nlmsg_hdr(msg);
  388. struct ether_addr mac_a;
  389. struct genlmsghdr *ghdr;
  390. struct router *router;
  391. uint8_t *orig;
  392. uint8_t tq;
  393. // parse netlink entry
  394. if (!genlmsg_valid_hdr(nlh, 0))
  395. return NL_OK;
  396. ghdr = nlmsg_data(nlh);
  397. if (ghdr->cmd != BATADV_CMD_GET_ORIGINATORS)
  398. return NL_OK;
  399. if (nla_parse(attrs, BATADV_ATTR_MAX, genlmsg_attrdata(ghdr, 0),
  400. genlmsg_len(ghdr), batadv_genl_policy)) {
  401. return NL_OK;
  402. }
  403. if (batadv_genl_missing_attrs(attrs, mandatory, ARRAY_SIZE(mandatory)))
  404. return NL_OK;
  405. orig = nla_data(attrs[BATADV_ATTR_ORIG_ADDRESS]);
  406. tq = nla_get_u8(attrs[BATADV_ATTR_TQ]);
  407. if (!attrs[BATADV_ATTR_FLAG_BEST])
  408. return NL_OK;
  409. MAC2ETHER(mac_a, orig);
  410. // update router
  411. router = router_find_orig(&mac_a);
  412. if (!router)
  413. return NL_OK;
  414. DEBUG_MSG("Found TQ for router " F_MAC " (originator " F_MAC "), it's %d",
  415. F_MAC_VAR(router->src), F_MAC_VAR(router->originator), tq);
  416. router->tq = tq;
  417. if (router->tq > G.max_tq)
  418. G.max_tq = router->tq;
  419. return NL_OK;
  420. }
  421. static int parse_tt_local(struct nl_msg *msg,
  422. void *arg __attribute__((unused)))
  423. {
  424. static const enum batadv_nl_attrs mandatory[] = {
  425. BATADV_ATTR_TT_ADDRESS,
  426. };
  427. struct nlattr *attrs[BATADV_ATTR_MAX + 1];
  428. struct nlmsghdr *nlh = nlmsg_hdr(msg);
  429. struct ether_addr mac_a;
  430. struct genlmsghdr *ghdr;
  431. struct router *router;
  432. uint8_t *addr;
  433. // parse netlink entry
  434. if (!genlmsg_valid_hdr(nlh, 0))
  435. return NL_OK;
  436. ghdr = nlmsg_data(nlh);
  437. if (ghdr->cmd != BATADV_CMD_GET_TRANSTABLE_LOCAL)
  438. return NL_OK;
  439. if (nla_parse(attrs, BATADV_ATTR_MAX, genlmsg_attrdata(ghdr, 0),
  440. genlmsg_len(ghdr), batadv_genl_policy)) {
  441. return NL_OK;
  442. }
  443. if (batadv_genl_missing_attrs(attrs, mandatory, ARRAY_SIZE(mandatory)))
  444. return NL_OK;
  445. addr = nla_data(attrs[BATADV_ATTR_TT_ADDRESS]);
  446. MAC2ETHER(mac_a, addr);
  447. // update router
  448. router = router_find_src(&mac_a);
  449. if (!router)
  450. return NL_OK;
  451. DEBUG_MSG("Found router " F_MAC " in transtable_local, assigning TQ %d",
  452. F_MAC_VAR(router->src), LOCAL_TQ);
  453. router->tq = LOCAL_TQ;
  454. if (router->tq > G.max_tq)
  455. G.max_tq = router->tq;
  456. return NL_OK;
  457. }
  458. static void update_tqs(void) {
  459. struct router *router;
  460. bool update_originators = false;
  461. struct ether_addr unspec;
  462. struct batadv_nlquery_opts opts;
  463. int ret;
  464. // reset TQs
  465. memset(&unspec, 0, sizeof(unspec));
  466. foreach(router, G.routers) {
  467. router->tq = 0;
  468. if (ether_addr_equal(router->originator, unspec))
  469. update_originators = true;
  470. }
  471. // translate all router's MAC addresses to originators simultaneously
  472. if (update_originators) {
  473. opts.err = 0;
  474. ret = batadv_genl_query(G.mesh_iface,
  475. BATADV_CMD_GET_TRANSTABLE_GLOBAL,
  476. parse_tt_global, NLM_F_DUMP, &opts);
  477. if (ret < 0)
  478. fprintf(stderr, "Parsing of global translation table failed\n");
  479. }
  480. // look up TQs of originators
  481. G.max_tq = 0;
  482. opts.err = 0;
  483. ret = batadv_genl_query(G.mesh_iface,
  484. BATADV_CMD_GET_ORIGINATORS,
  485. parse_originator, NLM_F_DUMP, &opts);
  486. if (ret < 0)
  487. fprintf(stderr, "Parsing of originators failed\n");
  488. // if all routers have a TQ value, we don't need to check translocal
  489. foreach(router, G.routers) {
  490. if (router->tq == 0)
  491. break;
  492. }
  493. if (router != NULL) {
  494. opts.err = 0;
  495. ret = batadv_genl_query(G.mesh_iface,
  496. BATADV_CMD_GET_TRANSTABLE_LOCAL,
  497. parse_tt_local, NLM_F_DUMP, &opts);
  498. if (ret < 0)
  499. fprintf(stderr, "Parsing of global translation table failed\n");
  500. }
  501. foreach(router, G.routers) {
  502. if (router->tq == 0) {
  503. if (ether_addr_equal(router->originator, unspec))
  504. fprintf(stderr,
  505. "Unable to find router " F_MAC " in transtable_{global,local}\n",
  506. F_MAC_VAR(router->src));
  507. else
  508. fprintf(stderr,
  509. "Unable to find TQ for originator " F_MAC " (router " F_MAC ")\n",
  510. F_MAC_VAR(router->originator),
  511. F_MAC_VAR(router->src));
  512. }
  513. }
  514. }
  515. static int fork_execvp_timeout(struct timespec *timeout, const char *file, const char *const argv[]) {
  516. int ret;
  517. pid_t child;
  518. siginfo_t info;
  519. sigset_t signals, oldsignals;
  520. sigemptyset(&signals);
  521. sigaddset(&signals, SIGCHLD);
  522. sigprocmask(SIG_BLOCK, &signals, &oldsignals);
  523. child = fork();
  524. if (child == 0) {
  525. sigprocmask(SIG_SETMASK, &oldsignals, NULL);
  526. // casting discards const, but should be safe
  527. // (see http://stackoverflow.com/q/36925388)
  528. execvp(file, (char**) argv);
  529. fprintf(stderr, "can't execvp(\"%s\", ...): %s\n", file, strerror(errno));
  530. _exit(1);
  531. }
  532. else if (child < 0) {
  533. perror("Failed to fork()");
  534. return -1;
  535. }
  536. ret = sigtimedwait(&signals, &info, timeout);
  537. sigprocmask(SIG_SETMASK, &oldsignals, NULL);
  538. if (ret == SIGCHLD) {
  539. if (info.si_pid != child) {
  540. cleanup();
  541. error_message(1, 0,
  542. "BUG: We received a SIGCHLD from a child we didn't spawn (expected PID %d, got %d)",
  543. child, info.si_pid);
  544. }
  545. waitpid(child, NULL, 0);
  546. return info.si_status;
  547. }
  548. if (ret < 0 && errno == EAGAIN)
  549. error_message(0, 0, "warning: child %d took too long, killing", child);
  550. else if (ret < 0)
  551. warn_errno("sigtimedwait failed, killing child");
  552. else
  553. error_message(1, 0,
  554. "BUG: sigtimedwait() returned some other signal than SIGCHLD: %d",
  555. ret);
  556. kill(child, SIGKILL);
  557. kill(child, SIGCONT);
  558. waitpid(child, NULL, 0);
  559. return -1;
  560. }
  561. static bool election_required(void)
  562. {
  563. if (!G.best_router)
  564. return true;
  565. /* should never happen. G.max_tq also contains G.best_router->tq */
  566. if (G.max_tq < G.best_router->tq)
  567. return false;
  568. if ((G.max_tq - G.best_router->tq) <= G.hysteresis_thresh)
  569. return false;
  570. return true;
  571. }
  572. static void update_ebtables(void) {
  573. struct timespec timeout = {
  574. .tv_nsec = EBTABLES_TIMEOUT,
  575. };
  576. char mac[F_MAC_LEN + 1];
  577. struct router *router;
  578. if (!election_required()) {
  579. DEBUG_MSG(F_MAC " is still good enough with TQ=%d (max_tq=%d), not executing ebtables",
  580. F_MAC_VAR(G.best_router->src),
  581. G.best_router->tq,
  582. G.max_tq);
  583. return;
  584. }
  585. foreach(router, G.routers) {
  586. if (router->tq == G.max_tq) {
  587. snprintf(mac, sizeof(mac), F_MAC, F_MAC_VAR(router->src));
  588. break;
  589. }
  590. }
  591. if (G.best_router)
  592. fprintf(stderr, "Switching from " F_MAC " (TQ=%d) to %s (TQ=%d)\n",
  593. F_MAC_VAR(G.best_router->src),
  594. G.best_router->tq,
  595. mac,
  596. G.max_tq);
  597. else
  598. fprintf(stderr, "Switching to %s (TQ=%d)\n",
  599. mac,
  600. G.max_tq);
  601. G.best_router = router;
  602. if (fork_execvp_timeout(&timeout, "ebtables", (const char *[])
  603. { "ebtables", "--concurrent", "-F", G.chain, NULL }))
  604. error_message(0, 0, "warning: flushing ebtables chain %s failed, not adding a new rule", G.chain);
  605. else if (fork_execvp_timeout(&timeout, "ebtables", (const char *[])
  606. { "ebtables", "--concurrent", "-A", G.chain, "-s", mac, "-j", "ACCEPT", NULL }))
  607. error_message(0, 0, "warning: adding new rule to ebtables chain %s failed", G.chain);
  608. }
  609. static void sighandler(int sig __attribute__((unused)))
  610. {
  611. G.stop_daemon = 1;
  612. }
  613. int main(int argc, char *argv[]) {
  614. int retval;
  615. fd_set rfds;
  616. struct timeval tv;
  617. struct timespec next_update;
  618. struct timespec now;
  619. struct timespec diff;
  620. clock_gettime(CLOCK_MONOTONIC, &next_update);
  621. next_update.tv_sec += MIN_INTERVAL;
  622. G.sock = -1;
  623. parse_cmdline(argc, argv);
  624. if (G.sock < 0)
  625. usage("No interface set!");
  626. if (G.chain == NULL)
  627. usage("No chain set!");
  628. G.stop_daemon = 0;
  629. signal(SIGINT, sighandler);
  630. signal(SIGTERM, sighandler);
  631. while (!G.stop_daemon) {
  632. FD_ZERO(&rfds);
  633. FD_SET(G.sock, &rfds);
  634. tv.tv_sec = MAX_INTERVAL;
  635. tv.tv_usec = 0;
  636. retval = select(G.sock + 1, &rfds, NULL, NULL, &tv);
  637. if (retval < 0) {
  638. if (errno != EINTR)
  639. exit_errno("select() failed");
  640. } else if (retval) {
  641. if (FD_ISSET(G.sock, &rfds)) {
  642. handle_ra(G.sock);
  643. }
  644. }
  645. else
  646. DEBUG_MSG("select() timeout expired");
  647. clock_gettime(CLOCK_MONOTONIC, &now);
  648. if (G.routers != NULL &&
  649. timespec_diff(&now, &next_update, &diff)) {
  650. expire_routers();
  651. // all routers could have expired, check again
  652. if (G.routers != NULL) {
  653. update_tqs();
  654. update_ebtables();
  655. next_update = now;
  656. next_update.tv_sec += MIN_INTERVAL;
  657. }
  658. }
  659. }
  660. cleanup();
  661. return 0;
  662. }