net.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. /*
  2. net.c -- most of the network code
  3. Copyright (C) 1998-2005 Ivo Timmermans,
  4. 2000-2015 Guus Sliepen <guus@tinc-vpn.org>
  5. 2006 Scott Lamb <slamb@slamb.org>
  6. 2011 Loïc Grenié <loic.grenie@gmail.com>
  7. This program is free software; you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation; either version 2 of the License, or
  10. (at your option) any later version.
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License along
  16. with this program; if not, write to the Free Software Foundation, Inc.,
  17. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. */
  19. #include "system.h"
  20. #include <openssl/rand.h>
  21. #include "utils.h"
  22. #include "avl_tree.h"
  23. #include "conf.h"
  24. #include "connection.h"
  25. #include "device.h"
  26. #include "event.h"
  27. #include "graph.h"
  28. #include "logger.h"
  29. #include "meta.h"
  30. #include "net.h"
  31. #include "netutl.h"
  32. #include "process.h"
  33. #include "protocol.h"
  34. #include "route.h"
  35. #include "subnet.h"
  36. #include "xalloc.h"
  37. bool do_purge = false;
  38. volatile bool running = false;
  39. #ifdef HAVE_PSELECT
  40. bool graph_dump = false;
  41. #endif
  42. time_t now = 0;
  43. int contradicting_add_edge = 0;
  44. int contradicting_del_edge = 0;
  45. static int sleeptime = 10;
  46. /* Purge edges and subnets of unreachable nodes. Use carefully. */
  47. static void purge(void) {
  48. avl_node_t *nnode, *nnext, *enode, *enext, *snode, *snext;
  49. node_t *n;
  50. edge_t *e;
  51. subnet_t *s;
  52. ifdebug(PROTOCOL) logger(LOG_DEBUG, "Purging unreachable nodes");
  53. /* Remove all edges and subnets owned by unreachable nodes. */
  54. for(nnode = node_tree->head; nnode; nnode = nnext) {
  55. nnext = nnode->next;
  56. n = nnode->data;
  57. if(!n->status.reachable) {
  58. ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Purging node %s (%s)", n->name,
  59. n->hostname);
  60. for(snode = n->subnet_tree->head; snode; snode = snext) {
  61. snext = snode->next;
  62. s = snode->data;
  63. send_del_subnet(everyone, s);
  64. if(!strictsubnets) {
  65. subnet_del(n, s);
  66. }
  67. }
  68. for(enode = n->edge_tree->head; enode; enode = enext) {
  69. enext = enode->next;
  70. e = enode->data;
  71. if(!tunnelserver) {
  72. send_del_edge(everyone, e);
  73. }
  74. edge_del(e);
  75. }
  76. }
  77. }
  78. /* Check if anyone else claims to have an edge to an unreachable node. If not, delete node. */
  79. for(nnode = node_tree->head; nnode; nnode = nnext) {
  80. nnext = nnode->next;
  81. n = nnode->data;
  82. if(!n->status.reachable) {
  83. for(enode = edge_weight_tree->head; enode; enode = enext) {
  84. enext = enode->next;
  85. e = enode->data;
  86. if(e->to == n) {
  87. break;
  88. }
  89. }
  90. if(!enode && (!strictsubnets || !n->subnet_tree->head))
  91. /* in strictsubnets mode do not delete nodes with subnets */
  92. {
  93. node_del(n);
  94. }
  95. }
  96. }
  97. }
  98. /*
  99. put all file descriptors in an fd_set array
  100. While we're at it, purge stuff that needs to be removed.
  101. */
  102. static int build_fdset(fd_set *readset, fd_set *writeset) {
  103. avl_node_t *node, *next;
  104. connection_t *c;
  105. int i, max = 0;
  106. FD_ZERO(readset);
  107. FD_ZERO(writeset);
  108. for(node = connection_tree->head; node; node = next) {
  109. next = node->next;
  110. c = node->data;
  111. if(c->status.remove) {
  112. connection_del(c);
  113. if(!connection_tree->head) {
  114. purge();
  115. }
  116. } else {
  117. FD_SET(c->socket, readset);
  118. if(c->outbuflen > 0 || c->status.connecting) {
  119. FD_SET(c->socket, writeset);
  120. }
  121. if(c->socket > max) {
  122. max = c->socket;
  123. }
  124. }
  125. }
  126. for(i = 0; i < listen_sockets; i++) {
  127. FD_SET(listen_socket[i].tcp, readset);
  128. if(listen_socket[i].tcp > max) {
  129. max = listen_socket[i].tcp;
  130. }
  131. FD_SET(listen_socket[i].udp, readset);
  132. if(listen_socket[i].udp > max) {
  133. max = listen_socket[i].udp;
  134. }
  135. }
  136. if(device_fd >= 0) {
  137. FD_SET(device_fd, readset);
  138. }
  139. if(device_fd > max) {
  140. max = device_fd;
  141. }
  142. return max;
  143. }
  144. /* Put a misbehaving connection in the tarpit */
  145. void tarpit(int fd) {
  146. static int pits[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
  147. static int next_pit = 0;
  148. if(pits[next_pit] != -1) {
  149. closesocket(pits[next_pit]);
  150. }
  151. pits[next_pit++] = fd;
  152. if(next_pit >= (int)(sizeof pits / sizeof pits[0])) {
  153. next_pit = 0;
  154. }
  155. }
  156. /*
  157. Terminate a connection:
  158. - Close the socket
  159. - Remove associated edge and tell other connections about it if report = true
  160. - Check if we need to retry making an outgoing connection
  161. - Deactivate the host
  162. */
  163. void terminate_connection(connection_t *c, bool report) {
  164. if(c->status.remove) {
  165. return;
  166. }
  167. ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Closing connection with %s (%s)",
  168. c->name, c->hostname);
  169. c->status.remove = true;
  170. c->status.active = false;
  171. if(c->node) {
  172. c->node->connection = NULL;
  173. }
  174. if(c->socket) {
  175. if(c->status.tarpit) {
  176. tarpit(c->socket);
  177. } else {
  178. closesocket(c->socket);
  179. }
  180. }
  181. if(c->edge) {
  182. if(!c->node) {
  183. logger(LOG_ERR, "Connection to %s (%s) has an edge but node is NULL!", c->name, c->hostname);
  184. // And that should never happen.
  185. abort();
  186. }
  187. if(report && !tunnelserver) {
  188. send_del_edge(everyone, c->edge);
  189. }
  190. edge_del(c->edge);
  191. c->edge = NULL;
  192. /* Run MST and SSSP algorithms */
  193. graph();
  194. /* If the node is not reachable anymore but we remember it had an edge to us, clean it up */
  195. if(report && !c->node->status.reachable) {
  196. edge_t *e;
  197. e = lookup_edge(c->node, myself);
  198. if(e) {
  199. if(!tunnelserver) {
  200. send_del_edge(everyone, e);
  201. }
  202. edge_del(e);
  203. }
  204. }
  205. }
  206. free_connection_partially(c);
  207. /* Check if this was our outgoing connection */
  208. if(c->outgoing) {
  209. c->status.remove = false;
  210. do_outgoing_connection(c);
  211. }
  212. #ifndef HAVE_MINGW
  213. /* Clean up dead proxy processes */
  214. while(waitpid(-1, NULL, WNOHANG) > 0);
  215. #endif
  216. }
  217. /*
  218. Check if the other end is active.
  219. If we have sent packets, but didn't receive any,
  220. then possibly the other end is dead. We send a
  221. PING request over the meta connection. If the other
  222. end does not reply in time, we consider them dead
  223. and close the connection.
  224. */
  225. static void check_dead_connections(void) {
  226. avl_node_t *node, *next;
  227. connection_t *c;
  228. for(node = connection_tree->head; node; node = next) {
  229. next = node->next;
  230. c = node->data;
  231. if(c->last_ping_time + pingtimeout <= now) {
  232. if(c->status.active) {
  233. if(c->status.pinged) {
  234. ifdebug(CONNECTIONS) logger(LOG_INFO, "%s (%s) didn't respond to PING in %ld seconds",
  235. c->name, c->hostname, (long)(now - c->last_ping_time));
  236. c->status.timeout = true;
  237. terminate_connection(c, true);
  238. } else if(c->last_ping_time + pinginterval <= now) {
  239. send_ping(c);
  240. }
  241. } else {
  242. if(c->status.remove) {
  243. logger(LOG_WARNING, "Old connection_t for %s (%s) status %04x still lingering, deleting...",
  244. c->name, c->hostname, bitfield_to_int(&c->status, sizeof(c->status)));
  245. connection_del(c);
  246. continue;
  247. }
  248. ifdebug(CONNECTIONS) logger(LOG_WARNING, "Timeout from %s (%s) during authentication",
  249. c->name, c->hostname);
  250. if(c->status.connecting) {
  251. c->status.connecting = false;
  252. closesocket(c->socket);
  253. do_outgoing_connection(c);
  254. } else {
  255. c->status.tarpit = true;
  256. terminate_connection(c, false);
  257. }
  258. }
  259. }
  260. if(c->outbuflen > 0 && c->last_flushed_time + pingtimeout <= now) {
  261. if(c->status.active) {
  262. ifdebug(CONNECTIONS) logger(LOG_INFO,
  263. "%s (%s) could not flush for %ld seconds (%d bytes remaining)",
  264. c->name, c->hostname, (long)(now - c->last_flushed_time), c->outbuflen);
  265. c->status.timeout = true;
  266. terminate_connection(c, true);
  267. }
  268. }
  269. }
  270. }
  271. /*
  272. check all connections to see if anything
  273. happened on their sockets
  274. */
  275. static void check_network_activity(fd_set *readset, fd_set *writeset) {
  276. connection_t *c;
  277. avl_node_t *node;
  278. int result, i;
  279. socklen_t len = sizeof(result);
  280. vpn_packet_t packet;
  281. static int errors = 0;
  282. /* check input from kernel */
  283. if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
  284. if(devops.read(&packet)) {
  285. if(packet.len) {
  286. errors = 0;
  287. packet.priority = 0;
  288. route(myself, &packet);
  289. }
  290. } else {
  291. usleep(errors * 50000);
  292. errors++;
  293. if(errors > 10) {
  294. logger(LOG_ERR, "Too many errors from %s, exiting!", device);
  295. running = false;
  296. }
  297. }
  298. }
  299. /* check meta connections */
  300. for(node = connection_tree->head; node; node = node->next) {
  301. c = node->data;
  302. if(c->status.remove) {
  303. continue;
  304. }
  305. if(FD_ISSET(c->socket, writeset)) {
  306. if(c->status.connecting) {
  307. c->status.connecting = false;
  308. getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
  309. if(!result) {
  310. finish_connecting(c);
  311. } else {
  312. ifdebug(CONNECTIONS) logger(LOG_DEBUG,
  313. "Error while connecting to %s (%s): %s",
  314. c->name, c->hostname, sockstrerror(result));
  315. closesocket(c->socket);
  316. do_outgoing_connection(c);
  317. continue;
  318. }
  319. }
  320. if(!flush_meta(c)) {
  321. terminate_connection(c, c->status.active);
  322. continue;
  323. }
  324. }
  325. if(FD_ISSET(c->socket, readset)) {
  326. if(!receive_meta(c)) {
  327. c->status.tarpit = true;
  328. terminate_connection(c, c->status.active);
  329. continue;
  330. }
  331. }
  332. }
  333. for(i = 0; i < listen_sockets; i++) {
  334. if(FD_ISSET(listen_socket[i].udp, readset)) {
  335. handle_incoming_vpn_data(i);
  336. }
  337. if(FD_ISSET(listen_socket[i].tcp, readset)) {
  338. handle_new_meta_connection(listen_socket[i].tcp);
  339. }
  340. }
  341. }
  342. /*
  343. this is where it all happens...
  344. */
  345. int main_loop(void) {
  346. fd_set readset, writeset;
  347. #ifdef HAVE_PSELECT
  348. struct timespec tv;
  349. sigset_t omask, block_mask;
  350. time_t next_event;
  351. #else
  352. struct timeval tv;
  353. #endif
  354. int r, maxfd;
  355. time_t last_ping_check, last_config_check, last_graph_dump;
  356. event_t *event;
  357. last_ping_check = now;
  358. last_config_check = now;
  359. last_graph_dump = now;
  360. srand(now);
  361. #ifdef HAVE_PSELECT
  362. if(lookup_config(config_tree, "GraphDumpFile")) {
  363. graph_dump = true;
  364. }
  365. /* Block SIGHUP & SIGALRM */
  366. sigemptyset(&block_mask);
  367. sigaddset(&block_mask, SIGHUP);
  368. sigaddset(&block_mask, SIGALRM);
  369. sigprocmask(SIG_BLOCK, &block_mask, &omask);
  370. #endif
  371. running = true;
  372. while(running) {
  373. #ifdef HAVE_PSELECT
  374. next_event = last_ping_check + pingtimeout;
  375. if(graph_dump && next_event > last_graph_dump + 60) {
  376. next_event = last_graph_dump + 60;
  377. }
  378. if((event = peek_next_event()) && next_event > event->time) {
  379. next_event = event->time;
  380. }
  381. if(next_event <= now) {
  382. tv.tv_sec = 0;
  383. } else {
  384. tv.tv_sec = next_event - now;
  385. }
  386. tv.tv_nsec = 0;
  387. #else
  388. tv.tv_sec = 1;
  389. tv.tv_usec = 0;
  390. #endif
  391. maxfd = build_fdset(&readset, &writeset);
  392. #ifdef HAVE_MINGW
  393. LeaveCriticalSection(&mutex);
  394. #endif
  395. #ifdef HAVE_PSELECT
  396. r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
  397. #else
  398. r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
  399. #endif
  400. now = time(NULL);
  401. #ifdef HAVE_MINGW
  402. EnterCriticalSection(&mutex);
  403. #endif
  404. if(r < 0) {
  405. if(!sockwouldblock(sockerrno)) {
  406. logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
  407. dump_connections();
  408. return 1;
  409. }
  410. }
  411. if(r > 0) {
  412. check_network_activity(&readset, &writeset);
  413. }
  414. if(do_purge) {
  415. purge();
  416. do_purge = false;
  417. }
  418. /* Let's check if everybody is still alive */
  419. if(last_ping_check + pingtimeout <= now) {
  420. check_dead_connections();
  421. last_ping_check = now;
  422. if(routing_mode == RMODE_SWITCH) {
  423. age_subnets();
  424. }
  425. age_past_requests();
  426. /* Should we regenerate our key? */
  427. if(keyexpires <= now) {
  428. avl_node_t *node;
  429. node_t *n;
  430. ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
  431. for(node = node_tree->head; node; node = node->next) {
  432. n = node->data;
  433. if(n->inkey) {
  434. free(n->inkey);
  435. n->inkey = NULL;
  436. }
  437. }
  438. send_key_changed();
  439. keyexpires = now + keylifetime;
  440. }
  441. /* Detect ADD_EDGE/DEL_EDGE storms that are caused when
  442. * two tinc daemons with the same name are on the VPN.
  443. * If so, sleep a while. If this happens multiple times
  444. * in a row, sleep longer. */
  445. if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
  446. logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
  447. usleep(sleeptime * 1000000LL);
  448. sleeptime *= 2;
  449. if(sleeptime < 0) {
  450. sleeptime = 3600;
  451. }
  452. } else {
  453. sleeptime /= 2;
  454. if(sleeptime < 10) {
  455. sleeptime = 10;
  456. }
  457. }
  458. contradicting_add_edge = 0;
  459. contradicting_del_edge = 0;
  460. }
  461. if(sigalrm) {
  462. avl_node_t *node;
  463. logger(LOG_INFO, "Flushing event queue");
  464. expire_events();
  465. for(node = connection_tree->head; node; node = node->next) {
  466. connection_t *c = node->data;
  467. if(c->status.active) {
  468. send_ping(c);
  469. }
  470. }
  471. sigalrm = false;
  472. }
  473. while((event = get_expired_event())) {
  474. event->handler(event->data);
  475. free_event(event);
  476. }
  477. if(sighup) {
  478. connection_t *c;
  479. avl_node_t *node, *next;
  480. char *fname;
  481. struct stat s;
  482. sighup = false;
  483. reopenlogger();
  484. /* Reread our own configuration file */
  485. exit_configuration(&config_tree);
  486. init_configuration(&config_tree);
  487. if(!read_server_config()) {
  488. logger(LOG_ERR, "Unable to reread configuration file, exitting.");
  489. return 1;
  490. }
  491. /* Cancel non-active outgoing connections */
  492. for(node = connection_tree->head; node; node = next) {
  493. next = node->next;
  494. c = node->data;
  495. c->outgoing = NULL;
  496. if(c->status.connecting) {
  497. terminate_connection(c, false);
  498. connection_del(c);
  499. }
  500. }
  501. /* Wipe list of outgoing connections */
  502. for(list_node_t *node = outgoing_list->head; node; node = node->next) {
  503. outgoing_t *outgoing = node->data;
  504. if(outgoing->event) {
  505. event_del(outgoing->event);
  506. }
  507. }
  508. list_delete_list(outgoing_list);
  509. /* Close connections to hosts that have a changed or deleted host config file */
  510. for(node = connection_tree->head; node; node = node->next) {
  511. c = node->data;
  512. xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
  513. if(stat(fname, &s) || s.st_mtime > last_config_check) {
  514. terminate_connection(c, c->status.active);
  515. }
  516. free(fname);
  517. }
  518. last_config_check = now;
  519. /* If StrictSubnet is set, expire deleted Subnets and read new ones in */
  520. if(strictsubnets) {
  521. subnet_t *subnet;
  522. for(node = subnet_tree->head; node; node = node->next) {
  523. subnet = node->data;
  524. subnet->expires = 1;
  525. }
  526. load_all_subnets();
  527. for(node = subnet_tree->head; node; node = next) {
  528. next = node->next;
  529. subnet = node->data;
  530. if(subnet->expires == 1) {
  531. send_del_subnet(everyone, subnet);
  532. if(subnet->owner->status.reachable) {
  533. subnet_update(subnet->owner, subnet, false);
  534. }
  535. subnet_del(subnet->owner, subnet);
  536. } else if(subnet->expires == -1) {
  537. subnet->expires = 0;
  538. } else {
  539. send_add_subnet(everyone, subnet);
  540. if(subnet->owner->status.reachable) {
  541. subnet_update(subnet->owner, subnet, true);
  542. }
  543. }
  544. }
  545. }
  546. /* Try to make outgoing connections */
  547. try_outgoing_connections();
  548. }
  549. /* Dump graph if wanted every 60 seconds*/
  550. if(last_graph_dump + 60 <= now) {
  551. dump_graph();
  552. last_graph_dump = now;
  553. }
  554. }
  555. #ifdef HAVE_PSELECT
  556. /* Restore SIGHUP & SIGALARM mask */
  557. sigprocmask(SIG_SETMASK, &omask, NULL);
  558. #endif
  559. return 0;
  560. }