1 /*
2  * Copyright (c) 2015, Laurent COUSTET <ed@zehome.com>
3  *
4  * All rights reserved.
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  *       notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above copyright
11  *       notice, this list of conditions and the following disclaimer in the
12  *       documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
18  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
23  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 #include <stdint.h>
26 #include <unistd.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdarg.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #include <time.h>
35 #include <getopt.h>
36 #include <pwd.h>
37 
38 #include <sys/types.h>
39 #include <sys/select.h>
40 #include <sys/time.h>
41 #include <sys/un.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <netdb.h>
45 #include <ev.h>
46 
47 #include "includes.h"
48 #include "mlvpn.h"
49 #include "tool.h"
50 #include "setproctitle.h"
51 #include "crypto.h"
52 #ifdef ENABLE_CONTROL
53 #include "control.h"
54 #endif
55 #include "tuntap_generic.h"
56 
57 /* Linux specific things */
58 #ifdef HAVE_LINUX
59 #include <sys/prctl.h>
60 #include "systemd.h"
61 #endif
62 
63 #ifdef HAVE_FREEBSD
64 #define _NSIG _SIG_MAXSIG
65 #include <sys/endian.h>
66 #endif
67 
68 /* GLOBALS */
69 struct tuntap_s tuntap;
70 char *_progname;
71 static char **saved_argv;
72 struct ev_loop *loop;
73 static ev_timer reorder_drain_timeout;
74 char *status_command = NULL;
75 char *process_title = NULL;
76 int logdebug = 0;
77 
78 static uint64_t data_seq = 0;
79 
80 struct mlvpn_status_s mlvpn_status = {
81     .start_time = 0,
82     .last_reload = 0,
83     .fallback_mode = 0,
84     .connected = 0,
85     .initialized = 0
86 };
87 struct mlvpn_options_s mlvpn_options = {
88     .change_process_title = 1,
89     .process_name = "mlvpn",
90     .control_unix_path = "",
91     .control_bind_host = "",
92     .control_bind_port = "",
93     .ip4 = "",
94     .ip6 = "",
95     .ip4_gateway = "",
96     .ip6_gateway = "",
97     .ip4_routes = "",
98     .ip6_routes = "",
99     .mtu = 0,
100     .config_path = "mlvpn.conf",
101     .config_fd = -1,
102     .debug = 0,
103     .verbose = 2,
104     .unpriv_user = "mlvpn",
105     .cleartext_data = 1,
106     .root_allowed = 0,
107     .reorder_buffer_size = 0
108 };
109 #ifdef HAVE_FILTERS
110 struct mlvpn_filters_s mlvpn_filters = {
111     .count = 0
112 };
113 #endif
114 
115 struct mlvpn_reorder_buffer *reorder_buffer;
116 freebuffer_t *freebuf;
117 
118 static char *optstr = "c:n:u:hvVD:";
119 static struct option long_options[] = {
120     {"config",        required_argument, 0, 'c' },
121     {"debug",         no_argument,       0, 2   },
122     {"name",          required_argument, 0, 'n' },
123     {"natural-title", no_argument,       0, 1   },
124     {"help",          no_argument,       0, 'h' },
125     {"user",          required_argument, 0, 'u' },
126     {"verbose",       no_argument,       0, 'v' },
127     {"quiet",         no_argument,       0, 'q' },
128     {"version",       no_argument,       0, 'V' },
129     {"yes-run-as-root",no_argument,      0, 3   },
130     {0,               0,                 0, 0 }
131 };
132 
133 static int mlvpn_rtun_start(mlvpn_tunnel_t *t);
134 static void mlvpn_rtun_read(EV_P_ ev_io *w, int revents);
135 static void mlvpn_rtun_write(EV_P_ ev_io *w, int revents);
136 static uint32_t mlvpn_rtun_reorder_drain(uint32_t reorder);
137 static void mlvpn_rtun_reorder_drain_timeout(EV_P_ ev_timer *w, int revents);
138 static void mlvpn_rtun_check_timeout(EV_P_ ev_timer *w, int revents);
139 static void mlvpn_rtun_send_keepalive(ev_tstamp now, mlvpn_tunnel_t *t);
140 static void mlvpn_rtun_send_disconnect(mlvpn_tunnel_t *t);
141 static int mlvpn_rtun_send(mlvpn_tunnel_t *tun, circular_buffer_t *pktbuf);
142 static void mlvpn_rtun_send_auth(mlvpn_tunnel_t *t);
143 static void mlvpn_rtun_status_up(mlvpn_tunnel_t *t);
144 static void mlvpn_rtun_tick_connect(mlvpn_tunnel_t *t);
145 static void mlvpn_rtun_recalc_weight();
146 static void mlvpn_update_status();
147 static int mlvpn_rtun_bind(mlvpn_tunnel_t *t);
148 static void update_process_title();
149 static void mlvpn_tuntap_init();
150 static int
151 mlvpn_protocol_read(mlvpn_tunnel_t *tun,
152                     mlvpn_pkt_t *rawpkt,
153                     mlvpn_pkt_t *decap_pkt);
154 
155 
156 static void
usage(char ** argv)157 usage(char **argv)
158 {
159     fprintf(stderr,
160             "usage: %s [options]\n\n"
161             "Options:\n"
162             " -c, --config [path]   path to config file (ex. /etc/mlvpn.conf)\n"
163             " --debug               don't use syslog, print to stdout\n"
164             " --natural-title       do not change process title\n"
165             " -n, --name            change process-title and include 'name'\n"
166             " -h, --help            this help\n"
167             " -u, --user [username] drop privileges to user 'username'\n"
168             " --yes-run-as-root     ! please do not use !\n"
169             " -v --verbose          increase verbosity\n"
170             " -q --quiet            decrease verbosity\n"
171             " -V, --version         output version information and exit\n"
172             "\n"
173             "For more details see mlvpn(1) and mlvpn.conf(5).\n", argv[0]);
174     exit(2);
175 }
176 
177 int
mlvpn_sock_set_nonblocking(int fd)178 mlvpn_sock_set_nonblocking(int fd)
179 {
180     int ret = 0;
181     int fl = fcntl(fd, F_GETFL);
182     if (fl < 0)
183     {
184         log_warn(NULL, "fcntl");
185         ret = -1;
186     } else {
187         fl |= O_NONBLOCK;
188         if ( (ret = fcntl(fd, F_SETFL, fl)) < 0)
189             log_warn(NULL, "Unable to set socket %d non blocking",
190                fd);
191     }
192     return ret;
193 }
194 
195 inline static
mlvpn_rtun_tick(mlvpn_tunnel_t * t)196 void mlvpn_rtun_tick(mlvpn_tunnel_t *t) {
197     t->last_activity = ev_now(EV_DEFAULT_UC);
198 }
199 
200 /* Inject the packet to the tuntap device (real network) */
201 inline static
mlvpn_rtun_inject_tuntap(mlvpn_pkt_t * pkt)202 void mlvpn_rtun_inject_tuntap(mlvpn_pkt_t *pkt)
203 {
204     mlvpn_pkt_t *tuntap_pkt = mlvpn_pktbuffer_write(tuntap.sbuf);
205     tuntap_pkt->len = pkt->len;
206     memcpy(tuntap_pkt->data, pkt->data, tuntap_pkt->len);
207     /* Send the packet back into the LAN */
208     if (!ev_is_active(&tuntap.io_write)) {
209         ev_io_start(EV_A_ &tuntap.io_write);
210     }
211 }
212 
213 static void
mlvpn_rtun_reorder_drain_timeout(EV_P_ ev_timer * w,int revents)214 mlvpn_rtun_reorder_drain_timeout(EV_P_ ev_timer *w, int revents)
215 {
216     log_debug("reorder", "reorder timeout. Packet loss?");
217     mlvpn_rtun_reorder_drain(0);
218     if (freebuf->used == 0) {
219         ev_timer_stop(EV_A_ w);
220     }
221 }
222 
223 static uint32_t
mlvpn_rtun_reorder_drain(uint32_t reorder)224 mlvpn_rtun_reorder_drain(uint32_t reorder)
225 {
226     int i;
227     uint32_t drained = 0;
228     mlvpn_pkt_t *drained_pkts[128];
229     mlvpn_pkt_t *pkt;
230     /* Try to drain packets */
231     if (reorder) {
232         drained = mlvpn_reorder_drain(reorder_buffer, drained_pkts, 128);
233         for(i = 0; i < drained; i++) {
234             pkt = drained_pkts[i];
235             mlvpn_rtun_inject_tuntap(pkt);
236             mlvpn_freebuffer_free(freebuf, drained_pkts[i]);
237         }
238     } else {
239         while ((pkt = mlvpn_freebuffer_drain_used(freebuf)) != NULL) {
240             drained++;
241             mlvpn_rtun_inject_tuntap(pkt);
242         }
243         mlvpn_freebuffer_reset(freebuf);
244         mlvpn_reorder_reset(reorder_buffer);
245     }
246     if (freebuf->used == 0) {
247         ev_timer_stop(EV_A_ &reorder_drain_timeout);
248     }
249     return drained;
250 }
251 
252 /* Count the loss on the last 64 packets */
253 static void
mlvpn_loss_update(mlvpn_tunnel_t * tun,uint64_t seq)254 mlvpn_loss_update(mlvpn_tunnel_t *tun, uint64_t seq)
255 {
256     if (seq > tun->seq_last + 64) {
257         /* consider a connection reset. */
258         tun->seq_vect = (uint64_t) -1;
259         tun->seq_last = seq;
260     } else if (seq > tun->seq_last) {
261         /* new sequence number -- recent message arrive */
262         tun->seq_vect <<= seq - tun->seq_last;
263         tun->seq_vect |= 1;
264         tun->seq_last = seq;
265     } else if (seq >= tun->seq_last - 63) {
266         tun->seq_vect |= (1 << (tun->seq_last - seq));
267     }
268 }
269 
270 int
mlvpn_loss_ratio(mlvpn_tunnel_t * tun)271 mlvpn_loss_ratio(mlvpn_tunnel_t *tun)
272 {
273     int loss = 0;
274     int i;
275     /* Count zeroes */
276     for (i = 0; i < 64; i++) {
277         if (! (1 & (tun->seq_vect >> i))) {
278             loss++;
279         }
280     }
281     return loss * 100 / 64;
282 }
283 
284 static int
mlvpn_rtun_recv_data(mlvpn_tunnel_t * tun,mlvpn_pkt_t * inpkt)285 mlvpn_rtun_recv_data(mlvpn_tunnel_t *tun, mlvpn_pkt_t *inpkt)
286 {
287     int ret;
288     uint32_t drained;
289     if (reorder_buffer == NULL || !inpkt->reorder) {
290         mlvpn_rtun_inject_tuntap(inpkt);
291         return 1;
292     } else {
293         mlvpn_pkt_t *pkt = mlvpn_freebuffer_get(freebuf);
294         memcpy(pkt, inpkt, sizeof(mlvpn_pkt_t));
295         ret = mlvpn_reorder_insert(reorder_buffer, pkt);
296         if (ret != 0) {
297             log_warnx("net", "reorder_buffer_insert failed: %d", ret);
298             mlvpn_reorder_reset(reorder_buffer);
299             drained = mlvpn_rtun_reorder_drain(0);
300         } else {
301             drained = mlvpn_rtun_reorder_drain(1);
302         }
303         if (freebuf->used > 0) {
304             ev_timer_again(EV_A_ &reorder_drain_timeout);
305         }
306         //log_debug("reorder", "drained %d packets", drained);
307     }
308     return drained;
309 }
310 
311 
312 /* read from the rtunnel => write directly to the tap send buffer */
313 static void
mlvpn_rtun_read(EV_P_ ev_io * w,int revents)314 mlvpn_rtun_read(EV_P_ ev_io *w, int revents)
315 {
316     mlvpn_tunnel_t *tun = w->data;
317     ssize_t len;
318     struct sockaddr_storage clientaddr;
319     socklen_t addrlen = sizeof(clientaddr);
320     mlvpn_pkt_t pkt;
321     len = recvfrom(tun->fd, pkt.data,
322                    sizeof(pkt.data),
323                    MSG_DONTWAIT, (struct sockaddr *)&clientaddr, &addrlen);
324     if (len < 0) {
325         if (errno != EAGAIN && errno != EWOULDBLOCK) {
326             log_warn("net", "%s read error", tun->name);
327             mlvpn_rtun_status_down(tun);
328         }
329     } else if (len == 0) {
330         log_info("protocol", "%s peer closed the connection", tun->name);
331     } else {
332         pkt.len = len;
333         mlvpn_pkt_t decap_pkt;
334 
335         /* validate the received packet */
336         if (mlvpn_protocol_read(tun, &pkt, &decap_pkt) < 0) {
337             return;
338         }
339 
340         tun->recvbytes += len;
341         tun->recvpackets += 1;
342 
343         if (! tun->addrinfo)
344             fatalx("tun->addrinfo is NULL!");
345 
346         if ((tun->addrinfo->ai_addrlen != addrlen) ||
347                 (memcmp(tun->addrinfo->ai_addr, &clientaddr, addrlen) != 0)) {
348             if (mlvpn_options.cleartext_data && tun->status >= MLVPN_AUTHOK) {
349                 log_warnx("protocol", "%s rejected non authenticated connection",
350                     tun->name);
351                 return;
352             }
353             char clienthost[NI_MAXHOST];
354             char clientport[NI_MAXSERV];
355             int ret;
356             if ( (ret = getnameinfo((struct sockaddr *)&clientaddr, addrlen,
357                                     clienthost, sizeof(clienthost),
358                                     clientport, sizeof(clientport),
359                                     NI_NUMERICHOST|NI_NUMERICSERV)) < 0) {
360                 log_warn("protocol", "%s error in getnameinfo: %d",
361                        tun->name, ret);
362             } else {
363                 log_info("protocol", "%s new connection -> %s:%s",
364                    tun->name, clienthost, clientport);
365                 memcpy(tun->addrinfo->ai_addr, &clientaddr, addrlen);
366             }
367         }
368         log_debug("net", "< %s recv %d bytes (type=%d, seq=%"PRIu64", reorder=%d)",
369             tun->name, (int)len, decap_pkt.type, decap_pkt.seq, decap_pkt.reorder);
370 
371         if (decap_pkt.type == MLVPN_PKT_DATA) {
372             if (tun->status >= MLVPN_AUTHOK) {
373                 mlvpn_rtun_tick(tun);
374                 mlvpn_rtun_recv_data(tun, &decap_pkt);
375             } else {
376                 log_debug("protocol", "%s ignoring non authenticated packet",
377                     tun->name);
378             }
379         } else if (decap_pkt.type == MLVPN_PKT_KEEPALIVE &&
380                 tun->status >= MLVPN_AUTHOK) {
381             log_debug("protocol", "%s keepalive received", tun->name);
382             mlvpn_rtun_tick(tun);
383             tun->last_keepalive_ack = ev_now(EV_DEFAULT_UC);
384             /* Avoid flooding the network if multiple packets are queued */
385             if (tun->last_keepalive_ack_sent + 1 < tun->last_keepalive_ack) {
386                 tun->last_keepalive_ack_sent = tun->last_keepalive_ack;
387                 mlvpn_rtun_send_keepalive(tun->last_keepalive_ack, tun);
388             }
389         } else if (decap_pkt.type == MLVPN_PKT_DISCONNECT &&
390                 tun->status >= MLVPN_AUTHOK) {
391             log_info("protocol", "%s disconnect received", tun->name);
392             mlvpn_rtun_status_down(tun);
393         } else if (decap_pkt.type == MLVPN_PKT_AUTH ||
394                 decap_pkt.type == MLVPN_PKT_AUTH_OK) {
395             mlvpn_rtun_send_auth(tun);
396         }
397     }
398 }
399 
400 static int
mlvpn_protocol_read(mlvpn_tunnel_t * tun,mlvpn_pkt_t * pkt,mlvpn_pkt_t * decap_pkt)401 mlvpn_protocol_read(
402     mlvpn_tunnel_t *tun, mlvpn_pkt_t *pkt,
403     mlvpn_pkt_t *decap_pkt)
404 {
405     unsigned char nonce[crypto_NONCEBYTES];
406     int ret;
407     uint16_t rlen;
408     mlvpn_proto_t proto;
409     uint64_t now64 = mlvpn_timestamp64(ev_now(EV_DEFAULT_UC));
410     /* Overkill */
411     memset(&proto, 0, sizeof(proto));
412     memset(decap_pkt, 0, sizeof(*decap_pkt));
413 
414     /* pkt->data contains mlvpn_proto_t struct */
415     if (pkt->len > sizeof(pkt->data) || pkt->len > sizeof(proto) ||
416             pkt->len < (PKTHDRSIZ(proto))) {
417         log_warnx("protocol", "%s received invalid packet of %d bytes",
418             tun->name, pkt->len);
419         goto fail;
420     }
421     memcpy(&proto, pkt->data, pkt->len);
422     rlen = be16toh(proto.len);
423     if (rlen == 0 || rlen > sizeof(proto.data)) {
424         log_warnx("protocol", "%s invalid packet size: %d", tun->name, rlen);
425         goto fail;
426     }
427     proto.seq = be64toh(proto.seq);
428     proto.timestamp = be16toh(proto.timestamp);
429     proto.timestamp_reply = be16toh(proto.timestamp_reply);
430     proto.flow_id = be32toh(proto.flow_id);
431     /* now auth the packet using libsodium before further checks */
432 #ifdef ENABLE_CRYPTO
433     if (mlvpn_options.cleartext_data && proto.flags == MLVPN_PKT_DATA) {
434         memcpy(decap_pkt->data, &proto.data, rlen);
435     } else {
436         sodium_memzero(nonce, sizeof(nonce));
437         memcpy(nonce, &proto.seq, sizeof(proto.seq));
438         memcpy(nonce + sizeof(proto.seq), &proto.flow_id, sizeof(proto.flow_id));
439         if ((ret = crypto_decrypt((unsigned char *)decap_pkt->data,
440                                   (const unsigned char *)&proto.data, rlen,
441                                   nonce)) != 0) {
442             log_warnx("protocol", "%s crypto_decrypt failed: %d",
443                 tun->name, ret);
444             goto fail;
445         }
446         rlen -= crypto_PADSIZE;
447     }
448 #else
449     memcpy(decap_pkt->data, &proto.data, rlen);
450 #endif
451     decap_pkt->len = rlen;
452     decap_pkt->type = proto.flags;
453     if (proto.version >= 1) {
454         decap_pkt->reorder = proto.reorder;
455         decap_pkt->seq = be64toh(proto.data_seq);
456         mlvpn_loss_update(tun, decap_pkt->seq);
457     } else {
458         decap_pkt->reorder = 0;
459         decap_pkt->seq = 0;
460     }
461     if (proto.timestamp != (uint16_t)-1) {
462         tun->saved_timestamp = proto.timestamp;
463         tun->saved_timestamp_received_at = now64;
464     }
465     if (proto.timestamp_reply != (uint16_t)-1) {
466         uint16_t now16 = mlvpn_timestamp16(now64);
467         double R = mlvpn_timestamp16_diff(now16, proto.timestamp_reply);
468         if (R < 5000) { /* ignore large values, e.g. server was Ctrl-Zed */
469             if (!tun->rtt_hit) { /* first measurement */
470                 tun->srtt = R;
471                 tun->rttvar = R / 2;
472                 tun->rtt_hit = 1;
473             } else {
474                 const double alpha = 1.0 / 8.0;
475                 const double beta = 1.0 / 4.0;
476                 tun->rttvar = (1 - beta) * tun->rttvar + (beta * fabs(tun->srtt - R));
477                 tun->srtt = (1 - alpha) * tun->srtt + (alpha * R);
478             }
479         }
480         log_debug("rtt", "%ums srtt %ums loss ratio: %d",
481             (unsigned int)R, (unsigned int)tun->srtt, mlvpn_loss_ratio(tun));
482     }
483     return 0;
484 fail:
485     return -1;
486 }
487 
488 static int
mlvpn_rtun_send(mlvpn_tunnel_t * tun,circular_buffer_t * pktbuf)489 mlvpn_rtun_send(mlvpn_tunnel_t *tun, circular_buffer_t *pktbuf)
490 {
491     unsigned char nonce[crypto_NONCEBYTES];
492     ssize_t ret;
493     size_t wlen;
494     mlvpn_proto_t proto;
495     uint64_t now64 = mlvpn_timestamp64(ev_now(EV_DEFAULT_UC));
496     memset(&proto, 0, sizeof(proto));
497 
498     mlvpn_pkt_t *pkt = mlvpn_pktbuffer_read(pktbuf);
499     if (pkt->type == MLVPN_PKT_DATA && pkt->reorder) {
500         proto.data_seq = data_seq++;
501     }
502     wlen = PKTHDRSIZ(proto) + pkt->len;
503     proto.len = pkt->len;
504     proto.flags = pkt->type;
505     if (pkt->reorder) {
506         proto.seq = tun->seq++;
507     }
508     proto.flow_id = tun->flow_id;
509     proto.version = MLVPN_PROTOCOL_VERSION;
510     proto.reorder = pkt->reorder;
511 
512     /* we have a recent received timestamp */
513     if (now64 - tun->saved_timestamp_received_at < 1000 ) {
514         /* send "corrected" timestamp advanced by how long we held it */
515         /* Cast to uint16_t there intentional */
516         proto.timestamp_reply = tun->saved_timestamp + (now64 - tun->saved_timestamp_received_at);
517         tun->saved_timestamp = -1;
518         tun->saved_timestamp_received_at = 0;
519     } else {
520         proto.timestamp_reply = -1;
521     }
522     proto.timestamp = mlvpn_timestamp16(now64);
523 #ifdef ENABLE_CRYPTO
524     if (mlvpn_options.cleartext_data && pkt->type == MLVPN_PKT_DATA) {
525         memcpy(&proto.data, &pkt->data, wlen);
526     } else {
527         if (wlen + crypto_PADSIZE > sizeof(proto.data)) {
528             log_warnx("protocol", "%s packet too long: %u/%d (packet=%d)",
529                 tun->name,
530                 (unsigned int)wlen + crypto_PADSIZE,
531                 (unsigned int)sizeof(proto.data),
532                 pkt->len);
533             return -1;
534         }
535         sodium_memzero(nonce, sizeof(nonce));
536         memcpy(nonce, &proto.seq, sizeof(proto.seq));
537         memcpy(nonce + sizeof(proto.seq), &proto.flow_id, sizeof(proto.flow_id));
538         if ((ret = crypto_encrypt((unsigned char *)&proto.data,
539                                   (const unsigned char *)&pkt->data, pkt->len,
540                                   nonce)) != 0) {
541             log_warnx("protocol", "%s crypto_encrypt failed: %d incorrect password?",
542                 tun->name, (int)ret);
543             return -1;
544         }
545         proto.len += crypto_PADSIZE;
546         wlen += crypto_PADSIZE;
547     }
548 #else
549     memcpy(&proto.data, &pkt->data, wlen);
550 #endif
551     proto.len = htobe16(proto.len);
552     proto.seq = htobe64(proto.seq);
553     proto.data_seq = htobe64(proto.data_seq);
554     proto.flow_id = htobe32(proto.flow_id);
555     proto.timestamp = htobe16(proto.timestamp);
556     proto.timestamp_reply = htobe16(proto.timestamp_reply);
557     ret = sendto(tun->fd, &proto, wlen, MSG_DONTWAIT,
558                  tun->addrinfo->ai_addr, tun->addrinfo->ai_addrlen);
559     if (ret < 0)
560     {
561         if (errno != EAGAIN && errno != EWOULDBLOCK) {
562             log_warn("net", "%s write error", tun->name);
563             mlvpn_rtun_status_down(tun);
564         }
565     } else {
566         tun->sentpackets++;
567         tun->sentbytes += ret;
568         if (wlen != ret)
569         {
570             log_warnx("net", "%s write error %d/%u",
571                 tun->name, (int)ret, (unsigned int)wlen);
572         } else {
573             log_debug("net", "> %s sent %d bytes (size=%d, type=%d, seq=%"PRIu64", reorder=%d)",
574                 tun->name, (int)ret, pkt->len, pkt->type, pkt->seq, pkt->reorder);
575         }
576     }
577 
578     if (ev_is_active(&tun->io_write) && mlvpn_cb_is_empty(pktbuf)) {
579         ev_io_stop(EV_A_ &tun->io_write);
580     }
581     return ret;
582 }
583 
584 
585 static void
mlvpn_rtun_write(EV_P_ ev_io * w,int revents)586 mlvpn_rtun_write(EV_P_ ev_io *w, int revents)
587 {
588     mlvpn_tunnel_t *tun = w->data;
589     if (! mlvpn_cb_is_empty(tun->hpsbuf)) {
590         mlvpn_rtun_send(tun, tun->hpsbuf);
591     }
592 
593     if (! mlvpn_cb_is_empty(tun->sbuf)) {
594         mlvpn_rtun_send(tun, tun->sbuf);
595     }
596 }
597 
598 mlvpn_tunnel_t *
mlvpn_rtun_new(const char * name,const char * bindaddr,const char * bindport,uint32_t bindfib,const char * destaddr,const char * destport,int server_mode,uint32_t timeout,int fallback_only,uint32_t bandwidth,uint32_t loss_tolerence)599 mlvpn_rtun_new(const char *name,
600                const char *bindaddr, const char *bindport, uint32_t bindfib,
601                const char *destaddr, const char *destport,
602                int server_mode, uint32_t timeout,
603                int fallback_only, uint32_t bandwidth,
604                uint32_t loss_tolerence)
605 {
606     mlvpn_tunnel_t *new;
607 
608     /* Some basic checks */
609     if (server_mode)
610     {
611         if (bindport == NULL)
612         {
613             log_warnx(NULL,
614                 "cannot initialize socket without bindport");
615             return NULL;
616         }
617     } else {
618         if (destaddr == NULL || destport == NULL)
619         {
620             log_warnx(NULL,
621                 "cannot initialize socket without destaddr or destport");
622             return NULL;
623         }
624     }
625 
626     new = (mlvpn_tunnel_t *)calloc(1, sizeof(mlvpn_tunnel_t));
627     if (! new)
628         fatal(NULL, "calloc failed");
629     /* other values are enforced by calloc to 0/NULL */
630     new->name = strdup(name);
631     new->fd = -1;
632     new->server_mode = server_mode;
633     new->weight = 1;
634     new->status = MLVPN_DISCONNECTED;
635     new->addrinfo = NULL;
636     new->sentpackets = 0;
637     new->sentbytes = 0;
638     new->recvbytes = 0;
639     new->seq = 0;
640     new->expected_receiver_seq = 0;
641     new->saved_timestamp = -1;
642     new->saved_timestamp_received_at = 0;
643     new->srtt = 1000;
644     new->rttvar = 500;
645     new->rtt_hit = 0;
646     new->seq_last = 0;
647     new->seq_vect = (uint64_t) -1;
648     new->flow_id = crypto_nonce_random();
649     new->bandwidth = bandwidth;
650     new->fallback_only = fallback_only;
651     new->loss_tolerence = loss_tolerence;
652     if (bindaddr)
653         strlcpy(new->bindaddr, bindaddr, sizeof(new->bindaddr));
654     if (bindport)
655         strlcpy(new->bindport, bindport, sizeof(new->bindport));
656 	new->bindfib = bindfib;
657     if (destaddr)
658         strlcpy(new->destaddr, destaddr, sizeof(new->destaddr));
659     if (destport)
660         strlcpy(new->destport, destport, sizeof(new->destport));
661     new->sbuf = mlvpn_pktbuffer_init(PKTBUFSIZE);
662     new->hpsbuf = mlvpn_pktbuffer_init(PKTBUFSIZE);
663     mlvpn_rtun_tick(new);
664     new->timeout = timeout;
665     new->next_keepalive = 0;
666     LIST_INSERT_HEAD(&rtuns, new, entries);
667     new->io_read.data = new;
668     new->io_write.data = new;
669     new->io_timeout.data = new;
670     ev_init(&new->io_read, mlvpn_rtun_read);
671     ev_init(&new->io_write, mlvpn_rtun_write);
672     ev_timer_init(&new->io_timeout, mlvpn_rtun_check_timeout,
673         0., MLVPN_IO_TIMEOUT_DEFAULT);
674     ev_timer_start(EV_A_ &new->io_timeout);
675     update_process_title();
676     return new;
677 }
678 
679 void
mlvpn_rtun_drop(mlvpn_tunnel_t * t)680 mlvpn_rtun_drop(mlvpn_tunnel_t *t)
681 {
682     mlvpn_tunnel_t *tmp;
683     mlvpn_rtun_send_disconnect(t);
684     mlvpn_rtun_status_down(t);
685     ev_timer_stop(EV_A_ &t->io_timeout);
686     ev_io_stop(EV_A_ &t->io_read);
687 
688     LIST_FOREACH(tmp, &rtuns, entries)
689     {
690         if (mystr_eq(tmp->name, t->name))
691         {
692             LIST_REMOVE(tmp, entries);
693             if (tmp->name)
694                 free(tmp->name);
695             if (tmp->addrinfo)
696                 freeaddrinfo(tmp->addrinfo);
697             mlvpn_pktbuffer_free(tmp->sbuf);
698             mlvpn_pktbuffer_free(tmp->hpsbuf);
699             /* Safety */
700             tmp->name = NULL;
701             break;
702         }
703     }
704     update_process_title();
705 }
706 
707 /* Based on tunnel bandwidth, compute a "weight" value
708  * to balance correctly the round robin rtun_choose.
709  */
710 static void
mlvpn_rtun_recalc_weight()711 mlvpn_rtun_recalc_weight()
712 {
713     mlvpn_tunnel_t *t;
714     uint32_t bandwidth_total = 0;
715     int warned = 0;
716     /* If the bandwidth limit is not set on all interfaces, then
717      * it's impossible to balance correctly! */
718     LIST_FOREACH(t, &rtuns, entries)
719     {
720         if (t->bandwidth == 0)
721             warned++;
722         bandwidth_total += t->bandwidth;
723     }
724     if (warned && bandwidth_total > 0) {
725         log_warnx("config", "you must set the bandwidth on every tunnel");
726     }
727     if (warned == 0)
728     {
729         LIST_FOREACH(t, &rtuns, entries)
730         {
731             /* useless, but we want to be sure not to divide by 0 ! */
732             if (t->bandwidth > 0 && bandwidth_total > 0)
733             {
734                 t->weight = (((double)t->bandwidth /
735                               (double)bandwidth_total) * 100.0);
736                 log_debug("wrr", "%s weight = %f (%u %u)", t->name, t->weight,
737                     t->bandwidth, bandwidth_total);
738             }
739         }
740     }
741 }
742 
743 static int
mlvpn_rtun_bind(mlvpn_tunnel_t * t)744 mlvpn_rtun_bind(mlvpn_tunnel_t *t)
745 {
746     struct addrinfo hints, *res;
747     int n, fd;
748 
749     memset(&hints, 0, sizeof(hints));
750     /* AI_PASSIVE flag: the resulting address is used to bind
751        to a socket for accepting incoming connections.
752        So, when the hostname==NULL, getaddrinfo function will
753        return one entry per allowed protocol family containing
754        the unspecified address for that family. */
755     hints.ai_flags    = AI_PASSIVE;
756     hints.ai_family   = AF_UNSPEC;
757     fd = t->fd;
758     hints.ai_socktype = SOCK_DGRAM;
759 
760     n = priv_getaddrinfo(t->bindaddr, t->bindport, &res, &hints);
761     if (n < 0)
762     {
763         log_warnx(NULL, "%s getaddrinfo error: %s", t->name, gai_strerror(n));
764         return -1;
765     }
766 
767     /* Try open socket with each address getaddrinfo returned,
768        until getting a valid listening socket. */
769     log_info(NULL, "%s bind to %s", t->name, *t->bindaddr ? t->bindaddr : "any");
770     n = bind(fd, res->ai_addr, res->ai_addrlen);
771     freeaddrinfo(res);
772     if (n < 0)
773     {
774         log_warn(NULL, "%s bind error", t->name);
775         return -1;
776     }
777     return 0;
778 }
779 
780 static int
mlvpn_rtun_start(mlvpn_tunnel_t * t)781 mlvpn_rtun_start(mlvpn_tunnel_t *t)
782 {
783     int ret, fd = -1;
784 	int fib = 0;
785     char *addr, *port;
786     struct addrinfo hints, *res;
787 
788     fd = t->fd;
789     if (t->server_mode)
790     {
791         addr = t->bindaddr;
792         port = t->bindport;
793 		fib = t->bindfib;
794     } else {
795         addr = t->destaddr;
796         port = t->destport;
797 		fib = t->bindfib;
798     }
799 
800     /* Initialize hints */
801     memset(&hints, 0, sizeof(hints));
802     hints.ai_family = AF_UNSPEC;
803     hints.ai_socktype = SOCK_DGRAM;
804 
805     ret = priv_getaddrinfo(addr, port, &t->addrinfo, &hints);
806     if (ret < 0 || !t->addrinfo)
807     {
808         log_warnx("dns", "%s getaddrinfo(%s,%s) failed: %s",
809            t->name, addr, port, gai_strerror(ret));
810         return -1;
811     }
812 
813     res = t->addrinfo;
814     while (res)
815     {
816         /* creation de la socket(2) */
817         if ( (fd = socket(t->addrinfo->ai_family,
818                           t->addrinfo->ai_socktype,
819                           t->addrinfo->ai_protocol)) < 0)
820         {
821             log_warn(NULL, "%s socket creation error",
822                 t->name);
823         } else {
824 #if (defined(HAVE_FREEBSD) || defined(HAVE_OPENBSD)) && !defined(__DragonFly__)
825 			/* Setting SO_SETFIB (fib) supported on FreeBSD and OpenBSD only */
826 			if (setsockopt(fd, SOL_SOCKET, SO_SETFIB, &fib, sizeof(fib)) < 0)
827 			{
828       			log_warnx(NULL, "Cannot set FIB %d for kernel socket", fib);
829 				goto error;
830 			}
831 #endif
832             t->fd = fd;
833             break;
834         }
835         res = res->ai_next;
836     }
837 
838     if (fd < 0) {
839         log_warnx("dns", "%s connection failed. Check DNS?",
840             t->name);
841         goto error;
842     }
843 
844     /* setup non blocking sockets */
845     socklen_t val = 1;
846     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(socklen_t)) < 0) {
847         log_warn(NULL, "%s setsockopt SO_REUSEADDR failed", t->name);
848         goto error;
849     }
850     if (*t->bindaddr) {
851         if (mlvpn_rtun_bind(t) < 0) {
852             goto error;
853         }
854     }
855 
856     /* set non blocking after connect... May lockup the entiere process */
857     mlvpn_sock_set_nonblocking(fd);
858     mlvpn_rtun_tick(t);
859     ev_io_set(&t->io_read, fd, EV_READ);
860     ev_io_set(&t->io_write, fd, EV_WRITE);
861     ev_io_start(EV_A_ &t->io_read);
862     t->io_timeout.repeat = MLVPN_IO_TIMEOUT_DEFAULT;
863     return 0;
864 error:
865     if (t->fd > 0) {
866         close(t->fd);
867         t->fd = -1;
868     }
869     if (t->io_timeout.repeat < MLVPN_IO_TIMEOUT_MAXIMUM)
870         t->io_timeout.repeat *= MLVPN_IO_TIMEOUT_INCREMENT;
871     return -1;
872 }
873 
874 static void
mlvpn_script_get_env(int * env_len,char *** env)875 mlvpn_script_get_env(int *env_len, char ***env) {
876     char **envp;
877     int arglen;
878     *env_len = 8;
879     *env = (char **)calloc(*env_len + 1, sizeof(char *));
880     if (! *env)
881         fatal(NULL, "out of memory");
882     envp = *env;
883     arglen = sizeof(mlvpn_options.ip4) + 4;
884     envp[0] = calloc(1, arglen + 1);
885     if (snprintf(envp[0], arglen, "IP4=%s", mlvpn_options.ip4) < 0)
886         log_warn(NULL, "snprintf IP4= failed");
887 
888     arglen = sizeof(mlvpn_options.ip6) + 4;
889     envp[1] = calloc(1, arglen + 1);
890     if (snprintf(envp[1], arglen, "IP6=%s", mlvpn_options.ip6) < 0)
891         log_warn(NULL, "snprintf IP6= failed");
892 
893     arglen = sizeof(mlvpn_options.ip4_gateway) + 12;
894     envp[2] = calloc(1, arglen + 1);
895     if (snprintf(envp[2], arglen, "IP4_GATEWAY=%s", mlvpn_options.ip4_gateway) < 0)
896         log_warn(NULL, "snprintf IP4_GATEWAY= failed");
897 
898     arglen = sizeof(mlvpn_options.ip6_gateway) + 12;
899     envp[3] = calloc(1, arglen + 1);
900     if (snprintf(envp[3], arglen, "IP6_GATEWAY=%s", mlvpn_options.ip6_gateway) < 0)
901         log_warn(NULL, "snprintf IP6_GATEWAY= failed");
902 
903     arglen = sizeof(mlvpn_options.ip4_routes) + 11;
904     envp[4] = calloc(1, arglen + 1);
905     if (snprintf(envp[4], arglen, "IP4_ROUTES=%s", mlvpn_options.ip4_routes) < 0)
906         log_warn(NULL, "snprintf IP4_ROUTES= failed");
907 
908     arglen = sizeof(mlvpn_options.ip6_routes) + 11;
909     envp[5] = calloc(1, arglen + 1);
910     if (snprintf(envp[5], arglen, "IP6_ROUTES=%s", mlvpn_options.ip6_routes) < 0)
911         log_warn(NULL, "snprintf IP6_ROUTES= failed");
912 
913     arglen = sizeof(tuntap.devname) + 7;
914     envp[6] = calloc(1, arglen + 1);
915     if (snprintf(envp[6], arglen, "DEVICE=%s", tuntap.devname) < 0)
916         log_warn(NULL, "snprintf DEVICE= failed");
917 
918     envp[7] = calloc(1, 16);
919     if (snprintf(envp[7], 15, "MTU=%d", mlvpn_options.mtu) < 0)
920         log_warn(NULL, "snprintf MTU= failed");
921     envp[8] = NULL;
922 }
923 
924 static void
mlvpn_free_script_env(char ** env)925 mlvpn_free_script_env(char **env)
926 {
927     char **envp = env;
928     while (*envp) {
929         free(*envp);
930         envp++;
931     }
932     free(env);
933 }
934 
935 static void
mlvpn_rtun_status_up(mlvpn_tunnel_t * t)936 mlvpn_rtun_status_up(mlvpn_tunnel_t *t)
937 {
938     char *cmdargs[4] = {tuntap.devname, "rtun_up", t->name, NULL};
939     char **env;
940     int env_len;
941     ev_tstamp now = ev_now(EV_DEFAULT_UC);
942     t->status = MLVPN_AUTHOK;
943     t->next_keepalive = NEXT_KEEPALIVE(now, t);
944     t->last_activity = now;
945     t->last_keepalive_ack = now;
946     t->last_keepalive_ack_sent = now;
947     mlvpn_update_status();
948     mlvpn_rtun_wrr_reset(&rtuns, mlvpn_status.fallback_mode);
949     mlvpn_script_get_env(&env_len, &env);
950     priv_run_script(3, cmdargs, env_len, env);
951     if (mlvpn_status.connected > 0 && mlvpn_status.initialized == 0) {
952         cmdargs[0] = tuntap.devname;
953         cmdargs[1] = "tuntap_up";
954         cmdargs[2] = NULL;
955         priv_run_script(2, cmdargs, env_len, env);
956         mlvpn_status.initialized = 1;
957         if (reorder_buffer != NULL) {
958             mlvpn_rtun_reorder_drain(0);
959             mlvpn_reorder_reset(reorder_buffer);
960         }
961     }
962     mlvpn_free_script_env(env);
963     update_process_title();
964 }
965 
966 void
mlvpn_rtun_status_down(mlvpn_tunnel_t * t)967 mlvpn_rtun_status_down(mlvpn_tunnel_t *t)
968 {
969     char *cmdargs[4] = {tuntap.devname, "rtun_down", t->name, NULL};
970     char **env;
971     int env_len;
972     enum chap_status old_status = t->status;
973     t->status = MLVPN_DISCONNECTED;
974     t->disconnects++;
975     mlvpn_pktbuffer_reset(t->sbuf);
976     mlvpn_pktbuffer_reset(t->hpsbuf);
977     if (ev_is_active(&t->io_write)) {
978         ev_io_stop(EV_A_ &t->io_write);
979     }
980 
981     mlvpn_update_status();
982     if (old_status >= MLVPN_AUTHOK)
983     {
984         mlvpn_script_get_env(&env_len, &env);
985         priv_run_script(3, cmdargs, env_len, env);
986         /* Re-initialize weight round robin */
987         mlvpn_rtun_wrr_reset(&rtuns, mlvpn_status.fallback_mode);
988         if (mlvpn_status.connected == 0 && mlvpn_status.initialized == 1) {
989             cmdargs[0] = tuntap.devname;
990             cmdargs[1] = "tuntap_down";
991             cmdargs[2] = NULL;
992             priv_run_script(2, cmdargs, env_len, env);
993             mlvpn_status.initialized = 0;
994         }
995         mlvpn_free_script_env(env);
996         if (reorder_buffer != NULL) {
997             mlvpn_rtun_reorder_drain(0);
998             mlvpn_reorder_reset(reorder_buffer);
999         }
1000     }
1001     update_process_title();
1002 }
1003 
1004 static void
mlvpn_update_status()1005 mlvpn_update_status()
1006 {
1007     mlvpn_tunnel_t *t;
1008     mlvpn_status.fallback_mode = mlvpn_options.fallback_available;
1009     mlvpn_status.connected = 0;
1010     LIST_FOREACH(t, &rtuns, entries)
1011     {
1012         if (t->status >= MLVPN_AUTHOK) {
1013             if (!t->fallback_only)
1014                 mlvpn_status.fallback_mode = 0;
1015             mlvpn_status.connected++;
1016         }
1017     }
1018 }
1019 
1020 static void
mlvpn_rtun_challenge_send(mlvpn_tunnel_t * t)1021 mlvpn_rtun_challenge_send(mlvpn_tunnel_t *t)
1022 {
1023     mlvpn_pkt_t *pkt;
1024 
1025     if (mlvpn_cb_is_full(t->hpsbuf))
1026         log_warnx("net", "%s high priority buffer: overflow", t->name);
1027 
1028     pkt = mlvpn_pktbuffer_write(t->hpsbuf);
1029     pkt->data[0] = 'A';
1030     pkt->data[1] = 'U';
1031     pkt->len = 2;
1032     pkt->type = MLVPN_PKT_AUTH;
1033 
1034     t->status = MLVPN_AUTHSENT;
1035     log_debug("protocol", "%s mlvpn_rtun_challenge_send", t->name);
1036 }
1037 
1038 static void
mlvpn_rtun_send_auth(mlvpn_tunnel_t * t)1039 mlvpn_rtun_send_auth(mlvpn_tunnel_t *t)
1040 {
1041     mlvpn_pkt_t *pkt;
1042     if (t->server_mode)
1043     {
1044         /* server side */
1045         if (t->status == MLVPN_DISCONNECTED || t->status >= MLVPN_AUTHOK)
1046         {
1047             if (mlvpn_cb_is_full(t->hpsbuf)) {
1048                 log_warnx("net", "%s high priority buffer: overflow", t->name);
1049                 mlvpn_cb_reset(t->hpsbuf);
1050             }
1051             pkt = mlvpn_pktbuffer_write(t->hpsbuf);
1052             pkt->data[0] = 'O';
1053             pkt->data[1] = 'K';
1054             pkt->len = 2;
1055             pkt->type = MLVPN_PKT_AUTH_OK;
1056             if (t->status < MLVPN_AUTHOK)
1057                 t->status = MLVPN_AUTHSENT;
1058             log_debug("protocol", "%s sending 'OK'", t->name);
1059             log_info("protocol", "%s authenticated", t->name);
1060             mlvpn_rtun_tick(t);
1061             mlvpn_rtun_status_up(t);
1062             if (!ev_is_active(&t->io_write)) {
1063                 ev_io_start(EV_A_ &t->io_write);
1064             }
1065         }
1066     } else {
1067         /* client side */
1068         if (t->status == MLVPN_AUTHSENT) {
1069             log_info("protocol", "%s authenticated", t->name);
1070             mlvpn_rtun_tick(t);
1071             mlvpn_rtun_status_up(t);
1072         }
1073     }
1074 }
1075 
1076 static void
mlvpn_rtun_tick_connect(mlvpn_tunnel_t * t)1077 mlvpn_rtun_tick_connect(mlvpn_tunnel_t *t)
1078 {
1079     ev_tstamp now = ev_now(EV_DEFAULT_UC);
1080     if (t->server_mode) {
1081         if (t->fd < 0) {
1082             if (mlvpn_rtun_start(t) == 0) {
1083                 t->conn_attempts = 0;
1084             } else {
1085                 return;
1086             }
1087         }
1088     } else {
1089         if (t->status < MLVPN_AUTHOK) {
1090             t->conn_attempts++;
1091             t->last_connection_attempt = now;
1092             if (t->fd < 0) {
1093                 if (mlvpn_rtun_start(t) == 0) {
1094                     t->conn_attempts = 0;
1095                 } else {
1096                     return;
1097                 }
1098             }
1099         }
1100         mlvpn_rtun_challenge_send(t);
1101     }
1102 }
1103 
1104 mlvpn_tunnel_t *
mlvpn_rtun_choose()1105 mlvpn_rtun_choose()
1106 {
1107     mlvpn_tunnel_t *tun;
1108     tun = mlvpn_rtun_wrr_choose();
1109     return tun;
1110 }
1111 
1112 static void
mlvpn_rtun_send_keepalive(ev_tstamp now,mlvpn_tunnel_t * t)1113 mlvpn_rtun_send_keepalive(ev_tstamp now, mlvpn_tunnel_t *t)
1114 {
1115     mlvpn_pkt_t *pkt;
1116     if (mlvpn_cb_is_full(t->hpsbuf))
1117         log_warnx("net", "%s high priority buffer: overflow", t->name);
1118     else {
1119         log_debug("protocol", "%s sending keepalive", t->name);
1120         pkt = mlvpn_pktbuffer_write(t->hpsbuf);
1121         pkt->type = MLVPN_PKT_KEEPALIVE;
1122     }
1123     t->next_keepalive = NEXT_KEEPALIVE(now, t);
1124 }
1125 
1126 static void
mlvpn_rtun_send_disconnect(mlvpn_tunnel_t * t)1127 mlvpn_rtun_send_disconnect(mlvpn_tunnel_t *t)
1128 {
1129     mlvpn_pkt_t *pkt;
1130     if (mlvpn_cb_is_full(t->hpsbuf))
1131         log_warnx("net", "%s high priority buffer: overflow", t->name);
1132     else {
1133         log_debug("protocol", "%s sending disconnect", t->name);
1134         pkt = mlvpn_pktbuffer_write(t->hpsbuf);
1135         pkt->type = MLVPN_PKT_DISCONNECT;
1136     }
1137     mlvpn_rtun_send(t, t->hpsbuf);
1138 }
1139 
1140 static void
mlvpn_rtun_check_lossy(mlvpn_tunnel_t * tun)1141 mlvpn_rtun_check_lossy(mlvpn_tunnel_t *tun)
1142 {
1143     int loss = mlvpn_loss_ratio(tun);
1144     int status_changed = 0;
1145     if (loss >= tun->loss_tolerence && tun->status == MLVPN_AUTHOK) {
1146         log_info("rtt", "%s packet loss reached threashold: %d%%/%d%%",
1147             tun->name, loss, tun->loss_tolerence);
1148         tun->status = MLVPN_LOSSY;
1149         status_changed = 1;
1150     } else if (loss < tun->loss_tolerence && tun->status == MLVPN_LOSSY) {
1151         log_info("rtt", "%s packet loss acceptable again: %d%%/%d%%",
1152             tun->name, loss, tun->loss_tolerence);
1153         tun->status = MLVPN_AUTHOK;
1154         status_changed = 1;
1155     }
1156     /* are all links in lossy mode ? switch to fallback ? */
1157     if (status_changed) {
1158         mlvpn_tunnel_t *t;
1159         LIST_FOREACH(t, &rtuns, entries) {
1160             if (! t->fallback_only && t->status != MLVPN_LOSSY) {
1161                 mlvpn_status.fallback_mode = 0;
1162                 mlvpn_rtun_wrr_reset(&rtuns, mlvpn_status.fallback_mode);
1163                 return;
1164             }
1165         }
1166         if (mlvpn_options.fallback_available) {
1167             log_info(NULL, "all tunnels are down or lossy, switch fallback mode");
1168             mlvpn_status.fallback_mode = 1;
1169             mlvpn_rtun_wrr_reset(&rtuns, mlvpn_status.fallback_mode);
1170         } else {
1171             log_info(NULL, "all tunnels are down or lossy but fallback is not available");
1172         }
1173     }
1174 }
1175 
1176 static void
mlvpn_rtun_check_timeout(EV_P_ ev_timer * w,int revents)1177 mlvpn_rtun_check_timeout(EV_P_ ev_timer *w, int revents)
1178 {
1179     mlvpn_tunnel_t *t = w->data;
1180     ev_tstamp now = ev_now(EV_DEFAULT_UC);
1181     double max_srtt = 0.0;
1182     double tmp;
1183     if (t->status >= MLVPN_AUTHOK && t->timeout > 0) {
1184         /* We don't want to monitor fallback only links inside the
1185          * reorder timeout algorithm
1186          */
1187         if (!t->fallback_only && t->rtt_hit) {
1188             tmp = t->srtt + (4 * t->rttvar);
1189             max_srtt = max_srtt > tmp ? max_srtt : tmp;
1190         }
1191         if ((t->last_keepalive_ack != 0) && (t->last_keepalive_ack + t->timeout) < now) {
1192             log_info("protocol", "%s timeout", t->name);
1193             mlvpn_rtun_status_down(t);
1194         } else {
1195             if (now > t->next_keepalive)
1196                 mlvpn_rtun_send_keepalive(now, t);
1197         }
1198     } else if (t->status < MLVPN_AUTHOK) {
1199         mlvpn_rtun_tick_connect(t);
1200     }
1201     if (!ev_is_active(&t->io_write) && ! mlvpn_cb_is_empty(t->hpsbuf)) {
1202         ev_io_start(EV_A_ &t->io_write);
1203     }
1204     /* Update the reorder algorithm */
1205     if (t->rtt_hit && max_srtt > 0) {
1206         /* Apply a factor to the srtt in order to get a window */
1207         max_srtt *= 2.0;
1208         log_debug("reorder", "adjusting reordering drain timeout to %.0fms",
1209             max_srtt);
1210         reorder_drain_timeout.repeat = max_srtt / 1000.0;
1211     } else {
1212         reorder_drain_timeout.repeat = 0.8; /* Conservative 800ms shot */
1213     }
1214     mlvpn_rtun_check_lossy(t);
1215 }
1216 
1217 static void
tuntap_io_event(EV_P_ ev_io * w,int revents)1218 tuntap_io_event(EV_P_ ev_io *w, int revents)
1219 {
1220     if (revents & EV_READ) {
1221         mlvpn_tuntap_read(&tuntap);
1222     } else if (revents & EV_WRITE) {
1223         mlvpn_tuntap_write(&tuntap);
1224         /* Nothing else to read */
1225         if (mlvpn_cb_is_empty(tuntap.sbuf)) {
1226             ev_io_stop(EV_A_ &tuntap.io_write);
1227         }
1228     }
1229 }
1230 
1231 static void
mlvpn_tuntap_init()1232 mlvpn_tuntap_init()
1233 {
1234     mlvpn_proto_t proto;
1235     memset(&tuntap, 0, sizeof(tuntap));
1236     snprintf(tuntap.devname, MLVPN_IFNAMSIZ-1, "%s", "mlvpn0");
1237     tuntap.maxmtu = 1500 - PKTHDRSIZ(proto) - IP4_UDP_OVERHEAD;
1238     log_debug(NULL, "absolute maximum mtu: %d", tuntap.maxmtu);
1239     tuntap.type = MLVPN_TUNTAPMODE_TUN;
1240     tuntap.sbuf = mlvpn_pktbuffer_init(PKTBUFSIZE);
1241     ev_init(&tuntap.io_read, tuntap_io_event);
1242     ev_init(&tuntap.io_write, tuntap_io_event);
1243 }
1244 
1245 static void
update_process_title()1246 update_process_title()
1247 {
1248     if (! process_title)
1249         return;
1250     char title[1024];
1251     char *s;
1252     mlvpn_tunnel_t *t;
1253     char status[32];
1254     int len;
1255     memset(title, 0, sizeof(title));
1256     if (*process_title)
1257         strlcat(title, process_title, sizeof(title));
1258     LIST_FOREACH(t, &rtuns, entries)
1259     {
1260         switch(t->status) {
1261             case MLVPN_AUTHOK:
1262                 s = "@";
1263                 break;
1264             case MLVPN_LOSSY:
1265                 s = "~";
1266                 break;
1267             default:
1268                 s = "!";
1269                 break;
1270         }
1271         len = snprintf(status, sizeof(status) - 1, " %s%s", s, t->name);
1272         if (len) {
1273             status[len] = 0;
1274             strlcat(title, status, sizeof(title));
1275         }
1276     }
1277     setproctitle("%s", title);
1278 }
1279 
1280 static void
mlvpn_config_reload(EV_P_ ev_signal * w,int revents)1281 mlvpn_config_reload(EV_P_ ev_signal *w, int revents)
1282 {
1283     log_info("config", "reload (SIGHUP)");
1284     priv_reload_resolver();
1285     /* configuration file path does not matter after
1286      * the first intialization.
1287      */
1288     int config_fd = priv_open_config("");
1289     if (config_fd > 0)
1290     {
1291         if (mlvpn_config(config_fd, 0) != 0) {
1292             log_warn("config", "reload failed");
1293         } else {
1294             if (time(&mlvpn_status.last_reload) == -1)
1295                 log_warn("config", "last_reload time set failed");
1296             mlvpn_rtun_recalc_weight();
1297         }
1298     } else {
1299         log_warn("config", "open failed");
1300     }
1301 }
1302 
1303 static void
mlvpn_quit(EV_P_ ev_signal * w,int revents)1304 mlvpn_quit(EV_P_ ev_signal *w, int revents)
1305 {
1306     mlvpn_tunnel_t *t;
1307     log_info(NULL, "killed by signal SIGTERM, SIGQUIT or SIGINT");
1308     LIST_FOREACH(t, &rtuns, entries)
1309     {
1310         ev_timer_stop(EV_A_ &t->io_timeout);
1311         ev_io_stop(EV_A_ &t->io_read);
1312         if (t->status >= MLVPN_AUTHOK) {
1313             mlvpn_rtun_send_disconnect(t);
1314         }
1315     }
1316     ev_break(EV_A_ EVBREAK_ALL);
1317 }
1318 
1319 int
main(int argc,char ** argv)1320 main(int argc, char **argv)
1321 {
1322     int i, c, option_index, config_fd;
1323     struct stat st;
1324     ev_signal signal_hup;
1325     ev_signal signal_sigquit, signal_sigint, signal_sigterm;
1326     extern char *__progname;
1327 #ifdef ENABLE_CONTROL
1328     struct mlvpn_control control;
1329 #endif
1330     /* uptime statistics */
1331     if (time(&mlvpn_status.start_time) == -1)
1332         log_warn(NULL, "start_time time() failed");
1333     if (time(&mlvpn_status.last_reload) == -1)
1334         log_warn(NULL, "last_reload time() failed");
1335 
1336     log_init(1, 2, "mlvpn");
1337 
1338     _progname = strdup(__progname);
1339     saved_argv = calloc(argc + 1, sizeof(*saved_argv));
1340     for(i = 0; i < argc; i++) {
1341         saved_argv[i] = strdup(argv[i]);
1342     }
1343     saved_argv[i] = NULL;
1344     compat_init_setproctitle(argc, argv);
1345     argv = saved_argv;
1346 
1347     /* Parse the command line quickly for config file name.
1348      * This is needed for priv_init to know where the config
1349      * file is.
1350      *
1351      * priv_init will not allow to change the config file path.
1352      */
1353     while(1)
1354     {
1355         c = getopt_long(argc, saved_argv, optstr,
1356                         long_options, &option_index);
1357         if (c == -1)
1358             break;
1359 
1360         switch (c)
1361         {
1362         case 1:  /* --natural-title */
1363             mlvpn_options.change_process_title = 0;
1364             break;
1365         case 2:  /* --debug */
1366             mlvpn_options.debug = 1;
1367             break;
1368         case 3:  /* --yes-run-as-root */
1369             mlvpn_options.root_allowed = 1;
1370             break;
1371         case 'c': /* --config */
1372             strlcpy(mlvpn_options.config_path, optarg,
1373                     sizeof(mlvpn_options.config_path));
1374             break;
1375         case 'D': /* debug= */
1376             mlvpn_options.debug = 1;
1377             log_accept(optarg);
1378             break;
1379         case 'n': /* --name */
1380             strlcpy(mlvpn_options.process_name, optarg,
1381                     sizeof(mlvpn_options.process_name));
1382             break;
1383         case 'u': /* --user */
1384             strlcpy(mlvpn_options.unpriv_user, optarg,
1385                     sizeof(mlvpn_options.unpriv_user));
1386             break;
1387         case 'v': /* --verbose */
1388             mlvpn_options.verbose++;
1389             break;
1390         case 'V': /* --version */
1391             printf("mlvpn version %s.\n", VERSION);
1392             _exit(0);
1393             break;
1394         case 'q': /* --quiet */
1395             mlvpn_options.verbose--;
1396             break;
1397         case 'h': /* --help */
1398         default:
1399             usage(argv);
1400         }
1401     }
1402 
1403     /* Config file check */
1404     if (access(mlvpn_options.config_path, R_OK) != 0) {
1405         log_warnx("config", "unable to read config file %s",
1406             mlvpn_options.config_path);
1407     }
1408     if (stat(mlvpn_options.config_path, &st) < 0) {
1409         fatal("config", "unable to open file");
1410     } else if (st.st_mode & (S_IRWXG|S_IRWXO)) {
1411         fatal("config", "file is group/other accessible");
1412     }
1413 
1414     /* Some common checks */
1415     if (getuid() == 0)
1416     {
1417         void *pw = getpwnam(mlvpn_options.unpriv_user);
1418         if (!mlvpn_options.root_allowed && ! pw)
1419             fatal(NULL, "you are not allowed to run this program as root. "
1420                         "please specify a valid user with --user option");
1421         if (! pw)
1422             fatal(NULL, "invalid unprivilged username");
1423     }
1424 
1425 #ifdef HAVE_LINUX
1426     if (access("/dev/net/tun", R_OK|W_OK) != 0)
1427     {
1428         fatal(NULL, "unable to open /dev/net/tun");
1429     }
1430 #endif
1431 
1432     if (mlvpn_options.change_process_title)
1433     {
1434         if (*mlvpn_options.process_name)
1435         {
1436             __progname = strdup(mlvpn_options.process_name);
1437             process_title = mlvpn_options.process_name;
1438             setproctitle("%s [priv]", mlvpn_options.process_name);
1439         } else {
1440             __progname = "mlvpn";
1441             process_title = "";
1442             setproctitle("[priv]");
1443         }
1444     }
1445 
1446     if (crypto_init() == -1)
1447         fatal(NULL, "libsodium initialization failed");
1448 
1449     log_init(mlvpn_options.debug, mlvpn_options.verbose, __progname);
1450 
1451 #ifdef HAVE_LINUX
1452     mlvpn_systemd_notify();
1453 #endif
1454 
1455     priv_init(argv, mlvpn_options.unpriv_user);
1456     if (mlvpn_options.change_process_title)
1457         update_process_title();
1458 
1459     LIST_INIT(&rtuns);
1460     freebuf = mlvpn_freebuffer_init(512);
1461 
1462     /* Kill me if my root process dies ! */
1463 #ifdef HAVE_LINUX
1464     prctl(PR_SET_PDEATHSIG, SIGCHLD);
1465 #endif
1466 
1467     /* Config file opening / parsing */
1468     config_fd = priv_open_config(mlvpn_options.config_path);
1469     if (config_fd < 0)
1470         fatalx("cannot open config file");
1471     if (! (loop = ev_default_loop(EVFLAG_AUTO)))
1472         fatal(NULL, "cannot initialize libev. check LIBEV_FLAGS?");
1473     /* tun/tap initialization */
1474     mlvpn_tuntap_init();
1475     if (mlvpn_config(config_fd, 1) != 0)
1476         fatalx("cannot open config file");
1477 
1478     if (mlvpn_tuntap_alloc(&tuntap) <= 0)
1479         fatalx("cannot create tunnel device");
1480     else
1481         log_info(NULL, "created interface `%s'", tuntap.devname);
1482 
1483     /* This is a dummy value which will be overwritten when the first
1484      * SRTT values will be available
1485      */
1486     ev_init(&reorder_drain_timeout, &mlvpn_rtun_reorder_drain_timeout);
1487     ev_io_set(&tuntap.io_read, tuntap.fd, EV_READ);
1488     ev_io_set(&tuntap.io_write, tuntap.fd, EV_WRITE);
1489     ev_io_start(loop, &tuntap.io_read);
1490 
1491     priv_set_running_state();
1492 
1493 #ifdef ENABLE_CONTROL
1494     /* Initialize mlvpn remote control system */
1495     strlcpy(control.fifo_path, mlvpn_options.control_unix_path,
1496         sizeof(control.fifo_path));
1497     control.mode = MLVPN_CONTROL_READWRITE;
1498     control.fifo_mode = 0600;
1499     control.bindaddr = strdup(mlvpn_options.control_bind_host);
1500     control.bindport = strdup(mlvpn_options.control_bind_port);
1501     mlvpn_control_init(&control);
1502 #endif
1503 
1504     /* re-compute rtun weight based on bandwidth allocation */
1505     mlvpn_rtun_recalc_weight();
1506 
1507     /* Last check before running */
1508     if (getppid() == 1)
1509         fatalx("Privileged process died");
1510 
1511     ev_signal_init(&signal_hup, mlvpn_config_reload, SIGHUP);
1512     ev_signal_init(&signal_sigint, mlvpn_quit, SIGINT);
1513     ev_signal_init(&signal_sigquit, mlvpn_quit, SIGQUIT);
1514     ev_signal_init(&signal_sigterm, mlvpn_quit, SIGTERM);
1515     ev_signal_start(loop, &signal_hup);
1516     ev_signal_start(loop, &signal_sigint);
1517     ev_signal_start(loop, &signal_sigquit);
1518     ev_signal_start(loop, &signal_sigterm);
1519 
1520     ev_run(loop, 0);
1521 
1522     free(_progname);
1523     return 0;
1524 }
1525