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