+bool send_sptps_data(void *handle, uint8_t type, const void *data, size_t len) {
+ node_t *to = handle;
+ meshlink_handle_t *mesh = to->mesh;
+
+ /* Send it via TCP if it is a handshake packet, TCPOnly is in use, or this packet is larger than the MTU. */
+
+ if(type >= SPTPS_HANDSHAKE || ((mesh->self->options | to->options) & OPTION_TCPONLY) || (type != PKT_PROBE && len > to->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(!to->status.validkey) {
+ to->incompression = mesh->self->incompression;
+ return send_request(mesh, to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, mesh->self->name, to->name, buf, to->incompression);
+ } else {
+ return send_request(mesh, to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, mesh->self->name, to->name, REQ_SPTPS, buf);
+ }
+ }
+
+ /* Otherwise, send the packet via UDP */
+
+ const sockaddr_t *sa;
+ int sock;
+
+ if(to->status.broadcast)
+ choose_broadcast_address(mesh, to, &sa, &sock);
+ else
+ choose_udp_address(mesh, to, &sa, &sock);
+
+ if(sendto(mesh->listen_socket[sock].udp.fd, data, len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
+ if(sockmsgsize(sockerrno)) {
+ if(to->maxmtu >= len)
+ to->maxmtu = len - 1;
+ if(to->mtu >= len)
+ to->mtu = len - 1;
+ } else {
+ logger(mesh, MESHLINK_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", to->name, to->hostname, sockstrerror(sockerrno));
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool receive_sptps_record(void *handle, uint8_t type, const void *data, uint16_t len) {
+ node_t *from = handle;
+ meshlink_handle_t *mesh = from->mesh;
+
+ if(type == SPTPS_HANDSHAKE) {
+ if(!from->status.validkey) {
+ from->status.validkey = true;
+ from->status.waitingforkey = false;
+ logger(mesh, MESHLINK_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
+ }
+ return true;
+ }
+
+ if(len > MTU) {
+ logger(mesh, MESHLINK_ERROR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
+ return false;
+ }
+
+ vpn_packet_t inpkt;
+
+ if(type == PKT_PROBE) {
+ inpkt.len = len;
+ inpkt.probe = true;
+ memcpy(inpkt.data, data, len);
+ mtu_probe_h(mesh, from, &inpkt, len);
+ return true;
+ } else {
+ inpkt.probe = false;
+ }
+
+ if(type & ~(PKT_COMPRESSED)) {
+ logger(mesh, MESHLINK_ERROR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
+ return false;
+ }
+
+ if(type & PKT_COMPRESSED) {
+ uint16_t ulen = uncompress_packet(inpkt.data, (const uint8_t *)data, len, from->incompression);
+ if(ulen < 0) {
+ return false;
+ } else {
+ inpkt.len = ulen;
+ }
+ if(inpkt.len > MAXSIZE)
+ abort();
+ } else {
+ memcpy(inpkt.data, data, len);
+ inpkt.len = len;
+ }
+
+ receive_packet(mesh, from, &inpkt);
+ return true;