Update THANKS and copyright information.
[tinc] / 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 "avl_tree.h"
26 #include "conf.h"
27 #include "connection.h"
28 #include "event.h"
29 #include "logger.h"
30 #include "meta.h"
31 #include "net.h"
32 #include "netutl.h"
33 #include "protocol.h"
34 #include "utils.h"
35 #include "xalloc.h"
36
37 #ifdef WSAEINPROGRESS
38 #define EINPROGRESS WSAEINPROGRESS
39 #endif
40
41 /* Needed on Mac OS/X */
42 #ifndef SOL_TCP
43 #define SOL_TCP IPPROTO_TCP
44 #endif
45
46 int addressfamily = AF_UNSPEC;
47 int maxtimeout = 900;
48 int seconds_till_retry = 5;
49
50 listen_socket_t listen_socket[MAXSOCKETS];
51 int listen_sockets;
52 list_t *outgoing_list = NULL;
53
54 /* Setup sockets */
55
56 static void configure_tcp(connection_t *c)
57 {
58         int option;
59
60 #ifdef O_NONBLOCK
61         int flags = fcntl(c->socket, F_GETFL);
62
63         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
64                 logger(LOG_ERR, _("fcntl for %s: %s"), c->hostname, strerror(errno));
65         }
66 #elif defined(WIN32)
67         unsigned long arg = 1;
68
69         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
70                 logger(LOG_ERR, _("ioctlsocket for %s: WSA error %d"), c->hostname, WSAGetLastError());
71         }
72 #endif
73
74 #if defined(SOL_TCP) && defined(TCP_NODELAY)
75         option = 1;
76         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
77 #endif
78
79 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
80         option = IPTOS_LOWDELAY;
81         setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
82 #endif
83 }
84
85 int setup_listen_socket(const sockaddr_t *sa)
86 {
87         int nfd;
88         char *addrstr;
89         int option;
90         char *iface;
91
92         cp();
93
94         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
95
96         if(nfd < 0) {
97                 ifdebug(STATUS) logger(LOG_ERR, _("Creating metasocket failed: %s"), strerror(errno));
98                 return -1;
99         }
100
101         /* Optimize TCP settings */
102
103         option = 1;
104         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
105
106 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
107         if(sa->sa.sa_family == AF_INET6)
108                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
109 #endif
110
111         if(get_config_string
112            (lookup_config(config_tree, "BindToInterface"), &iface)) {
113 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
114                 struct ifreq ifr;
115
116                 memset(&ifr, 0, sizeof(ifr));
117                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
118
119                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr))) {
120                         closesocket(nfd);
121                         logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
122                                    strerror(errno));
123                         return -1;
124                 }
125 #else
126                 logger(LOG_WARNING, _("BindToInterface not supported on this platform"));
127 #endif
128         }
129
130         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
131                 closesocket(nfd);
132                 addrstr = sockaddr2hostname(sa);
133                 logger(LOG_ERR, _("Can't bind to %s/tcp: %s"), addrstr,
134                            strerror(errno));
135                 free(addrstr);
136                 return -1;
137         }
138
139         if(listen(nfd, 3)) {
140                 closesocket(nfd);
141                 logger(LOG_ERR, _("System call `%s' failed: %s"), "listen",
142                            strerror(errno));
143                 return -1;
144         }
145
146         return nfd;
147 }
148
149 int setup_vpn_in_socket(const sockaddr_t *sa)
150 {
151         int nfd;
152         char *addrstr;
153         int option;
154
155         cp();
156
157         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
158
159         if(nfd < 0) {
160                 logger(LOG_ERR, _("Creating UDP socket failed: %s"), strerror(errno));
161                 return -1;
162         }
163
164 #ifdef O_NONBLOCK
165         {
166                 int flags = fcntl(nfd, F_GETFL);
167
168                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
169                         closesocket(nfd);
170                         logger(LOG_ERR, _("System call `%s' failed: %s"), "fcntl",
171                                    strerror(errno));
172                         return -1;
173                 }
174         }
175 #elif defined(WIN32)
176         {
177                 unsigned long arg = 1;
178                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
179                         closesocket(nfd);
180                         logger(LOG_ERR, _("Call to `%s' failed: WSA error %d"), "ioctlsocket",
181                                 WSAGetLastError());
182                         return -1;
183                 }
184         }
185 #endif
186
187         option = 1;
188         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
189
190 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
191         if(sa->sa.sa_family == AF_INET6)
192                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
193 #endif
194
195 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
196         {
197                 bool choice;
198
199                 if(!get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) || choice) {
200                         option = IP_PMTUDISC_DO;
201                         setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, &option, sizeof(option));
202                 }
203         }
204 #endif
205
206 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
207         {
208                 bool choice;
209
210                 if(!get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) || choice) {
211                         option = IPV6_PMTUDISC_DO;
212                         setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, &option, sizeof(option));
213                 }
214         }
215 #endif
216
217 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
218         {
219                 char *iface;
220                 struct ifreq ifr;
221
222                 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
223                         memset(&ifr, 0, sizeof(ifr));
224                         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
225
226                         if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr))) {
227                                 closesocket(nfd);
228                                 logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
229                                            strerror(errno));
230                                 return -1;
231                         }
232                 }
233         }
234 #endif
235
236         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
237                 closesocket(nfd);
238                 addrstr = sockaddr2hostname(sa);
239                 logger(LOG_ERR, _("Can't bind to %s/udp: %s"), addrstr,
240                            strerror(errno));
241                 free(addrstr);
242                 return -1;
243         }
244
245         return nfd;
246 }
247
248 void retry_outgoing(outgoing_t *outgoing)
249 {
250         event_t *event;
251
252         cp();
253
254         outgoing->timeout += 5;
255
256         if(outgoing->timeout > maxtimeout)
257                 outgoing->timeout = maxtimeout;
258
259         event = new_event();
260         event->handler = (event_handler_t) setup_outgoing_connection;
261         event->time = now + outgoing->timeout;
262         event->data = outgoing;
263         event_add(event);
264
265         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
266                            _("Trying to re-establish outgoing connection in %d seconds"),
267                            outgoing->timeout);
268 }
269
270 void finish_connecting(connection_t *c)
271 {
272         cp();
273
274         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Connected to %s (%s)"), c->name, c->hostname);
275
276         configure_tcp(c);
277
278         c->last_ping_time = now;
279
280         send_id(c);
281 }
282
283 void do_outgoing_connection(connection_t *c)
284 {
285         char *address, *port;
286         int result;
287
288         cp();
289
290 begin:
291         if(!c->outgoing->ai) {
292                 if(!c->outgoing->cfg) {
293                         ifdebug(CONNECTIONS) logger(LOG_ERR, _("Could not set up a meta connection to %s"),
294                                            c->name);
295                         c->status.remove = true;
296                         retry_outgoing(c->outgoing);
297                         return;
298                 }
299
300                 get_config_string(c->outgoing->cfg, &address);
301
302                 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
303                         asprintf(&port, "655");
304
305                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
306                 free(address);
307                 free(port);
308
309                 c->outgoing->aip = c->outgoing->ai;
310                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
311         }
312
313         if(!c->outgoing->aip) {
314                 if(c->outgoing->ai)
315                         freeaddrinfo(c->outgoing->ai);
316                 c->outgoing->ai = NULL;
317                 goto begin;
318         }
319
320         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
321         c->outgoing->aip = c->outgoing->aip->ai_next;
322
323         if(c->hostname)
324                 free(c->hostname);
325
326         c->hostname = sockaddr2hostname(&c->address);
327
328         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Trying to connect to %s (%s)"), c->name,
329                            c->hostname);
330
331         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
332
333         if(c->socket == -1) {
334                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("Creating socket for %s failed: %s"), c->hostname,
335                                    strerror(errno));
336
337                 goto begin;
338         }
339
340 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
341         int option = 1;
342         if(c->address.sa.sa_family == AF_INET6)
343                 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
344 #endif
345
346         /* Optimize TCP settings */
347
348         configure_tcp(c);
349
350         /* Connect */
351
352         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
353
354         if(result == -1) {
355                 if(errno == EINPROGRESS
356 #if defined(WIN32) && !defined(O_NONBLOCK)
357                    || WSAGetLastError() == WSAEWOULDBLOCK
358 #endif
359                 ) {
360                         c->status.connecting = true;
361                         return;
362                 }
363
364                 closesocket(c->socket);
365
366                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("%s: %s"), c->hostname, strerror(errno));
367
368                 goto begin;
369         }
370
371         finish_connecting(c);
372
373         return;
374 }
375
376 void setup_outgoing_connection(outgoing_t *outgoing)
377 {
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 = now;
413
414         connection_add(c);
415
416         do_outgoing_connection(c);
417 }
418
419 /*
420   accept a new tcp connect and create a
421   new connection
422 */
423 bool handle_new_meta_connection(int sock)
424 {
425         connection_t *c;
426         sockaddr_t sa;
427         int fd;
428         socklen_t len = sizeof(sa);
429
430         cp();
431
432         fd = accept(sock, &sa.sa, &len);
433
434         if(fd < 0) {
435                 logger(LOG_ERR, _("Accepting a new connection failed: %s"),
436                            strerror(errno));
437                 return false;
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 = now;
453
454         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection from %s"), c->hostname);
455
456         configure_tcp(c);
457
458         connection_add(c);
459
460         c->allow_request = ID;
461         send_id(c);
462
463         return true;
464 }
465
466 void free_outgoing(outgoing_t *outgoing) {
467         if(outgoing->ai)
468                 freeaddrinfo(outgoing->ai);
469
470         if(outgoing->name)
471                 free(outgoing->name);
472
473         free(outgoing);
474 }
475
476 void try_outgoing_connections(void)
477 {
478         static config_t *cfg = NULL;
479         char *name;
480         outgoing_t *outgoing;
481         connection_t *c;
482         avl_node_t *node;
483         
484         cp();
485
486         if(outgoing_list) {
487                 for(node = connection_tree->head; node; node = node->next) {
488                         c = node->data;
489                         c->outgoing = NULL;
490                 }
491
492                 list_delete_list(outgoing_list);
493         }
494
495         outgoing_list = list_alloc((list_action_t)free_outgoing);
496                         
497         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
498                 get_config_string(cfg, &name);
499
500                 if(!check_id(name)) {
501                         logger(LOG_ERR,
502                                    _("Invalid name for outgoing connection in %s line %d"),
503                                    cfg->file, cfg->line);
504                         free(name);
505                         continue;
506                 }
507
508                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
509                 outgoing->name = name;
510                 list_insert_tail(outgoing_list, outgoing);
511                 setup_outgoing_connection(outgoing);
512         }
513 }