+static void receive_packet(node_t *n, vpn_packet_t *packet) {
+ logger(DEBUG_TRAFFIC, LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
+ packet->len, n->name, n->hostname);
+
+ n->in_packets++;
+ n->in_bytes += packet->len;
+
+ route(n, packet);
+}
+
+static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
+ if(n->status.sptps)
+ return sptps_verify_datagram(&n->sptps, DATA(inpkt), inpkt->len);
+
+#ifdef DISABLE_LEGACY
+ return false;
+#else
+ if(!digest_active(n->indigest) || inpkt->len < sizeof(seqno_t) + digest_length(n->indigest))
+ return false;
+
+ return digest_verify(n->indigest, SEQNO(inpkt), inpkt->len - digest_length(n->indigest), DATA(inpkt) + inpkt->len - digest_length(n->indigest));
+#endif
+}
+
+static bool receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
+ vpn_packet_t pkt1, pkt2;
+ vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
+ int nextpkt = 0;
+ size_t outlen;
+ pkt1.offset = DEFAULT_PACKET_OFFSET;
+ pkt2.offset = DEFAULT_PACKET_OFFSET;
+
+ if(n->status.sptps) {
+ if(!n->sptps.state) {
+ if(!n->status.waitingforkey) {
+ logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but we haven't exchanged keys yet", n->name, n->hostname);
+ send_req_key(n);
+ } else {
+ logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet", n->name, n->hostname);
+ }
+ return false;
+ }
+ inpkt->offset += 2 * sizeof(node_id_t);
+ if(!sptps_receive_data(&n->sptps, DATA(inpkt), inpkt->len - 2 * sizeof(node_id_t))) {
+ logger(DEBUG_TRAFFIC, LOG_ERR, "Got bad packet from %s (%s)", n->name, n->hostname);
+ return false;
+ }
+ return true;
+ }
+
+#ifdef DISABLE_LEGACY
+ return false;
+#else
+ if(!n->status.validkey) {
+ logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet", n->name, n->hostname);
+ return false;
+ }
+
+ /* Check packet length */
+
+ if(inpkt->len < sizeof(seqno_t) + digest_length(n->indigest)) {
+ logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got too short packet from %s (%s)",
+ n->name, n->hostname);
+ return false;
+ }
+
+ /* It's a legacy UDP packet, the data starts after the seqno */
+
+ inpkt->offset += sizeof(seqno_t);
+
+ /* Check the message authentication code */
+
+ if(digest_active(n->indigest)) {
+ inpkt->len -= digest_length(n->indigest);
+ if(!digest_verify(n->indigest, SEQNO(inpkt), inpkt->len, SEQNO(inpkt) + inpkt->len)) {
+ logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
+ return false;
+ }
+ }
+ /* Decrypt the packet */
+
+ if(cipher_active(n->incipher)) {
+ vpn_packet_t *outpkt = pkt[nextpkt++];
+ outlen = MAXSIZE;
+
+ if(!cipher_decrypt(n->incipher, SEQNO(inpkt), inpkt->len, SEQNO(outpkt), &outlen, true)) {
+ logger(DEBUG_TRAFFIC, LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
+ return false;
+ }
+
+ outpkt->len = outlen;
+ inpkt = outpkt;
+ }
+
+ /* Check the sequence number */
+
+ seqno_t seqno;
+ memcpy(&seqno, SEQNO(inpkt), sizeof seqno);
+ seqno = ntohl(seqno);
+ inpkt->len -= sizeof seqno;
+
+ if(replaywin) {
+ if(seqno != n->received_seqno + 1) {
+ if(seqno >= n->received_seqno + replaywin * 8) {
+ if(n->farfuture++ < replaywin >> 2) {
+ logger(DEBUG_ALWAYS, LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
+ n->name, n->hostname, seqno - n->received_seqno - 1, n->farfuture);
+ return false;
+ }
+ logger(DEBUG_ALWAYS, LOG_WARNING, "Lost %d packets from %s (%s)",
+ seqno - n->received_seqno - 1, n->name, n->hostname);
+ memset(n->late, 0, replaywin);
+ } else if (seqno <= n->received_seqno) {
+ if((n->received_seqno >= replaywin * 8 && seqno <= n->received_seqno - replaywin * 8) || !(n->late[(seqno / 8) % replaywin] & (1 << seqno % 8))) {
+ logger(DEBUG_ALWAYS, LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
+ n->name, n->hostname, seqno, n->received_seqno);
+ return false;
+ }
+ } else {
+ for(int i = n->received_seqno + 1; i < seqno; i++)
+ n->late[(i / 8) % replaywin] |= 1 << i % 8;
+ }
+ }
+
+ n->farfuture = 0;
+ n->late[(seqno / 8) % replaywin] &= ~(1 << seqno % 8);
+ }
+
+ if(seqno > n->received_seqno)
+ n->received_seqno = seqno;
+
+ n->received++;
+
+ if(n->received_seqno > MAX_SEQNO)
+ regenerate_key();
+
+ /* Decompress the packet */
+
+ length_t origlen = inpkt->len;
+
+ if(n->incompression) {
+ vpn_packet_t *outpkt = pkt[nextpkt++];
+
+ if((outpkt->len = uncompress_packet(DATA(outpkt), DATA(inpkt), inpkt->len, n->incompression)) < 0) {
+ logger(DEBUG_TRAFFIC, LOG_ERR, "Error while uncompressing packet from %s (%s)",
+ n->name, n->hostname);
+ return false;
+ }
+
+ inpkt = outpkt;
+
+ origlen -= MTU/64 + 20;
+ }
+
+ inpkt->priority = 0;
+
+ if(!DATA(inpkt)[12] && !DATA(inpkt)[13])
+ udp_probe_h(n, inpkt, origlen);
+ else
+ receive_packet(n, inpkt);
+ return true;
+#endif
+}
+
+void receive_tcppacket(connection_t *c, const char *buffer, int len) {
+ vpn_packet_t outpkt;
+ outpkt.offset = DEFAULT_PACKET_OFFSET;
+
+ if(len > sizeof outpkt.data - outpkt.offset)
+ return;
+
+ outpkt.len = len;
+ if(c->options & OPTION_TCPONLY)
+ outpkt.priority = 0;
+ else
+ outpkt.priority = -1;
+ memcpy(DATA(&outpkt), buffer, len);
+
+ receive_packet(c->node, &outpkt);
+}
+
+static void send_sptps_packet(node_t *n, vpn_packet_t *origpkt) {
+ if(!n->status.validkey && !n->connection)
+ return;
+
+ uint8_t type = 0;
+ int offset = 0;
+
+ if(!(DATA(origpkt)[12] | DATA(origpkt)[13])) {
+ sptps_send_record(&n->sptps, PKT_PROBE, (char *)DATA(origpkt), origpkt->len);
+ return;
+ }
+
+ if(routing_mode == RMODE_ROUTER)
+ offset = 14;
+ else
+ type = PKT_MAC;
+
+ if(origpkt->len < offset)
+ return;
+
+ vpn_packet_t outpkt;
+
+ if(n->outcompression) {
+ outpkt.offset = 0;
+ int len = compress_packet(DATA(&outpkt) + offset, DATA(origpkt) + offset, origpkt->len - offset, n->outcompression);
+ if(len < 0) {
+ logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)", n->name, n->hostname);
+ } else if(len < origpkt->len - offset) {
+ outpkt.len = len + offset;
+ origpkt = &outpkt;
+ type |= PKT_COMPRESSED;
+ }
+ }
+
+ /* If we have a direct metaconnection to n, and we can't use UDP, then
+ don't bother with SPTPS and just use a "plaintext" PACKET message.
+ We don't really care about end-to-end security since we're not
+ sending the message through any intermediate nodes. */
+ if(n->connection && origpkt->len > n->minmtu)
+ send_tcppacket(n->connection, origpkt);
+ else
+ sptps_send_record(&n->sptps, type, DATA(origpkt) + offset, origpkt->len - offset);
+ return;
+}
+
+static void adapt_socket(const sockaddr_t *sa, int *sock) {
+ /* Make sure we have a suitable socket for the chosen address */
+ if(listen_socket[*sock].sa.sa.sa_family != sa->sa.sa_family) {
+ for(int i = 0; i < listen_sockets; i++) {
+ if(listen_socket[i].sa.sa.sa_family == sa->sa.sa_family) {
+ *sock = i;
+ break;
+ }
+ }
+ }
+}
+
+static void choose_udp_address(const node_t *n, const sockaddr_t **sa, int *sock) {
+ /* Latest guess */
+ *sa = &n->address;
+ *sock = n->sock;
+
+ /* If the UDP address is confirmed, use it. */
+ if(n->status.udp_confirmed)
+ return;
+
+ /* Send every third packet to n->address; that could be set
+ to the node's reflexive UDP address discovered during key
+ exchange. */
+
+ static int x = 0;
+ if(++x >= 3) {
+ x = 0;
+ return;
+ }
+
+ /* Otherwise, address are found in edges to this node.
+ So we pick a random edge and a random socket. */
+
+ int i = 0;
+ int j = rand() % n->edge_tree->count;
+ edge_t *candidate = NULL;
+
+ for splay_each(edge_t, e, n->edge_tree) {
+ if(i++ == j) {
+ candidate = e->reverse;
+ break;
+ }
+ }
+
+ if(candidate) {
+ *sa = &candidate->address;
+ *sock = rand() % listen_sockets;
+ }
+
+ adapt_socket(*sa, sock);
+}
+
+static void choose_local_address(const node_t *n, const sockaddr_t **sa, int *sock) {
+ *sa = NULL;
+
+ /* Pick one of the edges from this node at random, then use its local address. */
+
+ int i = 0;
+ int j = rand() % n->edge_tree->count;
+ edge_t *candidate = NULL;
+
+ for splay_each(edge_t, e, n->edge_tree) {
+ if(i++ == j) {
+ candidate = e;
+ break;
+ }
+ }
+
+ if (candidate && candidate->local_address.sa.sa_family) {
+ *sa = &candidate->local_address;
+ *sock = rand() % listen_sockets;
+ adapt_socket(*sa, sock);
+ }
+}
+
+static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
+ vpn_packet_t pkt1, pkt2;
+ vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
+ vpn_packet_t *inpkt = origpkt;
+ int nextpkt = 0;
+ vpn_packet_t *outpkt;
+ int origlen = origpkt->len;
+ size_t outlen;
+#if defined(SOL_IP) && defined(IP_TOS)
+ static int priority = 0;
+ int origpriority = origpkt->priority;
+#endif
+
+ pkt1.offset = DEFAULT_PACKET_OFFSET;
+ pkt2.offset = DEFAULT_PACKET_OFFSET;
+
+ if(!n->status.reachable) {
+ logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
+ return;
+ }
+
+ if(n->status.sptps)
+ return send_sptps_packet(n, origpkt);
+
+#ifdef DISABLE_LEGACY
+ return;
+#else
+ /* Make sure we have a valid key */
+
+ if(!n->status.validkey) {
+ logger(DEBUG_TRAFFIC, LOG_INFO,
+ "No valid key known yet for %s (%s), forwarding via TCP",
+ n->name, n->hostname);
+ send_tcppacket(n->nexthop->connection, origpkt);
+ return;
+ }
+
+ if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (DATA(inpkt)[12] | DATA(inpkt)[13])) {
+ logger(DEBUG_TRAFFIC, LOG_INFO,
+ "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
+ n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
+
+ if(n != n->nexthop)
+ send_packet(n->nexthop, origpkt);
+ else
+ send_tcppacket(n->nexthop->connection, origpkt);
+
+ return;
+ }
+
+ /* Compress the packet */
+
+ if(n->outcompression) {
+ outpkt = pkt[nextpkt++];
+
+ if((outpkt->len = compress_packet(DATA(outpkt), DATA(inpkt), inpkt->len, n->outcompression)) < 0) {
+ logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)",
+ n->name, n->hostname);
+ return;
+ }
+
+ inpkt = outpkt;
+ }
+
+ /* Add sequence number */
+
+ seqno_t seqno = htonl(++(n->sent_seqno));
+ memcpy(SEQNO(inpkt), &seqno, sizeof seqno);
+ inpkt->len += sizeof seqno;
+
+ /* Encrypt the packet */
+
+ if(cipher_active(n->outcipher)) {
+ outpkt = pkt[nextpkt++];
+ outlen = MAXSIZE;
+
+ if(!cipher_encrypt(n->outcipher, SEQNO(inpkt), inpkt->len, SEQNO(outpkt), &outlen, true)) {
+ logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
+ goto end;
+ }
+
+ outpkt->len = outlen;
+ inpkt = outpkt;
+ }
+
+ /* Add the message authentication code */
+
+ if(digest_active(n->outdigest)) {
+ if(!digest_create(n->outdigest, SEQNO(inpkt), inpkt->len, SEQNO(inpkt) + inpkt->len)) {
+ logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
+ goto end;
+ }
+
+ inpkt->len += digest_length(n->outdigest);
+ }
+
+ /* Send the packet */
+
+ const sockaddr_t *sa = NULL;
+ int sock;
+
+ if(n->status.send_locally)
+ choose_local_address(n, &sa, &sock);
+ if(!sa)
+ choose_udp_address(n, &sa, &sock);
+
+#if defined(SOL_IP) && defined(IP_TOS)
+ if(priorityinheritance && origpriority != priority
+ && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
+ priority = origpriority;
+ logger(DEBUG_TRAFFIC, LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
+ if(setsockopt(listen_socket[n->sock].udp.fd, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
+ logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setsockopt", sockstrerror(sockerrno));
+ }
+#endif
+
+ if(sendto(listen_socket[sock].udp.fd, SEQNO(inpkt), inpkt->len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
+ if(sockmsgsize(sockerrno)) {
+ if(n->maxmtu >= origlen)
+ n->maxmtu = origlen - 1;
+ if(n->mtu >= origlen)
+ n->mtu = origlen - 1;
+ try_fix_mtu(n);
+ } else
+ logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
+ }
+
+end:
+ origpkt->len = origlen;
+#endif
+}
+
+static bool send_sptps_data_priv(node_t *to, node_t *from, int type, const void *data, size_t len) {
+ node_t *relay = (to->via != myself && (type == PKT_PROBE || (len - SPTPS_DATAGRAM_OVERHEAD) <= to->via->minmtu)) ? to->via : to->nexthop;
+ bool direct = from == myself && to == relay;
+ bool relay_supported = (relay->options >> 24) >= 4;
+ bool tcponly = (myself->options | relay->options) & OPTION_TCPONLY;
+
+ /* Send it via TCP if it is a handshake packet, TCPOnly is in use, this is a relay packet that the other node cannot understand, or this packet is larger than the MTU.
+ TODO: When relaying, the original sender does not know the end-to-end PMTU (it only knows the PMTU of the first hop).
+ This can lead to scenarios where large packets are sent over UDP to relay, but then relay has no choice but fall back to TCP. */
+
+ if(type == SPTPS_HANDSHAKE || tcponly || (!direct && !relay_supported) || (type != PKT_PROBE && (len - SPTPS_DATAGRAM_OVERHEAD) > relay->minmtu)) {
+ char buf[len * 4 / 3 + 5];
+ b64encode(data, buf, len);
+ /* If no valid key is known yet, send the packets using ANS_KEY requests,
+ to ensure we get to learn the reflexive UDP address. */
+ if(from == myself && !to->status.validkey) {
+ to->incompression = myself->incompression;
+ return send_request(to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, from->name, to->name, buf, to->incompression);
+ } else {
+ return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, from->name, to->name, REQ_SPTPS, buf);
+ }
+ }
+
+ size_t overhead = 0;
+ if(relay_supported) overhead += sizeof to->id + sizeof from->id;
+ char buf[len + overhead]; char* buf_ptr = buf;
+ if(relay_supported) {
+ if(direct) {
+ /* Inform the recipient that this packet was sent directly. */
+ node_id_t nullid = {};
+ memcpy(buf_ptr, &nullid, sizeof nullid); buf_ptr += sizeof nullid;
+ } else {
+ memcpy(buf_ptr, &to->id, sizeof to->id); buf_ptr += sizeof to->id;
+ }
+ memcpy(buf_ptr, &from->id, sizeof from->id); buf_ptr += sizeof from->id;
+
+ }
+ /* TODO: if this copy turns out to be a performance concern, change sptps_send_record() to add some "pre-padding" to the buffer and use that instead */
+ memcpy(buf_ptr, data, len); buf_ptr += len;
+
+ const sockaddr_t *sa = NULL;
+ int sock;
+ if(relay->status.send_locally)
+ choose_local_address(relay, &sa, &sock);
+ if(!sa)
+ choose_udp_address(relay, &sa, &sock);
+ logger(DEBUG_TRAFFIC, LOG_INFO, "Sending packet from %s (%s) to %s (%s) via %s (%s)", from->name, from->hostname, to->name, to->hostname, relay->name, relay->hostname);
+ if(sendto(listen_socket[sock].udp.fd, buf, buf_ptr - buf, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
+ if(sockmsgsize(sockerrno)) {
+ // Compensate for SPTPS overhead
+ len -= SPTPS_DATAGRAM_OVERHEAD;
+ if(relay->maxmtu >= len)
+ relay->maxmtu = len - 1;
+ if(relay->mtu >= len)
+ relay->mtu = len - 1;
+ try_fix_mtu(relay);
+ } else {
+ logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", relay->name, relay->hostname, sockstrerror(sockerrno));
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool send_sptps_data(void *handle, uint8_t type, const void *data, size_t len) {
+ return send_sptps_data_priv(handle, myself, type, data, len);
+}
+
+bool receive_sptps_record(void *handle, uint8_t type, const void *data, uint16_t len) {
+ node_t *from = handle;
+
+ if(type == SPTPS_HANDSHAKE) {
+ if(!from->status.validkey) {
+ from->status.validkey = true;
+ from->status.waitingforkey = false;
+ logger(DEBUG_META, LOG_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
+ }
+ return true;
+ }
+
+ if(len > MTU) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
+ return false;
+ }
+
+ vpn_packet_t inpkt;
+ inpkt.offset = DEFAULT_PACKET_OFFSET;
+
+ if(type == PKT_PROBE) {
+ inpkt.len = len;
+ memcpy(DATA(&inpkt), data, len);
+ udp_probe_h(from, &inpkt, len);
+ return true;
+ }
+
+ if(type & ~(PKT_COMPRESSED | PKT_MAC)) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
+ return false;
+ }
+
+ /* Check if we have the headers we need */
+ if(routing_mode != RMODE_ROUTER && !(type & PKT_MAC)) {
+ logger(DEBUG_TRAFFIC, LOG_ERR, "Received packet from %s (%s) without MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
+ return false;
+ } else if(routing_mode == RMODE_ROUTER && (type & PKT_MAC)) {
+ logger(DEBUG_TRAFFIC, LOG_WARNING, "Received packet from %s (%s) with MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
+ }
+
+ int offset = (type & PKT_MAC) ? 0 : 14;
+ if(type & PKT_COMPRESSED) {
+ length_t ulen = uncompress_packet(DATA(&inpkt) + offset, (const uint8_t *)data, len, from->incompression);
+ if(ulen < 0) {
+ return false;
+ } else {
+ inpkt.len = ulen + offset;
+ }
+ if(inpkt.len > MAXSIZE)
+ abort();
+ } else {
+ memcpy(DATA(&inpkt) + offset, data, len);
+ inpkt.len = len + offset;
+ }
+
+ /* Generate the Ethernet packet type if necessary */
+ if(offset) {
+ switch(DATA(&inpkt)[14] >> 4) {
+ case 4:
+ DATA(&inpkt)[12] = 0x08;
+ DATA(&inpkt)[13] = 0x00;
+ break;
+ case 6:
+ DATA(&inpkt)[12] = 0x86;
+ DATA(&inpkt)[13] = 0xDD;
+ break;
+ default:
+ logger(DEBUG_TRAFFIC, LOG_ERR,
+ "Unknown IP version %d while reading packet from %s (%s)",
+ DATA(&inpkt)[14] >> 4, from->name, from->hostname);
+ return false;
+ }
+ }
+
+ receive_packet(from, &inpkt);
+ return true;