Add a better autoconf check for libevent.
[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-2009 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id$
21 */
22
23 #include "system.h"
24
25 #include <zlib.h>
26 #include LZO1X_H
27
28 #include "splay_tree.h"
29 #include "cipher.h"
30 #include "conf.h"
31 #include "connection.h"
32 #include "crypto.h"
33 #include "digest.h"
34 #include "device.h"
35 #include "ethernet.h"
36 #include "graph.h"
37 #include "list.h"
38 #include "logger.h"
39 #include "net.h"
40 #include "netutl.h"
41 #include "protocol.h"
42 #include "process.h"
43 #include "route.h"
44 #include "utils.h"
45 #include "xalloc.h"
46
47 #ifdef WSAEMSGSIZE
48 #define EMSGSIZE WSAEMSGSIZE
49 #endif
50
51 int keylifetime = 0;
52 int keyexpires = 0;
53 static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS];
54
55 static void send_udppacket(node_t *, vpn_packet_t *);
56
57 #define MAX_SEQNO 1073741824
58
59 static void send_mtu_probe_handler(int fd, short events, void *data) {
60         node_t *n = data;
61         vpn_packet_t packet;
62         int len, i;
63         
64         cp();
65
66         n->mtuprobes++;
67
68         if(!n->status.reachable) {
69                 logger(LOG_DEBUG, _("Trying to send MTU probe to unreachable node %s (%s)"), n->name, n->hostname);
70                 return;
71         }
72
73         if(n->mtuprobes >= 10 && !n->minmtu) {
74                 ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname);
75                 return;
76         }
77
78         for(i = 0; i < 3; i++) {
79                 if(n->mtuprobes >= 30 || n->minmtu >= n->maxmtu) {
80                         n->mtu = n->minmtu;
81                         ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
82                         return;
83                 }
84
85                 len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
86                 if(len < 64)
87                         len = 64;
88                 
89                 memset(packet.data, 0, 14);
90                 randomize(packet.data + 14, len - 14);
91                 packet.len = len;
92                 packet.priority = 0;
93
94                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending MTU probe length %d to %s (%s)"), len, n->name, n->hostname);
95
96                 send_udppacket(n, &packet);
97         }
98
99         event_add(&n->mtuevent, &(struct timeval){1, 0});
100 }
101
102 void send_mtu_probe(node_t *n) {
103         if(!timeout_initialized(&n->mtuevent))
104                 timeout_set(&n->mtuevent, send_mtu_probe_handler, n);
105         send_mtu_probe_handler(0, 0, n);
106 }
107
108 void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) {
109         ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
110
111         if(!packet->data[0]) {
112                 packet->data[0] = 1;
113                 send_packet(n, packet);
114         } else {
115                 if(n->minmtu < len)
116                         n->minmtu = len;
117         }
118 }
119
120 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
121         if(level == 10) {
122                 lzo_uint lzolen = MAXSIZE;
123                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
124                 return lzolen;
125         } else if(level < 10) {
126                 unsigned long destlen = MAXSIZE;
127                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
128                         return destlen;
129                 else
130                         return -1;
131         } else {
132                 lzo_uint lzolen = MAXSIZE;
133                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
134                 return lzolen;
135         }
136         
137         return -1;
138 }
139
140 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) {
141         if(level > 9) {
142                 lzo_uint lzolen = MAXSIZE;
143                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
144                         return lzolen;
145                 else
146                         return -1;
147         } else {
148                 unsigned long destlen = MAXSIZE;
149                 if(uncompress(dest, &destlen, source, len) == Z_OK)
150                         return destlen;
151                 else
152                         return -1;
153         }
154         
155         return -1;
156 }
157
158 /* VPN packet I/O */
159
160 static void receive_packet(node_t *n, vpn_packet_t *packet) {
161         cp();
162
163         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
164                            packet->len, n->name, n->hostname);
165
166         route(n, packet);
167 }
168
169 static bool try_mac(node_t *n, const vpn_packet_t *inpkt)
170 {
171         if(!digest_active(&n->indigest) || inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest))
172                 return false;
173
174         return digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len);
175 }
176
177 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
178 {
179         vpn_packet_t pkt1, pkt2;
180         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
181         int nextpkt = 0;
182         vpn_packet_t *outpkt = pkt[0];
183         size_t outlen;
184         int i;
185
186         cp();
187
188         if(!cipher_active(&n->incipher)) {
189                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got packet from %s (%s) but he hasn't got our key yet"),
190                                         n->name, n->hostname);
191                 return;
192         }
193
194         /* Check packet length */
195
196         if(inpkt->len < sizeof inpkt->seqno + digest_length(&n->indigest)) {
197                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
198                                         n->name, n->hostname);
199                 return;
200         }
201
202         /* Check the message authentication code */
203
204         if(digest_active(&n->indigest) && !digest_verify(&n->indigest, &inpkt->seqno, inpkt->len, (const char *)&inpkt->seqno + inpkt->len)) {
205                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"), n->name, n->hostname);
206                 return;
207         }
208
209         /* Decrypt the packet */
210
211         if(cipher_active(&n->incipher)) {
212                 outpkt = pkt[nextpkt++];
213                 outlen = MAXSIZE;
214
215                 if(!cipher_decrypt(&n->incipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
216                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s)"), n->name, n->hostname);
217                         return;
218                 }
219                 
220                 outpkt->len = outlen;
221                 inpkt = outpkt;
222         }
223
224         /* Check the sequence number */
225
226         inpkt->len -= sizeof inpkt->seqno;
227         inpkt->seqno = ntohl(inpkt->seqno);
228
229         if(inpkt->seqno != n->received_seqno + 1) {
230                 if(inpkt->seqno >= n->received_seqno + sizeof n->late * 8) {
231                         logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
232                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
233                         
234                         memset(n->late, 0, sizeof n->late);
235                 } else if (inpkt->seqno <= n->received_seqno) {
236                         if((n->received_seqno >= sizeof n->late * 8 && inpkt->seqno <= n->received_seqno - sizeof n->late * 8) || !(n->late[(inpkt->seqno / 8) % sizeof n->late] & (1 << inpkt->seqno % 8))) {
237                                 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
238                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
239                                 return;
240                         }
241                 } else {
242                         for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
243                                 n->late[(i / 8) % sizeof n->late] |= 1 << i % 8;
244                 }
245         }
246         
247         n->late[(inpkt->seqno / 8) % sizeof n->late] &= ~(1 << inpkt->seqno % 8);
248
249         if(inpkt->seqno > n->received_seqno)
250                 n->received_seqno = inpkt->seqno;
251                         
252         if(n->received_seqno > MAX_SEQNO)
253                 regenerate_key();
254
255         /* Decompress the packet */
256
257         length_t origlen = inpkt->len;
258
259         if(n->incompression) {
260                 outpkt = pkt[nextpkt++];
261
262                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) {
263                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
264                                                  n->name, n->hostname);
265                         return;
266                 }
267
268                 inpkt = outpkt;
269
270                 origlen -= MTU/64 + 20;
271         }
272
273         inpkt->priority = 0;
274
275         if(!inpkt->data[12] && !inpkt->data[13])
276                 mtu_probe_h(n, inpkt, origlen);
277         else
278                 receive_packet(n, inpkt);
279 }
280
281 void receive_tcppacket(connection_t *c, char *buffer, int len) {
282         vpn_packet_t outpkt;
283
284         cp();
285
286         outpkt.len = len;
287         if(c->options & OPTION_TCPONLY)
288                 outpkt.priority = 0;
289         else
290                 outpkt.priority = -1;
291         memcpy(outpkt.data, buffer, len);
292
293         receive_packet(c->node, &outpkt);
294 }
295
296 static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
297         vpn_packet_t pkt1, pkt2;
298         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
299         vpn_packet_t *inpkt = origpkt;
300         int nextpkt = 0;
301         vpn_packet_t *outpkt;
302         int origlen;
303         size_t outlen;
304         static int priority = 0;
305         int origpriority;
306         int sock;
307
308         cp();
309
310         if(!n->status.reachable) {
311                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Trying to send UDP packet to unreachable node %s (%s)"), n->name, n->hostname);
312                 return;
313         }
314
315         /* Make sure we have a valid key */
316
317         if(!n->status.validkey) {
318                 ifdebug(TRAFFIC) logger(LOG_INFO,
319                                    _("No valid key known yet for %s (%s), forwarding via TCP"),
320                                    n->name, n->hostname);
321
322                 if(!n->status.waitingforkey)
323                         send_req_key(n);
324
325                 n->status.waitingforkey = true;
326
327                 send_tcppacket(n->nexthop->connection, origpkt);
328
329                 return;
330         }
331
332         if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) {
333                 ifdebug(TRAFFIC) logger(LOG_INFO,
334                                 _("Packet for %s (%s) larger than minimum MTU, forwarding via TCP"),
335                                 n->name, n->hostname);
336
337                 send_tcppacket(n->nexthop->connection, origpkt);
338
339                 return;
340         }
341
342         origlen = inpkt->len;
343         origpriority = inpkt->priority;
344
345         /* Compress the packet */
346
347         if(n->outcompression) {
348                 outpkt = pkt[nextpkt++];
349
350                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) {
351                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
352                                    n->name, n->hostname);
353                         return;
354                 }
355
356                 inpkt = outpkt;
357         }
358
359         /* Add sequence number */
360
361         inpkt->seqno = htonl(++(n->sent_seqno));
362         inpkt->len += sizeof inpkt->seqno;
363
364         /* Encrypt the packet */
365
366         if(cipher_active(&n->outcipher)) {
367                 outpkt = pkt[nextpkt++];
368                 outlen = MAXSIZE;
369
370                 if(!cipher_encrypt(&n->outcipher, &inpkt->seqno, inpkt->len, &outpkt->seqno, &outlen, true)) {
371                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s)"), n->name, n->hostname);
372                         goto end;
373                 }
374
375                 outpkt->len = outlen;
376                 inpkt = outpkt;
377         }
378
379         /* Add the message authentication code */
380
381         if(digest_active(&n->outdigest)) {
382                 digest_create(&n->outdigest, &inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len);
383                 inpkt->len += digest_length(&n->outdigest);
384         }
385
386         /* Determine which socket we have to use */
387
388         for(sock = 0; sock < listen_sockets; sock++)
389                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
390                         break;
391
392         if(sock >= listen_sockets)
393                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
394
395         /* Send the packet */
396
397 #if defined(SOL_IP) && defined(IP_TOS)
398         if(priorityinheritance && origpriority != priority
399            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
400                 priority = origpriority;
401                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
402                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof priority))     /* SO_PRIORITY doesn't seem to work */
403                         logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
404         }
405 #endif
406
407         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
408                 if(errno == EMSGSIZE) {
409                         if(n->maxmtu >= origlen)
410                                 n->maxmtu = origlen - 1;
411                         if(n->mtu >= origlen)
412                                 n->mtu = origlen - 1;
413                 } else
414                         logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
415         }
416
417 end:
418         origpkt->len = origlen;
419 }
420
421 /*
422   send a packet to the given vpn ip.
423 */
424 void send_packet(const node_t *n, vpn_packet_t *packet) {
425         node_t *via;
426
427         cp();
428
429         if(n == myself) {
430                 if(overwrite_mac)
431                          memcpy(packet->data, mymac.x, ETH_ALEN);
432                 write_packet(packet);
433                 return;
434         }
435
436         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
437                            packet->len, n->name, n->hostname);
438
439         if(!n->status.reachable) {
440                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
441                                    n->name, n->hostname);
442                 return;
443         }
444
445         via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via;
446
447         if(via != n)
448                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending packet to %s via %s (%s)"),
449                            n->name, via->name, n->via->hostname);
450
451         if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) {
452                 if(!send_tcppacket(via->connection, packet))
453                         terminate_connection(via->connection, true);
454         } else
455                 send_udppacket(via, packet);
456 }
457
458 /* Broadcast a packet using the minimum spanning tree */
459
460 void broadcast_packet(const node_t *from, vpn_packet_t *packet) {
461         splay_node_t *node;
462         connection_t *c;
463
464         cp();
465
466         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
467                            packet->len, from->name, from->hostname);
468
469         if(from != myself) {
470                 send_packet(myself, packet);
471
472                 // In TunnelServer mode, do not forward broadcast packets.
473                 // The MST might not be valid and create loops.
474                 if(tunnelserver)
475                         return;
476         }
477
478         for(node = connection_tree->head; node; node = node->next) {
479                 c = node->data;
480
481                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
482                         send_packet(c->node, packet);
483         }
484 }
485
486 static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) {
487         splay_node_t *node;
488         edge_t *e;
489         node_t *n = NULL;
490
491         for(node = edge_weight_tree->head; node; node = node->next) {
492                 e = node->data;
493
494                 if(sockaddrcmp_noport(from, &e->address))
495                         continue;
496
497                 if(!n)
498                         n = e->to;
499
500                 if(!try_mac(e->to, pkt))
501                         continue;
502
503                 n = e->to;
504                 break;
505         }
506
507         return n;
508 }
509
510 void handle_incoming_vpn_data(int sock, short events, void *data)
511 {
512         vpn_packet_t pkt;
513         char *hostname;
514         sockaddr_t from;
515         socklen_t fromlen = sizeof from;
516         node_t *n;
517
518         cp();
519
520         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
521
522         if(pkt.len < 0) {
523                 if(errno != EAGAIN && errno != EINTR)
524                         logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
525                 return;
526         }
527
528         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
529
530         n = lookup_node_udp(&from);
531
532         if(!n) {
533                 n = try_harder(&from, &pkt);
534                 if(n)
535                         update_node_udp(n, &from);
536                 else ifdebug(PROTOCOL) {
537                         hostname = sockaddr2hostname(&from);
538                         logger(LOG_WARNING, _("Received UDP packet from unknown source %s"), hostname);
539                         free(hostname);
540                         return;
541                 }
542                 else
543                         return;
544         }
545
546         receive_udppacket(n, &pkt);
547 }
548
549 void handle_device_data(int sock, short events, void *data) {
550         vpn_packet_t packet;
551
552         if(read_packet(&packet))
553                 route(myself, &packet);
554 }