]> git.meshlink.io Git - meshlink/blob - src/net_packet.c
Move the routing header out of the SPTPS payload.
[meshlink] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "conf.h"
23 #include "connection.h"
24 #include "crypto.h"
25 #include "graph.h"
26 #include "logger.h"
27 #include "meshlink_internal.h"
28 #include "net.h"
29 #include "netutl.h"
30 #include "protocol.h"
31 #include "utils.h"
32 #include "xalloc.h"
33
34 int keylifetime = 0;
35
36 static void send_udppacket(meshlink_handle_t *mesh, node_t *, vpn_packet_t *);
37
38 #define MAX_SEQNO 1073741824
39
40 /* mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
41    mtuprobes ==    31: sleep pinginterval seconds
42    mtuprobes ==    32: send 1 burst, sleep pingtimeout second
43    mtuprobes ==    33: no response from other side, restart PMTU discovery process
44
45    Probes are sent in batches of at least three, with random sizes between the
46    lower and upper boundaries for the MTU thus far discovered.
47
48    After the initial discovery, a fourth packet is added to each batch with a
49    size larger than the currently known PMTU, to test if the PMTU has increased.
50
51    In case local discovery is enabled, another packet is added to each batch,
52    which will be broadcast to the local network.
53
54 */
55
56 static void send_mtu_probe_handler(event_loop_t *loop, void *data) {
57         meshlink_handle_t *mesh = loop->data;
58         node_t *n = data;
59         int timeout = 1;
60
61         n->mtuprobes++;
62
63         if(!n->status.reachable || !n->status.validkey) {
64                 logger(mesh, MESHLINK_INFO, "Trying to send MTU probe to unreachable or rekeying node %s", n->name);
65                 n->mtuprobes = 0;
66                 return;
67         }
68
69         if(n->mtuprobes > 32) {
70                 if(!n->minmtu) {
71                         n->mtuprobes = 31;
72                         timeout = mesh->pinginterval;
73                         goto end;
74                 }
75
76                 logger(mesh, MESHLINK_INFO, "%s did not respond to UDP ping, restarting PMTU discovery", n->name);
77                 n->status.udp_confirmed = false;
78                 n->mtuprobes = 1;
79                 n->minmtu = 0;
80                 n->maxmtu = MTU;
81         }
82
83         if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
84                 logger(mesh, MESHLINK_INFO, "No response to MTU probes from %s", n->name);
85                 n->mtuprobes = 31;
86         }
87
88         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
89                 if(n->minmtu > n->maxmtu) {
90                         n->minmtu = n->maxmtu;
91                 } else {
92                         n->maxmtu = n->minmtu;
93                 }
94
95                 n->mtu = n->minmtu;
96                 logger(mesh, MESHLINK_INFO, "Fixing MTU of %s to %d after %d probes", n->name, n->mtu, n->mtuprobes);
97                 n->mtuprobes = 31;
98         }
99
100         if(n->mtuprobes == 31) {
101                 timeout = mesh->pinginterval;
102                 goto end;
103         } else if(n->mtuprobes == 32) {
104                 timeout = mesh->pingtimeout;
105         }
106
107         for(int i = 0; i < 4 + mesh->localdiscovery; i++) {
108                 int len;
109
110                 if(i == 0) {
111                         if(n->mtuprobes < 30 || n->maxmtu + 8 >= MTU) {
112                                 continue;
113                         }
114
115                         len = n->maxmtu + 8;
116                 } else if(n->maxmtu <= n->minmtu) {
117                         len = n->maxmtu;
118                 } else {
119                         len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu);
120                 }
121
122                 if(len < 64) {
123                         len = 64;
124                 }
125
126                 vpn_packet_t packet;
127                 packet.probe = true;
128                 memset(packet.data, 0, 14);
129                 randomize(packet.data + 14, len - 14);
130                 packet.len = len;
131                 n->status.broadcast = i >= 4 && n->mtuprobes <= 10 && n->prevedge;
132
133                 logger(mesh, MESHLINK_DEBUG, "Sending MTU probe length %d to %s", len, n->name);
134
135                 send_udppacket(mesh, n, &packet);
136         }
137
138         n->status.broadcast = false;
139
140 end:
141         timeout_set(&mesh->loop, &n->mtutimeout, &(struct timeval) {
142                 timeout, rand() % 100000
143         });
144 }
145
146 void send_mtu_probe(meshlink_handle_t *mesh, node_t *n) {
147         timeout_add(&mesh->loop, &n->mtutimeout, send_mtu_probe_handler, n, &(struct timeval) {
148                 1, 0
149         });
150         send_mtu_probe_handler(&mesh->loop, n);
151 }
152
153 static void mtu_probe_h(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *packet, uint16_t len) {
154         logger(mesh, MESHLINK_DEBUG, "Got MTU probe length %d from %s", packet->len, n->name);
155
156         if(!packet->data[0]) {
157                 /* It's a probe request, send back a reply */
158
159                 packet->data[0] = 1;
160
161                 /* Temporarily set udp_confirmed, so that the reply is sent
162                    back exactly the way it came in. */
163
164                 bool udp_confirmed = n->status.udp_confirmed;
165                 n->status.udp_confirmed = true;
166                 send_udppacket(mesh, n, packet);
167                 n->status.udp_confirmed = udp_confirmed;
168         } else {
169                 /* It's a valid reply: now we know bidirectional communication
170                    is possible using the address and socket that the reply
171                    packet used. */
172
173                 n->status.udp_confirmed = true;
174
175                 /* If we haven't established the PMTU yet, restart the discovery process. */
176
177                 if(n->mtuprobes > 30) {
178                         if(len == n->maxmtu + 8) {
179                                 logger(mesh, MESHLINK_INFO, "Increase in PMTU to %s detected, restarting PMTU discovery", n->name);
180                                 n->maxmtu = MTU;
181                                 n->mtuprobes = 10;
182                                 return;
183                         }
184
185                         if(n->minmtu) {
186                                 n->mtuprobes = 30;
187                         } else {
188                                 n->mtuprobes = 1;
189                         }
190                 }
191
192                 /* If applicable, raise the minimum supported MTU */
193
194                 if(len > n->maxmtu) {
195                         len = n->maxmtu;
196                 }
197
198                 if(n->minmtu < len) {
199                         n->minmtu = len;
200                 }
201         }
202 }
203
204 /* VPN packet I/O */
205
206 static void receive_udppacket(meshlink_handle_t *mesh, node_t *n, const void *data, uint16_t len) {
207         if(!n->sptps.state) {
208                 if(!n->status.waitingforkey) {
209                         logger(mesh, MESHLINK_DEBUG, "Got packet from %s but we haven't exchanged keys yet", n->name);
210                         send_req_key(mesh, n);
211                 } else {
212                         logger(mesh, MESHLINK_DEBUG, "Got packet from %s but he hasn't got our key yet", n->name);
213                 }
214
215                 return;
216         }
217
218         sptps_receive_data(&n->sptps, data, len);
219 }
220
221 static void send_sptps_packet(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *origpkt) {
222         if(!n->status.validkey) {
223                 logger(mesh, MESHLINK_INFO, "No valid key known yet for %s", n->name);
224
225                 if(!n->status.waitingforkey) {
226                         send_req_key(mesh, n);
227                 } else if(n->last_req_key + 10 < mesh->loop.now.tv_sec) {
228                         logger(mesh, MESHLINK_DEBUG, "No key from %s after 10 seconds, restarting SPTPS", n->name);
229                         sptps_stop(&n->sptps);
230                         n->status.waitingforkey = false;
231                         send_req_key(mesh, n);
232                 }
233
234                 return;
235         }
236
237         uint8_t type = 0;
238
239         // If it's a probe, send it immediately without trying to compress it.
240         if(origpkt->probe) {
241                 sptps_send_record(&n->sptps, PKT_PROBE, origpkt->data, origpkt->len);
242                 return;
243         }
244
245         if(n->outcompression) {
246                 logger(mesh, MESHLINK_ERROR, "Error while compressing packet to %s", n->name);
247                 return;
248         }
249
250         sptps_send_record(&n->sptps, type, origpkt->data, origpkt->len);
251         return;
252 }
253
254 static void choose_udp_address(meshlink_handle_t *mesh, const node_t *n, const sockaddr_t **sa, int *sock) {
255         /* Latest guess */
256         *sa = &n->address;
257         *sock = n->sock;
258
259         /* If the UDP address is confirmed, use it. */
260         if(n->status.udp_confirmed) {
261                 return;
262         }
263
264         /* Send every third packet to n->address; that could be set
265            to the node's reflexive UDP address discovered during key
266            exchange. */
267
268         static int x = 0;
269
270         if(++x >= 3) {
271                 x = 0;
272                 return;
273         }
274
275         /* Otherwise, address are found in edges to this node.
276            So we pick a random edge and a random socket. */
277
278         int i = 0;
279         int j = rand() % n->edge_tree->count;
280         edge_t *candidate = NULL;
281
282         for splay_each(edge_t, e, n->edge_tree) {
283                 if(i++ == j) {
284                         candidate = e->reverse;
285                         break;
286                 }
287         }
288
289         if(candidate) {
290                 *sa = &candidate->address;
291                 *sock = rand() % mesh->listen_sockets;
292         }
293
294         /* Make sure we have a suitable socket for the chosen address */
295         if(mesh->listen_socket[*sock].sa.sa.sa_family != (*sa)->sa.sa_family) {
296                 for(int i = 0; i < mesh->listen_sockets; i++) {
297                         if(mesh->listen_socket[i].sa.sa.sa_family == (*sa)->sa.sa_family) {
298                                 *sock = i;
299                                 break;
300                         }
301                 }
302         }
303 }
304
305 static void choose_broadcast_address(meshlink_handle_t *mesh, const node_t *n, const sockaddr_t **sa, int *sock) {
306         static sockaddr_t broadcast_ipv4 = {
307                 .in = {
308                         .sin_family = AF_INET,
309                         .sin_addr.s_addr = -1,
310                 }
311         };
312
313         static sockaddr_t broadcast_ipv6 = {
314                 .in6 = {
315                         .sin6_family = AF_INET6,
316                         .sin6_addr.s6_addr[0x0] = 0xff,
317                         .sin6_addr.s6_addr[0x1] = 0x02,
318                         .sin6_addr.s6_addr[0xf] = 0x01,
319                 }
320         };
321
322         *sock = rand() % mesh->listen_sockets;
323
324         if(mesh->listen_socket[*sock].sa.sa.sa_family == AF_INET6) {
325                 if(mesh->localdiscovery_address.sa.sa_family == AF_INET6) {
326                         mesh->localdiscovery_address.in6.sin6_port = n->prevedge->address.in.sin_port;
327                         *sa = &mesh->localdiscovery_address;
328                 } else {
329                         broadcast_ipv6.in6.sin6_port = n->prevedge->address.in.sin_port;
330                         broadcast_ipv6.in6.sin6_scope_id = mesh->listen_socket[*sock].sa.in6.sin6_scope_id;
331                         *sa = &broadcast_ipv6;
332                 }
333         } else {
334                 if(mesh->localdiscovery_address.sa.sa_family == AF_INET) {
335                         mesh->localdiscovery_address.in.sin_port = n->prevedge->address.in.sin_port;
336                         *sa = &mesh->localdiscovery_address;
337                 } else {
338                         broadcast_ipv4.in.sin_port = n->prevedge->address.in.sin_port;
339                         *sa = &broadcast_ipv4;
340                 }
341         }
342 }
343
344 static void send_udppacket(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *origpkt) {
345         if(!n->status.reachable) {
346                 logger(mesh, MESHLINK_INFO, "Trying to send UDP packet to unreachable node %s", n->name);
347                 return;
348         }
349
350         send_sptps_packet(mesh, n, origpkt);
351 }
352
353 bool send_sptps_data(void *handle, uint8_t type, const void *data, size_t len) {
354         node_t *to = handle;
355         meshlink_handle_t *mesh = to->mesh;
356
357         /* Send it via TCP if it is a handshake packet, TCPOnly is in use, or this packet is larger than the MTU. */
358
359         if(type >= SPTPS_HANDSHAKE || ((mesh->self->options | to->options) & OPTION_TCPONLY) || (type != PKT_PROBE && len > to->minmtu)) {
360                 char buf[len * 4 / 3 + 5];
361                 b64encode(data, buf, len);
362
363                 /* If no valid key is known yet, send the packets using ANS_KEY requests,
364                    to ensure we get to learn the reflexive UDP address. */
365                 if(!to->status.validkey) {
366                         to->incompression = mesh->self->incompression;
367                         return send_request(mesh, to->nexthop->connection, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, mesh->self->name, to->name, buf, to->incompression);
368                 } else {
369                         return send_request(mesh, to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, mesh->self->name, to->name, REQ_SPTPS, buf);
370                 }
371         }
372
373         /* Otherwise, send the packet via UDP */
374
375         const sockaddr_t *sa;
376         int sock;
377
378         if(to->status.broadcast) {
379                 choose_broadcast_address(mesh, to, &sa, &sock);
380         } else {
381                 choose_udp_address(mesh, to, &sa, &sock);
382         }
383
384         /* Add the source and destination IDs */
385
386         vpn_packet_t pkt;
387         pkt.src = mesh->self->id;
388         pkt.dst = to->id;
389         memcpy(pkt.data, data, len);
390
391         if(sendto(mesh->listen_socket[sock].udp.fd, &pkt.src, len + 16, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
392                 if(sockmsgsize(sockerrno)) {
393                         if(to->maxmtu >= len) {
394                                 to->maxmtu = len - 1;
395                         }
396
397                         if(to->mtu >= len) {
398                                 to->mtu = len - 1;
399                         }
400                 } else {
401                         logger(mesh, MESHLINK_WARNING, "Error sending UDP SPTPS packet to %s: %s", to->name, sockstrerror(sockerrno));
402                         return false;
403                 }
404         }
405
406         return true;
407 }
408
409 bool receive_sptps_record(void *handle, uint8_t type, const void *data, uint16_t len) {
410         node_t *from = handle;
411         meshlink_handle_t *mesh = from->mesh;
412
413         assert(!from->status.blacklisted);
414
415         if(type == SPTPS_HANDSHAKE) {
416                 if(!from->status.validkey) {
417                         logger(mesh, MESHLINK_INFO, "SPTPS key exchange with %s succesful", from->name);
418                         from->status.validkey = true;
419                         from->status.waitingforkey = false;
420
421                         if(from->utcp) {
422                                 utcp_reset_timers(from->utcp);
423                         }
424                 }
425
426                 return true;
427         }
428
429         if(len > MTU) {
430                 logger(mesh, MESHLINK_ERROR, "Packet from %s larger than maximum supported size (%d > %d)", from->name, len, MTU);
431                 return false;
432         }
433
434         if(type == SPTPS_UNENCRYPTED) {
435                 /* This is a packet that needs to be forwarded */
436                 struct {
437                         uint64_t src;
438                         uint64_t dst;
439                 } hdr;
440
441                 if(len < sizeof(hdr)) {
442                         logger(mesh, MESHLINK_ERROR, "Too short packet from %s", from->name);
443                         return false;
444                 }
445
446                 memcpy(&hdr, data, sizeof(hdr));
447
448                 if(hdr.src == mesh->self->id) {
449                         logger(mesh, MESHLINK_WARNING, "Dropping packet from ourself");
450                         return true;
451                 }
452
453                 node_t *orig = lookup_node_id(mesh, hdr.src);
454
455                 if(!orig) {
456                         logger(mesh, MESHLINK_ERROR, "Received packet from %s with unknown source", from->name);
457                         return true;
458                 }
459
460                 if(orig->status.blacklisted) {
461                         logger(mesh, MESHLINK_WARNING, "Dropping packet from blacklisted node %s", orig->name);
462                         return true;
463                 }
464
465                 if(hdr.dst == mesh->self->id) {
466                         receive_udppacket(mesh, orig, data, len);
467                 }
468
469                 // TODO: forward
470                 return true;
471         }
472
473         if(type == PKT_PROBE) {
474                 vpn_packet_t inpkt;
475                 inpkt.len = len;
476                 inpkt.probe = true;
477                 memcpy(inpkt.data, data, len);
478                 mtu_probe_h(mesh, from, &inpkt, len);
479                 return true;
480         }
481
482         if(type & ~(PKT_COMPRESSED)) {
483                 logger(mesh, MESHLINK_ERROR, "Unexpected SPTPS record type %d len %d from %s", type, len, from->name);
484                 return false;
485         }
486
487         if(type & PKT_COMPRESSED) {
488                 logger(mesh, MESHLINK_ERROR, "Error while decompressing packet from %s", from->name);
489                 return false;
490         }
491
492         if(mesh->receive_cb) {
493                 mesh->receive_cb(mesh, (meshlink_node_t *)from, data, len);
494         }
495
496         return true;
497 }
498
499 /*
500   send a packet to the given vpn ip.
501 */
502 void send_packet(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *packet) {
503         if(n == mesh->self) {
504                 n->out_packets++;
505                 n->out_bytes += packet->len;
506                 // TODO: send to application
507                 return;
508         }
509
510         logger(mesh, MESHLINK_DEBUG, "Sending packet of %d bytes to %s", packet->len, n->name);
511
512         if(!n->status.reachable) {
513                 logger(mesh, MESHLINK_WARNING, "Node %s is not reachable", n->name);
514                 return;
515         }
516
517         n->out_packets++;
518         n->out_bytes += packet->len;
519
520         send_sptps_packet(mesh, n, packet);
521         return;
522 }
523
524 /* Broadcast a packet using the minimum spanning tree */
525
526 void broadcast_packet(meshlink_handle_t *mesh, const node_t *from, vpn_packet_t *packet) {
527         // Always give ourself a copy of the packet.
528         if(from != mesh->self) {
529                 send_packet(mesh, mesh->self, packet);
530         }
531
532         logger(mesh, MESHLINK_INFO, "Broadcasting packet of %d bytes from %s", packet->len, from->name);
533
534         for list_each(connection_t, c, mesh->connections)
535                 if(c->status.active && c->status.mst && c != from->nexthop->connection) {
536                         send_packet(mesh, c->node, packet);
537                 }
538 }
539
540 void forward_udppacket(meshlink_handle_t *mesh, const node_t *from, vpn_packet_t *pkt) {
541         node_t *to = lookup_node_id(mesh, pkt->dst);
542
543         if(!to) {
544                 logger(mesh, MESHLINK_WARNING, "Received UDP packet from %s with unknown destination", from->name);
545                 return;
546         }
547
548         if(pkt->len > to->minmtu) {
549                 // send via TCP
550                 abort();
551         }
552
553         const sockaddr_t *sa;
554         int sock;
555
556         choose_udp_address(mesh, to, &sa, &sock);
557
558         if(sendto(mesh->listen_socket[sock].udp.fd, &pkt->src, pkt->len + 16, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
559                 if(sockmsgsize(sockerrno)) {
560                         if(to->maxmtu >= pkt->len) {
561                                 to->maxmtu = pkt->len - 1;
562                         }
563
564                         if(to->mtu >= pkt->len) {
565                                 to->mtu = pkt->len - 1;
566                         }
567                 } else {
568                         logger(mesh, MESHLINK_WARNING, "Error forwarding UDP SPTPS packet to %s: %s", to->name, sockstrerror(sockerrno));
569                 }
570         }
571 }
572
573 void handle_incoming_vpn_data(event_loop_t *loop, void *data, int flags) {
574         (void)flags;
575         meshlink_handle_t *mesh = loop->data;
576         listen_socket_t *ls = data;
577         vpn_packet_t pkt;
578         char *hostname;
579         sockaddr_t from = {0};
580         socklen_t fromlen = sizeof(from);
581         node_t *n;
582         int len;
583
584         len = recvfrom(ls->udp.fd, &pkt.src, 16 + MAXSIZE, 0, &from.sa, &fromlen);
585
586         if(len <= 16 || len > MAXSIZE + 16) {
587                 if(!sockwouldblock(sockerrno)) {
588                         logger(mesh, MESHLINK_ERROR, "Receiving packet failed: %s", sockstrerror(sockerrno));
589                 }
590
591                 return;
592         }
593
594         if(!pkt.src || !pkt.dst) {
595                 logger(mesh, MESHLINK_WARNING, "Unhandled NULL ids in packet header");
596                 return;
597         }
598
599         pkt.len = len - 16;
600
601         n = lookup_node_id(mesh, pkt.src);
602
603         if(!n) {
604                 hostname = sockaddr2hostname(&from);
605                 logger(mesh, MESHLINK_WARNING, "Received UDP packet from unknown source %s", hostname);
606                 free(hostname);
607                 return;
608         }
609
610         if(n->status.blacklisted) {
611                 logger(mesh, MESHLINK_WARNING, "Dropping packet from blacklisted node %s", n->name);
612                 return;
613         }
614
615         if(n == mesh->self) {
616                 logger(mesh, MESHLINK_WARNING, "Dropping packet from ourself");
617                 return;
618         }
619
620         n->sock = ls - mesh->listen_socket;
621
622         if(sockaddrcmp_noport(&n->address, &from)) {
623                 update_node_udp(mesh, n, &from);
624         }
625
626         if(pkt.dst != mesh->self->id) {
627                 forward_udppacket(mesh, n, &pkt);
628         } else {
629                 receive_udppacket(mesh, n, pkt.data, pkt.len);
630         }
631 }