2 net_packet.c -- Handles in- and outgoing VPN packets
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5 2010 Timothy Redaelli <timothy@redaelli.eu>
6 2010 Brandon Black <blblack@gmail.com>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <openssl/rand.h>
26 #include <openssl/err.h>
27 #include <openssl/evp.h>
28 #include <openssl/pem.h>
29 #include <openssl/hmac.h>
41 #include "connection.h"
58 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
61 static void send_udppacket(node_t *, vpn_packet_t *);
63 unsigned replaywin = 16;
64 bool localdiscovery = false;
66 #define MAX_SEQNO 1073741824
68 /* mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
69 mtuprobes == 31: sleep pinginterval seconds
70 mtuprobes == 32: send 1 burst, sleep pingtimeout second
71 mtuprobes == 33: no response from other side, restart PMTU discovery process
73 Probes are sent in batches of three, with random sizes between the lower and
74 upper boundaries for the MTU thus far discovered.
76 In case local discovery is enabled, a fourth packet is added to each batch,
77 which will be broadcast to the local network.
80 static void send_mtu_probe_handler(void *data) {
86 if(!n->status.reachable || !n->status.validkey) {
87 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
92 if(n->mtuprobes > 32) {
95 timeout = pinginterval;
99 logger(DEBUG_TRAFFIC, LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
100 n->status.udp_confirmed = false;
106 if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
107 logger(DEBUG_TRAFFIC, LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
111 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
112 if(n->minmtu > n->maxmtu)
113 n->minmtu = n->maxmtu;
115 n->maxmtu = n->minmtu;
117 logger(DEBUG_TRAFFIC, LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
121 if(n->mtuprobes == 31) {
122 timeout = pinginterval;
124 } else if(n->mtuprobes == 32) {
125 timeout = pingtimeout;
128 for(int i = 0; i < 3 + localdiscovery; i++) {
131 if(n->maxmtu <= n->minmtu)
134 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
140 memset(packet.data, 0, 14);
141 randomize(packet.data + 14, len - 14);
143 if(i >= 3 && n->mtuprobes <= 10)
144 packet.priority = -1;
148 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
150 send_udppacket(n, &packet);
153 n->probe_counter = 0;
154 gettimeofday(&n->probe_time, NULL);
156 /* Calculate the packet loss of incoming traffic by comparing the rate of
157 packets received to the rate with which the sequence number has increased.
160 if(n->received > n->prev_received)
161 n->packetloss = 1.0 - (n->received - n->prev_received) / (float)(n->received_seqno - n->prev_received_seqno);
163 n->packetloss = n->received_seqno <= n->prev_received_seqno;
165 n->prev_received_seqno = n->received_seqno;
166 n->prev_received = n->received;
169 timeout_set(&n->mtutimeout, &(struct timeval){timeout, rand() % 100000});
172 void send_mtu_probe(node_t *n) {
173 timeout_add(&n->mtutimeout, send_mtu_probe_handler, n, &(struct timeval){1, 0});
174 send_mtu_probe_handler(n);
177 static void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
178 logger(DEBUG_TRAFFIC, LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
180 if(!packet->data[0]) {
181 /* It's a probe request, send back a reply */
185 /* Temporarily set udp_confirmed, so that the reply is sent
186 back exactly the way it came in. */
188 bool udp_confirmed = n->status.udp_confirmed;
189 n->status.udp_confirmed = true;
190 send_udppacket(n, packet);
191 n->status.udp_confirmed = udp_confirmed;
193 /* It's a valid reply: now we know bidirectional communication
194 is possible using the address and socket that the reply
197 n->status.udp_confirmed = true;
199 /* If we haven't established the PMTU yet, restart the discovery process. */
201 if(n->mtuprobes > 30) {
208 /* If applicable, raise the minimum supported MTU */
215 /* Calculate RTT and bandwidth.
216 The RTT is the time between the MTU probe burst was sent and the first
217 reply is received. The bandwidth is measured using the time between the
218 arrival of the first and third probe reply.
221 struct timeval now, diff;
222 gettimeofday(&now, NULL);
223 timersub(&now, &n->probe_time, &diff);
226 if(n->probe_counter == 1) {
227 n->rtt = diff.tv_sec + diff.tv_usec * 1e-6;
229 } else if(n->probe_counter == 3) {
230 n->bandwidth = 2.0 * len / (diff.tv_sec + diff.tv_usec * 1e-6);
231 logger(DEBUG_TRAFFIC, LOG_DEBUG, "%s (%s) RTT %.2f ms, burst bandwidth %.3f Mbit/s, rx packet loss %.2f %%", n->name, n->hostname, n->rtt * 1e3, n->bandwidth * 8e-6, n->packetloss * 1e2);
236 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
238 memcpy(dest, source, len);
240 } else if(level == 10) {
242 lzo_uint lzolen = MAXSIZE;
243 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
248 } else if(level < 10) {
250 unsigned long destlen = MAXSIZE;
251 if(compress2(dest, &destlen, source, len, level) == Z_OK)
258 lzo_uint lzolen = MAXSIZE;
259 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
269 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
271 memcpy(dest, source, len);
273 } else if(level > 9) {
275 lzo_uint lzolen = MAXSIZE;
276 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
284 unsigned long destlen = MAXSIZE;
285 if(uncompress(dest, &destlen, source, len) == Z_OK)
297 static void receive_packet(node_t *n, vpn_packet_t *packet) {
298 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
299 packet->len, n->name, n->hostname);
302 n->in_bytes += packet->len;
307 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
309 return sptps_verify_datagram(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
311 if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
314 return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
317 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
318 vpn_packet_t pkt1, pkt2;
319 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
321 vpn_packet_t *outpkt = pkt[0];
324 if(n->status.sptps) {
325 sptps_receive_data(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
329 if(!cipher_active(&n->incipher)) {
330 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
331 n->name, n->hostname);
335 /* Check packet length */
337 if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
338 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got too short packet from %s (%s)",
339 n->name, n->hostname);
343 /* Check the message authentication code */
345 if(digest_active(&n->indigest)) {
346 inpkt->len -= n->indigest.maclength;
347 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
348 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
352 /* Decrypt the packet */
354 if(cipher_active(&n->incipher)) {
355 outpkt = pkt[nextpkt++];
358 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
359 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
363 outpkt->len = outlen;
367 /* Check the sequence number */
369 inpkt->len -= sizeof inpkt->seqno;
370 inpkt->seqno = ntohl(inpkt->seqno);
373 if(inpkt->seqno != n->received_seqno + 1) {
374 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
375 if(n->farfuture++ < replaywin >> 2) {
376 logger(DEBUG_ALWAYS, LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
377 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
380 logger(DEBUG_ALWAYS, LOG_WARNING, "Lost %d packets from %s (%s)",
381 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
382 memset(n->late, 0, replaywin);
383 } else if (inpkt->seqno <= n->received_seqno) {
384 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
385 logger(DEBUG_ALWAYS, LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
386 n->name, n->hostname, inpkt->seqno, n->received_seqno);
390 for(int i = n->received_seqno + 1; i < inpkt->seqno; i++)
391 n->late[(i / 8) % replaywin] |= 1 << i % 8;
396 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
399 if(inpkt->seqno > n->received_seqno)
400 n->received_seqno = inpkt->seqno;
404 if(n->received_seqno > MAX_SEQNO)
407 /* Decompress the packet */
409 length_t origlen = inpkt->len;
411 if(n->incompression) {
412 outpkt = pkt[nextpkt++];
414 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
415 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while uncompressing packet from %s (%s)",
416 n->name, n->hostname);
422 origlen -= MTU/64 + 20;
427 if(!inpkt->data[12] && !inpkt->data[13])
428 mtu_probe_h(n, inpkt, origlen);
430 receive_packet(n, inpkt);
433 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
437 if(c->options & OPTION_TCPONLY)
440 outpkt.priority = -1;
441 memcpy(outpkt.data, buffer, len);
443 receive_packet(c->node, &outpkt);
446 static void send_sptps_packet(node_t *n, vpn_packet_t *origpkt) {
447 if(!n->status.validkey) {
448 logger(DEBUG_TRAFFIC, LOG_INFO, "No valid key known yet for %s (%s)", n->name, n->hostname);
449 if(!n->status.waitingforkey)
451 else if(n->last_req_key + 10 < time(NULL)) {
452 logger(DEBUG_ALWAYS, LOG_DEBUG, "No key from %s after 10 seconds, restarting SPTPS", n->name);
453 sptps_stop(&n->sptps);
454 n->status.waitingforkey = false;
463 if(!(origpkt->data[12] | origpkt->data[13])) {
464 sptps_send_record(&n->sptps, PKT_PROBE, (char *)origpkt->data, origpkt->len);
468 if(routing_mode == RMODE_ROUTER)
473 if(origpkt->len < offset)
478 if(n->outcompression) {
479 int len = compress_packet(outpkt.data + offset, origpkt->data + offset, origpkt->len - offset, n->outcompression);
481 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)", n->name, n->hostname);
482 } else if(len < origpkt->len - offset) {
483 outpkt.len = len + offset;
485 type |= PKT_COMPRESSED;
489 sptps_send_record(&n->sptps, type, (char *)origpkt->data + offset, origpkt->len - offset);
493 static void choose_udp_address(const node_t *n, const sockaddr_t **sa, int *sock) {
498 /* If the UDP address is confirmed, use it. */
499 if(n->status.udp_confirmed)
502 /* Send every third packet to n->address; that could be set
503 to the node's reflexive UDP address discovered during key
512 /* Otherwise, address are found in edges to this node.
513 So we pick a random edge and a random socket. */
516 int j = rand() % n->edge_tree->count;
517 edge_t *candidate = NULL;
519 for splay_each(edge_t, e, n->edge_tree) {
521 candidate = e->reverse;
527 *sa = &candidate->address;
528 *sock = rand() % listen_sockets;
531 /* Make sure we have a suitable socket for the chosen address */
532 if(listen_socket[*sock].sa.sa.sa_family != (*sa)->sa.sa_family) {
533 for(int i = 0; i < listen_sockets; i++) {
534 if(listen_socket[i].sa.sa.sa_family == (*sa)->sa.sa_family) {
542 static void choose_broadcast_address(const node_t *n, const sockaddr_t **sa, int *sock) {
543 static sockaddr_t broadcast_ipv4 = {
545 .sin_family = AF_INET,
546 .sin_addr.s_addr = -1,
550 static sockaddr_t broadcast_ipv6 = {
552 .sin6_family = AF_INET6,
553 .sin6_addr.s6_addr[0x0] = 0xff,
554 .sin6_addr.s6_addr[0x1] = 0x02,
555 .sin6_addr.s6_addr[0xf] = 0x01,
559 *sock = rand() % listen_sockets;
561 if(listen_socket[*sock].sa.sa.sa_family == AF_INET6) {
562 broadcast_ipv6.in6.sin6_port = n->prevedge->address.in.sin_port;
563 broadcast_ipv6.in6.sin6_scope_id = listen_socket[*sock].sa.in6.sin6_scope_id;
564 *sa = &broadcast_ipv6;
566 broadcast_ipv4.in.sin_port = n->prevedge->address.in.sin_port;
567 *sa = &broadcast_ipv4;
571 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
572 vpn_packet_t pkt1, pkt2;
573 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
574 vpn_packet_t *inpkt = origpkt;
576 vpn_packet_t *outpkt;
577 int origlen = origpkt->len;
579 #if defined(SOL_IP) && defined(IP_TOS)
580 static int priority = 0;
582 int origpriority = origpkt->priority;
584 if(!n->status.reachable) {
585 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
590 return send_sptps_packet(n, origpkt);
592 /* Make sure we have a valid key */
594 if(!n->status.validkey) {
595 logger(DEBUG_TRAFFIC, LOG_INFO,
596 "No valid key known yet for %s (%s), forwarding via TCP",
597 n->name, n->hostname);
599 if(n->last_req_key + 10 <= now.tv_sec) {
601 n->last_req_key = now.tv_sec;
604 send_tcppacket(n->nexthop->connection, origpkt);
609 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
610 logger(DEBUG_TRAFFIC, LOG_INFO,
611 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
612 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
615 send_packet(n->nexthop, origpkt);
617 send_tcppacket(n->nexthop->connection, origpkt);
622 /* Compress the packet */
624 if(n->outcompression) {
625 outpkt = pkt[nextpkt++];
627 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
628 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)",
629 n->name, n->hostname);
636 /* Add sequence number */
638 inpkt->seqno = htonl(++(n->sent_seqno));
639 inpkt->len += sizeof inpkt->seqno;
641 /* Encrypt the packet */
643 if(cipher_active(&n->outcipher)) {
644 outpkt = pkt[nextpkt++];
647 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
648 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
652 outpkt->len = outlen;
656 /* Add the message authentication code */
658 if(digest_active(&n->outdigest)) {
659 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
660 inpkt->len += digest_length(&n->outdigest);
663 /* Send the packet */
665 const sockaddr_t *sa;
668 /* Overloaded use of priority field: -1 means local broadcast */
670 if(origpriority == -1 && n->prevedge)
671 choose_broadcast_address(n, &sa, &sock);
673 choose_udp_address(n, &sa, &sock);
675 #if defined(SOL_IP) && defined(IP_TOS)
676 if(priorityinheritance && origpriority != priority
677 && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
678 priority = origpriority;
679 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
680 if(setsockopt(listen_socket[n->sock].udp.fd, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
681 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
685 if(sendto(listen_socket[sock].udp.fd, (char *) &inpkt->seqno, inpkt->len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
686 if(sockmsgsize(sockerrno)) {
687 if(n->maxmtu >= origlen)
688 n->maxmtu = origlen - 1;
689 if(n->mtu >= origlen)
690 n->mtu = origlen - 1;
692 logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
696 origpkt->len = origlen;
699 bool send_sptps_data(void *handle, uint8_t type, const char *data, size_t len) {
702 /* Send it via TCP if it is a handshake packet, TCPOnly is in use, or this packet is larger than the MTU. */
704 if(type >= SPTPS_HANDSHAKE || ((myself->options | to->options) & OPTION_TCPONLY) || (type != PKT_PROBE && len > to->minmtu)) {
705 char buf[len * 4 / 3 + 5];
706 b64encode(data, buf, len);
707 /* If no valid key is known yet, send the packets using ANS_KEY requests,
708 to ensure we get to learn the reflexive UDP address. */
709 if(!to->status.validkey)
710 return send_request(to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, myself->name, to->name, buf, myself->incompression);
712 return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, to->name, REQ_SPTPS, buf);
715 /* Otherwise, send the packet via UDP */
717 const sockaddr_t *sa;
720 choose_udp_address(to, &sa, &sock);
722 if(sendto(listen_socket[sock].udp.fd, data, len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
723 if(sockmsgsize(sockerrno)) {
724 if(to->maxmtu >= len)
725 to->maxmtu = len - 1;
729 logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", to->name, to->hostname, sockstrerror(sockerrno));
737 bool receive_sptps_record(void *handle, uint8_t type, const char *data, uint16_t len) {
738 node_t *from = handle;
740 if(type == SPTPS_HANDSHAKE) {
741 if(!from->status.validkey) {
742 from->status.validkey = true;
743 from->status.waitingforkey = false;
744 logger(DEBUG_META, LOG_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
750 logger(DEBUG_ALWAYS, LOG_ERR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
756 if(type == PKT_PROBE) {
758 memcpy(inpkt.data, data, len);
759 mtu_probe_h(from, &inpkt, len);
763 if(type & ~(PKT_COMPRESSED | PKT_MAC)) {
764 logger(DEBUG_ALWAYS, LOG_ERR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
768 /* Check if we have the headers we need */
769 if(routing_mode != RMODE_ROUTER && !(type & PKT_MAC)) {
770 logger(DEBUG_TRAFFIC, LOG_ERR, "Received packet from %s (%s) without MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
772 } else if(routing_mode == RMODE_ROUTER && (type & PKT_MAC)) {
773 logger(DEBUG_TRAFFIC, LOG_WARNING, "Received packet from %s (%s) with MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
776 int offset = (type & PKT_MAC) ? 0 : 14;
777 if(type & PKT_COMPRESSED) {
778 length_t ulen = uncompress_packet(inpkt.data + offset, (const uint8_t *)data, len, from->incompression);
782 inpkt.len = ulen + offset;
784 if(inpkt.len > MAXSIZE)
787 memcpy(inpkt.data + offset, data, len);
788 inpkt.len = len + offset;
791 /* Generate the Ethernet packet type if necessary */
793 switch(inpkt.data[14] >> 4) {
795 inpkt.data[12] = 0x08;
796 inpkt.data[13] = 0x00;
799 inpkt.data[12] = 0x86;
800 inpkt.data[13] = 0xDD;
803 logger(DEBUG_TRAFFIC, LOG_ERR,
804 "Unknown IP version %d while reading packet from %s (%s)",
805 inpkt.data[14] >> 4, from->name, from->hostname);
810 receive_packet(from, &inpkt);
815 send a packet to the given vpn ip.
817 void send_packet(node_t *n, vpn_packet_t *packet) {
822 memcpy(packet->data, mymac.x, ETH_ALEN);
824 n->out_bytes += packet->len;
825 devops.write(packet);
829 logger(DEBUG_TRAFFIC, LOG_ERR, "Sending packet of %d bytes to %s (%s)",
830 packet->len, n->name, n->hostname);
832 if(!n->status.reachable) {
833 logger(DEBUG_TRAFFIC, LOG_INFO, "Node %s (%s) is not reachable",
834 n->name, n->hostname);
839 n->out_bytes += packet->len;
841 if(n->status.sptps) {
842 send_sptps_packet(n, packet);
846 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
849 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending packet to %s via %s (%s)",
850 n->name, via->name, n->via->hostname);
852 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
853 if(!send_tcppacket(via->connection, packet))
854 terminate_connection(via->connection, true);
856 send_udppacket(via, packet);
859 /* Broadcast a packet using the minimum spanning tree */
861 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
862 // Always give ourself a copy of the packet.
864 send_packet(myself, packet);
866 // In TunnelServer mode, do not forward broadcast packets.
867 // The MST might not be valid and create loops.
868 if(tunnelserver || broadcast_mode == BMODE_NONE)
871 logger(DEBUG_TRAFFIC, LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
872 packet->len, from->name, from->hostname);
874 switch(broadcast_mode) {
875 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
876 // This guarantees all nodes receive the broadcast packet, and
877 // usually distributes the sending of broadcast packets over all nodes.
879 for list_each(connection_t, c, connection_list)
880 if(c->status.active && c->status.mst && c != from->nexthop->connection)
881 send_packet(c->node, packet);
884 // In direct mode, we send copies to each node we know of.
885 // However, this only reaches nodes that can be reached in a single hop.
886 // We don't have enough information to forward broadcast packets in this case.
891 for splay_each(node_t, n, node_tree)
892 if(n->status.reachable && ((n->via == myself && n->nexthop == n) || n->via == n))
893 send_packet(n, packet);
901 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
904 static time_t last_hard_try = 0;
906 for splay_each(edge_t, e, edge_weight_tree) {
907 if(!e->to->status.reachable || e->to == myself)
910 if(sockaddrcmp_noport(from, &e->address)) {
911 if(last_hard_try == now.tv_sec)
916 if(!try_mac(e->to, pkt))
924 last_hard_try = now.tv_sec;
926 last_hard_try = now.tv_sec;
930 void handle_incoming_vpn_data(void *data, int flags) {
931 listen_socket_t *ls = data;
934 sockaddr_t from = {{0}};
935 socklen_t fromlen = sizeof from;
939 len = recvfrom(ls->udp.fd, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
941 if(len <= 0 || len > MAXSIZE) {
942 if(!sockwouldblock(sockerrno))
943 logger(DEBUG_ALWAYS, LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
949 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
951 n = lookup_node_udp(&from);
954 n = try_harder(&from, &pkt);
956 update_node_udp(n, &from);
957 else if(debug_level >= DEBUG_PROTOCOL) {
958 hostname = sockaddr2hostname(&from);
959 logger(DEBUG_PROTOCOL, LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
967 n->sock = ls - listen_socket;
969 receive_udppacket(n, &pkt);
972 void handle_device_data(void *data, int flags) {
977 if(devops.read(&packet)) {
978 myself->in_packets++;
979 myself->in_bytes += packet.len;
980 route(myself, &packet);