]> git.meshlink.io Git - meshlink/blob - src/net_socket.c
Merge branch 'master' into 1.1
[meshlink] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2009 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id$
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 #ifdef WSAEINPROGRESS
37 #define EINPROGRESS WSAEINPROGRESS
38 #endif
39
40 /* Needed on Mac OS/X */
41 #ifndef SOL_TCP
42 #define SOL_TCP IPPROTO_TCP
43 #endif
44
45 int addressfamily = AF_UNSPEC;
46 int maxtimeout = 900;
47 int seconds_till_retry = 5;
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 #ifdef O_NONBLOCK
59         int flags = fcntl(c->socket, F_GETFL);
60
61         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
62                 logger(LOG_ERR, _("fcntl for %s: %s"), c->hostname, strerror(errno));
63         }
64 #elif defined(WIN32)
65         unsigned long arg = 1;
66
67         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
68                 logger(LOG_ERR, _("ioctlsocket for %s: WSA error %d"), c->hostname, WSAGetLastError());
69         }
70 #endif
71
72 #if defined(SOL_TCP) && defined(TCP_NODELAY)
73         option = 1;
74         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof option);
75 #endif
76
77 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
78         option = IPTOS_LOWDELAY;
79         setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof option);
80 #endif
81 }
82
83 int setup_listen_socket(const sockaddr_t *sa) {
84         int nfd;
85         char *addrstr;
86         int option;
87         char *iface;
88
89         cp();
90
91         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
92
93         if(nfd < 0) {
94                 ifdebug(STATUS) logger(LOG_ERR, _("Creating metasocket failed: %s"), strerror(errno));
95                 return -1;
96         }
97
98         /* Optimize TCP settings */
99
100         option = 1;
101         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof option);
102
103 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
104         if(sa->sa.sa_family == AF_INET6)
105                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
106 #endif
107
108         if(get_config_string
109            (lookup_config(config_tree, "BindToInterface"), &iface)) {
110 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
111                 struct ifreq ifr;
112
113                 memset(&ifr, 0, sizeof ifr);
114                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
115
116                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof ifr)) {
117                         closesocket(nfd);
118                         logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
119                                    strerror(errno));
120                         return -1;
121                 }
122 #else
123                 logger(LOG_WARNING, _("BindToInterface not supported on this platform"));
124 #endif
125         }
126
127         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
128                 closesocket(nfd);
129                 addrstr = sockaddr2hostname(sa);
130                 logger(LOG_ERR, _("Can't bind to %s/tcp: %s"), addrstr,
131                            strerror(errno));
132                 free(addrstr);
133                 return -1;
134         }
135
136         if(listen(nfd, 3)) {
137                 closesocket(nfd);
138                 logger(LOG_ERR, _("System call `%s' failed: %s"), "listen",
139                            strerror(errno));
140                 return -1;
141         }
142
143         return nfd;
144 }
145
146 int setup_vpn_in_socket(const sockaddr_t *sa) {
147         int nfd;
148         char *addrstr;
149         int option;
150
151         cp();
152
153         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
154
155         if(nfd < 0) {
156                 logger(LOG_ERR, _("Creating UDP socket failed: %s"), strerror(errno));
157                 return -1;
158         }
159
160 #ifdef O_NONBLOCK
161         {
162                 int flags = fcntl(nfd, F_GETFL);
163
164                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
165                         closesocket(nfd);
166                         logger(LOG_ERR, _("System call `%s' failed: %s"), "fcntl",
167                                    strerror(errno));
168                         return -1;
169                 }
170         }
171 #elif defined(WIN32)
172         {
173                 unsigned long arg = 1;
174                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
175                         closesocket(nfd);
176                         logger(LOG_ERR, _("Call to `%s' failed: WSA error %d"), "ioctlsocket",
177                                 WSAGetLastError());
178                         return -1;
179                 }
180         }
181 #endif
182
183         option = 1;
184         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof option);
185
186 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
187         if(sa->sa.sa_family == AF_INET6)
188                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
189 #endif
190
191 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
192         if(myself->options & OPTION_PMTU_DISCOVERY) {
193                 option = IP_PMTUDISC_DO;
194                 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, &option, sizeof(option));
195         }
196 #endif
197
198 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
199         if(myself->options & OPTION_PMTU_DISCOVERY) {
200                 option = IPV6_PMTUDISC_DO;
201                 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, &option, sizeof(option));
202         }
203 #endif
204
205 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
206         {
207                 char *iface;
208                 struct ifreq ifr;
209
210                 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
211                         memset(&ifr, 0, sizeof ifr);
212                         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
213
214                         if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof ifr)) {
215                                 closesocket(nfd);
216                                 logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
217                                            strerror(errno));
218                                 return -1;
219                         }
220                 }
221         }
222 #endif
223
224         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
225                 closesocket(nfd);
226                 addrstr = sockaddr2hostname(sa);
227                 logger(LOG_ERR, _("Can't bind to %s/udp: %s"), addrstr,
228                            strerror(errno));
229                 free(addrstr);
230                 return -1;
231         }
232
233         return nfd;
234 }
235
236 static void retry_outgoing_handler(int fd, short events, void *data) {
237         setup_outgoing_connection(data);
238 }
239
240 void retry_outgoing(outgoing_t *outgoing) {
241         cp();
242
243         outgoing->timeout += 5;
244
245         if(outgoing->timeout > maxtimeout)
246                 outgoing->timeout = maxtimeout;
247
248         timeout_set(&outgoing->ev, retry_outgoing_handler, outgoing);
249         event_add(&outgoing->ev, &(struct timeval){outgoing->timeout, 0});
250
251         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
252                            _("Trying to re-establish outgoing connection in %d seconds"),
253                            outgoing->timeout);
254 }
255
256 void finish_connecting(connection_t *c) {
257         cp();
258
259         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Connected to %s (%s)"), c->name, c->hostname);
260
261         configure_tcp(c);
262
263         c->last_ping_time = time(NULL);
264         c->status.connecting = false;
265
266         send_id(c);
267 }
268
269 void do_outgoing_connection(connection_t *c) {
270         char *address, *port;
271         int result;
272
273         cp();
274
275 begin:
276         if(!c->outgoing->ai) {
277                 if(!c->outgoing->cfg) {
278                         ifdebug(CONNECTIONS) logger(LOG_ERR, _("Could not set up a meta connection to %s"),
279                                            c->name);
280                         retry_outgoing(c->outgoing);
281                         c->outgoing = NULL;
282                         connection_del(c);
283                         return;
284                 }
285
286                 get_config_string(c->outgoing->cfg, &address);
287
288                 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
289                         asprintf(&port, "655");
290
291                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
292                 free(address);
293                 free(port);
294
295                 c->outgoing->aip = c->outgoing->ai;
296                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
297         }
298
299         if(!c->outgoing->aip) {
300                 if(c->outgoing->ai)
301                         freeaddrinfo(c->outgoing->ai);
302                 c->outgoing->ai = NULL;
303                 goto begin;
304         }
305
306         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
307         c->outgoing->aip = c->outgoing->aip->ai_next;
308
309         if(c->hostname)
310                 free(c->hostname);
311
312         c->hostname = sockaddr2hostname(&c->address);
313
314         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Trying to connect to %s (%s)"), c->name,
315                            c->hostname);
316
317         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
318
319         if(c->socket == -1) {
320                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("Creating socket for %s failed: %s"), c->hostname,
321                                    strerror(errno));
322
323                 goto begin;
324         }
325
326 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
327         int option = 1;
328         if(c->address.sa.sa_family == AF_INET6)
329                 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
330 #endif
331
332         /* Optimize TCP settings */
333
334         configure_tcp(c);
335
336         /* Connect */
337
338         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
339
340         if(result == -1) {
341                 if(errno == EINPROGRESS
342 #if defined(WIN32) && !defined(O_NONBLOCK)
343                    || WSAGetLastError() == WSAEWOULDBLOCK
344 #endif
345                 ) {
346                         c->status.connecting = true;
347                         return;
348                 }
349
350                 closesocket(c->socket);
351
352                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("%s: %s"), c->hostname, strerror(errno));
353
354                 goto begin;
355         }
356
357         finish_connecting(c);
358
359         return;
360 }
361
362 void handle_meta_read(struct bufferevent *event, void *data) {
363         logger(LOG_EMERG, _("handle_meta_read() called"));
364         abort();
365 }
366
367 void handle_meta_write(struct bufferevent *event, void *data) {
368         ifdebug(META) logger(LOG_DEBUG, _("handle_meta_write() called"));
369 }
370
371 void handle_meta_connection_error(struct bufferevent *event, short what, void *data) {
372         connection_t *c = data;
373         logger(LOG_EMERG, _("handle_meta_connection_error() called: %d: %s"), what, strerror(errno));
374         terminate_connection(c, c->status.active);
375 }
376
377 void setup_outgoing_connection(outgoing_t *outgoing) {
378         connection_t *c;
379         node_t *n;
380
381         cp();
382
383         n = lookup_node(outgoing->name);
384
385         if(n)
386                 if(n->connection) {
387                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Already connected to %s"), outgoing->name);
388
389                         n->connection->outgoing = outgoing;
390                         return;
391                 }
392
393         c = new_connection();
394         c->name = xstrdup(outgoing->name);
395         c->outcipher = myself->connection->outcipher;
396         c->outdigest = myself->connection->outdigest;
397         c->outmaclength = myself->connection->outmaclength;
398         c->outcompression = myself->connection->outcompression;
399
400         init_configuration(&c->config_tree);
401         read_connection_config(c);
402
403         outgoing->cfg = lookup_config(c->config_tree, "Address");
404
405         if(!outgoing->cfg) {
406                 logger(LOG_ERR, _("No address specified for %s"), c->name);
407                 free_connection(c);
408                 return;
409         }
410
411         c->outgoing = outgoing;
412         c->last_ping_time = time(NULL);
413
414         connection_add(c);
415
416         do_outgoing_connection(c);
417
418         event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
419         event_add(&c->inevent, NULL);
420         c->buffer = bufferevent_new(c->socket, handle_meta_read, handle_meta_write, handle_meta_connection_error, c);
421         if(!c->buffer) {
422                 logger(LOG_EMERG, _("bufferevent_new() failed: %s"), strerror(errno));
423                 abort();
424         }
425         bufferevent_disable(c->buffer, EV_READ);
426 }
427
428 /*
429   accept a new tcp connect and create a
430   new connection
431 */
432 void handle_new_meta_connection(int sock, short events, void *data) {
433         connection_t *c;
434         sockaddr_t sa;
435         int fd;
436         socklen_t len = sizeof sa;
437
438         cp();
439
440         fd = accept(sock, &sa.sa, &len);
441
442         if(fd < 0) {
443                 logger(LOG_ERR, _("Accepting a new connection failed: %s"), strerror(errno));
444                 return;
445         }
446
447         sockaddrunmap(&sa);
448
449         c = new_connection();
450         c->name = xstrdup("<unknown>");
451         c->outcipher = myself->connection->outcipher;
452         c->outdigest = myself->connection->outdigest;
453         c->outmaclength = myself->connection->outmaclength;
454         c->outcompression = myself->connection->outcompression;
455
456         c->address = sa;
457         c->hostname = sockaddr2hostname(&sa);
458         c->socket = fd;
459         c->last_ping_time = time(NULL);
460
461         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection from %s"), c->hostname);
462
463         event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
464         event_add(&c->inevent, NULL);
465         c->buffer = bufferevent_new(c->socket, NULL, handle_meta_write, handle_meta_connection_error, c);
466         if(!c->buffer) {
467                 logger(LOG_EMERG, _("bufferevent_new() failed: %s"), strerror(errno));
468                 abort();
469         }
470         bufferevent_disable(c->buffer, EV_READ);
471                 
472         configure_tcp(c);
473
474         connection_add(c);
475
476         c->allow_request = ID;
477         send_id(c);
478 }
479
480 void free_outgoing(outgoing_t *outgoing) {
481         if(outgoing->ai)
482                 freeaddrinfo(outgoing->ai);
483
484         if(outgoing->name)
485                 free(outgoing->name);
486
487         free(outgoing);
488 }
489
490 void try_outgoing_connections(void)
491 {
492         static config_t *cfg = NULL;
493         char *name;
494         outgoing_t *outgoing;
495         connection_t *c;
496         splay_node_t *node;
497         
498         cp();
499
500         if(outgoing_list) {
501                 for(node = connection_tree->head; node; node = node->next) {
502                         c = node->data;
503                         c->outgoing = NULL;
504                 }
505
506                 list_delete_list(outgoing_list);
507         }
508
509         outgoing_list = list_alloc((list_action_t)free_outgoing);
510                         
511         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
512                 get_config_string(cfg, &name);
513
514                 if(!check_id(name)) {
515                         logger(LOG_ERR,
516                                    _("Invalid name for outgoing connection in %s line %d"),
517                                    cfg->file, cfg->line);
518                         free(name);
519                         continue;
520                 }
521
522                 outgoing = xmalloc_and_zero(sizeof *outgoing);
523                 outgoing->name = name;
524                 list_insert_tail(outgoing_list, outgoing);
525                 setup_outgoing_connection(outgoing);
526         }
527 }