Releasing 1.0.35.
[oweals/tinc.git] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2016 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 "avl_tree.h"
40 #include "conf.h"
41 #include "connection.h"
42 #include "device.h"
43 #include "ethernet.h"
44 #include "event.h"
45 #include "graph.h"
46 #include "logger.h"
47 #include "net.h"
48 #include "netutl.h"
49 #include "protocol.h"
50 #include "process.h"
51 #include "route.h"
52 #include "utils.h"
53 #include "xalloc.h"
54
55 int keylifetime = 0;
56 int keyexpires = 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 at least three, with random sizes between the
74    lower and upper boundaries for the MTU thus far discovered.
75
76    After the initial discovery, a fourth packet is added to each batch with a
77    size larger than the currently known PMTU, to test if the PMTU has increased.
78
79    In case local discovery is enabled, another packet is added to each batch,
80    which will be broadcast to the local network.
81
82 */
83
84 void send_mtu_probe(node_t *n) {
85         vpn_packet_t packet;
86         int len, i;
87         int timeout = 1;
88
89         n->mtuprobes++;
90         n->mtuevent = NULL;
91
92         if(!n->status.reachable || !n->status.validkey) {
93                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
94                 n->mtuprobes = 0;
95                 return;
96         }
97
98         if(n->mtuprobes > 32) {
99                 if(!n->minmtu) {
100                         n->mtuprobes = 31;
101                         timeout = pinginterval;
102                         goto end;
103                 }
104
105                 ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
106                 n->mtuprobes = 1;
107                 n->minmtu = 0;
108                 n->maxmtu = MTU;
109         }
110
111         if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
112                 ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
113                 n->mtuprobes = 31;
114         }
115
116         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
117                 if(n->minmtu > n->maxmtu) {
118                         n->minmtu = n->maxmtu;
119                 } else {
120                         n->maxmtu = n->minmtu;
121                 }
122
123                 n->mtu = n->minmtu;
124                 ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
125                 n->mtuprobes = 31;
126         }
127
128         if(n->mtuprobes == 31) {
129                 timeout = pinginterval;
130                 goto end;
131         } else if(n->mtuprobes == 32) {
132                 timeout = pingtimeout;
133         }
134
135         for(i = 0; i < 4 + localdiscovery; i++) {
136                 if(i == 0) {
137                         if(n->mtuprobes < 30 || n->maxmtu + 8 >= MTU) {
138                                 continue;
139                         }
140
141                         len = n->maxmtu + 8;
142                 } else if(n->maxmtu <= n->minmtu) {
143                         len = n->maxmtu;
144                 } else {
145                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
146                 }
147
148                 if(len < 64) {
149                         len = 64;
150                 }
151
152                 memset(packet.data, 0, 14);
153                 RAND_bytes(packet.data + 14, len - 14);
154                 packet.len = len;
155
156                 if(i >= 4 && n->mtuprobes <= 10) {
157                         packet.priority = -1;
158                 } else {
159                         packet.priority = 0;
160                 }
161
162                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
163
164                 send_udppacket(n, &packet);
165         }
166
167 end:
168         n->mtuevent = new_event();
169         n->mtuevent->handler = (event_handler_t)send_mtu_probe;
170         n->mtuevent->data = n;
171         n->mtuevent->time = now + timeout;
172         event_add(n->mtuevent);
173 }
174
175 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
176         ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
177
178         if(!packet->data[0]) {
179                 packet->data[0] = 1;
180                 send_udppacket(n, packet);
181         } else {
182                 if(n->mtuprobes > 30) {
183                         if(len == n->maxmtu + 8) {
184                                 ifdebug(TRAFFIC) logger(LOG_INFO, "Increase in PMTU to %s (%s) detected, restarting PMTU discovery", n->name, n->hostname);
185                                 n->maxmtu = MTU;
186                                 n->mtuprobes = 10;
187                                 return;
188                         }
189
190                         if(n->minmtu) {
191                                 n->mtuprobes = 30;
192                         } else {
193                                 n->mtuprobes = 1;
194                         }
195                 }
196
197                 if(len > n->maxmtu) {
198                         len = n->maxmtu;
199                 }
200
201                 if(n->minmtu < len) {
202                         n->minmtu = len;
203                 }
204         }
205 }
206
207 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
208         if(level == 0) {
209                 memcpy(dest, source, len);
210                 return len;
211         } else if(level == 10) {
212 #ifdef HAVE_LZO
213                 lzo_uint lzolen = MAXSIZE;
214                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
215                 return lzolen;
216 #else
217                 return 0;
218 #endif
219         } else if(level < 10) {
220 #ifdef HAVE_ZLIB
221                 unsigned long destlen = MAXSIZE;
222
223                 if(compress2(dest, &destlen, source, len, level) == Z_OK) {
224                         return destlen;
225                 } else
226 #endif
227                         return 0;
228         } else {
229 #ifdef HAVE_LZO
230                 lzo_uint lzolen = MAXSIZE;
231                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
232                 return lzolen;
233 #else
234                 return 0;
235 #endif
236         }
237
238         return 0;
239 }
240
241 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
242         if(level == 0) {
243                 memcpy(dest, source, len);
244                 return len;
245         } else if(level > 9) {
246 #ifdef HAVE_LZO
247                 lzo_uint lzolen = MAXSIZE;
248
249                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK) {
250                         return lzolen;
251                 } else
252 #endif
253                         return 0;
254         }
255
256 #ifdef HAVE_ZLIB
257         else {
258                 unsigned long destlen = MAXSIZE;
259
260                 if(uncompress(dest, &destlen, source, len) == Z_OK) {
261                         return destlen;
262                 } else {
263                         return 0;
264                 }
265         }
266
267 #endif
268
269         return -1;
270 }
271
272 /* VPN packet I/O */
273
274 static void receive_packet(node_t *n, vpn_packet_t *packet) {
275         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
276                                 packet->len, n->name, n->hostname);
277
278         route(n, packet);
279 }
280
281 static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) {
282         unsigned char hmac[EVP_MAX_MD_SIZE];
283
284         if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
285                 return false;
286         }
287
288         HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL);
289
290         return !memcmp_constant_time(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength);
291 }
292
293 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
294         vpn_packet_t pkt1, pkt2;
295         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
296         int nextpkt = 0;
297         vpn_packet_t *outpkt;
298         int outlen, outpad;
299         unsigned char hmac[EVP_MAX_MD_SIZE];
300
301         if(!n->inkey) {
302                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
303                                         n->name, n->hostname);
304                 return;
305         }
306
307         /* Check packet length */
308
309         if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
310                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
311                                         n->name, n->hostname);
312                 return;
313         }
314
315         /* Check the message authentication code */
316
317         if(n->indigest && n->inmaclength) {
318                 inpkt->len -= n->inmaclength;
319                 HMAC(n->indigest, n->inkey, n->inkeylength,
320                      (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
321
322                 if(memcmp_constant_time(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
323                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
324                                                 n->name, n->hostname);
325                         return;
326                 }
327         }
328
329         /* Decrypt the packet */
330
331         if(n->incipher) {
332                 outpkt = pkt[nextpkt++];
333
334                 if(!EVP_DecryptInit_ex(n->inctx, NULL, NULL, NULL, NULL)
335                                 || !EVP_DecryptUpdate(n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
336                                                       (unsigned char *) &inpkt->seqno, inpkt->len)
337                                 || !EVP_DecryptFinal_ex(n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
338                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
339                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
340                         return;
341                 }
342
343                 outpkt->len = outlen + outpad;
344                 inpkt = outpkt;
345         }
346
347         /* Check the sequence number */
348
349         inpkt->len -= sizeof(inpkt->seqno);
350         inpkt->seqno = ntohl(inpkt->seqno);
351
352         if(replaywin) {
353                 if(inpkt->seqno != n->received_seqno + 1) {
354                         if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
355                                 if(n->farfuture++ < replaywin >> 2) {
356                                         ifdebug(TRAFFIC) logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
357                                                                 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
358                                         return;
359                                 }
360
361                                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Lost %d packets from %s (%s)",
362                                                         inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
363                                 memset(n->late, 0, replaywin);
364                         } else if(inpkt->seqno <= n->received_seqno) {
365                                 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
366                                         ifdebug(TRAFFIC) logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
367                                                                 n->name, n->hostname, inpkt->seqno, n->received_seqno);
368                                         return;
369                                 }
370                         } else {
371                                 for(uint32_t i = n->received_seqno + 1; i < inpkt->seqno; i++) {
372                                         n->late[(i / 8) % replaywin] |= 1 << i % 8;
373                                 }
374                         }
375                 }
376
377                 n->farfuture = 0;
378                 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
379         }
380
381         if(inpkt->seqno > n->received_seqno) {
382                 n->received_seqno = inpkt->seqno;
383         }
384
385         if(n->received_seqno > MAX_SEQNO) {
386                 keyexpires = 0;
387         }
388
389         /* Decompress the packet */
390
391         length_t origlen = inpkt->len;
392
393         if(n->incompression) {
394                 outpkt = pkt[nextpkt++];
395
396                 if(!(outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression))) {
397                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
398                                                 n->name, n->hostname);
399                         return;
400                 }
401
402                 inpkt = outpkt;
403
404                 origlen -= MTU / 64 + 20;
405         }
406
407         inpkt->priority = 0;
408
409         if(!inpkt->data[12] && !inpkt->data[13]) {
410                 mtu_probe_h(n, inpkt, origlen);
411         } else {
412                 receive_packet(n, inpkt);
413         }
414 }
415
416 void receive_tcppacket(connection_t *c, const char *buffer, length_t len) {
417         vpn_packet_t outpkt;
418
419         if(len > sizeof(outpkt.data)) {
420                 return;
421         }
422
423         outpkt.len = len;
424
425         if(c->options & OPTION_TCPONLY) {
426                 outpkt.priority = 0;
427         } else {
428                 outpkt.priority = -1;
429         }
430
431         memcpy(outpkt.data, buffer, len);
432
433         receive_packet(c->node, &outpkt);
434 }
435
436 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
437         vpn_packet_t pkt1, pkt2;
438         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
439         vpn_packet_t *inpkt = origpkt;
440         int nextpkt = 0;
441         vpn_packet_t *outpkt;
442         int origlen;
443         int outlen, outpad;
444         int origpriority;
445
446         if(!n->status.reachable) {
447                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
448                 return;
449         }
450
451         /* Make sure we have a valid key */
452
453         if(!n->status.validkey) {
454                 ifdebug(TRAFFIC) logger(LOG_INFO,
455                                         "No valid key known yet for %s (%s), forwarding via TCP",
456                                         n->name, n->hostname);
457
458                 if(n->last_req_key + 10 <= now) {
459                         send_req_key(n);
460                         n->last_req_key = now;
461                 }
462
463                 send_tcppacket(n->nexthop->connection, origpkt);
464
465                 return;
466         }
467
468         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
469                 ifdebug(TRAFFIC) logger(LOG_INFO,
470                                         "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
471                                         n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
472
473                 if(n != n->nexthop) {
474                         send_packet(n->nexthop, origpkt);
475                 } else {
476                         send_tcppacket(n->nexthop->connection, origpkt);
477                 }
478
479                 return;
480         }
481
482         origlen = inpkt->len;
483         origpriority = inpkt->priority;
484
485         /* Compress the packet */
486
487         if(n->outcompression) {
488                 outpkt = pkt[nextpkt++];
489
490                 if(!(outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression))) {
491                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
492                                                 n->name, n->hostname);
493                         return;
494                 }
495
496                 inpkt = outpkt;
497         }
498
499         /* Add sequence number */
500
501         inpkt->seqno = htonl(++(n->sent_seqno));
502         inpkt->len += sizeof(inpkt->seqno);
503
504         /* Encrypt the packet */
505
506         if(n->outcipher) {
507                 outpkt = pkt[nextpkt++];
508
509                 if(!EVP_EncryptInit_ex(n->outctx, NULL, NULL, NULL, NULL)
510                                 || !EVP_EncryptUpdate(n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
511                                                       (unsigned char *) &inpkt->seqno, inpkt->len)
512                                 || !EVP_EncryptFinal_ex(n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
513                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
514                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
515                         goto end;
516                 }
517
518                 outpkt->len = outlen + outpad;
519                 inpkt = outpkt;
520         }
521
522         /* Add the message authentication code */
523
524         if(n->outdigest && n->outmaclength) {
525                 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
526                      inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
527                 inpkt->len += n->outmaclength;
528         }
529
530         /* Determine which socket we have to use */
531
532         if(n->address.sa.sa_family != listen_socket[n->sock].sa.sa.sa_family) {
533                 for(int sock = 0; sock < listen_sockets; sock++) {
534                         if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family) {
535                                 n->sock = sock;
536                                 break;
537                         }
538                 }
539         }
540
541         /* Send the packet */
542
543         struct sockaddr *sa;
544         socklen_t sl;
545         int sock;
546         sockaddr_t broadcast;
547
548         /* Overloaded use of priority field: -1 means local broadcast */
549
550         if(origpriority == -1 && n->prevedge) {
551                 sock = rand() % listen_sockets;
552                 memset(&broadcast, 0, sizeof(broadcast));
553
554                 if(listen_socket[sock].sa.sa.sa_family == AF_INET6) {
555                         broadcast.in6.sin6_family = AF_INET6;
556                         broadcast.in6.sin6_addr.s6_addr[0x0] = 0xff;
557                         broadcast.in6.sin6_addr.s6_addr[0x1] = 0x02;
558                         broadcast.in6.sin6_addr.s6_addr[0xf] = 0x01;
559                         broadcast.in6.sin6_port = n->prevedge->address.in.sin_port;
560                         broadcast.in6.sin6_scope_id = listen_socket[sock].sa.in6.sin6_scope_id;
561                 } else {
562                         broadcast.in.sin_family = AF_INET;
563                         broadcast.in.sin_addr.s_addr = -1;
564                         broadcast.in.sin_port = n->prevedge->address.in.sin_port;
565                 }
566
567                 sa = &broadcast.sa;
568                 sl = SALEN(broadcast.sa);
569         } else {
570                 if(origpriority == -1) {
571                         origpriority = 0;
572                 }
573
574                 sa = &(n->address.sa);
575                 sl = SALEN(n->address.sa);
576                 sock = n->sock;
577         }
578
579         if(priorityinheritance && origpriority != listen_socket[n->sock].priority) {
580                 listen_socket[n->sock].priority = origpriority;
581
582                 switch(listen_socket[n->sock].sa.sa.sa_family) {
583 #if defined(IP_TOS)
584
585                 case AF_INET:
586                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting IPv4 outgoing packet priority to %d", origpriority);
587
588                         if(setsockopt(listen_socket[n->sock].udp, IPPROTO_IP, IP_TOS, (void *)&origpriority, sizeof(origpriority))) { /* SO_PRIORITY doesn't seem to work */
589                                 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
590                         }
591
592                         break;
593 #endif
594 #if defined(IPV6_TCLASS)
595
596                 case AF_INET6:
597                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting IPv6 outgoing packet priority to %d", origpriority);
598
599                         if(setsockopt(listen_socket[n->sock].udp, IPPROTO_IPV6, IPV6_TCLASS, (void *)&origpriority, sizeof(origpriority))) {
600                                 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
601                         }
602
603                         break;
604 #endif
605
606                 default:
607                         break;
608                 }
609         }
610
611         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) {
612                 if(sockmsgsize(sockerrno)) {
613                         if(n->maxmtu >= origlen) {
614                                 n->maxmtu = origlen - 1;
615                         }
616
617                         if(n->mtu >= origlen) {
618                                 n->mtu = origlen - 1;
619                         }
620                 } else {
621                         ifdebug(TRAFFIC) logger(LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
622                 }
623         }
624
625 end:
626         origpkt->len = origlen;
627 }
628
629 /*
630   send a packet to the given vpn ip.
631 */
632 void send_packet(const node_t *n, vpn_packet_t *packet) {
633         node_t *via;
634
635         if(n == myself) {
636                 if(overwrite_mac) {
637                         memcpy(packet->data, mymac.x, ETH_ALEN);
638                 }
639
640                 devops.write(packet);
641                 return;
642         }
643
644         ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
645                                 packet->len, n->name, n->hostname);
646
647         if(!n->status.reachable) {
648                 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
649                                         n->name, n->hostname);
650                 return;
651         }
652
653         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
654
655         if(via != n)
656                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
657                                         n->name, via->name, n->via->hostname);
658
659         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
660                 if(!send_tcppacket(via->connection, packet)) {
661                         terminate_connection(via->connection, true);
662                 }
663         } else {
664                 send_udppacket(via, packet);
665         }
666 }
667
668 /* Broadcast a packet using the minimum spanning tree */
669
670 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
671         avl_node_t *node;
672         connection_t *c;
673         node_t *n;
674
675         // Always give ourself a copy of the packet.
676         if(from != myself) {
677                 send_packet(myself, packet);
678         }
679
680         // In TunnelServer mode, do not forward broadcast packets.
681         // The MST might not be valid and create loops.
682         if(tunnelserver || broadcast_mode == BMODE_NONE) {
683                 return;
684         }
685
686         ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
687                                 packet->len, from->name, from->hostname);
688
689         switch(broadcast_mode) {
690         // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
691         // This guarantees all nodes receive the broadcast packet, and
692         // usually distributes the sending of broadcast packets over all nodes.
693         case BMODE_MST:
694                 for(node = connection_tree->head; node; node = node->next) {
695                         c = node->data;
696
697                         if(c->status.active && c->status.mst && c != from->nexthop->connection) {
698                                 send_packet(c->node, packet);
699                         }
700                 }
701
702                 break;
703
704         // In direct mode, we send copies to each node we know of.
705         // However, this only reaches nodes that can be reached in a single hop.
706         // We don't have enough information to forward broadcast packets in this case.
707         case BMODE_DIRECT:
708                 if(from != myself) {
709                         break;
710                 }
711
712                 for(node = node_udp_tree->head; node; node = node->next) {
713                         n = node->data;
714
715                         if(n->status.reachable && n != myself && ((n->via == myself && n->nexthop == n) || n->via == n)) {
716                                 send_packet(n, packet);
717                         }
718                 }
719
720                 break;
721
722         default:
723                 break;
724         }
725 }
726
727 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
728         avl_node_t *node;
729         edge_t *e;
730         node_t *n = NULL;
731         static time_t last_hard_try = 0;
732
733         for(node = edge_weight_tree->head; node; node = node->next) {
734                 e = node->data;
735
736                 if(e->to == myself) {
737                         continue;
738                 }
739
740                 if(last_hard_try == now && sockaddrcmp_noport(from, &e->address)) {
741                         continue;
742                 }
743
744                 if(!try_mac(e->to, pkt)) {
745                         continue;
746                 }
747
748                 n = e->to;
749                 break;
750         }
751
752         last_hard_try = now;
753         return n;
754 }
755
756 void handle_incoming_vpn_data(int sock) {
757         vpn_packet_t pkt;
758         char *hostname;
759         sockaddr_t from;
760         socklen_t fromlen = sizeof(from);
761         node_t *n;
762
763         ssize_t len = recvfrom(listen_socket[sock].udp, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
764
765         if(len <= 0 || len > UINT16_MAX) {
766                 if(len >= 0) {
767                         logger(LOG_ERR, "Receiving packet with invalid size");
768                 } else if(!sockwouldblock(sockerrno)) {
769                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
770                 }
771
772                 return;
773         }
774
775         pkt.len = len;
776         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
777
778         n = lookup_node_udp(&from);
779
780         if(!n) {
781                 n = try_harder(&from, &pkt);
782
783                 if(n) {
784                         update_node_udp(n, &from);
785                 } else ifdebug(PROTOCOL) {
786                         hostname = sockaddr2hostname(&from);
787                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
788                         free(hostname);
789                         return;
790                 } else {
791                         return;
792                 }
793         }
794
795         n->sock = sock;
796
797         receive_udppacket(n, &pkt);
798 }