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