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