gluon-radv-filterd.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /*
  2. Copyright (c) 2016 Jan-Philipp Litza <janphilipp@litza.de>
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright notice,
  9. this list of conditions and the following disclaimer in the documentation
  10. and/or other materials provided with the distribution.
  11. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  12. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  14. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  15. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  16. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  17. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  18. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  19. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  20. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21. */
  22. #define _GNU_SOURCE
  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/if.h>
  39. #include <linux/filter.h>
  40. #include <linux/if_packet.h>
  41. #include <linux/limits.h>
  42. #include <netinet/icmp6.h>
  43. #include <netinet/in.h>
  44. #include <netinet/ip6.h>
  45. #include "mac.h"
  46. // Recheck TQs after this time even if no RA was received
  47. #define MAX_INTERVAL 60
  48. // Recheck TQs at most this often, even if new RAs were received (they won't
  49. // become the preferred routers until the TQs have been rechecked)
  50. // Also, the first update will take at least this long
  51. #define MIN_INTERVAL 15
  52. // max execution time of a single ebtables call in nanoseconds
  53. #define EBTABLES_TIMEOUT 500000000 // 500ms
  54. // TQ value assigned to local routers
  55. #define LOCAL_TQ 512
  56. #define BUFSIZE 1500
  57. #define DEBUGFS "/sys/kernel/debug/batman_adv/%s/"
  58. #define ORIGINATORS DEBUGFS "originators"
  59. #define TRANSTABLE_GLOBAL DEBUGFS "transtable_global"
  60. #define TRANSTABLE_LOCAL DEBUGFS "transtable_local"
  61. #ifdef DEBUG
  62. #define CHECK(stmt) \
  63. if(!(stmt)) { \
  64. fprintf(stderr, "check failed: " #stmt "\n"); \
  65. goto check_failed; \
  66. }
  67. #define DEBUG_MSG(msg, ...) fprintf(stderr, msg "\n", ##__VA_ARGS__)
  68. #else
  69. #define CHECK(stmt) if(!(stmt)) goto check_failed;
  70. #define DEBUG_MSG(msg, ...) do {} while(0)
  71. #endif
  72. #ifndef ARRAY_SIZE
  73. #define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))
  74. #endif
  75. #define foreach(item, list) \
  76. for(item = list; item != NULL; item = item->next)
  77. struct router {
  78. struct router *next;
  79. macaddr_t src;
  80. time_t eol;
  81. macaddr_t originator;
  82. uint16_t tq;
  83. };
  84. struct global {
  85. int sock;
  86. struct router *routers;
  87. const char *mesh_iface;
  88. const char *chain;
  89. uint16_t max_tq;
  90. uint16_t hysteresis_thresh;
  91. struct router *best_router;
  92. } G = {
  93. .mesh_iface = "bat0",
  94. };
  95. static void error_message(int status, int errnum, char *message, ...) {
  96. va_list ap;
  97. va_start(ap, message);
  98. fflush(stdout);
  99. vfprintf(stderr, message, ap);
  100. if (errnum)
  101. fprintf(stderr, ": %s", strerror(errnum));
  102. fprintf(stderr, "\n");
  103. if (status)
  104. exit(status);
  105. }
  106. static void cleanup() {
  107. struct router *router;
  108. close(G.sock);
  109. while (G.routers != NULL) {
  110. router = G.routers;
  111. G.routers = router->next;
  112. free(router);
  113. }
  114. }
  115. static void usage(const char *msg) {
  116. if (msg != NULL && *msg != '\0') {
  117. fprintf(stderr, "ERROR: %s\n\n", msg);
  118. }
  119. fprintf(stderr,
  120. "Usage: %s [-m <mesh_iface>] [-t <thresh>] -c <chain> -i <iface>\n\n"
  121. " -m <mesh_iface> B.A.T.M.A.N. advanced mesh interface used to get metric\n"
  122. " information (\"TQ\") for the available gateways. Default: bat0\n"
  123. " -t <thresh> Minimum TQ difference required to switch the gateway.\n"
  124. " Default: 0\n"
  125. " -c <chain> ebtables chain that should be managed by the daemon. The\n"
  126. " chain already has to exist on program invocation and should\n"
  127. " have a DROP policy. It will be flushed by the program!\n"
  128. " -i <iface> Interface to listen on for router advertisements. Should be\n"
  129. " <mesh_iface> or a bridge on top of it, as no metric\n"
  130. " information will be available for hosts on other interfaces.\n\n",
  131. program_invocation_short_name);
  132. cleanup();
  133. if (msg == NULL)
  134. exit(EXIT_SUCCESS);
  135. else
  136. exit(EXIT_FAILURE);
  137. }
  138. #define exit_errmsg(message, ...) { \
  139. fprintf(stderr, message "\n", ##__VA_ARGS__); \
  140. cleanup(); \
  141. exit(1); \
  142. }
  143. static inline void exit_errno(const char *message) {
  144. cleanup();
  145. error_message(1, errno, "error: %s", message);
  146. }
  147. static inline void warn_errno(const char *message) {
  148. error_message(0, errno, "warning: %s", message);
  149. }
  150. static int init_packet_socket(unsigned int ifindex) {
  151. struct sock_filter radv_filter_code[] = {
  152. // check that this is an ICMPv6 packet
  153. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, offsetof(struct ip6_hdr, ip6_nxt)),
  154. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_ICMPV6, 0, 7),
  155. // check that this is a router advertisement
  156. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, sizeof(struct ip6_hdr) + offsetof(struct icmp6_hdr, icmp6_type)),
  157. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ND_ROUTER_ADVERT, 0, 5),
  158. // check that the code field in the ICMPv6 header is 0
  159. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, sizeof(struct ip6_hdr) + offsetof(struct nd_router_advert, nd_ra_code)),
  160. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0, 0, 3),
  161. // check that this is a default route (lifetime > 0)
  162. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, sizeof(struct ip6_hdr) + offsetof(struct nd_router_advert, nd_ra_router_lifetime)),
  163. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0, 1, 0),
  164. // return true
  165. BPF_STMT(BPF_RET|BPF_K, 0xffffffff),
  166. // return false
  167. BPF_STMT(BPF_RET|BPF_K, 0),
  168. };
  169. struct sock_fprog radv_filter = {
  170. .len = ARRAY_SIZE(radv_filter_code),
  171. .filter = radv_filter_code,
  172. };
  173. int sock = socket(AF_PACKET, SOCK_DGRAM|SOCK_CLOEXEC, htons(ETH_P_IPV6));
  174. if (sock < 0)
  175. exit_errno("can't open packet socket");
  176. int ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &radv_filter, sizeof(radv_filter));
  177. if (ret < 0)
  178. exit_errno("can't attach socket filter");
  179. struct sockaddr_ll bind_iface = {
  180. .sll_family = AF_PACKET,
  181. .sll_protocol = htons(ETH_P_IPV6),
  182. .sll_ifindex = ifindex,
  183. };
  184. bind(sock, (struct sockaddr *)&bind_iface, sizeof(bind_iface));
  185. return sock;
  186. }
  187. static void parse_cmdline(int argc, char *argv[]) {
  188. int c;
  189. unsigned int ifindex;
  190. unsigned long int threshold;
  191. char *endptr;
  192. while ((c = getopt(argc, argv, "c:hi:m:t:")) != -1) {
  193. switch (c) {
  194. case 'i':
  195. if (G.sock != 0)
  196. usage("-i given more than once");
  197. ifindex = if_nametoindex(optarg);
  198. if (ifindex == 0)
  199. exit_errmsg("Unknown interface: %s", optarg);
  200. G.sock = init_packet_socket(ifindex);
  201. break;
  202. case 'm':
  203. G.mesh_iface = optarg;
  204. break;
  205. case 'c':
  206. G.chain = optarg;
  207. break;
  208. case 't':
  209. threshold = strtoul(optarg, &endptr, 10);
  210. if (*endptr != '\0')
  211. exit_errmsg("Threshold must be a number: %s", optarg);
  212. if (threshold >= LOCAL_TQ)
  213. exit_errmsg("Threshold too large: %ld (max is %d)", threshold, LOCAL_TQ);
  214. G.hysteresis_thresh = (uint16_t) threshold;
  215. break;
  216. case 'h':
  217. usage(NULL);
  218. break;
  219. default:
  220. usage("");
  221. break;
  222. }
  223. }
  224. }
  225. static void handle_ra(int sock) {
  226. struct sockaddr_ll src;
  227. unsigned int addr_size = sizeof(src);
  228. size_t len;
  229. struct {
  230. struct ip6_hdr ip6;
  231. struct nd_router_advert ra;
  232. } pkt;
  233. len = recvfrom(sock, &pkt, sizeof(pkt), 0, (struct sockaddr *)&src, &addr_size);
  234. // BPF already checked that this is an ICMPv6 RA of a default router
  235. CHECK(len >= sizeof(pkt));
  236. CHECK(ntohs(pkt.ip6.ip6_plen) + sizeof(struct ip6_hdr) >= sizeof(pkt));
  237. DEBUG_MSG("received valid RA from " F_MAC, F_MAC_VAR(src.sll_addr));
  238. // update list of known routers
  239. struct router *router;
  240. foreach(router, G.routers) {
  241. if (!memcmp(router->src, src.sll_addr, sizeof(macaddr_t))) {
  242. break;
  243. }
  244. }
  245. if (!router) {
  246. router = malloc(sizeof(struct router));
  247. memcpy(router->src, src.sll_addr, sizeof(router->src));
  248. router->next = G.routers;
  249. G.routers = router;
  250. }
  251. router->eol = time(NULL) + pkt.ra.nd_ra_router_lifetime;
  252. check_failed:
  253. return;
  254. }
  255. static void expire_routers() {
  256. struct router **prev_ptr = &G.routers;
  257. struct router *router;
  258. time_t now = time(NULL);
  259. foreach(router, G.routers) {
  260. if (router->eol < now) {
  261. DEBUG_MSG("router " F_MAC " expired", F_MAC_VAR(router->src));
  262. *prev_ptr = router->next;
  263. if (G.best_router == router)
  264. G.best_router = NULL;
  265. free(router);
  266. } else {
  267. prev_ptr = &router->next;
  268. }
  269. }
  270. }
  271. static void update_tqs() {
  272. FILE *f;
  273. struct router *router;
  274. char path[PATH_MAX];
  275. char *line = NULL;
  276. size_t len = 0;
  277. uint8_t tq;
  278. bool update_originators = false;
  279. int i;
  280. macaddr_t mac_a, mac_b;
  281. macaddr_t unspec = {};
  282. // reset TQs
  283. foreach(router, G.routers) {
  284. router->tq = 0;
  285. if (!memcmp(router->originator, unspec, sizeof(unspec)))
  286. update_originators = true;
  287. }
  288. // TODO: Currently, we iterate over the whole list of routers all the
  289. // time. Maybe it would be a good idea to sort routers that already
  290. // have the current piece of information to the back. That way, we
  291. // could abort as soon as we hit the first router with the current
  292. // information filled in.
  293. if (update_originators) {
  294. // translate all router's MAC addresses to originators simultaneously
  295. snprintf(path, PATH_MAX, TRANSTABLE_GLOBAL, G.mesh_iface);
  296. f = fopen(path, "r");
  297. // skip header
  298. while (fgetc(f) != '\n') {}
  299. while (fgetc(f) != '\n') {}
  300. while (fscanf(f, " %*[*+] " F_MAC "%*[0-9 -] (%*3u) via " F_MAC " %*[^]]]\n",
  301. F_MAC_VAR_REF(mac_a), F_MAC_VAR_REF(mac_b)) == 12) {
  302. foreach(router, G.routers) {
  303. if (!memcmp(router->src, mac_a, sizeof(macaddr_t))) {
  304. DEBUG_MSG("Found originator for " F_MAC ", it's " F_MAC, F_MAC_VAR(router->src), F_MAC_VAR(mac_b));
  305. memcpy(router->originator, mac_b, sizeof(macaddr_t));
  306. break; // foreach
  307. }
  308. }
  309. }
  310. if (!feof(f)) {
  311. getline(&line, &len, f);
  312. fprintf(stderr, "Parsing transtable_global aborted at this line: %s\n", line);
  313. }
  314. fclose(f);
  315. }
  316. // look up TQs of originators
  317. G.max_tq = 0;
  318. snprintf(path, PATH_MAX, ORIGINATORS, G.mesh_iface);
  319. f = fopen(path, "r");
  320. // skip header
  321. while (fgetc(f) != '\n');
  322. while (fgetc(f) != '\n');
  323. while (fscanf(f, F_MAC " %*fs (%hhu) %*[^\n]\n",
  324. F_MAC_VAR_REF(mac_a), &tq) == 7) {
  325. foreach(router, G.routers) {
  326. if (!memcmp(router->originator, mac_a, sizeof(macaddr_t))) {
  327. DEBUG_MSG("Found TQ for router " F_MAC " (originator " F_MAC "), it's %d", F_MAC_VAR(router->src), F_MAC_VAR(router->originator), tq);
  328. router->tq = tq;
  329. if (tq > G.max_tq)
  330. G.max_tq = tq;
  331. break; // foreach
  332. }
  333. }
  334. }
  335. if (!feof(f)) {
  336. getline(&line, &len, f);
  337. fprintf(stderr, "Parsing originators aborted at this line: %s\n", line);
  338. }
  339. fclose(f);
  340. // if all routers have a TQ value, we don't need to check translocal
  341. foreach(router, G.routers) {
  342. if (router->tq == 0)
  343. break;
  344. }
  345. if (router != NULL) {
  346. // rate local routers (if present) the highest
  347. snprintf(path, PATH_MAX, TRANSTABLE_LOCAL, G.mesh_iface);
  348. f = fopen(path, "r");
  349. // skip header
  350. while (fgetc(f) != '\n');
  351. while (fgetc(f) != '\n');
  352. while (fscanf(f, " * " F_MAC " [%*5s] %*f", F_MAC_VAR_REF(mac_a)) == 6) {
  353. foreach(router, G.routers) {
  354. if (!memcmp(router->src, mac_a, sizeof(macaddr_t))) {
  355. DEBUG_MSG("Found router " F_MAC " in transtable_local, assigning TQ %d", F_MAC_VAR(router->src), LOCAL_TQ);
  356. router->tq = LOCAL_TQ;
  357. G.max_tq = LOCAL_TQ;
  358. break; // foreach
  359. }
  360. }
  361. }
  362. if (!feof(f)) {
  363. getline(&line, &len, f);
  364. fprintf(stderr, "Parsing transtable_local aborted at this line: %s\n", line);
  365. }
  366. fclose(f);
  367. }
  368. foreach(router, G.routers) {
  369. if (router->tq == 0) {
  370. if (!memcmp(router->originator, unspec, sizeof(unspec)))
  371. fprintf(stderr,
  372. "Unable to find router " F_MAC " in transtable_{global,local}\n",
  373. F_MAC_VAR(router->src));
  374. else
  375. fprintf(stderr,
  376. "Unable to find TQ for originator " F_MAC " (router " F_MAC ")\n",
  377. F_MAC_VAR(router->originator),
  378. F_MAC_VAR(router->src));
  379. }
  380. }
  381. free(line);
  382. }
  383. static int fork_execvp_timeout(struct timespec *timeout, const char *file, const char *const argv[]) {
  384. int ret;
  385. pid_t child;
  386. siginfo_t info;
  387. sigset_t signals, oldsignals;
  388. sigemptyset(&signals);
  389. sigaddset(&signals, SIGCHLD);
  390. sigprocmask(SIG_BLOCK, &signals, &oldsignals);
  391. child = fork();
  392. if (child == 0) {
  393. sigprocmask(SIG_SETMASK, &oldsignals, NULL);
  394. // casting discards const, but should be safe
  395. // (see http://stackoverflow.com/q/36925388)
  396. execvp(file, (char**) argv);
  397. fprintf(stderr, "can't execvp(\"%s\", ...): %s\n", file, strerror(errno));
  398. _exit(1);
  399. }
  400. else if (child < 0) {
  401. perror("Failed to fork()");
  402. return -1;
  403. }
  404. ret = sigtimedwait(&signals, &info, timeout);
  405. sigprocmask(SIG_SETMASK, &oldsignals, NULL);
  406. if (ret == SIGCHLD) {
  407. if (info.si_pid != child) {
  408. cleanup();
  409. error_message(1, 0,
  410. "BUG: We received a SIGCHLD from a child we didn't spawn (expected PID %d, got %d)",
  411. child, info.si_pid);
  412. }
  413. waitpid(child, NULL, 0);
  414. return info.si_status;
  415. }
  416. if (ret < 0 && errno == EAGAIN)
  417. error_message(0, 0, "warning: child %d took too long, killing", child);
  418. else if (ret < 0)
  419. warn_errno("sigtimedwait failed, killing child");
  420. else
  421. error_message(1, 0,
  422. "BUG: sigtimedwait() returned some other signal than SIGCHLD: %d",
  423. ret);
  424. kill(child, SIGKILL);
  425. kill(child, SIGCONT);
  426. waitpid(child, NULL, 0);
  427. return -1;
  428. }
  429. static void update_ebtables() {
  430. struct timespec timeout = {
  431. .tv_nsec = EBTABLES_TIMEOUT,
  432. };
  433. char mac[F_MAC_LEN + 1];
  434. struct router *router;
  435. if (G.best_router && G.best_router->tq >= G.max_tq - G.hysteresis_thresh) {
  436. DEBUG_MSG(F_MAC " is still good enough with TQ=%d (max_tq=%d), not executing ebtables",
  437. F_MAC_VAR(G.best_router->src),
  438. G.best_router->tq,
  439. G.max_tq);
  440. return;
  441. }
  442. foreach(router, G.routers) {
  443. if (router->tq == G.max_tq) {
  444. snprintf(mac, sizeof(mac), F_MAC, F_MAC_VAR(router->src));
  445. break;
  446. }
  447. }
  448. if (G.best_router)
  449. fprintf(stderr, "Switching from " F_MAC " (TQ=%d) to %s (TQ=%d)\n",
  450. F_MAC_VAR(G.best_router->src),
  451. G.best_router->tq,
  452. mac,
  453. G.max_tq);
  454. else
  455. fprintf(stderr, "Switching to %s (TQ=%d)\n",
  456. mac,
  457. G.max_tq);
  458. G.best_router = router;
  459. if (fork_execvp_timeout(&timeout, "ebtables", (const char *[])
  460. { "ebtables", "-F", G.chain, NULL }))
  461. error_message(0, 0, "warning: flushing ebtables chain %s failed, not adding a new rule", G.chain);
  462. else if (fork_execvp_timeout(&timeout, "ebtables", (const char *[])
  463. { "ebtables", "-A", G.chain, "-s", mac, "-j", "ACCEPT", NULL }))
  464. error_message(0, 0, "warning: adding new rule to ebtables chain %s failed", G.chain);
  465. }
  466. int main(int argc, char *argv[]) {
  467. int retval;
  468. fd_set rfds;
  469. struct timeval tv;
  470. time_t last_update = time(NULL);
  471. parse_cmdline(argc, argv);
  472. if (G.sock == 0)
  473. usage("No interface set!");
  474. if (G.chain == NULL)
  475. usage("No chain set!");
  476. while (1) {
  477. FD_ZERO(&rfds);
  478. FD_SET(G.sock, &rfds);
  479. tv.tv_sec = MAX_INTERVAL;
  480. tv.tv_usec = 0;
  481. retval = select(G.sock + 1, &rfds, NULL, NULL, &tv);
  482. if (retval < 0)
  483. exit_errno("select() failed");
  484. else if (retval) {
  485. if (FD_ISSET(G.sock, &rfds)) {
  486. handle_ra(G.sock);
  487. }
  488. }
  489. else
  490. DEBUG_MSG("select() timeout expired");
  491. if (G.routers != NULL && last_update <= time(NULL) - MIN_INTERVAL) {
  492. expire_routers();
  493. // all routers could have expired, check again
  494. if (G.routers != NULL) {
  495. update_tqs();
  496. update_ebtables();
  497. last_update = time(NULL);
  498. }
  499. }
  500. }
  501. cleanup();
  502. return 0;
  503. }