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