]> git.meshlink.io Git - meshlink/blob - src/net_packet.c
Count the number of correctly received UDP packets.
[meshlink] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2012 Guus Sliepen <guus@tinc-vpn.org>
5                   2010      Timothy Redaelli <timothy@redaelli.eu>
6                   2010      Brandon Black <blblack@gmail.com>
7
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.
12
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.
17
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.
21 */
22
23 #include "system.h"
24
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>
30
31 #ifdef HAVE_ZLIB
32 #include <zlib.h>
33 #endif
34
35 #ifdef HAVE_LZO
36 #include LZO1X_H
37 #endif
38
39 #include "cipher.h"
40 #include "conf.h"
41 #include "connection.h"
42 #include "crypto.h"
43 #include "digest.h"
44 #include "device.h"
45 #include "ethernet.h"
46 #include "graph.h"
47 #include "logger.h"
48 #include "net.h"
49 #include "netutl.h"
50 #include "protocol.h"
51 #include "process.h"
52 #include "route.h"
53 #include "utils.h"
54 #include "xalloc.h"
55
56 int keylifetime = 0;
57 #ifdef HAVE_LZO
58 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
59 #endif
60
61 static void send_udppacket(node_t *, vpn_packet_t *);
62
63 unsigned replaywin = 16;
64 bool localdiscovery = false;
65
66 #define MAX_SEQNO 1073741824
67
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
72
73    Probes are sent in batches of three, with random sizes between the lower and
74    upper boundaries for the MTU thus far discovered.
75
76    In case local discovery is enabled, a fourth packet is added to each batch,
77    which will be broadcast to the local network.
78 */
79
80 static void send_mtu_probe_handler(void *data) {
81         node_t *n = data;
82         int timeout = 1;
83
84         n->mtuprobes++;
85
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);
88                 n->mtuprobes = 0;
89                 return;
90         }
91
92         if(n->mtuprobes > 32) {
93                 if(!n->minmtu) {
94                         n->mtuprobes = 31;
95                         timeout = pinginterval;
96                         goto end;
97                 }
98
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;
101                 n->mtuprobes = 1;
102                 n->minmtu = 0;
103                 n->maxmtu = MTU;
104         }
105
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);
108                 n->mtuprobes = 31;
109         }
110
111         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
112                 if(n->minmtu > n->maxmtu)
113                         n->minmtu = n->maxmtu;
114                 else
115                         n->maxmtu = n->minmtu;
116                 n->mtu = 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);
118                 n->mtuprobes = 31;
119         }
120
121         if(n->mtuprobes == 31) {
122                 timeout = pinginterval;
123                 goto end;
124         } else if(n->mtuprobes == 32) {
125                 timeout = pingtimeout;
126         }
127
128         for(int i = 0; i < 3 + localdiscovery; i++) {
129                 int len;
130
131                 if(n->maxmtu <= n->minmtu)
132                         len = n->maxmtu;
133                 else
134                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
135
136                 if(len < 64)
137                         len = 64;
138
139                 vpn_packet_t packet;
140                 memset(packet.data, 0, 14);
141                 randomize(packet.data + 14, len - 14);
142                 packet.len = len;
143                 if(i >= 3 && n->mtuprobes <= 10)
144                         packet.priority = -1;
145                 else
146                         packet.priority = 0;
147
148                 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
149
150                 send_udppacket(n, &packet);
151         }
152
153 end:
154         timeout_set(&n->mtutimeout, &(struct timeval){timeout, rand() % 100000});
155 }
156
157 void send_mtu_probe(node_t *n) {
158         timeout_add(&n->mtutimeout, send_mtu_probe_handler, n, &(struct timeval){1, 0});
159         send_mtu_probe_handler(n);
160 }
161
162 static void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
163         logger(DEBUG_TRAFFIC, LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
164
165         if(!packet->data[0]) {
166                 /* It's a probe request, send back a reply */
167
168                 packet->data[0] = 1;
169
170                 /* Temporarily set udp_confirmed, so that the reply is sent
171                    back exactly the way it came in. */
172
173                 bool udp_confirmed = n->status.udp_confirmed;
174                 n->status.udp_confirmed = true;
175                 send_udppacket(n, packet);
176                 n->status.udp_confirmed = udp_confirmed;
177         } else {
178                 /* It's a valid reply: now we know bidirectional communication
179                    is possible using the address and socket that the reply
180                    packet used. */
181
182                 n->status.udp_confirmed = true;
183
184                 /* If we haven't established the PMTU yet, restart the discovery process. */
185
186                 if(n->mtuprobes > 30) {
187                         if(n->minmtu)
188                                 n->mtuprobes = 30;
189                         else
190                                 n->mtuprobes = 1;
191                 }
192
193                 /* If applicable, raise the minimum supported MTU */
194
195                 if(len > n->maxmtu)
196                         len = n->maxmtu;
197                 if(n->minmtu < len)
198                         n->minmtu = len;
199         }
200 }
201
202 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
203         if(level == 0) {
204                 memcpy(dest, source, len);
205                 return len;
206         } else if(level == 10) {
207 #ifdef HAVE_LZO
208                 lzo_uint lzolen = MAXSIZE;
209                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
210                 return lzolen;
211 #else
212                 return -1;
213 #endif
214         } else if(level < 10) {
215 #ifdef HAVE_ZLIB
216                 unsigned long destlen = MAXSIZE;
217                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
218                         return destlen;
219                 else
220 #endif
221                         return -1;
222         } else {
223 #ifdef HAVE_LZO
224                 lzo_uint lzolen = MAXSIZE;
225                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
226                 return lzolen;
227 #else
228                 return -1;
229 #endif
230         }
231
232         return -1;
233 }
234
235 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
236         if(level == 0) {
237                 memcpy(dest, source, len);
238                 return len;
239         } else if(level > 9) {
240 #ifdef HAVE_LZO
241                 lzo_uint lzolen = MAXSIZE;
242                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
243                         return lzolen;
244                 else
245 #endif
246                         return -1;
247         }
248 #ifdef HAVE_ZLIB
249         else {
250                 unsigned long destlen = MAXSIZE;
251                 if(uncompress(dest, &destlen, source, len) == Z_OK)
252                         return destlen;
253                 else
254                         return -1;
255         }
256 #endif
257
258         return -1;
259 }
260
261 /* VPN packet I/O */
262
263 static void receive_packet(node_t *n, vpn_packet_t *packet) {
264         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
265                            packet->len, n->name, n->hostname);
266
267         n->in_packets++;
268         n->in_bytes += packet->len;
269
270         route(n, packet);
271 }
272
273 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
274         if(n->status.sptps)
275                 return sptps_verify_datagram(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
276
277         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
278                 return false;
279
280         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
281 }
282
283 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
284         vpn_packet_t pkt1, pkt2;
285         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
286         int nextpkt = 0;
287         vpn_packet_t *outpkt = pkt[0];
288         size_t outlen;
289
290         if(n->status.sptps) {
291                 sptps_receive_data(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
292                 return;
293         }
294
295         if(!cipher_active(&n->incipher)) {
296                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
297                                         n->name, n->hostname);
298                 return;
299         }
300
301         /* Check packet length */
302
303         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
304                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got too short packet from %s (%s)",
305                                         n->name, n->hostname);
306                 return;
307         }
308
309         /* Check the message authentication code */
310
311         if(digest_active(&n->indigest)) {
312                 inpkt->len -= n->indigest.maclength;
313                 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
314                         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
315                         return;
316                 }
317         }
318         /* Decrypt the packet */
319
320         if(cipher_active(&n->incipher)) {
321                 outpkt = pkt[nextpkt++];
322                 outlen = MAXSIZE;
323
324                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
325                         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
326                         return;
327                 }
328
329                 outpkt->len = outlen;
330                 inpkt = outpkt;
331         }
332
333         /* Check the sequence number */
334
335         inpkt->len -= sizeof inpkt->seqno;
336         inpkt->seqno = ntohl(inpkt->seqno);
337
338         if(replaywin) {
339                 if(inpkt->seqno != n->received_seqno + 1) {
340                         if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
341                                 if(n->farfuture++ < replaywin >> 2) {
342                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
343                                                 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
344                                         return;
345                                 }
346                                 logger(DEBUG_ALWAYS, LOG_WARNING, "Lost %d packets from %s (%s)",
347                                                 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
348                                 memset(n->late, 0, replaywin);
349                         } else if (inpkt->seqno <= n->received_seqno) {
350                                 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
351                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
352                                                 n->name, n->hostname, inpkt->seqno, n->received_seqno);
353                                         return;
354                                 }
355                         } else {
356                                 for(int i = n->received_seqno + 1; i < inpkt->seqno; i++)
357                                         n->late[(i / 8) % replaywin] |= 1 << i % 8;
358                         }
359                 }
360
361                 n->farfuture = 0;
362                 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
363         }
364
365         if(inpkt->seqno > n->received_seqno)
366                 n->received_seqno = inpkt->seqno;
367
368         n->received++;
369
370         if(n->received_seqno > MAX_SEQNO)
371                 regenerate_key();
372
373         /* Decompress the packet */
374
375         length_t origlen = inpkt->len;
376
377         if(n->incompression) {
378                 outpkt = pkt[nextpkt++];
379
380                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
381                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while uncompressing packet from %s (%s)",
382                                                  n->name, n->hostname);
383                         return;
384                 }
385
386                 inpkt = outpkt;
387
388                 origlen -= MTU/64 + 20;
389         }
390
391         inpkt->priority = 0;
392
393         if(!inpkt->data[12] && !inpkt->data[13])
394                 mtu_probe_h(n, inpkt, origlen);
395         else
396                 receive_packet(n, inpkt);
397 }
398
399 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
400         vpn_packet_t outpkt;
401
402         outpkt.len = len;
403         if(c->options & OPTION_TCPONLY)
404                 outpkt.priority = 0;
405         else
406                 outpkt.priority = -1;
407         memcpy(outpkt.data, buffer, len);
408
409         receive_packet(c->node, &outpkt);
410 }
411
412 static void send_sptps_packet(node_t *n, vpn_packet_t *origpkt) {
413         if(!n->status.validkey) {
414                 logger(DEBUG_TRAFFIC, LOG_INFO, "No valid key known yet for %s (%s)", n->name, n->hostname);
415                 if(!n->status.waitingforkey)
416                         send_req_key(n);
417                 else if(n->last_req_key + 10 < time(NULL)) {
418                         logger(DEBUG_ALWAYS, LOG_DEBUG, "No key from %s after 10 seconds, restarting SPTPS", n->name);
419                         sptps_stop(&n->sptps);
420                         n->status.waitingforkey = false;
421                         send_req_key(n);
422                 }
423                 return;
424         }
425
426         uint8_t type = 0;
427         int offset = 0;
428
429         if(!(origpkt->data[12] | origpkt->data[13])) {
430                 sptps_send_record(&n->sptps, PKT_PROBE, (char *)origpkt->data, origpkt->len);
431                 return;
432         }
433
434         if(routing_mode == RMODE_ROUTER)
435                 offset = 14;
436         else
437                 type = PKT_MAC;
438
439         if(origpkt->len < offset)
440                 return;
441
442         vpn_packet_t outpkt;
443
444         if(n->outcompression) {
445                 int len = compress_packet(outpkt.data + offset, origpkt->data + offset, origpkt->len - offset, n->outcompression);
446                 if(len < 0) {
447                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)", n->name, n->hostname);
448                 } else if(len < origpkt->len - offset) {
449                         outpkt.len = len + offset;
450                         origpkt = &outpkt;
451                         type |= PKT_COMPRESSED;
452                 }
453         }
454
455         sptps_send_record(&n->sptps, type, (char *)origpkt->data + offset, origpkt->len - offset);
456         return;
457 }
458
459 static void choose_udp_address(const node_t *n, const sockaddr_t **sa, int *sock) {
460         /* Latest guess */
461         *sa = &n->address;
462         *sock = n->sock;
463
464         /* If the UDP address is confirmed, use it. */
465         if(n->status.udp_confirmed)
466                 return;
467
468         /* Send every third packet to n->address; that could be set
469            to the node's reflexive UDP address discovered during key
470            exchange. */
471
472         static int x = 0;
473         if(++x >= 3) {
474                 x = 0;
475                 return;
476         }
477
478         /* Otherwise, address are found in edges to this node.
479            So we pick a random edge and a random socket. */
480
481         int i = 0;
482         int j = rand() % n->edge_tree->count;
483         edge_t *candidate = NULL;
484
485         for splay_each(edge_t, e, n->edge_tree) {
486                 if(i++ == j) {
487                         candidate = e->reverse;
488                         break;
489                 }
490         }
491
492         if(candidate) {
493                 *sa = &candidate->address;
494                 *sock = rand() % listen_sockets;
495         }
496
497         /* Make sure we have a suitable socket for the chosen address */
498         if(listen_socket[*sock].sa.sa.sa_family != (*sa)->sa.sa_family) {
499                 for(int i = 0; i < listen_sockets; i++) {
500                         if(listen_socket[i].sa.sa.sa_family == (*sa)->sa.sa_family) {
501                                 *sock = i;
502                                 break;
503                         }
504                 }
505         }
506 }
507
508 static void choose_broadcast_address(const node_t *n, const sockaddr_t **sa, int *sock) {
509         static sockaddr_t broadcast_ipv4 = {
510                 .in = {
511                         .sin_family = AF_INET,
512                         .sin_addr.s_addr = -1,
513                 }
514         };
515
516         static sockaddr_t broadcast_ipv6 = {
517                 .in6 = {
518                         .sin6_family = AF_INET6,
519                         .sin6_addr.s6_addr[0x0] = 0xff,
520                         .sin6_addr.s6_addr[0x1] = 0x02,
521                         .sin6_addr.s6_addr[0xf] = 0x01,
522                 }
523         };
524
525         *sock = rand() % listen_sockets;
526
527         if(listen_socket[*sock].sa.sa.sa_family == AF_INET6) {
528                 broadcast_ipv6.in6.sin6_port = n->prevedge->address.in.sin_port;
529                 broadcast_ipv6.in6.sin6_scope_id = listen_socket[*sock].sa.in6.sin6_scope_id;
530                 *sa = &broadcast_ipv6;
531         } else {
532                 broadcast_ipv4.in.sin_port = n->prevedge->address.in.sin_port;
533                 *sa = &broadcast_ipv4;
534         }
535 }
536
537 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
538         vpn_packet_t pkt1, pkt2;
539         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
540         vpn_packet_t *inpkt = origpkt;
541         int nextpkt = 0;
542         vpn_packet_t *outpkt;
543         int origlen = origpkt->len;
544         size_t outlen;
545 #if defined(SOL_IP) && defined(IP_TOS)
546         static int priority = 0;
547 #endif
548         int origpriority = origpkt->priority;
549
550         if(!n->status.reachable) {
551                 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
552                 return;
553         }
554
555         if(n->status.sptps)
556                 return send_sptps_packet(n, origpkt);
557
558         /* Make sure we have a valid key */
559
560         if(!n->status.validkey) {
561                 logger(DEBUG_TRAFFIC, LOG_INFO,
562                                    "No valid key known yet for %s (%s), forwarding via TCP",
563                                    n->name, n->hostname);
564
565                 if(n->last_req_key + 10 <= now.tv_sec) {
566                         send_req_key(n);
567                         n->last_req_key = now.tv_sec;
568                 }
569
570                 send_tcppacket(n->nexthop->connection, origpkt);
571
572                 return;
573         }
574
575         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
576                 logger(DEBUG_TRAFFIC, LOG_INFO,
577                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
578                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
579
580                 if(n != n->nexthop)
581                         send_packet(n->nexthop, origpkt);
582                 else
583                         send_tcppacket(n->nexthop->connection, origpkt);
584
585                 return;
586         }
587
588         /* Compress the packet */
589
590         if(n->outcompression) {
591                 outpkt = pkt[nextpkt++];
592
593                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
594                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)",
595                                    n->name, n->hostname);
596                         return;
597                 }
598
599                 inpkt = outpkt;
600         }
601
602         /* Add sequence number */
603
604         inpkt->seqno = htonl(++(n->sent_seqno));
605         inpkt->len += sizeof inpkt->seqno;
606
607         /* Encrypt the packet */
608
609         if(cipher_active(&n->outcipher)) {
610                 outpkt = pkt[nextpkt++];
611                 outlen = MAXSIZE;
612
613                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
614                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
615                         goto end;
616                 }
617
618                 outpkt->len = outlen;
619                 inpkt = outpkt;
620         }
621
622         /* Add the message authentication code */
623
624         if(digest_active(&n->outdigest)) {
625                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
626                 inpkt->len += digest_length(&n->outdigest);
627         }
628
629         /* Send the packet */
630
631         const sockaddr_t *sa;
632         int sock;
633
634         /* Overloaded use of priority field: -1 means local broadcast */
635
636         if(origpriority == -1 && n->prevedge)
637                 choose_broadcast_address(n, &sa, &sock);
638         else
639                 choose_udp_address(n, &sa, &sock);
640
641 #if defined(SOL_IP) && defined(IP_TOS)
642         if(priorityinheritance && origpriority != priority
643            && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
644                 priority = origpriority;
645                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
646                 if(setsockopt(listen_socket[n->sock].udp.fd, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
647                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
648         }
649 #endif
650
651         if(sendto(listen_socket[sock].udp.fd, (char *) &inpkt->seqno, inpkt->len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
652                 if(sockmsgsize(sockerrno)) {
653                         if(n->maxmtu >= origlen)
654                                 n->maxmtu = origlen - 1;
655                         if(n->mtu >= origlen)
656                                 n->mtu = origlen - 1;
657                 } else
658                         logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
659         }
660
661 end:
662         origpkt->len = origlen;
663 }
664
665 bool send_sptps_data(void *handle, uint8_t type, const char *data, size_t len) {
666         node_t *to = handle;
667
668         /* Send it via TCP if it is a handshake packet, TCPOnly is in use, or this packet is larger than the MTU. */
669
670         if(type >= SPTPS_HANDSHAKE || ((myself->options | to->options) & OPTION_TCPONLY) || (type != PKT_PROBE && len > to->minmtu)) {
671                 char buf[len * 4 / 3 + 5];
672                 b64encode(data, buf, len);
673                 /* If no valid key is known yet, send the packets using ANS_KEY requests,
674                    to ensure we get to learn the reflexive UDP address. */
675                 if(!to->status.validkey)
676                         return send_request(to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, myself->name, to->name, buf, myself->incompression);
677                 else
678                         return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, to->name, REQ_SPTPS, buf);
679         }
680
681         /* Otherwise, send the packet via UDP */
682
683         const sockaddr_t *sa;
684         int sock;
685
686         choose_udp_address(to, &sa, &sock);
687
688         if(sendto(listen_socket[sock].udp.fd, data, len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
689                 if(sockmsgsize(sockerrno)) {
690                         if(to->maxmtu >= len)
691                                 to->maxmtu = len - 1;
692                         if(to->mtu >= len)
693                                 to->mtu = len - 1;
694                 } else {
695                         logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", to->name, to->hostname, sockstrerror(sockerrno));
696                         return false;
697                 }
698         }
699
700         return true;
701 }
702
703 bool receive_sptps_record(void *handle, uint8_t type, const char *data, uint16_t len) {
704         node_t *from = handle;
705
706         if(type == SPTPS_HANDSHAKE) {
707                 if(!from->status.validkey) {
708                         from->status.validkey = true;
709                         from->status.waitingforkey = false;
710                         logger(DEBUG_META, LOG_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
711                 }
712                 return true;
713         }
714
715         if(len > MTU) {
716                 logger(DEBUG_ALWAYS, LOG_ERR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
717                 return false;
718         }
719
720         vpn_packet_t inpkt;
721
722         if(type == PKT_PROBE) {
723                 inpkt.len = len;
724                 memcpy(inpkt.data, data, len);
725                 mtu_probe_h(from, &inpkt, len);
726                 return true;
727         }
728
729         if(type & ~(PKT_COMPRESSED | PKT_MAC)) {
730                 logger(DEBUG_ALWAYS, LOG_ERR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
731                 return false;
732         }
733
734         /* Check if we have the headers we need */
735         if(routing_mode != RMODE_ROUTER && !(type & PKT_MAC)) {
736                 logger(DEBUG_TRAFFIC, LOG_ERR, "Received packet from %s (%s) without MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
737                 return false;
738         } else if(routing_mode == RMODE_ROUTER && (type & PKT_MAC)) {
739                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Received packet from %s (%s) with MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
740         }
741
742         int offset = (type & PKT_MAC) ? 0 : 14;
743         if(type & PKT_COMPRESSED) {
744                 length_t ulen = uncompress_packet(inpkt.data + offset, (const uint8_t *)data, len, from->incompression);
745                 if(ulen < 0) {
746                         return false;
747                 } else {
748                         inpkt.len = ulen + offset;
749                 }
750                 if(inpkt.len > MAXSIZE)
751                         abort();
752         } else {
753                 memcpy(inpkt.data + offset, data, len);
754                 inpkt.len = len + offset;
755         }
756
757         /* Generate the Ethernet packet type if necessary */
758         if(offset) {
759                 switch(inpkt.data[14] >> 4) {
760                         case 4:
761                                 inpkt.data[12] = 0x08;
762                                 inpkt.data[13] = 0x00;
763                                 break;
764                         case 6:
765                                 inpkt.data[12] = 0x86;
766                                 inpkt.data[13] = 0xDD;
767                                 break;
768                         default:
769                                 logger(DEBUG_TRAFFIC, LOG_ERR,
770                                                    "Unknown IP version %d while reading packet from %s (%s)",
771                                                    inpkt.data[14] >> 4, from->name, from->hostname);
772                                 return false;
773                 }
774         }
775
776         receive_packet(from, &inpkt);
777         return true;
778 }
779
780 /*
781   send a packet to the given vpn ip.
782 */
783 void send_packet(node_t *n, vpn_packet_t *packet) {
784         node_t *via;
785
786         if(n == myself) {
787                 if(overwrite_mac)
788                          memcpy(packet->data, mymac.x, ETH_ALEN);
789                 n->out_packets++;
790                 n->out_bytes += packet->len;
791                 devops.write(packet);
792                 return;
793         }
794
795         logger(DEBUG_TRAFFIC, LOG_ERR, "Sending packet of %d bytes to %s (%s)",
796                            packet->len, n->name, n->hostname);
797
798         if(!n->status.reachable) {
799                 logger(DEBUG_TRAFFIC, LOG_INFO, "Node %s (%s) is not reachable",
800                                    n->name, n->hostname);
801                 return;
802         }
803
804         n->out_packets++;
805         n->out_bytes += packet->len;
806
807         if(n->status.sptps) {
808                 send_sptps_packet(n, packet);
809                 return;
810         }
811
812         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
813
814         if(via != n)
815                 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending packet to %s via %s (%s)",
816                            n->name, via->name, n->via->hostname);
817
818         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
819                 if(!send_tcppacket(via->connection, packet))
820                         terminate_connection(via->connection, true);
821         } else
822                 send_udppacket(via, packet);
823 }
824
825 /* Broadcast a packet using the minimum spanning tree */
826
827 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
828         // Always give ourself a copy of the packet.
829         if(from != myself)
830                 send_packet(myself, packet);
831
832         // In TunnelServer mode, do not forward broadcast packets.
833         // The MST might not be valid and create loops.
834         if(tunnelserver || broadcast_mode == BMODE_NONE)
835                 return;
836
837         logger(DEBUG_TRAFFIC, LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
838                            packet->len, from->name, from->hostname);
839
840         switch(broadcast_mode) {
841                 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
842                 // This guarantees all nodes receive the broadcast packet, and
843                 // usually distributes the sending of broadcast packets over all nodes.
844                 case BMODE_MST:
845                         for list_each(connection_t, c, connection_list)
846                                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
847                                         send_packet(c->node, packet);
848                         break;
849
850                 // In direct mode, we send copies to each node we know of.
851                 // However, this only reaches nodes that can be reached in a single hop.
852                 // We don't have enough information to forward broadcast packets in this case.
853                 case BMODE_DIRECT:
854                         if(from != myself)
855                                 break;
856
857                         for splay_each(node_t, n, node_tree)
858                                 if(n->status.reachable && ((n->via == myself && n->nexthop == n) || n->via == n))
859                                         send_packet(n, packet);
860                         break;
861
862                 default:
863                         break;
864         }
865 }
866
867 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
868         node_t *n = NULL;
869         bool hard = false;
870         static time_t last_hard_try = 0;
871
872         for splay_each(edge_t, e, edge_weight_tree) {
873                 if(!e->to->status.reachable || e->to == myself)
874                         continue;
875
876                 if(sockaddrcmp_noport(from, &e->address)) {
877                         if(last_hard_try == now.tv_sec)
878                                 continue;
879                         hard = true;
880                 }
881
882                 if(!try_mac(e->to, pkt))
883                         continue;
884
885                 n = e->to;
886                 break;
887         }
888
889         if(hard)
890                 last_hard_try = now.tv_sec;
891
892         last_hard_try = now.tv_sec;
893         return n;
894 }
895
896 void handle_incoming_vpn_data(void *data, int flags) {
897         listen_socket_t *ls = data;
898         vpn_packet_t pkt;
899         char *hostname;
900         sockaddr_t from = {{0}};
901         socklen_t fromlen = sizeof from;
902         node_t *n;
903         int len;
904
905         len = recvfrom(ls->udp.fd, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
906
907         if(len <= 0 || len > MAXSIZE) {
908                 if(!sockwouldblock(sockerrno))
909                         logger(DEBUG_ALWAYS, LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
910                 return;
911         }
912
913         pkt.len = len;
914
915         sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
916
917         n = lookup_node_udp(&from);
918
919         if(!n) {
920                 n = try_harder(&from, &pkt);
921                 if(n)
922                         update_node_udp(n, &from);
923                 else if(debug_level >= DEBUG_PROTOCOL) {
924                         hostname = sockaddr2hostname(&from);
925                         logger(DEBUG_PROTOCOL, LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
926                         free(hostname);
927                         return;
928                 }
929                 else
930                         return;
931         }
932
933         n->sock = ls - listen_socket;
934
935         receive_udppacket(n, &pkt);
936 }
937
938 void handle_device_data(void *data, int flags) {
939         vpn_packet_t packet;
940
941         packet.priority = 0;
942
943         if(devops.read(&packet)) {
944                 myself->in_packets++;
945                 myself->in_bytes += packet.len;
946                 route(myself, &packet);
947         }
948 }