]> git.meshlink.io Git - meshlink/blob - src/pmtu.c
Fast retries and timeout of UDP probes.
[meshlink] / src / pmtu.c
1 /*
2     pmtu.c -- PMTU probing
3     Copyright (C) 2020 Guus Sliepen <guus@tinc-vpn.org>
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 "crypto.h"
23 #include "logger.h"
24 #include "net.h"
25 #include "netutl.h"
26 #include "node.h"
27 #include "pmtu.h"
28 #include "protocol.h"
29 #include "utils.h"
30
31 /* PMTU probing serves two purposes:
32  *
33  * - establishing a working UDP connection between two peers
34  * - determining the path MTU (PMTU) between two peers
35  *
36  * Establishing a working UDP connection requires NAT hole punching and regular
37  * packets to keep the NAT mappings alive.  For this, we can use very small UDP
38  * packets, and send them rather frequently (once every 10 seconds).  This also
39  * allows us to detect connection loss rather quickly.
40  *
41  * For PMTU discovery, we need to send packets of various size, and determine
42  * which ones are received by the other end.  Once the PMTU is established, we
43  * want to keep monitoring that the discovered PMTU value is still valid.
44  * However, we assume PMTU changes are unlikely, so they do not have to be done
45  * very often.
46  *
47  * To keep track of how far we are in the PMTU probing process, the variable
48  * mtuprobes is used. The meaning of its value is:
49  *
50  * - mtuprobes ==    -4: maxmtu no longer valid, reset minmtu and maxmtu and go to 0
51  * - mtuprobes ==-2..-3: send one maxmtu probe every second
52  * - mtuprobes ==    -1: send one maxmtu and one maxmtu + 1 probe every pinginterval
53  * - mtuprobes == 0..19: initial discovery, send three packets per second, mtuprobes++
54  * - mtuprobes ==    20: fix PMTU, and go to -1
55  *
56  * The first probe is always the maximum MTU supported by the interface,
57  * then a binary search is done until the minimum and maximum converge,
58  * or until 20 packets have been sent.
59  *
60  * After the initial discovery, PMTU probing only sends two packets; one with
61  * the same size as the discovered PMTU, and one which has a size slightly
62  * larger than the currently known PMTU, to test if the PMTU has increased.
63  */
64
65 static void try_fix_mtu(meshlink_handle_t *mesh, node_t *n) {
66         if(n->mtuprobes < 0) {
67                 return;
68         }
69
70         if(n->mtuprobes == 20 || n->minmtu >= n->maxmtu) {
71                 if(n->minmtu > n->maxmtu) {
72                         n->minmtu = n->maxmtu;
73                 } else {
74                         n->maxmtu = n->minmtu;
75                 }
76
77                 n->mtu = n->minmtu;
78                 logger(mesh, MESHLINK_INFO, "Fixing PMTU of %s to %d after %d probes", n->name, n->mtu, n->mtuprobes);
79                 n->mtuprobes = -1;
80         }
81 }
82
83 static void udp_probe_timeout_handler(event_loop_t *loop, void *data) {
84         node_t *n = data;
85         meshlink_handle_t *mesh = loop->data;
86
87         if(!n->status.udp_confirmed) {
88                 return;
89         }
90
91         logger(mesh, MESHLINK_INFO, "Too much time has elapsed since last UDP ping response from %s, stopping UDP communication", n->name);
92         n->status.udp_confirmed = false;
93         n->mtuprobes = 0;
94         n->udpprobes = 0;
95         n->minmtu = 0;
96         n->maxmtu = MTU;
97
98         // If we also have a meta-connection to this node, send a PING on it as well
99         connection_t *c = n->connection;
100
101         if(c && !c->status.pinged) {
102                 send_ping(mesh, c);
103         }
104 }
105
106 static void send_udp_probe_reply(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *packet, uint16_t len) {
107         if(!n->status.validkey) {
108                 logger(mesh, MESHLINK_INFO, "Trying to send UDP probe reply to %s but we don't have his key yet", n->name);
109                 return;
110         }
111
112         packet->data[0] = 1;
113
114         if(packet->data[1]) {
115                 packet->data[1] = 1;
116                 memcpy(packet->data + 2, &len, 2);
117                 len = MIN_PROBE_SIZE;
118         }
119
120         /* Temporarily set udp_confirmed, so that the reply is sent
121            back exactly the way it came in. */
122
123         bool udp_confirmed = n->status.udp_confirmed;
124         n->status.udp_confirmed = true;
125         logger(mesh, MESHLINK_DEBUG, "Sending UDP reply length %d to %s", packet->len, n->name);
126         n->out_meta += packet->len;
127         send_udppacket(mesh, n, packet);
128         n->status.udp_confirmed = udp_confirmed;
129 }
130
131 void udp_probe_h(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *packet, uint16_t len) {
132         if(len < MIN_PROBE_SIZE) {
133                 logger(mesh, MESHLINK_WARNING, "Got too short PMTU probe length %d from %s", packet->len, n->name);
134                 return;
135         }
136
137         n->in_meta += packet->len;
138
139         if(!packet->data[0]) {
140                 /* It's a probe request, send back a reply */
141                 logger(mesh, MESHLINK_DEBUG, "Got PMTU probe length %d from %s", packet->len, n->name);
142                 send_udp_probe_reply(mesh, n, packet, len);
143                 return;
144         }
145
146         if(packet->data[1]) {
147                 memcpy(&len, packet->data + 2, 2);
148         }
149
150         logger(mesh, MESHLINK_DEBUG, "Got PMTU reply length %d from %s", len, n->name);
151
152         /* It's a valid reply: now we know bidirectional communication
153            is possible using the address and socket that the reply
154            packet used. */
155         if(!n->status.udp_confirmed) {
156                 char *address, *port;
157                 sockaddr2str(&n->address, &address, &port);
158                 send_request(mesh, n->nexthop->connection, NULL, "%d %s %s . -1 -1 -1 0 %s %s", ANS_KEY, n->name, n->name, address, port);
159
160                 free(address);
161                 free(port);
162                 n->status.udp_confirmed = true;
163         }
164
165         n->udpprobes = 0;
166
167         // Reset the UDP ping timer.
168
169         timeout_del(&mesh->loop, &n->udp_ping_timeout);
170         timeout_add(&mesh->loop, &n->udp_ping_timeout, &udp_probe_timeout_handler, n, &(struct timespec) {
171                 30, 0
172         });
173
174         if(len > n->maxmtu) {
175                 logger(mesh, MESHLINK_INFO, "Increase in PMTU to %s detected, restarting PMTU discovery", n->name);
176                 n->minmtu = len;
177                 n->maxmtu = MTU;
178                 /* Set mtuprobes to 1 so that try_pmtu() doesn't reset maxmtu */
179                 n->mtuprobes = 1;
180                 return;
181         } else if(n->mtuprobes < 0 && len == n->maxmtu) {
182                 /* We got a maxmtu sized packet, confirming the PMTU is still valid. */
183                 n->mtuprobes = -1;
184                 n->last_mtu_probe_sent = mesh->loop.now;
185         }
186
187         /* If applicable, raise the minimum supported PMTU */
188
189         if(n->minmtu < len) {
190                 n->minmtu = len;
191                 update_node_pmtu(mesh, n);
192         }
193
194         try_fix_mtu(mesh, n);
195 }
196
197 static void send_udp_probe_packet(meshlink_handle_t *mesh, node_t *n, int len) {
198         if(len < MIN_PROBE_SIZE) {
199                 len = MIN_PROBE_SIZE;
200         }
201
202         vpn_packet_t packet;
203         memset(packet.data, 0, 4);
204         packet.probe = true;
205         packet.data[0] = 0;
206         packet.data[1] = 1;
207         packet.data[2] = 0;
208         packet.data[3] = 0;
209
210         if(len > 4) {
211                 randomize(packet.data + 4, len - 4);
212         }
213
214         packet.len = len;
215
216         logger(mesh, MESHLINK_DEBUG, "Sending UDP probe length %d to %s", len, n->name);
217
218         n->out_meta += packet.len;
219         send_udppacket(mesh, n, &packet);
220 }
221
222 static void try_udp(meshlink_handle_t *mesh, node_t *n) {
223         /* Probe request */
224
225         if(n->udpprobes < -3) {
226                 /* We lost three UDP probes, UDP status is no longer unconfirmed */
227                 udp_probe_timeout_handler(&mesh->loop, n);
228         }
229
230         struct timespec elapsed;
231
232         timespec_sub(&mesh->loop.now, &n->last_udp_probe_sent, &elapsed);
233
234         int interval = (n->status.udp_confirmed && n->udpprobes >= 0) ? 10 : 2;
235
236         if(elapsed.tv_sec >= interval) {
237                 n->last_udp_probe_sent = mesh->loop.now;
238                 send_udp_probe_packet(mesh, n, MIN_PROBE_SIZE);
239                 n->udpprobes--;
240
241                 if(!n->status.udp_confirmed && n->prevedge) {
242                         n->status.broadcast = true;
243                         send_udp_probe_packet(mesh, n, MIN_PROBE_SIZE);
244                         n->status.broadcast = false;
245                 }
246         }
247 }
248
249 static uint16_t choose_initial_maxmtu(meshlink_handle_t *mesh, node_t *n) {
250 #ifdef IP_MTU
251
252         int sock = -1;
253
254         sockaddr_t sa_buf;
255         const sockaddr_t *sa;
256         int sockindex;
257         choose_udp_address(mesh, n, &sa, &sockindex, &sa_buf);
258
259         if(!sa) {
260                 return MTU;
261         }
262
263         sock = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
264
265         if(sock < 0) {
266                 logger(mesh, MESHLINK_ERROR, "Creating MTU assessment socket for %s failed: %s", n->name, sockstrerror(sockerrno));
267                 return MTU;
268         }
269
270         if(connect(sock, &sa->sa, SALEN(sa->sa))) {
271                 logger(mesh, MESHLINK_ERROR, "Connecting MTU assessment socket for %s failed: %s", n->name, sockstrerror(sockerrno));
272                 close(sock);
273                 return MTU;
274         }
275
276         int ip_mtu;
277         socklen_t ip_mtu_len = sizeof(ip_mtu);
278
279         if(getsockopt(sock, IPPROTO_IP, IP_MTU, &ip_mtu, &ip_mtu_len)) {
280                 logger(mesh, MESHLINK_ERROR, "getsockopt(IP_MTU) on %s failed: %s", n->name, sockstrerror(sockerrno));
281                 close(sock);
282                 return MTU;
283         }
284
285         close(sock);
286
287         /* Calculate the maximum SPTPS payload based on the interface MTU */
288         uint16_t mtu = ip_mtu;
289         mtu -= (sa->sa.sa_family == AF_INET6) ? 40 : 20; /* IPv6 or IPv4 */
290         mtu -= 8; /* UDP */
291         mtu -= 21; /* SPTPS */
292
293         if(mtu < 512) {
294                 logger(mesh, MESHLINK_ERROR, "getsockopt(IP_MTU) on %s returned absurdly small value: %d", n->name, ip_mtu);
295                 return MTU;
296         }
297
298         if(mtu > MTU) {
299                 return MTU;
300         }
301
302         logger(mesh, MESHLINK_INFO, "Using system-provided maximum MTU for %s: %hd", n->name, mtu);
303         return mtu;
304
305 #else
306         (void)n;
307         return MTU;
308 #endif
309 }
310
311 /* This function tries to determines the PMTU of a node.
312    By calling this function repeatedly, n->minmtu will be progressively
313    increased, and at some point, n->mtu will be fixed to n->minmtu.  If the PMTU
314    is already fixed, this function checks if it can be increased.
315 */
316
317 static void try_pmtu(meshlink_handle_t *mesh, node_t *n) {
318         if(!n->status.udp_confirmed) {
319                 n->mtuprobes = 0;
320                 n->minmtu = 0;
321                 n->maxmtu = MTU;
322                 return;
323         }
324
325         struct timespec elapsed;
326
327         timespec_sub(&mesh->loop.now, &n->last_mtu_probe_sent, &elapsed);
328
329         if(n->mtuprobes >= 0) {
330                 /* Fast probing, send three packets per second */
331                 if(n->mtuprobes != 0 && elapsed.tv_sec == 0 && elapsed.tv_nsec < 333333333) {
332                         return;
333                 }
334         } else {
335                 if(n->mtuprobes < -1) {
336                         /* We didn't get an answer to the last probe, try again once every second */
337                         if(elapsed.tv_sec < 1) {
338                                 return;
339                         }
340                 } else {
341                         /* Slow probing, send one packet every pinginterval */
342                         int pinginterval = mesh->dev_class_traits[n->devclass].pinginterval;
343
344                         if(elapsed.tv_sec < pinginterval) {
345                                 return;
346                         }
347                 }
348         }
349
350         n->last_mtu_probe_sent = mesh->loop.now;
351
352         if(n->mtuprobes < -3) {
353                 /* We lost three PMTU probes, restart discovery */
354                 logger(mesh, MESHLINK_INFO, "Decrease in PMTU to %s detected, restarting PMTU discovery", n->name);
355                 n->mtuprobes = 0;
356                 n->minmtu = 0;
357         }
358
359         if(n->mtuprobes < 0) {
360                 /* After the initial discovery, we only send one maxmtu and one
361                    maxmtu + 1 probe to detect PMTU increases. */
362                 send_udp_probe_packet(mesh, n, n->maxmtu);
363
364                 if(n->mtuprobes == -1 && n->maxmtu + 1 < MTU) {
365                         send_udp_probe_packet(mesh, n, n->maxmtu + 1);
366                 }
367
368                 n->mtuprobes--;
369         } else {
370                 /* Starting parameters. */
371                 uint16_t len;
372
373                 if(n->mtuprobes == 0) {
374                         /* First packet is always the maximum MTU size */
375                         n->maxmtu = choose_initial_maxmtu(mesh, n);
376                         len = n->maxmtu;
377                 } else {
378                         if(n->last_mtu_len == n->minmtu) {
379                                 /* The previous probe was succesful, increase the size */
380                                 len = n->minmtu + (n->maxmtu - n->minmtu + 1) / 2;
381                         } else {
382                                 /* The previous probe was unsuccesful, decrease the size */
383                                 len = n->minmtu + (n->last_mtu_len - n->minmtu) / 2;
384                         }
385                 }
386
387                 n->last_mtu_len = len;
388                 send_udp_probe_packet(mesh, n, len);
389                 n->mtuprobes++;
390         }
391
392         try_fix_mtu(mesh, n);
393 }
394
395 /* Keep the connection to the given node alive.
396  * Ensure we have a valid key, and check whether UDP is working.
397  */
398
399 void keepalive(meshlink_handle_t *mesh, node_t *n, bool traffic) {
400         if(!n->status.reachable || !n->status.validkey) {
401                 return;
402         }
403
404         try_udp(mesh, n);
405
406         if(traffic) {
407                 try_pmtu(mesh, n);
408         }
409
410         /* If we want to send traffic but we don't have a working UDP
411          * connection, we are going to forward the traffic to the nexthop, so
412          * try to keep that one alive as well. */
413
414         if(traffic && !n->status.udp_confirmed && n != n->nexthop) {
415                 keepalive(mesh, n->nexthop, traffic);
416         }
417 }
418