Let tinc figure out the exact MTU of the link.
[tinc] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2003 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2003 Guus Sliepen <guus@sliepen.eu.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: net_packet.c,v 1.1.2.45 2003/12/20 19:47:52 guus Exp $
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 #include <zlib.h>
32 #include <lzo1x.h>
33
34 #include "avl_tree.h"
35 #include "conf.h"
36 #include "connection.h"
37 #include "device.h"
38 #include "event.h"
39 #include "graph.h"
40 #include "list.h"
41 #include "logger.h"
42 #include "net.h"
43 #include "netutl.h"
44 #include "protocol.h"
45 #include "process.h"
46 #include "route.h"
47 #include "utils.h"
48 #include "xalloc.h"
49
50 int keylifetime = 0;
51 int keyexpires = 0;
52 EVP_CIPHER_CTX packet_ctx;
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 void send_mtu_probe(node_t *n)
60 {
61         vpn_packet_t packet;
62         int len, i;
63         
64         cp();
65
66         n->mtuprobes++;
67
68         for(i = 0; i < 3; i++) {
69                 if(n->mtuprobes >= 100 || n->probedmtu >= n->mtu) {
70                         n->mtu = n->probedmtu;
71                         ifdebug(TRAFFIC) logger(LOG_INFO, _("Fixing MTU of %s (%s) to %d after %d probes"), n->name, n->hostname, n->mtu, n->mtuprobes);
72                         return;
73                 }
74
75                 len = n->probedmtu + 1 + random() % (n->mtu - n->probedmtu);
76                 if(len < 64)
77                         len = 64;
78                 
79                 memset(packet.data, 0, 14);
80                 RAND_pseudo_bytes(packet.data + 14, len - 14);
81                 packet.len = len;
82
83                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Sending MTU probe length %d to %s (%s)"), len, n->name, n->hostname);
84
85                 send_udppacket(n, &packet);
86         }
87
88         n->mtuevent = xmalloc(sizeof(*n->mtuevent));
89         n->mtuevent->handler = (event_handler_t)send_mtu_probe;
90         n->mtuevent->data = n;
91         n->mtuevent->time = now + 1;
92         event_add(n->mtuevent);
93 }
94
95 void mtu_probe_h(node_t *n, vpn_packet_t *packet) {
96         ifdebug(TRAFFIC) logger(LOG_INFO, _("Got MTU probe length %d from %s (%s)"), packet->len, n->name, n->hostname);
97
98         if(!packet->data[0]) {
99                 packet->data[0] = 1;
100                 send_packet(n, packet);
101         } else {
102                 if(n->probedmtu < packet->len)
103                         n->probedmtu = packet->len;
104         }
105 }
106
107 static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
108 {
109         if(level == 10) {
110                 lzo_uint lzolen = MAXSIZE;
111                 lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem);
112                 return lzolen;
113         } else if(level < 10) {
114                 unsigned long destlen = MAXSIZE;
115                 if(compress2(dest, &destlen, source, len, level) == Z_OK)
116                         return destlen;
117                 else
118                         return -1;
119         } else {
120                 lzo_uint lzolen = MAXSIZE;
121                 lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem);
122                 return lzolen;
123         }
124         
125         return -1;
126 }
127
128 static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level)
129 {
130         if(level > 9) {
131                 lzo_uint lzolen = MAXSIZE;
132                 if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK)
133                         return lzolen;
134                 else
135                         return -1;
136         } else {
137                 unsigned long destlen = MAXSIZE;
138                 if(uncompress(dest, &destlen, source, len) == Z_OK)
139                         return destlen;
140                 else
141                         return -1;
142         }
143         
144         return -1;
145 }
146
147 /* VPN packet I/O */
148
149 static void receive_packet(node_t *n, vpn_packet_t *packet)
150 {
151         cp();
152
153         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"),
154                            packet->len, n->name, n->hostname);
155
156         route(n, packet);
157 }
158
159 static void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
160 {
161         vpn_packet_t pkt1, pkt2;
162         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
163         int nextpkt = 0;
164         vpn_packet_t *outpkt = pkt[0];
165         int outlen, outpad;
166         char hmac[EVP_MAX_MD_SIZE];
167         int i;
168
169         cp();
170
171         /* Check packet length */
172
173         if(inpkt->len < sizeof(inpkt->seqno) + myself->maclength) {
174                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got too short packet from %s (%s)"),
175                                         n->name, n->hostname);
176                 return;
177         }
178
179         /* Check the message authentication code */
180
181         if(myself->digest && myself->maclength) {
182                 inpkt->len -= myself->maclength;
183                 HMAC(myself->digest, myself->key, myself->keylength,
184                          (char *) &inpkt->seqno, inpkt->len, hmac, NULL);
185
186                 if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, myself->maclength)) {
187                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"),
188                                            n->name, n->hostname);
189                         return;
190                 }
191         }
192
193         /* Decrypt the packet */
194
195         if(myself->cipher) {
196                 outpkt = pkt[nextpkt++];
197
198                 if(!EVP_DecryptInit_ex(&packet_ctx, NULL, NULL, NULL, NULL)
199                                 || !EVP_DecryptUpdate(&packet_ctx, (char *) &outpkt->seqno, &outlen,
200                                         (char *) &inpkt->seqno, inpkt->len)
201                                 || !EVP_DecryptFinal_ex(&packet_ctx, (char *) &outpkt->seqno + outlen, &outpad)) {
202                         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Error decrypting packet from %s (%s): %s"),
203                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
204                         return;
205                 }
206                 
207                 outpkt->len = outlen + outpad;
208                 inpkt = outpkt;
209         }
210
211         /* Check the sequence number */
212
213         inpkt->len -= sizeof(inpkt->seqno);
214         inpkt->seqno = ntohl(inpkt->seqno);
215
216         if(inpkt->seqno != n->received_seqno + 1) {
217                 if(inpkt->seqno >= n->received_seqno + sizeof(n->late) * 8) {
218                         logger(LOG_WARNING, _("Lost %d packets from %s (%s)"),
219                                            inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
220                         
221                         memset(n->late, 0, sizeof(n->late));
222                 } else if (inpkt->seqno <= n->received_seqno) {
223                         if(inpkt->seqno <= n->received_seqno - sizeof(n->late) * 8 || !(n->late[(inpkt->seqno / 8) % sizeof(n->late)] & (1 << inpkt->seqno % 8))) {
224                                 logger(LOG_WARNING, _("Got late or replayed packet from %s (%s), seqno %d, last received %d"),
225                                            n->name, n->hostname, inpkt->seqno, n->received_seqno);
226                         } else
227                                 for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
228                                         n->late[(inpkt->seqno / 8) % sizeof(n->late)] |= 1 << i % 8;
229                 }
230         }
231         
232         n->received_seqno = inpkt->seqno;
233         n->late[(n->received_seqno / 8) % sizeof(n->late)] &= ~(1 << n->received_seqno % 8);
234                         
235         if(n->received_seqno > MAX_SEQNO)
236                 keyexpires = 0;
237
238         /* Decompress the packet */
239
240         if(myself->compression) {
241                 outpkt = pkt[nextpkt++];
242
243                 if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, myself->compression)) < 0) {
244                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while uncompressing packet from %s (%s)"),
245                                                  n->name, n->hostname);
246                         return;
247                 }
248
249                 inpkt = outpkt;
250         }
251
252         if(n->connection)
253                 n->connection->last_ping_time = now;
254
255         if(!inpkt->data[12] && !inpkt->data[13])
256                 mtu_probe_h(n, inpkt);
257         else
258                 receive_packet(n, inpkt);
259 }
260
261 void receive_tcppacket(connection_t *c, char *buffer, int len)
262 {
263         vpn_packet_t outpkt;
264
265         cp();
266
267         outpkt.len = len;
268         memcpy(outpkt.data, buffer, len);
269
270         receive_packet(c->node, &outpkt);
271 }
272
273 static void send_udppacket(node_t *n, vpn_packet_t *inpkt)
274 {
275         vpn_packet_t pkt1, pkt2;
276         vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
277         int nextpkt = 0;
278         vpn_packet_t *outpkt;
279         int origlen;
280         int outlen, outpad;
281         vpn_packet_t *copy;
282         static int priority = 0;
283         int origpriority;
284         int sock;
285
286         cp();
287
288         /* Make sure we have a valid key */
289
290         if(!n->status.validkey) {
291                 ifdebug(TRAFFIC) logger(LOG_INFO,
292                                    _("No valid key known yet for %s (%s), queueing packet"),
293                                    n->name, n->hostname);
294
295                 /* Since packet is on the stack of handle_tap_input(), we have to make a copy of it first. */
296
297                 *(copy = xmalloc(sizeof(*copy))) = *inpkt;
298
299                 list_insert_tail(n->queue, copy);
300
301                 if(n->queue->count > MAXQUEUELENGTH)
302                         list_delete_head(n->queue);
303
304                 if(!n->status.waitingforkey)
305                         send_req_key(n->nexthop->connection, myself, n);
306
307                 n->status.waitingforkey = true;
308
309                 return;
310         }
311
312         origlen = inpkt->len;
313         origpriority = inpkt->priority;
314
315         /* Compress the packet */
316
317         if(n->compression) {
318                 outpkt = pkt[nextpkt++];
319
320                 if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->compression)) < 0) {
321                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while compressing packet to %s (%s)"),
322                                    n->name, n->hostname);
323                         return;
324                 }
325
326                 inpkt = outpkt;
327         }
328
329         /* Add sequence number */
330
331         inpkt->seqno = htonl(++(n->sent_seqno));
332         inpkt->len += sizeof(inpkt->seqno);
333
334         /* Encrypt the packet */
335
336         if(n->cipher) {
337                 outpkt = pkt[nextpkt++];
338
339                 if(!EVP_EncryptInit_ex(&n->packet_ctx, NULL, NULL, NULL, NULL)
340                                 || !EVP_EncryptUpdate(&n->packet_ctx, (char *) &outpkt->seqno, &outlen,
341                                         (char *) &inpkt->seqno, inpkt->len)
342                                 || !EVP_EncryptFinal_ex(&n->packet_ctx, (char *) &outpkt->seqno + outlen, &outpad)) {
343                         ifdebug(TRAFFIC) logger(LOG_ERR, _("Error while encrypting packet to %s (%s): %s"),
344                                                 n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
345                         return;
346                 }
347
348                 outpkt->len = outlen + outpad;
349                 inpkt = outpkt;
350         }
351
352         /* Add the message authentication code */
353
354         if(n->digest && n->maclength) {
355                 HMAC(n->digest, n->key, n->keylength, (char *) &inpkt->seqno,
356                          inpkt->len, (char *) &inpkt->seqno + inpkt->len, &outlen);
357                 inpkt->len += n->maclength;
358         }
359
360         /* Determine which socket we have to use */
361
362         for(sock = 0; sock < listen_sockets; sock++)
363                 if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
364                         break;
365
366         if(sock >= listen_sockets)
367                 sock = 0;                               /* If none is available, just use the first and hope for the best. */
368
369         /* Send the packet */
370
371 #if defined(SOL_IP) && defined(IP_TOS)
372         if(priorityinheritance && origpriority != priority
373            && listen_socket[sock].sa.sa.sa_family == AF_INET) {
374                 priority = origpriority;
375                 ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
376                 if(setsockopt(listen_socket[sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority)))    /* SO_PRIORITY doesn't seem to work */
377                         logger(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
378         }
379 #endif
380
381         if((sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0) {
382                 logger(LOG_ERR, _("Error sending packet to %s (%s): %s"), n->name, n->hostname, strerror(errno));
383                 if(errno == EMSGSIZE) {
384                         if(n->mtu >= origlen)
385                                 n->mtu = origlen - 1;
386                 }
387                 return;
388         }
389
390         inpkt->len = origlen;
391 }
392
393 /*
394   send a packet to the given vpn ip.
395 */
396 void send_packet(const node_t *n, vpn_packet_t *packet)
397 {
398         node_t *via;
399
400         cp();
401
402         if(n == myself) {
403                 write_packet(packet);
404                 return;
405         }
406
407         ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
408                            packet->len, n->name, n->hostname);
409
410         if(!n->status.reachable) {
411                 ifdebug(TRAFFIC) logger(LOG_INFO, _("Node %s (%s) is not reachable"),
412                                    n->name, n->hostname);
413                 return;
414         }
415
416         via = (n->via == myself) ? n->nexthop : n->via;
417
418         if(via != n)
419                 ifdebug(TRAFFIC) logger(LOG_ERR, _("Sending packet to %s via %s (%s)"),
420                            n->name, via->name, n->via->hostname);
421
422         if((myself->options | via->options) & OPTION_TCPONLY) {
423                 if(!send_tcppacket(via->connection, packet))
424                         terminate_connection(via->connection, true);
425         } else
426                 send_udppacket(via, packet);
427 }
428
429 /* Broadcast a packet using the minimum spanning tree */
430
431 void broadcast_packet(const node_t *from, vpn_packet_t *packet)
432 {
433         avl_node_t *node;
434         connection_t *c;
435
436         cp();
437
438         ifdebug(TRAFFIC) logger(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
439                            packet->len, from->name, from->hostname);
440
441         for(node = connection_tree->head; node; node = node->next) {
442                 c = node->data;
443
444                 if(c->status.active && c->status.mst && c != from->nexthop->connection)
445                         send_packet(c->node, packet);
446         }
447 }
448
449 void flush_queue(node_t *n)
450 {
451         list_node_t *node, *next;
452
453         cp();
454
455         ifdebug(TRAFFIC) logger(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
456
457         for(node = n->queue->head; node; node = next) {
458                 next = node->next;
459                 send_udppacket(n, node->data);
460                 list_delete_node(n->queue, node);
461         }
462 }
463
464 void handle_incoming_vpn_data(int sock)
465 {
466         vpn_packet_t pkt;
467         char *hostname;
468         sockaddr_t from;
469         socklen_t fromlen = sizeof(from);
470         node_t *n;
471
472         cp();
473
474         pkt.len = recvfrom(sock, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen);
475
476         if(pkt.len < 0) {
477                 logger(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
478                 return;
479         }
480
481         sockaddrunmap(&from);           /* Some braindead IPv6 implementations do stupid things. */
482
483         n = lookup_node_udp(&from);
484
485         if(!n) {
486                 hostname = sockaddr2hostname(&from);
487                 logger(LOG_WARNING, _("Received UDP packet from unknown source %s"),
488                            hostname);
489                 free(hostname);
490                 return;
491         }
492
493         receive_udppacket(n, &pkt);
494 }