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