Reformat all code using astyle.
[tinc] / 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 -1;
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 -1;
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 -1;
235 #endif
236         }
237
238         return -1;
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 -1;
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 -1;
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         int i;
301
302         if(!n->inkey) {
303                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
304                                         n->name, n->hostname);
305                 return;
306         }
307
308         /* Check packet length */
309
310         if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
311                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
312                                         n->name, n->hostname);
313                 return;
314         }
315
316         /* Check the message authentication code */
317
318         if(n->indigest && n->inmaclength) {
319                 inpkt->len -= n->inmaclength;
320                 HMAC(n->indigest, n->inkey, n->inkeylength,
321                      (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);
322
323                 if(memcmp_constant_time(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
324                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
325                                                 n->name, n->hostname);
326                         return;
327                 }
328         }
329
330         /* Decrypt the packet */
331
332         if(n->incipher) {
333                 outpkt = pkt[nextpkt++];
334
335                 if(!EVP_DecryptInit_ex(n->inctx, NULL, NULL, NULL, NULL)
336                                 || !EVP_DecryptUpdate(n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
337                                                       (unsigned char *) &inpkt->seqno, inpkt->len)
338                                 || !EVP_DecryptFinal_ex(n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
339                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
340                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
341                         return;
342                 }
343
344                 outpkt->len = outlen + outpad;
345                 inpkt = outpkt;
346         }
347
348         /* Check the sequence number */
349
350         inpkt->len -= sizeof(inpkt->seqno);
351         inpkt->seqno = ntohl(inpkt->seqno);
352
353         if(replaywin) {
354                 if(inpkt->seqno != n->received_seqno + 1) {
355                         if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
356                                 if(n->farfuture++ < replaywin >> 2) {
357                                         ifdebug(TRAFFIC) logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
358                                                                 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
359                                         return;
360                                 }
361
362                                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Lost %d packets from %s (%s)",
363                                                         inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
364                                 memset(n->late, 0, replaywin);
365                         } else if(inpkt->seqno <= n->received_seqno) {
366                                 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
367                                         ifdebug(TRAFFIC) logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
368                                                                 n->name, n->hostname, inpkt->seqno, n->received_seqno);
369                                         return;
370                                 }
371                         } else {
372                                 for(i = n->received_seqno + 1; i < inpkt->seqno; i++) {
373                                         n->late[(i / 8) % replaywin] |= 1 << i % 8;
374                                 }
375                         }
376                 }
377
378                 n->farfuture = 0;
379                 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
380         }
381
382         if(inpkt->seqno > n->received_seqno) {
383                 n->received_seqno = inpkt->seqno;
384         }
385
386         if(n->received_seqno > MAX_SEQNO) {
387                 keyexpires = 0;
388         }
389
390         /* Decompress the packet */
391
392         length_t origlen = inpkt->len;
393
394         if(n->incompression) {
395                 outpkt = pkt[nextpkt++];
396
397                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
398                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)",
399                                                 n->name, n->hostname);
400                         return;
401                 }
402
403                 inpkt = outpkt;
404
405                 origlen -= MTU / 64 + 20;
406         }
407
408         inpkt->priority = 0;
409
410         if(!inpkt->data[12] && !inpkt->data[13]) {
411                 mtu_probe_h(n, inpkt, origlen);
412         } else {
413                 receive_packet(n, inpkt);
414         }
415 }
416
417 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
418         vpn_packet_t outpkt;
419
420         if(len > sizeof(outpkt.data)) {
421                 return;
422         }
423
424         outpkt.len = len;
425
426         if(c->options & OPTION_TCPONLY) {
427                 outpkt.priority = 0;
428         } else {
429                 outpkt.priority = -1;
430         }
431
432         memcpy(outpkt.data, buffer, len);
433
434         receive_packet(c->node, &outpkt);
435 }
436
437 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
438         vpn_packet_t pkt1, pkt2;
439         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
440         vpn_packet_t *inpkt = origpkt;
441         int nextpkt = 0;
442         vpn_packet_t *outpkt;
443         int origlen;
444         int outlen, outpad;
445         int origpriority;
446
447         if(!n->status.reachable) {
448                 ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
449                 return;
450         }
451
452         /* Make sure we have a valid key */
453
454         if(!n->status.validkey) {
455                 ifdebug(TRAFFIC) logger(LOG_INFO,
456                                         "No valid key known yet for %s (%s), forwarding via TCP",
457                                         n->name, n->hostname);
458
459                 if(n->last_req_key + 10 <= now) {
460                         send_req_key(n);
461                         n->last_req_key = now;
462                 }
463
464                 send_tcppacket(n->nexthop->connection, origpkt);
465
466                 return;
467         }
468
469         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
470                 ifdebug(TRAFFIC) logger(LOG_INFO,
471                                         "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
472                                         n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
473
474                 if(n != n->nexthop) {
475                         send_packet(n->nexthop, origpkt);
476                 } else {
477                         send_tcppacket(n->nexthop->connection, origpkt);
478                 }
479
480                 return;
481         }
482
483         origlen = inpkt->len;
484         origpriority = inpkt->priority;
485
486         /* Compress the packet */
487
488         if(n->outcompression) {
489                 outpkt = pkt[nextpkt++];
490
491                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
492                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)",
493                                                 n->name, n->hostname);
494                         return;
495                 }
496
497                 inpkt = outpkt;
498         }
499
500         /* Add sequence number */
501
502         inpkt->seqno = htonl(++(n->sent_seqno));
503         inpkt->len += sizeof(inpkt->seqno);
504
505         /* Encrypt the packet */
506
507         if(n->outcipher) {
508                 outpkt = pkt[nextpkt++];
509
510                 if(!EVP_EncryptInit_ex(n->outctx, NULL, NULL, NULL, NULL)
511                                 || !EVP_EncryptUpdate(n->outctx, (unsigned char *) &outpkt->seqno, &outlen,
512                                                       (unsigned char *) &inpkt->seqno, inpkt->len)
513                                 || !EVP_EncryptFinal_ex(n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
514                         ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s",
515                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
516                         goto end;
517                 }
518
519                 outpkt->len = outlen + outpad;
520                 inpkt = outpkt;
521         }
522
523         /* Add the message authentication code */
524
525         if(n->outdigest && n->outmaclength) {
526                 HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno,
527                      inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL);
528                 inpkt->len += n->outmaclength;
529         }
530
531         /* Determine which socket we have to use */
532
533         if(n->address.sa.sa_family != listen_socket[n->sock].sa.sa.sa_family) {
534                 for(int sock = 0; sock < listen_sockets; sock++) {
535                         if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family) {
536                                 n->sock = sock;
537                                 break;
538                         }
539                 }
540         }
541
542         /* Send the packet */
543
544         struct sockaddr *sa;
545         socklen_t sl;
546         int sock;
547         sockaddr_t broadcast;
548
549         /* Overloaded use of priority field: -1 means local broadcast */
550
551         if(origpriority == -1 && n->prevedge) {
552                 sock = rand() % listen_sockets;
553                 memset(&broadcast, 0, sizeof(broadcast));
554
555                 if(listen_socket[sock].sa.sa.sa_family == AF_INET6) {
556                         broadcast.in6.sin6_family = AF_INET6;
557                         broadcast.in6.sin6_addr.s6_addr[0x0] = 0xff;
558                         broadcast.in6.sin6_addr.s6_addr[0x1] = 0x02;
559                         broadcast.in6.sin6_addr.s6_addr[0xf] = 0x01;
560                         broadcast.in6.sin6_port = n->prevedge->address.in.sin_port;
561                         broadcast.in6.sin6_scope_id = listen_socket[sock].sa.in6.sin6_scope_id;
562                 } else {
563                         broadcast.in.sin_family = AF_INET;
564                         broadcast.in.sin_addr.s_addr = -1;
565                         broadcast.in.sin_port = n->prevedge->address.in.sin_port;
566                 }
567
568                 sa = &broadcast.sa;
569                 sl = SALEN(broadcast.sa);
570         } else {
571                 if(origpriority == -1) {
572                         origpriority = 0;
573                 }
574
575                 sa = &(n->address.sa);
576                 sl = SALEN(n->address.sa);
577                 sock = n->sock;
578         }
579
580         if(priorityinheritance && origpriority != listen_socket[n->sock].priority) {
581                 listen_socket[n->sock].priority = origpriority;
582
583                 switch(listen_socket[n->sock].sa.sa.sa_family) {
584 #if defined(SOL_IP) && defined(IP_TOS)
585
586                 case AF_INET:
587                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting IPv4 outgoing packet priority to %d", origpriority);
588
589                         if(setsockopt(listen_socket[n->sock].udp, SOL_IP, IP_TOS, (void *)&origpriority, sizeof(origpriority))) { /* SO_PRIORITY doesn't seem to work */
590                                 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
591                         }
592
593                         break;
594 #endif
595 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
596
597                 case AF_INET6:
598                         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting IPv6 outgoing packet priority to %d", origpriority);
599
600                         if(setsockopt(listen_socket[n->sock].udp, IPPROTO_IPV6, IPV6_TCLASS, (void *)&origpriority, sizeof(origpriority))) {
601                                 logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
602                         }
603
604                         break;
605 #endif
606
607                 default:
608                         break;
609                 }
610         }
611
612         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) {
613                 if(sockmsgsize(sockerrno)) {
614                         if(n->maxmtu >= origlen) {
615                                 n->maxmtu = origlen - 1;
616                         }
617
618                         if(n->mtu >= origlen) {
619                                 n->mtu = origlen - 1;
620                         }
621                 } else {
622                         ifdebug(TRAFFIC) logger(LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
623                 }
624         }
625
626 end:
627         origpkt->len = origlen;
628 }
629
630 /*
631   send a packet to the given vpn ip.
632 */
633 void send_packet(const node_t *n, vpn_packet_t *packet) {
634         node_t *via;
635
636         if(n == myself) {
637                 if(overwrite_mac) {
638                         memcpy(packet->data, mymac.x, ETH_ALEN);
639                 }
640
641                 devops.write(packet);
642                 return;
643         }
644
645         ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)",
646                                 packet->len, n->name, n->hostname);
647
648         if(!n->status.reachable) {
649                 ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable",
650                                         n->name, n->hostname);
651                 return;
652         }
653
654         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
655
656         if(via != n)
657                 ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)",
658                                         n->name, via->name, n->via->hostname);
659
660         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
661                 if(!send_tcppacket(via->connection, packet)) {
662                         terminate_connection(via->connection, true);
663                 }
664         } else {
665                 send_udppacket(via, packet);
666         }
667 }
668
669 /* Broadcast a packet using the minimum spanning tree */
670
671 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
672         avl_node_t *node;
673         connection_t *c;
674         node_t *n;
675
676         // Always give ourself a copy of the packet.
677         if(from != myself) {
678                 send_packet(myself, packet);
679         }
680
681         // In TunnelServer mode, do not forward broadcast packets.
682         // The MST might not be valid and create loops.
683         if(tunnelserver || broadcast_mode == BMODE_NONE) {
684                 return;
685         }
686
687         ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
688                                 packet->len, from->name, from->hostname);
689
690         switch(broadcast_mode) {
691         // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
692         // This guarantees all nodes receive the broadcast packet, and
693         // usually distributes the sending of broadcast packets over all nodes.
694         case BMODE_MST:
695                 for(node = connection_tree->head; node; node = node->next) {
696                         c = node->data;
697
698                         if(c->status.active && c->status.mst && c != from->nexthop->connection) {
699                                 send_packet(c->node, packet);
700                         }
701                 }
702
703                 break;
704
705         // In direct mode, we send copies to each node we know of.
706         // However, this only reaches nodes that can be reached in a single hop.
707         // We don't have enough information to forward broadcast packets in this case.
708         case BMODE_DIRECT:
709                 if(from != myself) {
710                         break;
711                 }
712
713                 for(node = node_udp_tree->head; node; node = node->next) {
714                         n = node->data;
715
716                         if(n->status.reachable && n != myself && ((n->via == myself && n->nexthop == n) || n->via == n)) {
717                                 send_packet(n, packet);
718                         }
719                 }
720
721                 break;
722
723         default:
724                 break;
725         }
726 }
727
728 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
729         avl_node_t *node;
730         edge_t *e;
731         node_t *n = NULL;
732         static time_t last_hard_try = 0;
733
734         for(node = edge_weight_tree->head; node; node = node->next) {
735                 e = node->data;
736
737                 if(e->to == myself) {
738                         continue;
739                 }
740
741                 if(last_hard_try == now && sockaddrcmp_noport(from, &e->address)) {
742                         continue;
743                 }
744
745                 if(!try_mac(e->to, pkt)) {
746                         continue;
747                 }
748
749                 n = e->to;
750                 break;
751         }
752
753         last_hard_try = now;
754         return n;
755 }
756
757 void handle_incoming_vpn_data(int sock) {
758         vpn_packet_t pkt;
759         char *hostname;
760         sockaddr_t from;
761         socklen_t fromlen = sizeof(from);
762         node_t *n;
763
764         pkt.len = recvfrom(listen_socket[sock].udp, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
765
766         if(pkt.len < 0) {
767                 if(!sockwouldblock(sockerrno)) {
768                         logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
769                 }
770
771                 return;
772         }
773
774         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
775
776         n = lookup_node_udp(&from);
777
778         if(!n) {
779                 n = try_harder(&from, &pkt);
780
781                 if(n) {
782                         update_node_udp(n, &from);
783                 } else ifdebug(PROTOCOL) {
784                         hostname = sockaddr2hostname(&from);
785                         logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
786                         free(hostname);
787                         return;
788                 } else {
789                         return;
790                 }
791         }
792
793         n->sock = sock;
794
795         receive_udppacket(n, &pkt);
796 }