]> git.meshlink.io Git - meshlink/blob - src/net_socket.c
Move RSA key generation into the wrappers.
[meshlink] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2007 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
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: WSA error %d"), c->hostname, WSAGetLastError());
68         }
69 #endif
70
71 #if defined(SOL_TCP) && defined(TCP_NODELAY)
72         option = 1;
73         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &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, &option, sizeof option);
79 #endif
80 }
81
82 int setup_listen_socket(const sockaddr_t *sa) {
83         int nfd;
84         char *addrstr;
85         int option;
86         char *iface;
87
88         cp();
89
90         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
91
92         if(nfd < 0) {
93                 ifdebug(STATUS) logger(LOG_ERR, _("Creating metasocket failed: %s"), strerror(errno));
94                 return -1;
95         }
96
97         /* Optimize TCP settings */
98
99         option = 1;
100         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof option);
101
102 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
103         if(sa->sa.sa_family == AF_INET6)
104                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
105 #endif
106
107         if(get_config_string
108            (lookup_config(config_tree, "BindToInterface"), &iface)) {
109 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
110                 struct ifreq ifr;
111
112                 memset(&ifr, 0, sizeof ifr);
113                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
114
115                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof ifr)) {
116                         closesocket(nfd);
117                         logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
118                                    strerror(errno));
119                         return -1;
120                 }
121 #else
122                 logger(LOG_WARNING, _("BindToInterface not supported on this platform"));
123 #endif
124         }
125
126         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
127                 closesocket(nfd);
128                 addrstr = sockaddr2hostname(sa);
129                 logger(LOG_ERR, _("Can't bind to %s/tcp: %s"), addrstr,
130                            strerror(errno));
131                 free(addrstr);
132                 return -1;
133         }
134
135         if(listen(nfd, 3)) {
136                 closesocket(nfd);
137                 logger(LOG_ERR, _("System call `%s' failed: %s"), "listen",
138                            strerror(errno));
139                 return -1;
140         }
141
142         return nfd;
143 }
144
145 int setup_vpn_in_socket(const sockaddr_t *sa) {
146         int nfd;
147         char *addrstr;
148         int option;
149
150         cp();
151
152         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
153
154         if(nfd < 0) {
155                 logger(LOG_ERR, _("Creating UDP socket failed: %s"), strerror(errno));
156                 return -1;
157         }
158
159 #ifdef O_NONBLOCK
160         {
161                 int flags = fcntl(nfd, F_GETFL);
162
163                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
164                         closesocket(nfd);
165                         logger(LOG_ERR, _("System call `%s' failed: %s"), "fcntl",
166                                    strerror(errno));
167                         return -1;
168                 }
169         }
170 #elif defined(WIN32)
171         {
172                 unsigned long arg = 1;
173                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
174                         closesocket(nfd);
175                         logger(LOG_ERR, _("Call to `%s' failed: WSA error %d"), "ioctlsocket",
176                                 WSAGetLastError());
177                         return -1;
178                 }
179         }
180 #endif
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 defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
191         {
192                 bool choice;
193
194                 if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice) {
195                         option = IP_PMTUDISC_DO;
196                         setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, &option, sizeof option);
197                 }
198         }
199 #endif
200
201 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
202         {
203                 bool choice;
204
205                 if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice) {
206                         option = IPV6_PMTUDISC_DO;
207                         setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, &option, sizeof option);
208                 }
209         }
210 #endif
211
212 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
213         {
214                 char *iface;
215                 struct ifreq ifr;
216
217                 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
218                         memset(&ifr, 0, sizeof ifr);
219                         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
220
221                         if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof ifr)) {
222                                 closesocket(nfd);
223                                 logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
224                                            strerror(errno));
225                                 return -1;
226                         }
227                 }
228         }
229 #endif
230
231         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
232                 closesocket(nfd);
233                 addrstr = sockaddr2hostname(sa);
234                 logger(LOG_ERR, _("Can't bind to %s/udp: %s"), addrstr,
235                            strerror(errno));
236                 free(addrstr);
237                 return -1;
238         }
239
240         return nfd;
241 }
242
243 static void retry_outgoing_handler(int fd, short events, void *data) {
244         setup_outgoing_connection(data);
245 }
246
247 void retry_outgoing(outgoing_t *outgoing) {
248         cp();
249
250         outgoing->timeout += 5;
251
252         if(outgoing->timeout > maxtimeout)
253                 outgoing->timeout = maxtimeout;
254
255         timeout_set(&outgoing->ev, retry_outgoing_handler, outgoing);
256         event_add(&outgoing->ev, &(struct timeval){outgoing->timeout, 0});
257
258         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
259                            _("Trying to re-establish outgoing connection in %d seconds"),
260                            outgoing->timeout);
261 }
262
263 void finish_connecting(connection_t *c) {
264         cp();
265
266         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Connected to %s (%s)"), c->name, c->hostname);
267
268         configure_tcp(c);
269
270         c->last_ping_time = time(NULL);
271         c->status.connecting = false;
272
273         send_id(c);
274 }
275
276 void do_outgoing_connection(connection_t *c) {
277         char *address, *port;
278         int result;
279
280         cp();
281
282 begin:
283         if(!c->outgoing->ai) {
284                 if(!c->outgoing->cfg) {
285                         ifdebug(CONNECTIONS) logger(LOG_ERR, _("Could not set up a meta connection to %s"),
286                                            c->name);
287                         retry_outgoing(c->outgoing);
288                         c->outgoing = NULL;
289                         connection_del(c);
290                         return;
291                 }
292
293                 get_config_string(c->outgoing->cfg, &address);
294
295                 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
296                         asprintf(&port, "655");
297
298                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
299                 free(address);
300                 free(port);
301
302                 c->outgoing->aip = c->outgoing->ai;
303                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
304         }
305
306         if(!c->outgoing->aip) {
307                 if(c->outgoing->ai)
308                         freeaddrinfo(c->outgoing->ai);
309                 c->outgoing->ai = NULL;
310                 goto begin;
311         }
312
313         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
314         c->outgoing->aip = c->outgoing->aip->ai_next;
315
316         if(c->hostname)
317                 free(c->hostname);
318
319         c->hostname = sockaddr2hostname(&c->address);
320
321         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Trying to connect to %s (%s)"), c->name,
322                            c->hostname);
323
324         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
325
326         if(c->socket == -1) {
327                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("Creating socket for %s failed: %s"), c->hostname,
328                                    strerror(errno));
329
330                 goto begin;
331         }
332
333 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
334         int option = 1;
335         if(c->address.sa.sa_family == AF_INET6)
336                 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
337 #endif
338
339         /* Optimize TCP settings */
340
341         configure_tcp(c);
342
343         /* Connect */
344
345         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
346
347         if(result == -1) {
348                 if(errno == EINPROGRESS
349 #if defined(WIN32) && !defined(O_NONBLOCK)
350                    || WSAGetLastError() == WSAEWOULDBLOCK
351 #endif
352                 ) {
353                         c->status.connecting = true;
354                         return;
355                 }
356
357                 closesocket(c->socket);
358
359                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("%s: %s"), c->hostname, strerror(errno));
360
361                 goto begin;
362         }
363
364         finish_connecting(c);
365
366         return;
367 }
368
369 void handle_meta_read(struct bufferevent *event, void *data) {
370         logger(LOG_EMERG, _("handle_meta_read() called"));
371         abort();
372 }
373
374 void handle_meta_write(struct bufferevent *event, void *data) {
375         ifdebug(META) logger(LOG_DEBUG, _("handle_meta_write() called"));
376 }
377
378 void handle_meta_connection_error(struct bufferevent *event, short what, void *data) {
379         connection_t *c = data;
380         logger(LOG_EMERG, _("handle_meta_connection_error() called: %d: %s"), what, strerror(errno));
381         terminate_connection(c, c->status.active);
382 }
383
384 void setup_outgoing_connection(outgoing_t *outgoing) {
385         connection_t *c;
386         node_t *n;
387
388         cp();
389
390         n = lookup_node(outgoing->name);
391
392         if(n)
393                 if(n->connection) {
394                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Already connected to %s"), outgoing->name);
395
396                         n->connection->outgoing = outgoing;
397                         return;
398                 }
399
400         c = new_connection();
401         c->name = xstrdup(outgoing->name);
402         c->outcipher = myself->connection->outcipher;
403         c->outdigest = myself->connection->outdigest;
404         c->outmaclength = myself->connection->outmaclength;
405         c->outcompression = myself->connection->outcompression;
406
407         init_configuration(&c->config_tree);
408         read_connection_config(c);
409
410         outgoing->cfg = lookup_config(c->config_tree, "Address");
411
412         if(!outgoing->cfg) {
413                 logger(LOG_ERR, _("No address specified for %s"), c->name);
414                 free_connection(c);
415                 free(outgoing->name);
416                 free(outgoing);
417                 return;
418         }
419
420         c->outgoing = outgoing;
421         c->last_ping_time = time(NULL);
422
423         connection_add(c);
424
425         do_outgoing_connection(c);
426
427         event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
428         event_add(&c->inevent, NULL);
429         c->buffer = bufferevent_new(c->socket, handle_meta_read, handle_meta_write, handle_meta_connection_error, c);
430         if(!c->buffer) {
431                 logger(LOG_EMERG, _("bufferevent_new() failed: %s"), strerror(errno));
432                 abort();
433         }
434         bufferevent_disable(c->buffer, EV_READ);
435 }
436
437 /*
438   accept a new tcp connect and create a
439   new connection
440 */
441 void handle_new_meta_connection(int sock, short events, void *data) {
442         connection_t *c;
443         sockaddr_t sa;
444         int fd;
445         socklen_t len = sizeof sa;
446
447         cp();
448
449         fd = accept(sock, &sa.sa, &len);
450
451         if(fd < 0) {
452                 logger(LOG_ERR, _("Accepting a new connection failed: %s"), strerror(errno));
453                 return;
454         }
455
456         sockaddrunmap(&sa);
457
458         c = new_connection();
459         c->name = xstrdup("<unknown>");
460         c->outcipher = myself->connection->outcipher;
461         c->outdigest = myself->connection->outdigest;
462         c->outmaclength = myself->connection->outmaclength;
463         c->outcompression = myself->connection->outcompression;
464
465         c->address = sa;
466         c->hostname = sockaddr2hostname(&sa);
467         c->socket = fd;
468         c->last_ping_time = time(NULL);
469
470         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection from %s"), c->hostname);
471
472         event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
473         event_add(&c->inevent, NULL);
474         c->buffer = bufferevent_new(c->socket, NULL, handle_meta_write, handle_meta_connection_error, c);
475         if(!c->buffer) {
476                 logger(LOG_EMERG, _("bufferevent_new() failed: %s"), strerror(errno));
477                 abort();
478         }
479         bufferevent_disable(c->buffer, EV_READ);
480                 
481         configure_tcp(c);
482
483         connection_add(c);
484
485         c->allow_request = ID;
486         send_id(c);
487 }
488
489 void try_outgoing_connections(void) {
490         static config_t *cfg = NULL;
491         char *name;
492         outgoing_t *outgoing;
493
494         cp();
495
496         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
497                 get_config_string(cfg, &name);
498
499                 if(!check_id(name)) {
500                         logger(LOG_ERR,
501                                    _("Invalid name for outgoing connection in %s line %d"),
502                                    cfg->file, cfg->line);
503                         free(name);
504                         continue;
505                 }
506
507                 outgoing = xmalloc_and_zero(sizeof *outgoing);
508                 outgoing->name = name;
509                 setup_outgoing_connection(outgoing);
510         }
511 }