Replace the connection_tree with a connection_list.
[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-2012 Guus Sliepen <guus@tinc-vpn.org>
5                   2010      Timothy Redaelli <timothy@redaelli.eu>
6                   2010      Brandon Black <blblack@gmail.com>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include <openssl/rand.h>
26 #include <openssl/err.h>
27 #include <openssl/evp.h>
28 #include <openssl/pem.h>
29 #include <openssl/hmac.h>
30
31 #ifdef HAVE_ZLIB
32 #include <zlib.h>
33 #endif
34
35 #ifdef HAVE_LZO
36 #include LZO1X_H
37 #endif
38
39 #include "cipher.h"
40 #include "conf.h"
41 #include "connection.h"
42 #include "crypto.h"
43 #include "digest.h"
44 #include "device.h"
45 #include "ethernet.h"
46 #include "graph.h"
47 #include "logger.h"
48 #include "net.h"
49 #include "netutl.h"
50 #include "protocol.h"
51 #include "process.h"
52 #include "route.h"
53 #include "utils.h"
54 #include "xalloc.h"
55
56 int keylifetime = 0;
57 #ifdef HAVE_LZO
58 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
59 #endif
60
61 static void send_udppacket(node_t *, vpn_packet_t *);
62
63 unsigned replaywin = 16;
64 bool localdiscovery = false;
65
66 #define MAX_SEQNO 1073741824
67
68 /* mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
69    mtuprobes ==    31: sleep pinginterval seconds
70    mtuprobes ==    32: send 1 burst, sleep pingtimeout second
71    mtuprobes ==    33: no response from other side, restart PMTU discovery process
72
73    Probes are sent in batches of three, with random sizes between the lower and
74    upper boundaries for the MTU thus far discovered.
75
76    In case local discovery is enabled, a fourth packet is added to each batch,
77    which will be broadcast to the local network.
78 */
79
80 static void send_mtu_probe_handler(int fd, short events, void *data) {
81         node_t *n = data;
82         vpn_packet_t packet;
83         int len, i;
84         int timeout = 1;
85         
86         n->mtuprobes++;
87
88         if(!n->status.reachable || !n->status.validkey) {
89                 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname);
90                 n->mtuprobes = 0;
91                 return;
92         }
93
94         if(n->mtuprobes > 32) {
95                 if(!n->minmtu) {
96                         n->mtuprobes = 31;
97                         timeout = pinginterval;
98                         goto end;
99                 }
100
101                 logger(DEBUG_TRAFFIC, LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname);
102                 n->mtuprobes = 1;
103                 n->minmtu = 0;
104                 n->maxmtu = MTU;
105         }
106
107         if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
108                 logger(DEBUG_TRAFFIC, LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
109                 n->mtuprobes = 31;
110         }
111
112         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
113                 if(n->minmtu > n->maxmtu)
114                         n->minmtu = n->maxmtu;
115                 else
116                         n->maxmtu = n->minmtu;
117                 n->mtu = n->minmtu;
118                 logger(DEBUG_TRAFFIC, LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
119                 n->mtuprobes = 31;
120         }
121
122         if(n->mtuprobes == 31) {
123                 timeout = pinginterval;
124                 goto end;
125         } else if(n->mtuprobes == 32) {
126                 timeout = pingtimeout;
127         }
128
129         for(i = 0; i < 3 + localdiscovery; i++) {
130                 if(n->maxmtu <= n->minmtu)
131                         len = n->maxmtu;
132                 else
133                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
134
135                 if(len < 64)
136                         len = 64;
137                 
138                 memset(packet.data, 0, 14);
139                 randomize(packet.data + 14, len - 14);
140                 packet.len = len;
141                 if(i >= 3 && n->mtuprobes <= 10)
142                         packet.priority = -1;
143                 else
144                         packet.priority = 0;
145
146                 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
147
148                 send_udppacket(n, &packet);
149         }
150
151 end:
152         event_add(&n->mtuevent, &(struct timeval){timeout, 0});
153 }
154
155 void send_mtu_probe(node_t *n) {
156         if(!timeout_initialized(&n->mtuevent))
157                 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
158         send_mtu_probe_handler(0, 0, n);
159 }
160
161 static void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
162         logger(DEBUG_TRAFFIC, LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
163
164         if(!packet->data[0]) {
165                 packet->data[0] = 1;
166                 send_udppacket(n, packet);
167         } else {
168                 if(n->mtuprobes > 30) {
169                         if(n->minmtu)
170                                 n->mtuprobes = 30;
171                         else
172                                 n->mtuprobes = 1;
173                 }
174
175                 if(len > n->maxmtu)
176                         len = n->maxmtu;
177                 if(n->minmtu < len)
178                         n->minmtu = len;
179         }
180 }
181
182 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
183         if(level == 0) {
184                 memcpy(dest, source, len);
185                 return len;
186         } else if(level == 10) {
187 #ifdef HAVE_LZO
188                 lzo_uint lzolen = MAXSIZE;
189                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
190                 return lzolen;
191 #else
192                 return -1;
193 #endif
194         } else if(level < 10) {
195 #ifdef HAVE_ZLIB
196                 unsigned long destlen = MAXSIZE;
197                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
198                         return destlen;
199                 else
200 #endif
201                         return -1;
202         } else {
203 #ifdef HAVE_LZO
204                 lzo_uint lzolen = MAXSIZE;
205                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
206                 return lzolen;
207 #else
208                 return -1;
209 #endif
210         }
211         
212         return -1;
213 }
214
215 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
216         if(level == 0) {
217                 memcpy(dest, source, len);
218                 return len;
219         } else if(level > 9) {
220 #ifdef HAVE_LZO
221                 lzo_uint lzolen = MAXSIZE;
222                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
223                         return lzolen;
224                 else
225 #endif
226                         return -1;
227         }
228 #ifdef HAVE_ZLIB
229         else {
230                 unsigned long destlen = MAXSIZE;
231                 if(uncompress(dest, &destlen, source, len) == Z_OK)
232                         return destlen;
233                 else
234                         return -1;
235         }
236 #endif
237
238         return -1;
239 }
240
241 /* VPN packet I/O */
242
243 static void receive_packet(node_t *n, vpn_packet_t *packet) {
244         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
245                            packet->len, n->name, n->hostname);
246
247         n->in_packets++;
248         n->in_bytes += packet->len;
249
250         route(n, packet);
251 }
252
253 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
254         if(n->status.sptps)
255                 return sptps_verify_datagram(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
256
257         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
258                 return false;
259
260         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
261 }
262
263 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
264         vpn_packet_t pkt1, pkt2;
265         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
266         int nextpkt = 0;
267         vpn_packet_t *outpkt = pkt[0];
268         size_t outlen;
269
270         if(n->status.sptps) {
271                 sptps_receive_data(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
272                 return;
273         }
274
275         if(!cipher_active(&n->incipher)) {
276                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
277                                         n->name, n->hostname);
278                 return;
279         }
280
281         /* Check packet length */
282
283         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
284                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got too short packet from %s (%s)",
285                                         n->name, n->hostname);
286                 return;
287         }
288
289         /* Check the message authentication code */
290
291         if(digest_active(&n->indigest)) {
292                 inpkt->len -= n->indigest.maclength;
293                 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
294                         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
295                         return;
296                 }
297         }
298         /* Decrypt the packet */
299
300         if(cipher_active(&n->incipher)) {
301                 outpkt = pkt[nextpkt++];
302                 outlen = MAXSIZE;
303
304                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
305                         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
306                         return;
307                 }
308                 
309                 outpkt->len = outlen;
310                 inpkt = outpkt;
311         }
312
313         /* Check the sequence number */
314
315         inpkt->len -= sizeof inpkt->seqno;
316         inpkt->seqno = ntohl(inpkt->seqno);
317
318         if(replaywin) {
319                 if(inpkt->seqno != n->received_seqno + 1) {
320                         if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
321                                 if(n->farfuture++ < replaywin >> 2) {
322                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
323                                                 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
324                                         return;
325                                 }
326                                 logger(DEBUG_ALWAYS, LOG_WARNING, "Lost %d packets from %s (%s)",
327                                                 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
328                                 memset(n->late, 0, replaywin);
329                         } else if (inpkt->seqno <= n->received_seqno) {
330                                 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
331                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
332                                                 n->name, n->hostname, inpkt->seqno, n->received_seqno);
333                                         return;
334                                 }
335                         } else {
336                                 for(int i = n->received_seqno + 1; i < inpkt->seqno; i++)
337                                         n->late[(i / 8) % replaywin] |= 1 << i % 8;
338                         }
339                 }
340
341                 n->farfuture = 0;
342                 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
343         }
344
345         if(inpkt->seqno > n->received_seqno)
346                 n->received_seqno = inpkt->seqno;
347                         
348         if(n->received_seqno > MAX_SEQNO)
349                 regenerate_key();
350
351         /* Decompress the packet */
352
353         length_t origlen = inpkt->len;
354
355         if(n->incompression) {
356                 outpkt = pkt[nextpkt++];
357
358                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
359                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while uncompressing packet from %s (%s)",
360                                                  n->name, n->hostname);
361                         return;
362                 }
363
364                 inpkt = outpkt;
365
366                 origlen -= MTU/64 + 20;
367         }
368
369         inpkt->priority = 0;
370
371         if(!inpkt->data[12] && !inpkt->data[13])
372                 mtu_probe_h(n, inpkt, origlen);
373         else
374                 receive_packet(n, inpkt);
375 }
376
377 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
378         vpn_packet_t outpkt;
379
380         outpkt.len = len;
381         if(c->options & OPTION_TCPONLY)
382                 outpkt.priority = 0;
383         else
384                 outpkt.priority = -1;
385         memcpy(outpkt.data, buffer, len);
386
387         receive_packet(c->node, &outpkt);
388 }
389
390 static void send_sptps_packet(node_t *n, vpn_packet_t *origpkt) {
391         if(!n->status.validkey) {
392                 logger(DEBUG_TRAFFIC, LOG_INFO, "No valid key known yet for %s (%s)", n->name, n->hostname);
393                 if(!n->status.waitingforkey)
394                         send_req_key(n);
395                 else if(n->last_req_key + 10 < time(NULL)) {
396                         sptps_stop(&n->sptps);
397                         n->status.waitingforkey = false;
398                         send_req_key(n);
399                 }
400                 return;
401         }
402
403         uint8_t type = 0;
404         int offset = 0;
405
406         if(!(origpkt->data[12] | origpkt->data[13])) {
407                 sptps_send_record(&n->sptps, PKT_PROBE, (char *)origpkt->data, origpkt->len);
408                 return;
409         }
410
411         if(routing_mode == RMODE_ROUTER)
412                 offset = 14;
413         else
414                 type = PKT_MAC;
415
416         if(origpkt->len < offset)
417                 return;
418
419         vpn_packet_t outpkt;
420
421         if(n->outcompression) {
422                 int len = compress_packet(outpkt.data + offset, origpkt->data + offset, origpkt->len - offset, n->outcompression);
423                 if(len < 0) {
424                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)", n->name, n->hostname);
425                 } else if(len < origpkt->len - offset) {
426                         outpkt.len = len + offset;
427                         origpkt = &outpkt;
428                         type |= PKT_COMPRESSED;
429                 }
430         }
431
432         sptps_send_record(&n->sptps, type, (char *)origpkt->data + offset, origpkt->len - offset);
433         return;
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 = origpkt->len;
443         size_t outlen;
444 #if defined(SOL_IP) && defined(IP_TOS)
445         static int priority = 0;
446 #endif
447         int origpriority = origpkt->priority;
448
449         if(!n->status.reachable) {
450                 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
451                 return;
452         }
453
454         if(n->status.sptps)
455                 return send_sptps_packet(n, origpkt);
456
457         /* Make sure we have a valid key */
458
459         if(!n->status.validkey) {
460                 time_t now = time(NULL);
461
462                 logger(DEBUG_TRAFFIC, LOG_INFO,
463                                    "No valid key known yet for %s (%s), forwarding via TCP",
464                                    n->name, n->hostname);
465
466                 if(n->last_req_key + 10 <= now) {
467                         send_req_key(n);
468                         n->last_req_key = now;
469                 }
470
471                 send_tcppacket(n->nexthop->connection, origpkt);
472
473                 return;
474         }
475
476         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
477                 logger(DEBUG_TRAFFIC, LOG_INFO,
478                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
479                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
480
481                 if(n != n->nexthop)
482                         send_packet(n->nexthop, origpkt);
483                 else
484                         send_tcppacket(n->nexthop->connection, origpkt);
485
486                 return;
487         }
488
489         /* Compress the packet */
490
491         if(n->outcompression) {
492                 outpkt = pkt[nextpkt++];
493
494                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
495                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)",
496                                    n->name, n->hostname);
497                         return;
498                 }
499
500                 inpkt = outpkt;
501         }
502
503         /* Add sequence number */
504
505         inpkt->seqno = htonl(++(n->sent_seqno));
506         inpkt->len += sizeof inpkt->seqno;
507
508         /* Encrypt the packet */
509
510         if(cipher_active(&n->outcipher)) {
511                 outpkt = pkt[nextpkt++];
512                 outlen = MAXSIZE;
513
514                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
515                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
516                         goto end;
517                 }
518
519                 outpkt->len = outlen;
520                 inpkt = outpkt;
521         }
522
523         /* Add the message authentication code */
524
525         if(digest_active(&n->outdigest)) {
526                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
527                 inpkt->len += digest_length(&n->outdigest);
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
547         /* Overloaded use of priority field: -1 means local broadcast */
548
549         if(origpriority == -1 && n->prevedge) {
550                 struct sockaddr_in in;
551                 in.sin_family = AF_INET;
552                 in.sin_addr.s_addr = -1;
553                 in.sin_port = n->prevedge->address.in.sin_port;
554                 sa = (struct sockaddr *)&in;
555                 sl = sizeof in;
556                 sock = 0;
557         } else {
558                 if(origpriority == -1)
559                         origpriority = 0;
560
561                 sa = &(n->address.sa);
562                 sl = SALEN(n->address.sa);
563                 sock = n->sock;
564         }
565
566 #if defined(SOL_IP) && defined(IP_TOS)
567         if(priorityinheritance && origpriority != priority
568            && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
569                 priority = origpriority;
570                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
571                 if(setsockopt(listen_socket[n->sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
572                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
573         }
574 #endif
575
576         if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) {
577                 if(sockmsgsize(sockerrno)) {
578                         if(n->maxmtu >= origlen)
579                                 n->maxmtu = origlen - 1;
580                         if(n->mtu >= origlen)
581                                 n->mtu = origlen - 1;
582                 } else
583                         logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
584         }
585
586 end:
587         origpkt->len = origlen;
588 }
589
590 bool send_sptps_data(void *handle, uint8_t type, const char *data, size_t len) {
591         node_t *to = handle;
592
593         if(type >= SPTPS_HANDSHAKE
594                         || ((myself->options | to->options) & OPTION_TCPONLY)
595                         || (type != PKT_PROBE && len > to->minmtu)) {
596                 char buf[len * 4 / 3 + 5];
597                 b64encode(data, buf, len);
598                 if(!to->status.validkey)
599                         return send_request(to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, myself->name, to->name, buf, myself->incompression);
600                 else
601                         return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, to->name, type >= SPTPS_HANDSHAKE ? REQ_SPTPS : REQ_PACKET, buf);
602         }
603
604         /* Send the packet */
605
606         struct sockaddr *sa;
607         socklen_t sl;
608         int sock;
609
610         sa = &(to->address.sa);
611         sl = SALEN(to->address.sa);
612         sock = to->sock;
613
614         if(sendto(listen_socket[sock].udp, data, len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) {
615                 if(sockmsgsize(sockerrno)) {
616                         if(to->maxmtu >= len)
617                                 to->maxmtu = len - 1;
618                         if(to->mtu >= len)
619                                 to->mtu = len - 1;
620                 } else {
621                         logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", to->name, to->hostname, sockstrerror(sockerrno));
622                         return false;
623                 }
624         }
625
626         return true;
627 }
628
629 bool receive_sptps_record(void *handle, uint8_t type, const char *data, uint16_t len) {
630         node_t *from = handle;
631
632         if(type == SPTPS_HANDSHAKE) {
633                 from->status.validkey = true;
634                 from->status.waitingforkey = false;
635                 logger(DEBUG_META, LOG_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
636                 return true;
637         }
638
639         if(len > MTU) {
640                 logger(DEBUG_ALWAYS, LOG_ERR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
641                 return false;
642         }
643
644         vpn_packet_t inpkt;
645
646         if(type == PKT_PROBE) {
647                 inpkt.len = len;
648                 memcpy(inpkt.data, data, len);
649                 mtu_probe_h(from, &inpkt, len);
650                 return true;
651         }
652
653         if(type & ~(PKT_COMPRESSED | PKT_MAC)) {
654                 logger(DEBUG_ALWAYS, LOG_ERR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
655                 return false;
656         }
657
658         /* Check if we have the headers we need */
659         if(routing_mode != RMODE_ROUTER && !(type & PKT_MAC)) {
660                 logger(DEBUG_TRAFFIC, LOG_ERR, "Received packet from %s (%s) without MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
661                 return false;
662         } else if(routing_mode == RMODE_ROUTER && (type & PKT_MAC)) {
663                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Received packet from %s (%s) with MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
664         }
665
666         int offset = (type & PKT_MAC) ? 0 : 14;
667         if(type & PKT_COMPRESSED) {
668                 len = uncompress_packet(inpkt.data + offset, (const uint8_t *)data, len, from->incompression);
669                 if(len < 0) {
670                         return false;
671                 } else {
672                         inpkt.len = len + offset;
673                 }
674                 if(inpkt.len > MAXSIZE)
675                         abort();
676         } else {
677                 memcpy(inpkt.data + offset, data, len);
678                 inpkt.len = len + offset;
679         }
680
681         /* Generate the Ethernet packet type if necessary */
682         if(offset) {
683                 switch(inpkt.data[14] >> 4) {
684                         case 4:
685                                 inpkt.data[12] = 0x08;
686                                 inpkt.data[13] = 0x00;
687                                 break;
688                         case 6:
689                                 inpkt.data[12] = 0x86;
690                                 inpkt.data[13] = 0xDD;
691                                 break;
692                         default:
693                                 logger(DEBUG_TRAFFIC, LOG_ERR,
694                                                    "Unknown IP version %d while reading packet from %s (%s)",
695                                                    inpkt.data[14] >> 4, from->name, from->hostname);
696                                 return false;
697                 }
698         }
699
700         receive_packet(from, &inpkt);
701         return true;
702 }
703
704 /*
705   send a packet to the given vpn ip.
706 */
707 void send_packet(node_t *n, vpn_packet_t *packet) {
708         node_t *via;
709
710         if(n == myself) {
711                 if(overwrite_mac)
712                          memcpy(packet->data, mymac.x, ETH_ALEN);
713                 n->out_packets++;
714                 n->out_bytes += packet->len;
715                 devops.write(packet);
716                 return;
717         }
718
719         logger(DEBUG_TRAFFIC, LOG_ERR, "Sending packet of %d bytes to %s (%s)",
720                            packet->len, n->name, n->hostname);
721
722         if(!n->status.reachable) {
723                 logger(DEBUG_TRAFFIC, LOG_INFO, "Node %s (%s) is not reachable",
724                                    n->name, n->hostname);
725                 return;
726         }
727
728         n->out_packets++;
729         n->out_bytes += packet->len;
730
731         if(n->status.sptps) {
732                 send_sptps_packet(n, packet);
733                 return;
734         }
735
736         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
737
738         if(via != n)
739                 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending packet to %s via %s (%s)",
740                            n->name, via->name, n->via->hostname);
741
742         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
743                 if(!send_tcppacket(via->connection, packet))
744                         terminate_connection(via->connection, true);
745         } else
746                 send_udppacket(via, packet);
747 }
748
749 /* Broadcast a packet using the minimum spanning tree */
750
751 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
752         // Always give ourself a copy of the packet.
753         if(from != myself)
754                 send_packet(myself, packet);
755
756         // In TunnelServer mode, do not forward broadcast packets.
757         // The MST might not be valid and create loops.
758         if(tunnelserver || broadcast_mode == BMODE_NONE)
759                 return;
760
761         logger(DEBUG_TRAFFIC, LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
762                            packet->len, from->name, from->hostname);
763
764         switch(broadcast_mode) {
765                 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
766                 // This guarantees all nodes receive the broadcast packet, and
767                 // usually distributes the sending of broadcast packets over all nodes.
768                 case BMODE_MST:
769                         for(list_node_t *node = connection_list->head, *next; node; node = next) {
770                                 next = node->next;
771                                 connection_t *c = node->data;
772
773                                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
774                                         send_packet(c->node, packet);
775                         }
776                         break;
777
778                 // In direct mode, we send copies to each node we know of.
779                 // However, this only reaches nodes that can be reached in a single hop.
780                 // We don't have enough information to forward broadcast packets in this case.
781                 case BMODE_DIRECT:
782                         if(from != myself)
783                                 break;
784
785                         for(splay_node_t *node = node_tree->head; node; node = node->next) {
786                                 node_t *n = node->data;
787
788                                 if(n->status.reachable && ((n->via == myself && n->nexthop == n) || n->via == n))
789                                         send_packet(n, packet);
790                         }
791                         break;
792
793                 default:
794                         break;
795         }
796 }
797
798 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
799         splay_node_t *node;
800         edge_t *e;
801         node_t *n = NULL;
802         bool hard = false;
803         static time_t last_hard_try = 0;
804         time_t now = time(NULL);
805
806         for(node = edge_weight_tree->head; node; node = node->next) {
807                 e = node->data;
808
809                 if(!e->to->status.reachable || e->to == myself)
810                         continue;
811
812                 if(sockaddrcmp_noport(from, &e->address)) {
813                         if(last_hard_try == now)
814                                 continue;
815                         hard = true;
816                 }
817
818                 if(!try_mac(e->to, pkt))
819                         continue;
820
821                 n = e->to;
822                 break;
823         }
824
825         if(hard)
826                 last_hard_try = now;
827
828         last_hard_try = now;
829         return n;
830 }
831
832 void handle_incoming_vpn_data(int sock, short events, void *data) {
833         vpn_packet_t pkt;
834         char *hostname;
835         sockaddr_t from = {{0}};
836         socklen_t fromlen = sizeof from;
837         node_t *n;
838         int len;
839
840         len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
841
842         if(len <= 0 || len > MAXSIZE) {
843                 if(!sockwouldblock(sockerrno))
844                         logger(DEBUG_ALWAYS, LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
845                 return;
846         }
847
848         pkt.len = len;
849
850         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
851
852         n = lookup_node_udp(&from);
853
854         if(!n) {
855                 n = try_harder(&from, &pkt);
856                 if(n)
857                         update_node_udp(n, &from);
858                 else if(debug_level >= DEBUG_PROTOCOL) {
859                         hostname = sockaddr2hostname(&from);
860                         logger(DEBUG_PROTOCOL, LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
861                         free(hostname);
862                         return;
863                 }
864                 else
865                         return;
866         }
867
868         n->sock = (intptr_t)data;
869
870         receive_udppacket(n, &pkt);
871 }
872
873 void handle_device_data(int sock, short events, void *data) {
874         vpn_packet_t packet;
875
876         packet.priority = 0;
877
878         if(devops.read(&packet)) {
879                 myself->in_packets++;
880                 myself->in_bytes += packet.len;
881                 route(myself, &packet);
882         }
883 }