9a67bb3cebb63e1c0529c09fc50f21c6f83e5094
[tinc] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2014 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2009      Florian Forster <octo@verplant.org>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include "avl_tree.h"
26 #include "conf.h"
27 #include "connection.h"
28 #include "event.h"
29 #include "logger.h"
30 #include "meta.h"
31 #include "net.h"
32 #include "netutl.h"
33 #include "protocol.h"
34 #include "utils.h"
35 #include "xalloc.h"
36
37 /* Needed on Mac OS/X */
38 #ifndef SOL_TCP
39 #define SOL_TCP IPPROTO_TCP
40 #endif
41
42 int addressfamily = AF_UNSPEC;
43 int maxtimeout = 900;
44 int seconds_till_retry = 5;
45 int udp_rcvbuf = 0;
46 int udp_sndbuf = 0;
47
48 listen_socket_t listen_socket[MAXSOCKETS];
49 int listen_sockets;
50 list_t *outgoing_list = NULL;
51
52 /* Setup sockets */
53
54 static void configure_tcp(connection_t *c) {
55         int option;
56
57 #ifdef O_NONBLOCK
58         int flags = fcntl(c->socket, F_GETFL);
59
60         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
61                 logger(LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
62         }
63 #elif defined(WIN32)
64         unsigned long arg = 1;
65
66         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
67                 logger(LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
68         }
69 #endif
70
71 #if defined(SOL_TCP) && defined(TCP_NODELAY)
72         option = 1;
73         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof(option));
74 #endif
75
76 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
77         option = IPTOS_LOWDELAY;
78         setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof(option));
79 #endif
80 }
81
82 static bool bind_to_interface(int sd) {
83         char *iface;
84
85 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
86         struct ifreq ifr;
87         int status;
88 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
89
90         if(!get_config_string(lookup_config (config_tree, "BindToInterface"), &iface))
91                 return true;
92
93 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
94         memset(&ifr, 0, sizeof(ifr));
95         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
96         ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
97         free(iface);
98
99         status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
100         if(status) {
101                 logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(errno));
102                 return false;
103         }
104
105 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
106         logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
107 #endif
108
109         return true;
110 }
111
112 int setup_listen_socket(const sockaddr_t *sa) {
113         int nfd;
114         char *addrstr;
115         int option;
116         char *iface;
117
118         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
119
120         if(nfd < 0) {
121                 ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
122                 return -1;
123         }
124
125 #ifdef FD_CLOEXEC
126         fcntl(nfd, F_SETFD, FD_CLOEXEC);
127 #endif
128
129         /* Optimize TCP settings */
130
131         option = 1;
132         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
133
134 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
135         if(sa->sa.sa_family == AF_INET6)
136                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
137 #endif
138
139         if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
140 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
141                 struct ifreq ifr;
142
143                 memset(&ifr, 0, sizeof(ifr));
144                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
145                 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
146                 free(iface);
147
148                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
149                         closesocket(nfd);
150                         logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(sockerrno));
151                         return -1;
152                 }
153
154 #else
155                 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
156 #endif
157         }
158
159         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
160                 closesocket(nfd);
161                 addrstr = sockaddr2hostname(sa);
162                 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
163                 free(addrstr);
164                 return -1;
165         }
166
167         if(listen(nfd, 3)) {
168                 closesocket(nfd);
169                 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
170                 return -1;
171         }
172
173         return nfd;
174 }
175
176 int setup_vpn_in_socket(const sockaddr_t *sa) {
177         int nfd;
178         char *addrstr;
179         int option;
180
181         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
182
183         if(nfd < 0) {
184                 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
185                 return -1;
186         }
187
188 #ifdef FD_CLOEXEC
189         fcntl(nfd, F_SETFD, FD_CLOEXEC);
190 #endif
191
192 #ifdef O_NONBLOCK
193         {
194                 int flags = fcntl(nfd, F_GETFL);
195
196                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
197                         closesocket(nfd);
198                         logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
199                                    strerror(errno));
200                         return -1;
201                 }
202         }
203 #elif defined(WIN32)
204         {
205                 unsigned long arg = 1;
206                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
207                         closesocket(nfd);
208                         logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
209                         return -1;
210                 }
211         }
212 #endif
213
214         option = 1;
215         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
216         setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
217
218         if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
219                 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
220
221         if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
222                 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
223
224 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
225         if(sa->sa.sa_family == AF_INET6)
226                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
227 #endif
228
229 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
230 #define IP_DONTFRAGMENT IP_DONTFRAG
231 #endif
232
233 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
234         if(myself->options & OPTION_PMTU_DISCOVERY) {
235                 option = IP_PMTUDISC_DO;
236                 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
237         }
238 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
239         if(myself->options & OPTION_PMTU_DISCOVERY) {
240                 option = 1;
241                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
242         }
243 #endif
244
245 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
246         if(myself->options & OPTION_PMTU_DISCOVERY) {
247                 option = IPV6_PMTUDISC_DO;
248                 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
249         }
250 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
251         if(myself->options & OPTION_PMTU_DISCOVERY) {
252                 option = 1;
253                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
254         }
255 #endif
256
257         if (!bind_to_interface(nfd)) {
258                 closesocket(nfd);
259                 return -1;
260         }
261
262         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
263                 closesocket(nfd);
264                 addrstr = sockaddr2hostname(sa);
265                 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
266                 free(addrstr);
267                 return -1;
268         }
269
270         return nfd;
271 } /* int setup_vpn_in_socket */
272
273 void retry_outgoing(outgoing_t *outgoing) {
274         outgoing->timeout += 5;
275
276         if(outgoing->timeout > maxtimeout)
277                 outgoing->timeout = maxtimeout;
278
279         if(outgoing->event)
280                 event_del(outgoing->event);
281         outgoing->event = new_event();
282         outgoing->event->handler = (event_handler_t) setup_outgoing_connection;
283         outgoing->event->time = now + outgoing->timeout;
284         outgoing->event->data = outgoing;
285         event_add(outgoing->event);
286
287         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
288                            "Trying to re-establish outgoing connection in %d seconds",
289                            outgoing->timeout);
290 }
291
292 void finish_connecting(connection_t *c) {
293         ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
294
295         c->last_ping_time = now;
296
297         send_id(c);
298 }
299
300 static void do_outgoing_pipe(connection_t *c, char *command) {
301 #ifndef HAVE_MINGW
302         int fd[2];
303
304         if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
305                 logger(LOG_ERR, "Could not create socketpair: %s\n", strerror(errno));
306                 return;
307         }
308
309         if(fork()) {
310                 c->socket = fd[0];
311                 close(fd[1]);
312                 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Using proxy %s", command);
313                 return;
314         }
315
316         close(0);
317         close(1);
318         close(fd[0]);
319         dup2(fd[1], 0);
320         dup2(fd[1], 1);
321         close(fd[1]);
322
323         // Other filedescriptors should be closed automatically by CLOEXEC
324
325         char *host = NULL;
326         char *port = NULL;
327
328         sockaddr2str(&c->address, &host, &port);
329         setenv("REMOTEADDRESS", host, true);
330         setenv("REMOTEPORT", port, true);
331         setenv("NODE", c->name, true);
332         setenv("NAME", myself->name, true);
333         if(netname)
334                 setenv("NETNAME", netname, true);
335
336         int result = system(command);
337         if(result < 0)
338                 logger(LOG_ERR, "Could not execute %s: %s\n", command, strerror(errno));
339         else if(result)
340                 logger(LOG_ERR, "%s exited with non-zero status %d", command, result);
341         exit(result);
342 #else
343         logger(LOG_ERR, "Proxy type exec not supported on this platform!");
344         return;
345 #endif
346 }
347
348 void do_outgoing_connection(connection_t *c) {
349         char *address, *port, *space;
350         struct addrinfo *proxyai = NULL;
351         int result;
352
353         if(!c->outgoing) {
354                 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
355                 abort();
356         }
357
358 begin:
359         if(!c->outgoing->ai) {
360                 if(!c->outgoing->cfg) {
361                         ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
362                                            c->name);
363                         c->status.remove = true;
364                         retry_outgoing(c->outgoing);
365                         c->outgoing = NULL;
366                         return;
367                 }
368
369                 get_config_string(c->outgoing->cfg, &address);
370
371                 space = strchr(address, ' ');
372                 if(space) {
373                         port = xstrdup(space + 1);
374                         *space = 0;
375                 } else {
376                         if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
377                                 port = xstrdup("655");
378                 }
379
380                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
381                 free(address);
382                 free(port);
383
384                 c->outgoing->aip = c->outgoing->ai;
385                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
386         }
387
388         if(!c->outgoing->aip) {
389                 if(c->outgoing->ai)
390                         freeaddrinfo(c->outgoing->ai);
391                 c->outgoing->ai = NULL;
392                 goto begin;
393         }
394
395         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
396         c->outgoing->aip = c->outgoing->aip->ai_next;
397
398         if(c->hostname)
399                 free(c->hostname);
400
401         c->hostname = sockaddr2hostname(&c->address);
402
403         ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
404                            c->hostname);
405
406         if(!proxytype) {
407                 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
408         } else if(proxytype == PROXY_EXEC) {
409                 do_outgoing_pipe(c, proxyhost);
410         } else {
411                 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
412                 if(!proxyai)
413                         goto begin;
414                 ifdebug(CONNECTIONS) logger(LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
415                 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
416         }
417
418         if(c->socket == -1) {
419                 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
420                 goto begin;
421         }
422
423         if(proxytype != PROXY_EXEC)
424                 configure_tcp(c);
425
426 #ifdef FD_CLOEXEC
427         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
428 #endif
429
430         if(proxytype != PROXY_EXEC) {
431 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
432                 int option = 1;
433                 if(c->address.sa.sa_family == AF_INET6)
434                         setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
435 #endif
436
437                 bind_to_interface(c->socket);
438         }
439
440         /* Connect */
441
442         if(!proxytype) {
443                 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
444         } else if(proxytype == PROXY_EXEC) {
445                 result = 0;
446         } else {
447                 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
448                 freeaddrinfo(proxyai);
449         }
450
451         if(result == -1) {
452                 if(sockinprogress(sockerrno)) {
453                         c->status.connecting = true;
454                         return;
455                 }
456
457                 closesocket(c->socket);
458
459                 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
460
461                 goto begin;
462         }
463
464         finish_connecting(c);
465
466         return;
467 }
468
469 void setup_outgoing_connection(outgoing_t *outgoing) {
470         connection_t *c;
471         node_t *n;
472
473         outgoing->event = NULL;
474
475         n = lookup_node(outgoing->name);
476
477         if(n)
478                 if(n->connection) {
479                         ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
480
481                         n->connection->outgoing = outgoing;
482                         return;
483                 }
484
485         c = new_connection();
486         c->name = xstrdup(outgoing->name);
487         c->outcipher = myself->connection->outcipher;
488         c->outdigest = myself->connection->outdigest;
489         c->outmaclength = myself->connection->outmaclength;
490         c->outcompression = myself->connection->outcompression;
491
492         init_configuration(&c->config_tree);
493         read_connection_config(c);
494
495         outgoing->cfg = lookup_config(c->config_tree, "Address");
496
497         if(!outgoing->cfg) {
498                 logger(LOG_ERR, "No address specified for %s", c->name);
499                 free_connection(c);
500                 return;
501         }
502
503         c->outgoing = outgoing;
504         c->last_ping_time = now;
505
506         connection_add(c);
507
508         do_outgoing_connection(c);
509 }
510
511 /*
512   accept a new tcp connect and create a
513   new connection
514 */
515 bool handle_new_meta_connection(int sock) {
516         connection_t *c;
517         sockaddr_t sa;
518         int fd;
519         socklen_t len = sizeof(sa);
520
521         fd = accept(sock, &sa.sa, &len);
522
523         if(fd < 0) {
524                 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
525                 return false;
526         }
527
528         sockaddrunmap(&sa);
529
530         c = new_connection();
531         c->name = xstrdup("<unknown>");
532         c->outcipher = myself->connection->outcipher;
533         c->outdigest = myself->connection->outdigest;
534         c->outmaclength = myself->connection->outmaclength;
535         c->outcompression = myself->connection->outcompression;
536
537         c->address = sa;
538         c->hostname = sockaddr2hostname(&sa);
539         c->socket = fd;
540         c->last_ping_time = now;
541
542         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
543
544         configure_tcp(c);
545
546         connection_add(c);
547
548         c->allow_request = ID;
549         send_id(c);
550
551         return true;
552 }
553
554 static void free_outgoing(outgoing_t *outgoing) {
555         if(outgoing->ai)
556                 freeaddrinfo(outgoing->ai);
557
558         if(outgoing->name)
559                 free(outgoing->name);
560
561         free(outgoing);
562 }
563
564 void try_outgoing_connections(void) {
565         static config_t *cfg = NULL;
566         char *name;
567         outgoing_t *outgoing;
568         
569         outgoing_list = list_alloc((list_action_t)free_outgoing);
570                         
571         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
572                 get_config_string(cfg, &name);
573
574                 if(!check_id(name)) {
575                         logger(LOG_ERR,
576                                    "Invalid name for outgoing connection in %s line %d",
577                                    cfg->file, cfg->line);
578                         free(name);
579                         continue;
580                 }
581
582                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
583                 outgoing->name = name;
584                 list_insert_tail(outgoing_list, outgoing);
585                 setup_outgoing_connection(outgoing);
586         }
587 }