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.
35 #include "connection.h"
52 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
55 static void send_udppacket(node_t *, vpn_packet_t *);
57 unsigned replaywin = 16;
58 bool localdiscovery = false;
59 sockaddr_t localdiscovery_address;
61 #define MAX_SEQNO 1073741824
63 /* mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
64 mtuprobes == 31: sleep pinginterval seconds
65 mtuprobes == 32: send 1 burst, sleep pingtimeout second
66 mtuprobes == 33: no response from other side, restart PMTU discovery process
68 Probes are sent in batches of at least three, with random sizes between the
69 lower and upper boundaries for the MTU thus far discovered.
71 After the initial discovery, a fourth packet is added to each batch with a
72 size larger than the currently known PMTU, to test if the PMTU has increased.
74 In case local discovery is enabled, another packet is added to each batch,
75 which will be broadcast to the local network.
79 static void send_mtu_probe_handler(void *data) {
85 if(!n->status.reachable || !n->status.validkey) {
86 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
91 if(n->mtuprobes > 32) {
94 timeout = pinginterval;
98 logger(DEBUG_TRAFFIC, LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
99 n->status.udp_confirmed = false;
105 if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
106 logger(DEBUG_TRAFFIC, LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
110 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
111 if(n->minmtu > n->maxmtu)
112 n->minmtu = n->maxmtu;
114 n->maxmtu = n->minmtu;
116 logger(DEBUG_TRAFFIC, LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
120 if(n->mtuprobes == 31) {
121 timeout = pinginterval;
123 } else if(n->mtuprobes == 32) {
124 timeout = pingtimeout;
127 for(int i = 0; i < 4 + localdiscovery; i++) {
131 if(n->mtuprobes < 30 || n->maxmtu + 8 >= MTU)
134 } else if(n->maxmtu <= n->minmtu) {
137 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
144 memset(packet.data, 0, 14);
145 randomize(packet.data + 14, len - 14);
147 if(i >= 4 && n->mtuprobes <= 10)
148 packet.priority = -1;
152 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
154 send_udppacket(n, &packet);
157 n->probe_counter = 0;
158 gettimeofday(&n->probe_time, NULL);
160 /* Calculate the packet loss of incoming traffic by comparing the rate of
161 packets received to the rate with which the sequence number has increased.
164 if(n->received > n->prev_received)
165 n->packetloss = 1.0 - (n->received - n->prev_received) / (float)(n->received_seqno - n->prev_received_seqno);
167 n->packetloss = n->received_seqno <= n->prev_received_seqno;
169 n->prev_received_seqno = n->received_seqno;
170 n->prev_received = n->received;
173 timeout_set(&n->mtutimeout, &(struct timeval){timeout, rand() % 100000});
176 void send_mtu_probe(node_t *n) {
177 timeout_add(&n->mtutimeout, send_mtu_probe_handler, n, &(struct timeval){1, 0});
178 send_mtu_probe_handler(n);
181 static void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
182 if(!packet->data[0]) {
183 logger(DEBUG_TRAFFIC, LOG_INFO, "Got MTU probe request %d from %s (%s)", packet->len, n->name, n->hostname);
185 /* It's a probe request, send back a reply */
187 /* Type 2 probe replies were introduced in protocol 17.3 */
188 if ((n->options >> 24) == 3) {
189 uint8_t* data = packet->data;
191 uint16_t len16 = htons(len); memcpy(data, &len16, 2); data += 2;
193 /* Legacy protocol: n won't understand type 2 probe replies. */
197 /* Temporarily set udp_confirmed, so that the reply is sent
198 back exactly the way it came in. */
200 bool udp_confirmed = n->status.udp_confirmed;
201 n->status.udp_confirmed = true;
202 send_udppacket(n, packet);
203 n->status.udp_confirmed = udp_confirmed;
205 length_t probelen = len;
206 if (packet->data[0] == 2) {
208 logger(DEBUG_TRAFFIC, LOG_WARNING, "Received invalid (too short) MTU probe reply from %s (%s)", n->name, n->hostname);
210 uint16_t probelen16; memcpy(&probelen16, packet->data + 1, 2); probelen = ntohs(probelen16);
213 logger(DEBUG_TRAFFIC, LOG_INFO, "Got type %d MTU probe reply %d from %s (%s)", packet->data[0], probelen, n->name, n->hostname);
215 /* It's a valid reply: now we know bidirectional communication
216 is possible using the address and socket that the reply
219 n->status.udp_confirmed = true;
221 /* If we haven't established the PMTU yet, restart the discovery process. */
223 if(n->mtuprobes > 30) {
224 if (probelen == n->maxmtu + 8) {
225 logger(DEBUG_TRAFFIC, LOG_INFO, "Increase in PMTU to %s (%s) detected, restarting PMTU discovery", n->name, n->hostname);
237 /* If applicable, raise the minimum supported MTU */
239 if(probelen > n->maxmtu)
240 probelen = n->maxmtu;
241 if(n->minmtu < probelen)
242 n->minmtu = probelen;
244 /* Calculate RTT and bandwidth.
245 The RTT is the time between the MTU probe burst was sent and the first
246 reply is received. The bandwidth is measured using the time between the
247 arrival of the first and third probe reply.
250 struct timeval now, diff;
251 gettimeofday(&now, NULL);
252 timersub(&now, &n->probe_time, &diff);
255 if(n->probe_counter == 1) {
256 n->rtt = diff.tv_sec + diff.tv_usec * 1e-6;
258 } else if(n->probe_counter == 3) {
259 n->bandwidth = 2.0 * probelen / (diff.tv_sec + diff.tv_usec * 1e-6);
260 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);
265 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
267 memcpy(dest, source, len);
269 } else if(level == 10) {
271 lzo_uint lzolen = MAXSIZE;
272 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
277 } else if(level < 10) {
279 unsigned long destlen = MAXSIZE;
280 if(compress2(dest, &destlen, source, len, level) == Z_OK)
287 lzo_uint lzolen = MAXSIZE;
288 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
298 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
300 memcpy(dest, source, len);
302 } else if(level > 9) {
304 lzo_uint lzolen = MAXSIZE;
305 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
313 unsigned long destlen = MAXSIZE;
314 if(uncompress(dest, &destlen, source, len) == Z_OK)
326 static void receive_packet(node_t *n, vpn_packet_t *packet) {
327 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
328 packet->len, n->name, n->hostname);
331 n->in_bytes += packet->len;
336 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
338 return sptps_verify_datagram(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
340 if(!digest_active(n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(n->indigest))
343 return digest_verify(n->indigest, &inpkt->seqno, inpkt->len - digest_length(n->indigest), (const char *)&inpkt->seqno + inpkt->len - digest_length(n->indigest));
346 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
347 vpn_packet_t pkt1, pkt2;
348 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
350 vpn_packet_t *outpkt = pkt[0];
353 if(n->status.sptps) {
354 if(!n->sptps.state) {
355 if(!n->status.waitingforkey) {
356 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but we haven't exchanged keys yet", n->name, n->hostname);
359 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet", n->name, n->hostname);
363 sptps_receive_data(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
367 if(!cipher_active(n->incipher)) {
368 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet", n->name, n->hostname);
372 /* Check packet length */
374 if(inpkt->len < sizeof inpkt->seqno + digest_length(n->indigest)) {
375 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got too short packet from %s (%s)",
376 n->name, n->hostname);
380 /* Check the message authentication code */
382 if(digest_active(n->indigest)) {
383 inpkt->len -= digest_length(n->indigest);
384 if(!digest_verify(n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
385 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
389 /* Decrypt the packet */
391 if(cipher_active(n->incipher)) {
392 outpkt = pkt[nextpkt++];
395 if(!cipher_decrypt(n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
396 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
400 outpkt->len = outlen;
404 /* Check the sequence number */
406 inpkt->len -= sizeof inpkt->seqno;
407 inpkt->seqno = ntohl(inpkt->seqno);
410 if(inpkt->seqno != n->received_seqno + 1) {
411 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
412 if(n->farfuture++ < replaywin >> 2) {
413 logger(DEBUG_ALWAYS, LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
414 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
417 logger(DEBUG_ALWAYS, LOG_WARNING, "Lost %d packets from %s (%s)",
418 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
419 memset(n->late, 0, replaywin);
420 } else if (inpkt->seqno <= n->received_seqno) {
421 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
422 logger(DEBUG_ALWAYS, LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
423 n->name, n->hostname, inpkt->seqno, n->received_seqno);
427 for(int i = n->received_seqno + 1; i < inpkt->seqno; i++)
428 n->late[(i / 8) % replaywin] |= 1 << i % 8;
433 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
436 if(inpkt->seqno > n->received_seqno)
437 n->received_seqno = inpkt->seqno;
441 if(n->received_seqno > MAX_SEQNO)
444 /* Decompress the packet */
446 length_t origlen = inpkt->len;
448 if(n->incompression) {
449 outpkt = pkt[nextpkt++];
451 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
452 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while uncompressing packet from %s (%s)",
453 n->name, n->hostname);
459 origlen -= MTU/64 + 20;
464 if(!inpkt->data[12] && !inpkt->data[13])
465 mtu_probe_h(n, inpkt, origlen);
467 receive_packet(n, inpkt);
470 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
473 if(len > sizeof outpkt.data)
477 if(c->options & OPTION_TCPONLY)
480 outpkt.priority = -1;
481 memcpy(outpkt.data, buffer, len);
483 receive_packet(c->node, &outpkt);
486 static void send_sptps_packet(node_t *n, vpn_packet_t *origpkt) {
487 if(!n->status.validkey) {
488 logger(DEBUG_TRAFFIC, LOG_INFO, "No valid key known yet for %s (%s)", n->name, n->hostname);
489 if(!n->status.waitingforkey)
491 else if(n->last_req_key + 10 < now.tv_sec) {
492 logger(DEBUG_ALWAYS, LOG_DEBUG, "No key from %s after 10 seconds, restarting SPTPS", n->name);
493 sptps_stop(&n->sptps);
494 n->status.waitingforkey = false;
503 if(!(origpkt->data[12] | origpkt->data[13])) {
504 sptps_send_record(&n->sptps, PKT_PROBE, (char *)origpkt->data, origpkt->len);
508 if(routing_mode == RMODE_ROUTER)
513 if(origpkt->len < offset)
518 if(n->outcompression) {
519 int len = compress_packet(outpkt.data + offset, origpkt->data + offset, origpkt->len - offset, n->outcompression);
521 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)", n->name, n->hostname);
522 } else if(len < origpkt->len - offset) {
523 outpkt.len = len + offset;
525 type |= PKT_COMPRESSED;
529 sptps_send_record(&n->sptps, type, (char *)origpkt->data + offset, origpkt->len - offset);
533 static void choose_udp_address(const node_t *n, const sockaddr_t **sa, int *sock) {
538 /* If the UDP address is confirmed, use it. */
539 if(n->status.udp_confirmed)
542 /* Send every third packet to n->address; that could be set
543 to the node's reflexive UDP address discovered during key
552 /* Otherwise, address are found in edges to this node.
553 So we pick a random edge and a random socket. */
556 int j = rand() % n->edge_tree->count;
557 edge_t *candidate = NULL;
559 for splay_each(edge_t, e, n->edge_tree) {
561 candidate = e->reverse;
567 *sa = &candidate->address;
568 *sock = rand() % listen_sockets;
571 /* Make sure we have a suitable socket for the chosen address */
572 if(listen_socket[*sock].sa.sa.sa_family != (*sa)->sa.sa_family) {
573 for(int i = 0; i < listen_sockets; i++) {
574 if(listen_socket[i].sa.sa.sa_family == (*sa)->sa.sa_family) {
582 static void choose_broadcast_address(const node_t *n, const sockaddr_t **sa, int *sock) {
583 static sockaddr_t broadcast_ipv4 = {
585 .sin_family = AF_INET,
586 .sin_addr.s_addr = -1,
590 static sockaddr_t broadcast_ipv6 = {
592 .sin6_family = AF_INET6,
593 .sin6_addr.s6_addr[0x0] = 0xff,
594 .sin6_addr.s6_addr[0x1] = 0x02,
595 .sin6_addr.s6_addr[0xf] = 0x01,
599 *sock = rand() % listen_sockets;
601 if(listen_socket[*sock].sa.sa.sa_family == AF_INET6) {
602 if(localdiscovery_address.sa.sa_family == AF_INET6) {
603 localdiscovery_address.in6.sin6_port = n->prevedge->address.in.sin_port;
604 *sa = &localdiscovery_address;
606 broadcast_ipv6.in6.sin6_port = n->prevedge->address.in.sin_port;
607 broadcast_ipv6.in6.sin6_scope_id = listen_socket[*sock].sa.in6.sin6_scope_id;
608 *sa = &broadcast_ipv6;
611 if(localdiscovery_address.sa.sa_family == AF_INET) {
612 localdiscovery_address.in.sin_port = n->prevedge->address.in.sin_port;
613 *sa = &localdiscovery_address;
615 broadcast_ipv4.in.sin_port = n->prevedge->address.in.sin_port;
616 *sa = &broadcast_ipv4;
621 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
622 vpn_packet_t pkt1, pkt2;
623 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
624 vpn_packet_t *inpkt = origpkt;
626 vpn_packet_t *outpkt;
627 int origlen = origpkt->len;
629 #if defined(SOL_IP) && defined(IP_TOS)
630 static int priority = 0;
632 int origpriority = origpkt->priority;
634 if(!n->status.reachable) {
635 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
640 return send_sptps_packet(n, origpkt);
642 /* Make sure we have a valid key */
644 if(!n->status.validkey) {
645 logger(DEBUG_TRAFFIC, LOG_INFO,
646 "No valid key known yet for %s (%s), forwarding via TCP",
647 n->name, n->hostname);
649 if(n->last_req_key + 10 <= now.tv_sec) {
651 n->last_req_key = now.tv_sec;
654 send_tcppacket(n->nexthop->connection, origpkt);
659 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
660 logger(DEBUG_TRAFFIC, LOG_INFO,
661 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
662 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
665 send_packet(n->nexthop, origpkt);
667 send_tcppacket(n->nexthop->connection, origpkt);
672 /* Compress the packet */
674 if(n->outcompression) {
675 outpkt = pkt[nextpkt++];
677 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
678 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)",
679 n->name, n->hostname);
686 /* Add sequence number */
688 inpkt->seqno = htonl(++(n->sent_seqno));
689 inpkt->len += sizeof inpkt->seqno;
691 /* Encrypt the packet */
693 if(cipher_active(n->outcipher)) {
694 outpkt = pkt[nextpkt++];
697 if(!cipher_encrypt(n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
698 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
702 outpkt->len = outlen;
706 /* Add the message authentication code */
708 if(digest_active(n->outdigest)) {
709 if(!digest_create(n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len)) {
710 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
714 inpkt->len += digest_length(n->outdigest);
717 /* Send the packet */
719 const sockaddr_t *sa;
722 /* Overloaded use of priority field: -1 means local broadcast */
724 if(origpriority == -1 && n->prevedge)
725 choose_broadcast_address(n, &sa, &sock);
727 choose_udp_address(n, &sa, &sock);
729 #if defined(SOL_IP) && defined(IP_TOS)
730 if(priorityinheritance && origpriority != priority
731 && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
732 priority = origpriority;
733 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
734 if(setsockopt(listen_socket[n->sock].udp.fd, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
735 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
739 if(sendto(listen_socket[sock].udp.fd, (char *) &inpkt->seqno, inpkt->len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
740 if(sockmsgsize(sockerrno)) {
741 if(n->maxmtu >= origlen)
742 n->maxmtu = origlen - 1;
743 if(n->mtu >= origlen)
744 n->mtu = origlen - 1;
746 logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
750 origpkt->len = origlen;
753 bool send_sptps_data(void *handle, uint8_t type, const char *data, size_t len) {
756 /* Send it via TCP if it is a handshake packet, TCPOnly is in use, or this packet is larger than the MTU. */
758 if(type >= SPTPS_HANDSHAKE || ((myself->options | to->options) & OPTION_TCPONLY) || (type != PKT_PROBE && len > to->minmtu)) {
759 char buf[len * 4 / 3 + 5];
760 b64encode(data, buf, len);
761 /* If no valid key is known yet, send the packets using ANS_KEY requests,
762 to ensure we get to learn the reflexive UDP address. */
763 if(!to->status.validkey)
764 return send_request(to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, myself->name, to->name, buf, myself->incompression);
766 return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, to->name, REQ_SPTPS, buf);
769 /* Otherwise, send the packet via UDP */
771 const sockaddr_t *sa;
774 choose_udp_address(to, &sa, &sock);
776 if(sendto(listen_socket[sock].udp.fd, data, len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
777 if(sockmsgsize(sockerrno)) {
778 if(to->maxmtu >= len)
779 to->maxmtu = len - 1;
783 logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", to->name, to->hostname, sockstrerror(sockerrno));
791 bool receive_sptps_record(void *handle, uint8_t type, const char *data, uint16_t len) {
792 node_t *from = handle;
794 if(type == SPTPS_HANDSHAKE) {
795 if(!from->status.validkey) {
796 from->status.validkey = true;
797 from->status.waitingforkey = false;
798 logger(DEBUG_META, LOG_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
804 logger(DEBUG_ALWAYS, LOG_ERR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
810 if(type == PKT_PROBE) {
812 memcpy(inpkt.data, data, len);
813 mtu_probe_h(from, &inpkt, len);
817 if(type & ~(PKT_COMPRESSED | PKT_MAC)) {
818 logger(DEBUG_ALWAYS, LOG_ERR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
822 /* Check if we have the headers we need */
823 if(routing_mode != RMODE_ROUTER && !(type & PKT_MAC)) {
824 logger(DEBUG_TRAFFIC, LOG_ERR, "Received packet from %s (%s) without MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
826 } else if(routing_mode == RMODE_ROUTER && (type & PKT_MAC)) {
827 logger(DEBUG_TRAFFIC, LOG_WARNING, "Received packet from %s (%s) with MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
830 int offset = (type & PKT_MAC) ? 0 : 14;
831 if(type & PKT_COMPRESSED) {
832 length_t ulen = uncompress_packet(inpkt.data + offset, (const uint8_t *)data, len, from->incompression);
836 inpkt.len = ulen + offset;
838 if(inpkt.len > MAXSIZE)
841 memcpy(inpkt.data + offset, data, len);
842 inpkt.len = len + offset;
845 /* Generate the Ethernet packet type if necessary */
847 switch(inpkt.data[14] >> 4) {
849 inpkt.data[12] = 0x08;
850 inpkt.data[13] = 0x00;
853 inpkt.data[12] = 0x86;
854 inpkt.data[13] = 0xDD;
857 logger(DEBUG_TRAFFIC, LOG_ERR,
858 "Unknown IP version %d while reading packet from %s (%s)",
859 inpkt.data[14] >> 4, from->name, from->hostname);
864 receive_packet(from, &inpkt);
869 send a packet to the given vpn ip.
871 void send_packet(node_t *n, vpn_packet_t *packet) {
876 memcpy(packet->data, mymac.x, ETH_ALEN);
878 n->out_bytes += packet->len;
879 devops.write(packet);
883 logger(DEBUG_TRAFFIC, LOG_ERR, "Sending packet of %d bytes to %s (%s)",
884 packet->len, n->name, n->hostname);
886 if(!n->status.reachable) {
887 logger(DEBUG_TRAFFIC, LOG_INFO, "Node %s (%s) is not reachable",
888 n->name, n->hostname);
893 n->out_bytes += packet->len;
895 if(n->status.sptps) {
896 send_sptps_packet(n, packet);
900 via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
903 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending packet to %s via %s (%s)",
904 n->name, via->name, n->via->hostname);
906 if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
907 if(!send_tcppacket(via->connection, packet))
908 terminate_connection(via->connection, true);
910 send_udppacket(via, packet);
913 /* Broadcast a packet using the minimum spanning tree */
915 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
916 // Always give ourself a copy of the packet.
918 send_packet(myself, packet);
920 // In TunnelServer mode, do not forward broadcast packets.
921 // The MST might not be valid and create loops.
922 if(tunnelserver || broadcast_mode == BMODE_NONE)
925 logger(DEBUG_TRAFFIC, LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
926 packet->len, from->name, from->hostname);
928 switch(broadcast_mode) {
929 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
930 // This guarantees all nodes receive the broadcast packet, and
931 // usually distributes the sending of broadcast packets over all nodes.
933 for list_each(connection_t, c, connection_list)
934 if(c->status.active && c->status.mst && c != from->nexthop->connection)
935 send_packet(c->node, packet);
938 // In direct mode, we send copies to each node we know of.
939 // However, this only reaches nodes that can be reached in a single hop.
940 // We don't have enough information to forward broadcast packets in this case.
945 for splay_each(node_t, n, node_tree)
946 if(n->status.reachable && ((n->via == myself && n->nexthop == n) || n->via == n))
947 send_packet(n, packet);
955 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
958 static time_t last_hard_try = 0;
960 for splay_each(edge_t, e, edge_weight_tree) {
961 if(!e->to->status.reachable || e->to == myself)
964 if(sockaddrcmp_noport(from, &e->address)) {
965 if(last_hard_try == now.tv_sec)
970 if(!try_mac(e->to, pkt))
978 last_hard_try = now.tv_sec;
980 last_hard_try = now.tv_sec;
984 void handle_incoming_vpn_data(void *data, int flags) {
985 listen_socket_t *ls = data;
988 sockaddr_t from = {{0}};
989 socklen_t fromlen = sizeof from;
993 len = recvfrom(ls->udp.fd, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
995 if(len <= 0 || len > MAXSIZE) {
996 if(!sockwouldblock(sockerrno))
997 logger(DEBUG_ALWAYS, LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
1003 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
1005 n = lookup_node_udp(&from);
1008 n = try_harder(&from, &pkt);
1010 update_node_udp(n, &from);
1011 else if(debug_level >= DEBUG_PROTOCOL) {
1012 hostname = sockaddr2hostname(&from);
1013 logger(DEBUG_PROTOCOL, LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
1021 n->sock = ls - listen_socket;
1023 receive_udppacket(n, &pkt);
1026 void handle_device_data(void *data, int flags) {
1027 vpn_packet_t packet;
1029 packet.priority = 0;
1031 if(devops.read(&packet)) {
1032 myself->in_packets++;
1033 myself->in_bytes += packet.len;
1034 route(myself, &packet);