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