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