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