2 net_packet.c -- Handles in- and outgoing VPN packets
3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 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.
28 #include "connection.h"
42 static void send_udppacket(node_t *, vpn_packet_t *);
44 unsigned replaywin = 16;
45 bool localdiscovery = false;
46 sockaddr_t localdiscovery_address;
48 #define MAX_SEQNO 1073741824
50 /* mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
51 mtuprobes == 31: sleep pinginterval seconds
52 mtuprobes == 32: send 1 burst, sleep pingtimeout second
53 mtuprobes == 33: no response from other side, restart PMTU discovery process
55 Probes are sent in batches of at least three, with random sizes between the
56 lower and upper boundaries for the MTU thus far discovered.
58 After the initial discovery, a fourth packet is added to each batch with a
59 size larger than the currently known PMTU, to test if the PMTU has increased.
61 In case local discovery is enabled, another packet is added to each batch,
62 which will be broadcast to the local network.
66 static void send_mtu_probe_handler(void *data) {
72 if(!n->status.reachable || !n->status.validkey) {
73 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
78 if(n->mtuprobes > 32) {
81 timeout = pinginterval;
85 logger(DEBUG_TRAFFIC, LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
86 n->status.udp_confirmed = false;
92 if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
93 logger(DEBUG_TRAFFIC, LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
97 if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
98 if(n->minmtu > n->maxmtu)
99 n->minmtu = n->maxmtu;
101 n->maxmtu = n->minmtu;
103 logger(DEBUG_TRAFFIC, LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
107 if(n->mtuprobes == 31) {
108 timeout = pinginterval;
110 } else if(n->mtuprobes == 32) {
111 timeout = pingtimeout;
114 for(int i = 0; i < 4 + localdiscovery; i++) {
118 if(n->mtuprobes < 30 || n->maxmtu + 8 >= MTU)
121 } else if(n->maxmtu <= n->minmtu) {
124 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
131 memset(packet.data, 0, 14);
132 randomize(packet.data + 14, len - 14);
135 n->status.broadcast = i >= 4 && n->mtuprobes <= 10 && n->prevedge;
137 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
139 send_udppacket(n, &packet);
142 n->status.broadcast = false;
143 n->probe_counter = 0;
144 gettimeofday(&n->probe_time, NULL);
146 /* Calculate the packet loss of incoming traffic by comparing the rate of
147 packets received to the rate with which the sequence number has increased.
150 if(n->received > n->prev_received)
151 n->packetloss = 1.0 - (n->received - n->prev_received) / (float)(n->received_seqno - n->prev_received_seqno);
153 n->packetloss = n->received_seqno <= n->prev_received_seqno;
155 n->prev_received_seqno = n->received_seqno;
156 n->prev_received = n->received;
159 timeout_set(&n->mtutimeout, &(struct timeval){timeout, rand() % 100000});
162 void send_mtu_probe(node_t *n) {
163 timeout_add(&n->mtutimeout, send_mtu_probe_handler, n, &(struct timeval){1, 0});
164 send_mtu_probe_handler(n);
167 static void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
168 logger(DEBUG_TRAFFIC, LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
170 if(!packet->data[0]) {
171 /* It's a probe request, send back a reply */
175 /* Temporarily set udp_confirmed, so that the reply is sent
176 back exactly the way it came in. */
178 bool udp_confirmed = n->status.udp_confirmed;
179 n->status.udp_confirmed = true;
180 send_udppacket(n, packet);
181 n->status.udp_confirmed = udp_confirmed;
183 /* It's a valid reply: now we know bidirectional communication
184 is possible using the address and socket that the reply
187 n->status.udp_confirmed = true;
189 /* If we haven't established the PMTU yet, restart the discovery process. */
191 if(n->mtuprobes > 30) {
192 if (len == n->maxmtu + 8) {
193 logger(DEBUG_TRAFFIC, LOG_INFO, "Increase in PMTU to %s (%s) detected, restarting PMTU discovery", n->name, n->hostname);
205 /* If applicable, raise the minimum supported MTU */
212 /* Calculate RTT and bandwidth.
213 The RTT is the time between the MTU probe burst was sent and the first
214 reply is received. The bandwidth is measured using the time between the
215 arrival of the first and third probe reply.
218 struct timeval now, diff;
219 gettimeofday(&now, NULL);
220 timersub(&now, &n->probe_time, &diff);
224 if(n->probe_counter == 1) {
225 n->rtt = diff.tv_sec + diff.tv_usec * 1e-6;
227 } else if(n->probe_counter == 3) {
228 n->bandwidth = 2.0 * len / (diff.tv_sec + diff.tv_usec * 1e-6);
229 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);
234 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
236 memcpy(dest, source, len);
238 } else if(level == 10) {
240 } else if(level < 10) {
242 unsigned long destlen = MAXSIZE;
243 if(compress2(dest, &destlen, source, len, level) == Z_OK)
255 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
257 memcpy(dest, source, len);
259 } else if(level > 9) {
264 unsigned long destlen = MAXSIZE;
265 if(uncompress(dest, &destlen, source, len) == Z_OK)
277 static void receive_packet(node_t *n, vpn_packet_t *packet) {
278 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
279 packet->len, n->name, n->hostname);
282 n->in_bytes += packet->len;
287 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
289 return sptps_verify_datagram(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
291 if(!digest_active(n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(n->indigest))
294 return digest_verify(n->indigest, &inpkt->seqno, inpkt->len - digest_length(n->indigest), (const char *)&inpkt->seqno + inpkt->len - digest_length(n->indigest));
297 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
298 vpn_packet_t pkt1, pkt2;
299 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
301 vpn_packet_t *outpkt = pkt[0];
304 if(n->status.sptps) {
305 if(!n->sptps.state) {
306 if(!n->status.waitingforkey) {
307 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but we haven't exchanged keys yet", n->name, n->hostname);
310 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet", n->name, n->hostname);
314 sptps_receive_data(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
318 if(!cipher_active(n->incipher)) {
319 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet", n->name, n->hostname);
323 /* Check packet length */
325 if(inpkt->len < sizeof inpkt->seqno + digest_length(n->indigest)) {
326 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got too short packet from %s (%s)",
327 n->name, n->hostname);
331 /* Check the message authentication code */
333 if(digest_active(n->indigest)) {
334 inpkt->len -= digest_length(n->indigest);
335 if(!digest_verify(n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
336 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
340 /* Decrypt the packet */
342 if(cipher_active(n->incipher)) {
343 outpkt = pkt[nextpkt++];
346 if(!cipher_decrypt(n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
347 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
351 outpkt->len = outlen;
355 /* Check the sequence number */
357 inpkt->len -= sizeof inpkt->seqno;
358 inpkt->seqno = ntohl(inpkt->seqno);
361 if(inpkt->seqno != n->received_seqno + 1) {
362 if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
363 logger(DEBUG_ALWAYS, LOG_WARNING, "Lost %d packets from %s (%s)",
364 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
365 memset(n->late, 0, replaywin);
366 } else if (inpkt->seqno <= n->received_seqno) {
367 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
368 logger(DEBUG_ALWAYS, LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
369 n->name, n->hostname, inpkt->seqno, n->received_seqno);
373 for(int i = n->received_seqno + 1; i < inpkt->seqno; i++)
374 n->late[(i / 8) % replaywin] |= 1 << i % 8;
378 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
381 if(inpkt->seqno > n->received_seqno)
382 n->received_seqno = inpkt->seqno;
386 if(n->received_seqno > MAX_SEQNO)
389 /* Decompress the packet */
391 length_t origlen = inpkt->len;
393 if(n->incompression) {
394 outpkt = pkt[nextpkt++];
396 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
397 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while uncompressing packet from %s (%s)",
398 n->name, n->hostname);
404 origlen -= MTU/64 + 20;
409 if(!inpkt->data[12] && !inpkt->data[13])
410 mtu_probe_h(n, inpkt, origlen);
412 receive_packet(n, inpkt);
415 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
418 if(len > sizeof outpkt.data)
422 if(c->options & OPTION_TCPONLY)
425 outpkt.priority = -1;
426 memcpy(outpkt.data, buffer, len);
428 receive_packet(c->node, &outpkt);
431 static void send_sptps_packet(node_t *n, vpn_packet_t *origpkt) {
432 if(!n->status.validkey) {
433 logger(DEBUG_TRAFFIC, LOG_INFO, "No valid key known yet for %s (%s)", n->name, n->hostname);
434 if(!n->status.waitingforkey)
436 else if(n->last_req_key + 10 < now.tv_sec) {
437 logger(DEBUG_ALWAYS, LOG_DEBUG, "No key from %s after 10 seconds, restarting SPTPS", n->name);
438 sptps_stop(&n->sptps);
439 n->status.waitingforkey = false;
448 if(!(origpkt->data[12] | origpkt->data[13])) {
449 sptps_send_record(&n->sptps, PKT_PROBE, (char *)origpkt->data, origpkt->len);
453 if(routing_mode == RMODE_ROUTER)
458 if(origpkt->len < offset)
463 if(n->outcompression) {
464 int len = compress_packet(outpkt.data + offset, origpkt->data + offset, origpkt->len - offset, n->outcompression);
466 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)", n->name, n->hostname);
467 } else if(len < origpkt->len - offset) {
468 outpkt.len = len + offset;
470 type |= PKT_COMPRESSED;
474 sptps_send_record(&n->sptps, type, (char *)origpkt->data + offset, origpkt->len - offset);
478 static void choose_udp_address(const node_t *n, const sockaddr_t **sa, int *sock) {
483 /* If the UDP address is confirmed, use it. */
484 if(n->status.udp_confirmed)
487 /* Send every third packet to n->address; that could be set
488 to the node's reflexive UDP address discovered during key
497 /* Otherwise, address are found in edges to this node.
498 So we pick a random edge and a random socket. */
501 int j = rand() % n->edge_tree->count;
502 edge_t *candidate = NULL;
504 for splay_each(edge_t, e, n->edge_tree) {
506 candidate = e->reverse;
512 *sa = &candidate->address;
513 *sock = rand() % listen_sockets;
516 /* Make sure we have a suitable socket for the chosen address */
517 if(listen_socket[*sock].sa.sa.sa_family != (*sa)->sa.sa_family) {
518 for(int i = 0; i < listen_sockets; i++) {
519 if(listen_socket[i].sa.sa.sa_family == (*sa)->sa.sa_family) {
527 static void choose_broadcast_address(const node_t *n, const sockaddr_t **sa, int *sock) {
528 static sockaddr_t broadcast_ipv4 = {
530 .sin_family = AF_INET,
531 .sin_addr.s_addr = -1,
535 static sockaddr_t broadcast_ipv6 = {
537 .sin6_family = AF_INET6,
538 .sin6_addr.s6_addr[0x0] = 0xff,
539 .sin6_addr.s6_addr[0x1] = 0x02,
540 .sin6_addr.s6_addr[0xf] = 0x01,
544 *sock = rand() % listen_sockets;
546 if(listen_socket[*sock].sa.sa.sa_family == AF_INET6) {
547 if(localdiscovery_address.sa.sa_family == AF_INET6) {
548 localdiscovery_address.in6.sin6_port = n->prevedge->address.in.sin_port;
549 *sa = &localdiscovery_address;
551 broadcast_ipv6.in6.sin6_port = n->prevedge->address.in.sin_port;
552 broadcast_ipv6.in6.sin6_scope_id = listen_socket[*sock].sa.in6.sin6_scope_id;
553 *sa = &broadcast_ipv6;
556 if(localdiscovery_address.sa.sa_family == AF_INET) {
557 localdiscovery_address.in.sin_port = n->prevedge->address.in.sin_port;
558 *sa = &localdiscovery_address;
560 broadcast_ipv4.in.sin_port = n->prevedge->address.in.sin_port;
561 *sa = &broadcast_ipv4;
566 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
567 vpn_packet_t pkt1, pkt2;
568 vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
569 vpn_packet_t *inpkt = origpkt;
571 vpn_packet_t *outpkt;
572 int origlen = origpkt->len;
574 #if defined(SOL_IP) && defined(IP_TOS)
575 static int priority = 0;
577 int origpriority = origpkt->priority;
579 if(!n->status.reachable) {
580 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
585 return send_sptps_packet(n, origpkt);
587 /* Make sure we have a valid key */
589 if(!n->status.validkey) {
590 logger(DEBUG_TRAFFIC, LOG_INFO,
591 "No valid key known yet for %s (%s), forwarding via TCP",
592 n->name, n->hostname);
594 if(n->last_req_key + 10 <= now.tv_sec) {
596 n->last_req_key = now.tv_sec;
599 send_tcppacket(n->nexthop->connection, origpkt);
604 if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
605 logger(DEBUG_TRAFFIC, LOG_INFO,
606 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
607 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
610 send_packet(n->nexthop, origpkt);
612 send_tcppacket(n->nexthop->connection, origpkt);
617 /* Compress the packet */
619 if(n->outcompression) {
620 outpkt = pkt[nextpkt++];
622 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
623 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)",
624 n->name, n->hostname);
631 /* Add sequence number */
633 inpkt->seqno = htonl(++(n->sent_seqno));
634 inpkt->len += sizeof inpkt->seqno;
636 /* Encrypt the packet */
638 if(cipher_active(n->outcipher)) {
639 outpkt = pkt[nextpkt++];
642 if(!cipher_encrypt(n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
643 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
647 outpkt->len = outlen;
651 /* Add the message authentication code */
653 if(digest_active(n->outdigest)) {
654 if(!digest_create(n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len)) {
655 logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
659 inpkt->len += digest_length(n->outdigest);
662 /* Send the packet */
664 const sockaddr_t *sa;
667 if(n->status.broadcast)
668 choose_broadcast_address(n, &sa, &sock);
670 choose_udp_address(n, &sa, &sock);
672 #if defined(SOL_IP) && defined(IP_TOS)
673 if(priorityinheritance && origpriority != priority
674 && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
675 priority = origpriority;
676 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
677 if(setsockopt(listen_socket[n->sock].udp.fd, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
678 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
682 if(sendto(listen_socket[sock].udp.fd, (char *) &inpkt->seqno, inpkt->len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
683 if(sockmsgsize(sockerrno)) {
684 if(n->maxmtu >= origlen)
685 n->maxmtu = origlen - 1;
686 if(n->mtu >= origlen)
687 n->mtu = origlen - 1;
689 logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
693 origpkt->len = origlen;
696 bool send_sptps_data(void *handle, uint8_t type, const char *data, size_t len) {
699 /* Send it via TCP if it is a handshake packet, TCPOnly is in use, or this packet is larger than the MTU. */
701 if(type >= SPTPS_HANDSHAKE || ((myself->options | to->options) & OPTION_TCPONLY) || (type != PKT_PROBE && len > to->minmtu)) {
702 char buf[len * 4 / 3 + 5];
703 b64encode(data, buf, len);
704 /* If no valid key is known yet, send the packets using ANS_KEY requests,
705 to ensure we get to learn the reflexive UDP address. */
706 if(!to->status.validkey) {
707 to->incompression = myself->incompression;
708 return send_request(to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, myself->name, to->name, buf, to->incompression);
710 return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, to->name, REQ_SPTPS, buf);
714 /* Otherwise, send the packet via UDP */
716 const sockaddr_t *sa;
719 if(to->status.broadcast)
720 choose_broadcast_address(to, &sa, &sock);
722 choose_udp_address(to, &sa, &sock);
724 if(sendto(listen_socket[sock].udp.fd, data, len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
725 if(sockmsgsize(sockerrno)) {
726 if(to->maxmtu >= len)
727 to->maxmtu = len - 1;
731 logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", to->name, to->hostname, sockstrerror(sockerrno));
739 bool receive_sptps_record(void *handle, uint8_t type, const char *data, uint16_t len) {
740 node_t *from = handle;
742 if(type == SPTPS_HANDSHAKE) {
743 if(!from->status.validkey) {
744 from->status.validkey = true;
745 from->status.waitingforkey = false;
746 logger(DEBUG_META, LOG_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
752 logger(DEBUG_ALWAYS, LOG_ERR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
758 if(type == PKT_PROBE) {
760 memcpy(inpkt.data, data, len);
761 mtu_probe_h(from, &inpkt, len);
765 if(type & ~(PKT_COMPRESSED | PKT_MAC)) {
766 logger(DEBUG_ALWAYS, LOG_ERR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
770 /* Check if we have the headers we need */
771 if(routing_mode != RMODE_ROUTER && !(type & PKT_MAC)) {
772 logger(DEBUG_TRAFFIC, LOG_ERR, "Received packet from %s (%s) without MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
774 } else if(routing_mode == RMODE_ROUTER && (type & PKT_MAC)) {
775 logger(DEBUG_TRAFFIC, LOG_WARNING, "Received packet from %s (%s) with MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
778 int offset = (type & PKT_MAC) ? 0 : 14;
779 if(type & PKT_COMPRESSED) {
780 length_t ulen = uncompress_packet(inpkt.data + offset, (const uint8_t *)data, len, from->incompression);
784 inpkt.len = ulen + offset;
786 if(inpkt.len > MAXSIZE)
789 memcpy(inpkt.data + offset, data, len);
790 inpkt.len = len + offset;
793 /* Generate the Ethernet packet type if necessary */
795 switch(inpkt.data[14] >> 4) {
797 inpkt.data[12] = 0x08;
798 inpkt.data[13] = 0x00;
801 inpkt.data[12] = 0x86;
802 inpkt.data[13] = 0xDD;
805 logger(DEBUG_TRAFFIC, LOG_ERR,
806 "Unknown IP version %d while reading packet from %s (%s)",
807 inpkt.data[14] >> 4, from->name, from->hostname);
812 receive_packet(from, &inpkt);
817 send a packet to the given vpn ip.
819 void send_packet(node_t *n, vpn_packet_t *packet) {
824 n->out_bytes += packet->len;
825 // TODO: send to application
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 logger(DEBUG_TRAFFIC, LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
867 packet->len, from->name, from->hostname);
869 switch(broadcast_mode) {
870 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
871 // This guarantees all nodes receive the broadcast packet, and
872 // usually distributes the sending of broadcast packets over all nodes.
874 for list_each(connection_t, c, connection_list)
875 if(c->status.active && c->status.mst && c != from->nexthop->connection)
876 send_packet(c->node, packet);
879 // In direct mode, we send copies to each node we know of.
880 // However, this only reaches nodes that can be reached in a single hop.
881 // We don't have enough information to forward broadcast packets in this case.
886 for splay_each(node_t, n, node_tree)
887 if(n->status.reachable && n != myself && ((n->via == myself && n->nexthop == n) || n->via == n))
888 send_packet(n, packet);
896 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
899 static time_t last_hard_try = 0;
901 for splay_each(edge_t, e, edge_weight_tree) {
902 if(!e->to->status.reachable || e->to == myself)
905 if(sockaddrcmp_noport(from, &e->address)) {
906 if(last_hard_try == now.tv_sec)
911 if(!try_mac(e->to, pkt))
919 last_hard_try = now.tv_sec;
921 last_hard_try = now.tv_sec;
925 void handle_incoming_vpn_data(void *data, int flags) {
926 listen_socket_t *ls = data;
929 sockaddr_t from = {{0}};
930 socklen_t fromlen = sizeof from;
934 len = recvfrom(ls->udp.fd, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
936 if(len <= 0 || len > MAXSIZE) {
937 if(!sockwouldblock(sockerrno))
938 logger(DEBUG_ALWAYS, LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
944 sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
946 n = lookup_node_udp(&from);
949 n = try_harder(&from, &pkt);
951 update_node_udp(n, &from);
952 else if(debug_level >= DEBUG_PROTOCOL) {
953 hostname = sockaddr2hostname(&from);
954 logger(DEBUG_PROTOCOL, LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
962 n->sock = ls - listen_socket;
964 receive_udppacket(n, &pkt);