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