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