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