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