Releasing 1.1pre5.
[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-2013 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(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->status.udp_confirmed = false;
101                 n->mtuprobes = 1;
102                 n->minmtu = 0;
103                 n->maxmtu = MTU;
104         }
105
106         if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
107                 logger(DEBUG_TRAFFIC, LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname);
108                 n->mtuprobes = 31;
109         }
110
111         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
112                 if(n->minmtu > n->maxmtu)
113                         n->minmtu = n->maxmtu;
114                 else
115                         n->maxmtu = n->minmtu;
116                 n->mtu = n->minmtu;
117                 logger(DEBUG_TRAFFIC, LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes);
118                 n->mtuprobes = 31;
119         }
120
121         if(n->mtuprobes == 31) {
122                 timeout = pinginterval;
123                 goto end;
124         } else if(n->mtuprobes == 32) {
125                 timeout = pingtimeout;
126         }
127
128         for(int i = 0; i < 3 + localdiscovery; i++) {
129                 int len;
130
131                 if(n->maxmtu <= n->minmtu)
132                         len = n->maxmtu;
133                 else
134                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
135
136                 if(len < 64)
137                         len = 64;
138
139                 vpn_packet_t packet;
140                 memset(packet.data, 0, 14);
141                 randomize(packet.data + 14, len - 14);
142                 packet.len = len;
143                 if(i >= 3 && n->mtuprobes <= 10)
144                         packet.priority = -1;
145                 else
146                         packet.priority = 0;
147
148                 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname);
149
150                 send_udppacket(n, &packet);
151         }
152
153         n->probe_counter = 0;
154         gettimeofday(&n->probe_time, NULL);
155
156         /* Calculate the packet loss of incoming traffic by comparing the rate of
157            packets received to the rate with which the sequence number has increased.
158          */
159
160         if(n->received > n->prev_received)
161                 n->packetloss = 1.0 - (n->received - n->prev_received) / (float)(n->received_seqno - n->prev_received_seqno);
162         else
163                 n->packetloss = n->received_seqno <= n->prev_received_seqno;
164
165         n->prev_received_seqno = n->received_seqno;
166         n->prev_received = n->received;
167
168 end:
169         timeout_set(&n->mtutimeout, &(struct timeval){timeout, rand() % 100000});
170 }
171
172 void send_mtu_probe(node_t *n) {
173         timeout_add(&n->mtutimeout, send_mtu_probe_handler, n, &(struct timeval){1, 0});
174         send_mtu_probe_handler(n);
175 }
176
177 static void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
178         logger(DEBUG_TRAFFIC, LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname);
179
180         if(!packet->data[0]) {
181                 /* It's a probe request, send back a reply */
182
183                 packet->data[0] = 1;
184
185                 /* Temporarily set udp_confirmed, so that the reply is sent
186                    back exactly the way it came in. */
187
188                 bool udp_confirmed = n->status.udp_confirmed;
189                 n->status.udp_confirmed = true;
190                 send_udppacket(n, packet);
191                 n->status.udp_confirmed = udp_confirmed;
192         } else {
193                 /* It's a valid reply: now we know bidirectional communication
194                    is possible using the address and socket that the reply
195                    packet used. */
196
197                 n->status.udp_confirmed = true;
198
199                 /* If we haven't established the PMTU yet, restart the discovery process. */
200
201                 if(n->mtuprobes > 30) {
202                         if(n->minmtu)
203                                 n->mtuprobes = 30;
204                         else
205                                 n->mtuprobes = 1;
206                 }
207
208                 /* If applicable, raise the minimum supported MTU */
209
210                 if(len > n->maxmtu)
211                         len = n->maxmtu;
212                 if(n->minmtu < len)
213                         n->minmtu = len;
214
215                 /* Calculate RTT and bandwidth.
216                    The RTT is the time between the MTU probe burst was sent and the first
217                    reply is received. The bandwidth is measured using the time between the
218                    arrival of the first and third probe reply.
219                  */
220
221                 struct timeval now, diff;
222                 gettimeofday(&now, NULL);
223                 timersub(&now, &n->probe_time, &diff);
224                 n->probe_counter++;
225
226                 if(n->probe_counter == 1) {
227                         n->rtt = diff.tv_sec + diff.tv_usec * 1e-6;
228                         n->probe_time = now;
229                 } else if(n->probe_counter == 3) {
230                         n->bandwidth = 2.0 * len / (diff.tv_sec + diff.tv_usec * 1e-6);
231                         logger(DEBUG_TRAFFIC, LOG_DEBUG, "%s (%s) RTT %.2f ms, burst bandwidth %.3f Mbit/s, rx packet loss %.2f %%", n->name, n->hostname, n->rtt * 1e3, n->bandwidth * 8e-6, n->packetloss * 1e2);
232                 }
233         }
234 }
235
236 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
237         if(level == 0) {
238                 memcpy(dest, source, len);
239                 return len;
240         } else if(level == 10) {
241 #ifdef HAVE_LZO
242                 lzo_uint lzolen = MAXSIZE;
243                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
244                 return lzolen;
245 #else
246                 return -1;
247 #endif
248         } else if(level < 10) {
249 #ifdef HAVE_ZLIB
250                 unsigned long destlen = MAXSIZE;
251                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
252                         return destlen;
253                 else
254 #endif
255                         return -1;
256         } else {
257 #ifdef HAVE_LZO
258                 lzo_uint lzolen = MAXSIZE;
259                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
260                 return lzolen;
261 #else
262                 return -1;
263 #endif
264         }
265
266         return -1;
267 }
268
269 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
270         if(level == 0) {
271                 memcpy(dest, source, len);
272                 return len;
273         } else if(level > 9) {
274 #ifdef HAVE_LZO
275                 lzo_uint lzolen = MAXSIZE;
276                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
277                         return lzolen;
278                 else
279 #endif
280                         return -1;
281         }
282 #ifdef HAVE_ZLIB
283         else {
284                 unsigned long destlen = MAXSIZE;
285                 if(uncompress(dest, &destlen, source, len) == Z_OK)
286                         return destlen;
287                 else
288                         return -1;
289         }
290 #endif
291
292         return -1;
293 }
294
295 /* VPN packet I/O */
296
297 static void receive_packet(node_t *n, vpn_packet_t *packet) {
298         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Received packet of %d bytes from %s (%s)",
299                            packet->len, n->name, n->hostname);
300
301         n->in_packets++;
302         n->in_bytes += packet->len;
303
304         route(n, packet);
305 }
306
307 static bool try_mac(node_t *n, const vpn_packet_t *inpkt) {
308         if(n->status.sptps)
309                 return sptps_verify_datagram(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
310
311         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
312                 return false;
313
314         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len - n->indigest.maclength, (const char *)&inpkt->seqno + inpkt->len - n->indigest.maclength);
315 }
316
317 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
318         vpn_packet_t pkt1, pkt2;
319         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
320         int nextpkt = 0;
321         vpn_packet_t *outpkt = pkt[0];
322         size_t outlen;
323
324         if(n->status.sptps) {
325                 sptps_receive_data(&n->sptps, (char *)&inpkt->seqno, inpkt->len);
326                 return;
327         }
328
329         if(!cipher_active(&n->incipher)) {
330                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
331                                         n->name, n->hostname);
332                 return;
333         }
334
335         /* Check packet length */
336
337         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
338                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got too short packet from %s (%s)",
339                                         n->name, n->hostname);
340                 return;
341         }
342
343         /* Check the message authentication code */
344
345         if(digest_active(&n->indigest)) {
346                 inpkt->len -= n->indigest.maclength;
347                 if(!digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
348                         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname);
349                         return;
350                 }
351         }
352         /* Decrypt the packet */
353
354         if(cipher_active(&n->incipher)) {
355                 outpkt = pkt[nextpkt++];
356                 outlen = MAXSIZE;
357
358                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
359                         logger(DEBUG_TRAFFIC, LOG_DEBUG, "Error decrypting packet from %s (%s)", n->name, n->hostname);
360                         return;
361                 }
362
363                 outpkt->len = outlen;
364                 inpkt = outpkt;
365         }
366
367         /* Check the sequence number */
368
369         inpkt->len -= sizeof inpkt->seqno;
370         inpkt->seqno = ntohl(inpkt->seqno);
371
372         if(replaywin) {
373                 if(inpkt->seqno != n->received_seqno + 1) {
374                         if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
375                                 if(n->farfuture++ < replaywin >> 2) {
376                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
377                                                 n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
378                                         return;
379                                 }
380                                 logger(DEBUG_ALWAYS, LOG_WARNING, "Lost %d packets from %s (%s)",
381                                                 inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
382                                 memset(n->late, 0, replaywin);
383                         } else if (inpkt->seqno <= n->received_seqno) {
384                                 if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
385                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
386                                                 n->name, n->hostname, inpkt->seqno, n->received_seqno);
387                                         return;
388                                 }
389                         } else {
390                                 for(int i = n->received_seqno + 1; i < inpkt->seqno; i++)
391                                         n->late[(i / 8) % replaywin] |= 1 << i % 8;
392                         }
393                 }
394
395                 n->farfuture = 0;
396                 n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
397         }
398
399         if(inpkt->seqno > n->received_seqno)
400                 n->received_seqno = inpkt->seqno;
401
402         n->received++;
403
404         if(n->received_seqno > MAX_SEQNO)
405                 regenerate_key();
406
407         /* Decompress the packet */
408
409         length_t origlen = inpkt->len;
410
411         if(n->incompression) {
412                 outpkt = pkt[nextpkt++];
413
414                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
415                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while uncompressing packet from %s (%s)",
416                                                  n->name, n->hostname);
417                         return;
418                 }
419
420                 inpkt = outpkt;
421
422                 origlen -= MTU/64 + 20;
423         }
424
425         inpkt->priority = 0;
426
427         if(!inpkt->data[12] && !inpkt->data[13])
428                 mtu_probe_h(n, inpkt, origlen);
429         else
430                 receive_packet(n, inpkt);
431 }
432
433 void receive_tcppacket(connection_t *c, const char *buffer, int len) {
434         vpn_packet_t outpkt;
435
436         outpkt.len = len;
437         if(c->options & OPTION_TCPONLY)
438                 outpkt.priority = 0;
439         else
440                 outpkt.priority = -1;
441         memcpy(outpkt.data, buffer, len);
442
443         receive_packet(c->node, &outpkt);
444 }
445
446 static void send_sptps_packet(node_t *n, vpn_packet_t *origpkt) {
447         if(!n->status.validkey) {
448                 logger(DEBUG_TRAFFIC, LOG_INFO, "No valid key known yet for %s (%s)", n->name, n->hostname);
449                 if(!n->status.waitingforkey)
450                         send_req_key(n);
451                 else if(n->last_req_key + 10 < time(NULL)) {
452                         logger(DEBUG_ALWAYS, LOG_DEBUG, "No key from %s after 10 seconds, restarting SPTPS", n->name);
453                         sptps_stop(&n->sptps);
454                         n->status.waitingforkey = false;
455                         send_req_key(n);
456                 }
457                 return;
458         }
459
460         uint8_t type = 0;
461         int offset = 0;
462
463         if(!(origpkt->data[12] | origpkt->data[13])) {
464                 sptps_send_record(&n->sptps, PKT_PROBE, (char *)origpkt->data, origpkt->len);
465                 return;
466         }
467
468         if(routing_mode == RMODE_ROUTER)
469                 offset = 14;
470         else
471                 type = PKT_MAC;
472
473         if(origpkt->len < offset)
474                 return;
475
476         vpn_packet_t outpkt;
477
478         if(n->outcompression) {
479                 int len = compress_packet(outpkt.data + offset, origpkt->data + offset, origpkt->len - offset, n->outcompression);
480                 if(len < 0) {
481                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)", n->name, n->hostname);
482                 } else if(len < origpkt->len - offset) {
483                         outpkt.len = len + offset;
484                         origpkt = &outpkt;
485                         type |= PKT_COMPRESSED;
486                 }
487         }
488
489         sptps_send_record(&n->sptps, type, (char *)origpkt->data + offset, origpkt->len - offset);
490         return;
491 }
492
493 static void choose_udp_address(const node_t *n, const sockaddr_t **sa, int *sock) {
494         /* Latest guess */
495         *sa = &n->address;
496         *sock = n->sock;
497
498         /* If the UDP address is confirmed, use it. */
499         if(n->status.udp_confirmed)
500                 return;
501
502         /* Send every third packet to n->address; that could be set
503            to the node's reflexive UDP address discovered during key
504            exchange. */
505
506         static int x = 0;
507         if(++x >= 3) {
508                 x = 0;
509                 return;
510         }
511
512         /* Otherwise, address are found in edges to this node.
513            So we pick a random edge and a random socket. */
514
515         int i = 0;
516         int j = rand() % n->edge_tree->count;
517         edge_t *candidate = NULL;
518
519         for splay_each(edge_t, e, n->edge_tree) {
520                 if(i++ == j) {
521                         candidate = e->reverse;
522                         break;
523                 }
524         }
525
526         if(candidate) {
527                 *sa = &candidate->address;
528                 *sock = rand() % listen_sockets;
529         }
530
531         /* Make sure we have a suitable socket for the chosen address */
532         if(listen_socket[*sock].sa.sa.sa_family != (*sa)->sa.sa_family) {
533                 for(int i = 0; i < listen_sockets; i++) {
534                         if(listen_socket[i].sa.sa.sa_family == (*sa)->sa.sa_family) {
535                                 *sock = i;
536                                 break;
537                         }
538                 }
539         }
540 }
541
542 static void choose_broadcast_address(const node_t *n, const sockaddr_t **sa, int *sock) {
543         static sockaddr_t broadcast_ipv4 = {
544                 .in = {
545                         .sin_family = AF_INET,
546                         .sin_addr.s_addr = -1,
547                 }
548         };
549
550         static sockaddr_t broadcast_ipv6 = {
551                 .in6 = {
552                         .sin6_family = AF_INET6,
553                         .sin6_addr.s6_addr[0x0] = 0xff,
554                         .sin6_addr.s6_addr[0x1] = 0x02,
555                         .sin6_addr.s6_addr[0xf] = 0x01,
556                 }
557         };
558
559         *sock = rand() % listen_sockets;
560
561         if(listen_socket[*sock].sa.sa.sa_family == AF_INET6) {
562                 broadcast_ipv6.in6.sin6_port = n->prevedge->address.in.sin_port;
563                 broadcast_ipv6.in6.sin6_scope_id = listen_socket[*sock].sa.in6.sin6_scope_id;
564                 *sa = &broadcast_ipv6;
565         } else {
566                 broadcast_ipv4.in.sin_port = n->prevedge->address.in.sin_port;
567                 *sa = &broadcast_ipv4;
568         }
569 }
570
571 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
572         vpn_packet_t pkt1, pkt2;
573         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
574         vpn_packet_t *inpkt = origpkt;
575         int nextpkt = 0;
576         vpn_packet_t *outpkt;
577         int origlen = origpkt->len;
578         size_t outlen;
579 #if defined(SOL_IP) && defined(IP_TOS)
580         static int priority = 0;
581 #endif
582         int origpriority = origpkt->priority;
583
584         if(!n->status.reachable) {
585                 logger(DEBUG_TRAFFIC, LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname);
586                 return;
587         }
588
589         if(n->status.sptps)
590                 return send_sptps_packet(n, origpkt);
591
592         /* Make sure we have a valid key */
593
594         if(!n->status.validkey) {
595                 logger(DEBUG_TRAFFIC, LOG_INFO,
596                                    "No valid key known yet for %s (%s), forwarding via TCP",
597                                    n->name, n->hostname);
598
599                 if(n->last_req_key + 10 <= now.tv_sec) {
600                         send_req_key(n);
601                         n->last_req_key = now.tv_sec;
602                 }
603
604                 send_tcppacket(n->nexthop->connection, origpkt);
605
606                 return;
607         }
608
609         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
610                 logger(DEBUG_TRAFFIC, LOG_INFO,
611                                 "Packet for %s (%s) larger than minimum MTU, forwarding via %s",
612                                 n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP");
613
614                 if(n != n->nexthop)
615                         send_packet(n->nexthop, origpkt);
616                 else
617                         send_tcppacket(n->nexthop->connection, origpkt);
618
619                 return;
620         }
621
622         /* Compress the packet */
623
624         if(n->outcompression) {
625                 outpkt = pkt[nextpkt++];
626
627                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
628                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while compressing packet to %s (%s)",
629                                    n->name, n->hostname);
630                         return;
631                 }
632
633                 inpkt = outpkt;
634         }
635
636         /* Add sequence number */
637
638         inpkt->seqno = htonl(++(n->sent_seqno));
639         inpkt->len += sizeof inpkt->seqno;
640
641         /* Encrypt the packet */
642
643         if(cipher_active(&n->outcipher)) {
644                 outpkt = pkt[nextpkt++];
645                 outlen = MAXSIZE;
646
647                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
648                         logger(DEBUG_TRAFFIC, LOG_ERR, "Error while encrypting packet to %s (%s)", n->name, n->hostname);
649                         goto end;
650                 }
651
652                 outpkt->len = outlen;
653                 inpkt = outpkt;
654         }
655
656         /* Add the message authentication code */
657
658         if(digest_active(&n->outdigest)) {
659                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
660                 inpkt->len += digest_length(&n->outdigest);
661         }
662
663         /* Send the packet */
664
665         const sockaddr_t *sa;
666         int sock;
667
668         /* Overloaded use of priority field: -1 means local broadcast */
669
670         if(origpriority == -1 && n->prevedge)
671                 choose_broadcast_address(n, &sa, &sock);
672         else
673                 choose_udp_address(n, &sa, &sock);
674
675 #if defined(SOL_IP) && defined(IP_TOS)
676         if(priorityinheritance && origpriority != priority
677            && listen_socket[n->sock].sa.sa.sa_family == AF_INET) {
678                 priority = origpriority;
679                 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Setting outgoing packet priority to %d", priority);
680                 if(setsockopt(listen_socket[n->sock].udp.fd, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
681                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno));
682         }
683 #endif
684
685         if(sendto(listen_socket[sock].udp.fd, (char *) &inpkt->seqno, inpkt->len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
686                 if(sockmsgsize(sockerrno)) {
687                         if(n->maxmtu >= origlen)
688                                 n->maxmtu = origlen - 1;
689                         if(n->mtu >= origlen)
690                                 n->mtu = origlen - 1;
691                 } else
692                         logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno));
693         }
694
695 end:
696         origpkt->len = origlen;
697 }
698
699 bool send_sptps_data(void *handle, uint8_t type, const char *data, size_t len) {
700         node_t *to = handle;
701
702         /* Send it via TCP if it is a handshake packet, TCPOnly is in use, or this packet is larger than the MTU. */
703
704         if(type >= SPTPS_HANDSHAKE || ((myself->options | to->options) & OPTION_TCPONLY) || (type != PKT_PROBE && len > to->minmtu)) {
705                 char buf[len * 4 / 3 + 5];
706                 b64encode(data, buf, len);
707                 /* If no valid key is known yet, send the packets using ANS_KEY requests,
708                    to ensure we get to learn the reflexive UDP address. */
709                 if(!to->status.validkey)
710                         return send_request(to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, myself->name, to->name, buf, myself->incompression);
711                 else
712                         return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, to->name, REQ_SPTPS, buf);
713         }
714
715         /* Otherwise, send the packet via UDP */
716
717         const sockaddr_t *sa;
718         int sock;
719
720         choose_udp_address(to, &sa, &sock);
721
722         if(sendto(listen_socket[sock].udp.fd, data, len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
723                 if(sockmsgsize(sockerrno)) {
724                         if(to->maxmtu >= len)
725                                 to->maxmtu = len - 1;
726                         if(to->mtu >= len)
727                                 to->mtu = len - 1;
728                 } else {
729                         logger(DEBUG_TRAFFIC, LOG_WARNING, "Error sending UDP SPTPS packet to %s (%s): %s", to->name, to->hostname, sockstrerror(sockerrno));
730                         return false;
731                 }
732         }
733
734         return true;
735 }
736
737 bool receive_sptps_record(void *handle, uint8_t type, const char *data, uint16_t len) {
738         node_t *from = handle;
739
740         if(type == SPTPS_HANDSHAKE) {
741                 if(!from->status.validkey) {
742                         from->status.validkey = true;
743                         from->status.waitingforkey = false;
744                         logger(DEBUG_META, LOG_INFO, "SPTPS key exchange with %s (%s) succesful", from->name, from->hostname);
745                 }
746                 return true;
747         }
748
749         if(len > MTU) {
750                 logger(DEBUG_ALWAYS, LOG_ERR, "Packet from %s (%s) larger than maximum supported size (%d > %d)", from->name, from->hostname, len, MTU);
751                 return false;
752         }
753
754         vpn_packet_t inpkt;
755
756         if(type == PKT_PROBE) {
757                 inpkt.len = len;
758                 memcpy(inpkt.data, data, len);
759                 mtu_probe_h(from, &inpkt, len);
760                 return true;
761         }
762
763         if(type & ~(PKT_COMPRESSED | PKT_MAC)) {
764                 logger(DEBUG_ALWAYS, LOG_ERR, "Unexpected SPTPS record type %d len %d from %s (%s)", type, len, from->name, from->hostname);
765                 return false;
766         }
767
768         /* Check if we have the headers we need */
769         if(routing_mode != RMODE_ROUTER && !(type & PKT_MAC)) {
770                 logger(DEBUG_TRAFFIC, LOG_ERR, "Received packet from %s (%s) without MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
771                 return false;
772         } else if(routing_mode == RMODE_ROUTER && (type & PKT_MAC)) {
773                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Received packet from %s (%s) with MAC header (maybe Mode is not set correctly)", from->name, from->hostname);
774         }
775
776         int offset = (type & PKT_MAC) ? 0 : 14;
777         if(type & PKT_COMPRESSED) {
778                 length_t ulen = uncompress_packet(inpkt.data + offset, (const uint8_t *)data, len, from->incompression);
779                 if(ulen < 0) {
780                         return false;
781                 } else {
782                         inpkt.len = ulen + offset;
783                 }
784                 if(inpkt.len > MAXSIZE)
785                         abort();
786         } else {
787                 memcpy(inpkt.data + offset, data, len);
788                 inpkt.len = len + offset;
789         }
790
791         /* Generate the Ethernet packet type if necessary */
792         if(offset) {
793                 switch(inpkt.data[14] >> 4) {
794                         case 4:
795                                 inpkt.data[12] = 0x08;
796                                 inpkt.data[13] = 0x00;
797                                 break;
798                         case 6:
799                                 inpkt.data[12] = 0x86;
800                                 inpkt.data[13] = 0xDD;
801                                 break;
802                         default:
803                                 logger(DEBUG_TRAFFIC, LOG_ERR,
804                                                    "Unknown IP version %d while reading packet from %s (%s)",
805                                                    inpkt.data[14] >> 4, from->name, from->hostname);
806                                 return false;
807                 }
808         }
809
810         receive_packet(from, &inpkt);
811         return true;
812 }
813
814 /*
815   send a packet to the given vpn ip.
816 */
817 void send_packet(node_t *n, vpn_packet_t *packet) {
818         node_t *via;
819
820         if(n == myself) {
821                 if(overwrite_mac)
822                          memcpy(packet->data, mymac.x, ETH_ALEN);
823                 n->out_packets++;
824                 n->out_bytes += packet->len;
825                 devops.write(packet);
826                 return;
827         }
828
829         logger(DEBUG_TRAFFIC, LOG_ERR, "Sending packet of %d bytes to %s (%s)",
830                            packet->len, n->name, n->hostname);
831
832         if(!n->status.reachable) {
833                 logger(DEBUG_TRAFFIC, LOG_INFO, "Node %s (%s) is not reachable",
834                                    n->name, n->hostname);
835                 return;
836         }
837
838         n->out_packets++;
839         n->out_bytes += packet->len;
840
841         if(n->status.sptps) {
842                 send_sptps_packet(n, packet);
843                 return;
844         }
845
846         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
847
848         if(via != n)
849                 logger(DEBUG_TRAFFIC, LOG_INFO, "Sending packet to %s via %s (%s)",
850                            n->name, via->name, n->via->hostname);
851
852         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
853                 if(!send_tcppacket(via->connection, packet))
854                         terminate_connection(via->connection, true);
855         } else
856                 send_udppacket(via, packet);
857 }
858
859 /* Broadcast a packet using the minimum spanning tree */
860
861 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
862         // Always give ourself a copy of the packet.
863         if(from != myself)
864                 send_packet(myself, packet);
865
866         // In TunnelServer mode, do not forward broadcast packets.
867         // The MST might not be valid and create loops.
868         if(tunnelserver || broadcast_mode == BMODE_NONE)
869                 return;
870
871         logger(DEBUG_TRAFFIC, LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)",
872                            packet->len, from->name, from->hostname);
873
874         switch(broadcast_mode) {
875                 // In MST mode, broadcast packets travel via the Minimum Spanning Tree.
876                 // This guarantees all nodes receive the broadcast packet, and
877                 // usually distributes the sending of broadcast packets over all nodes.
878                 case BMODE_MST:
879                         for list_each(connection_t, c, connection_list)
880                                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
881                                         send_packet(c->node, packet);
882                         break;
883
884                 // In direct mode, we send copies to each node we know of.
885                 // However, this only reaches nodes that can be reached in a single hop.
886                 // We don't have enough information to forward broadcast packets in this case.
887                 case BMODE_DIRECT:
888                         if(from != myself)
889                                 break;
890
891                         for splay_each(node_t, n, node_tree)
892                                 if(n->status.reachable && ((n->via == myself && n->nexthop == n) || n->via == n))
893                                         send_packet(n, packet);
894                         break;
895
896                 default:
897                         break;
898         }
899 }
900
901 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
902         node_t *n = NULL;
903         bool hard = false;
904         static time_t last_hard_try = 0;
905
906         for splay_each(edge_t, e, edge_weight_tree) {
907                 if(!e->to->status.reachable || e->to == myself)
908                         continue;
909
910                 if(sockaddrcmp_noport(from, &e->address)) {
911                         if(last_hard_try == now.tv_sec)
912                                 continue;
913                         hard = true;
914                 }
915
916                 if(!try_mac(e->to, pkt))
917                         continue;
918
919                 n = e->to;
920                 break;
921         }
922
923         if(hard)
924                 last_hard_try = now.tv_sec;
925
926         last_hard_try = now.tv_sec;
927         return n;
928 }
929
930 void handle_incoming_vpn_data(void *data, int flags) {
931         listen_socket_t *ls = data;
932         vpn_packet_t pkt;
933         char *hostname;
934         sockaddr_t from = {{0}};
935         socklen_t fromlen = sizeof from;
936         node_t *n;
937         int len;
938
939         len = recvfrom(ls->udp.fd, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
940
941         if(len <= 0 || len > MAXSIZE) {
942                 if(!sockwouldblock(sockerrno))
943                         logger(DEBUG_ALWAYS, LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno));
944                 return;
945         }
946
947         pkt.len = len;
948
949         sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
950
951         n = lookup_node_udp(&from);
952
953         if(!n) {
954                 n = try_harder(&from, &pkt);
955                 if(n)
956                         update_node_udp(n, &from);
957                 else if(debug_level >= DEBUG_PROTOCOL) {
958                         hostname = sockaddr2hostname(&from);
959                         logger(DEBUG_PROTOCOL, LOG_WARNING, "Received UDP packet from unknown source %s", hostname);
960                         free(hostname);
961                         return;
962                 }
963                 else
964                         return;
965         }
966
967         n->sock = ls - listen_socket;
968
969         receive_udppacket(n, &pkt);
970 }
971
972 void handle_device_data(void *data, int flags) {
973         vpn_packet_t packet;
974
975         packet.priority = 0;
976
977         if(devops.read(&packet)) {
978                 myself->in_packets++;
979                 myself->in_bytes += packet.len;
980                 route(myself, &packet);
981         }
982 }