More missing IPv6 definitions and autoconf checks to make sure it compiles
[tinc] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2002 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2002 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.25 2003/07/06 22:11:32 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <sys/time.h>
34 #include <sys/types.h>
35 #include <unistd.h>
36 #include <sys/ioctl.h>
37 /* SunOS really wants sys/socket.h BEFORE net/if.h,
38    and FreeBSD wants these lines below the rest. */
39 #include <arpa/inet.h>
40 #include <sys/socket.h>
41 #include <net/if.h>
42 #ifdef HAVE_NETINET_IN_SYSTM_H
43 #include <netinet/in_systm.h>
44 #endif
45 #ifdef HAVE_NETINET_IP_H
46 #include <netinet/ip.h>
47 #endif
48 #ifdef HAVE_NETINET_TCP_H
49 #include <netinet/tcp.h>
50 #endif
51
52 #include <utils.h>
53 #include <xalloc.h>
54 #include <avl_tree.h>
55 #include <list.h>
56
57 #include "conf.h"
58 #include "connection.h"
59 #include "meta.h"
60 #include "net.h"
61 #include "netutl.h"
62 #include "process.h"
63 #include "protocol.h"
64 #include "subnet.h"
65 #include "graph.h"
66 #include "process.h"
67 #include "route.h"
68 #include "device.h"
69 #include "event.h"
70 #include "logger.h"
71
72 #include "system.h"
73
74 #ifndef HAVE_RAND_PSEUDO_BYTES
75 #define RAND_pseudo_bytes RAND_bytes
76 #endif
77
78 int addressfamily = AF_UNSPEC;
79 int maxtimeout = 900;
80 int seconds_till_retry = 5;
81
82 listen_socket_t listen_socket[MAXSOCKETS];
83 int listen_sockets;
84
85 /* Setup sockets */
86
87 int setup_listen_socket(sockaddr_t *sa)
88 {
89         int nfd, flags;
90         char *addrstr;
91         int option;
92 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
93         char *interface;
94         struct ifreq ifr;
95 #endif
96
97         cp();
98
99         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
100
101         if(nfd < 0) {
102                 logger(DEBUG_ALWAYS, LOG_ERR, _("Creating metasocket failed: %s"), strerror(errno));
103                 return -1;
104         }
105
106         flags = fcntl(nfd, F_GETFL);
107
108         if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
109                 close(nfd);
110                 logger(DEBUG_ALWAYS, LOG_ERR, _("System call `%s' failed: %s"), "fcntl",
111                            strerror(errno));
112                 return -1;
113         }
114
115         /* Optimize TCP settings */
116
117         option = 1;
118         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
119
120 #if defined(SOL_TCP) && defined(TCP_NODELAY)
121         setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
122 #endif
123
124 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
125         option = IPTOS_LOWDELAY;
126         setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
127 #endif
128
129         if(get_config_string
130            (lookup_config(config_tree, "BindToInterface"), &interface)) {
131 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
132                 memset(&ifr, 0, sizeof(ifr));
133                 strncpy(ifr.ifr_ifrn.ifrn_name, interface, IFNAMSIZ);
134
135                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr))) {
136                         close(nfd);
137                         logger(DEBUG_ALWAYS, LOG_ERR, _("Can't bind to interface %s: %s"), interface,
138                                    strerror(errno));
139                         return -1;
140                 }
141 #else
142                 logger(DEBUG_ALWAYS, LOG_WARNING, _("BindToInterface not supported on this platform"));
143 #endif
144         }
145
146         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
147                 close(nfd);
148                 addrstr = sockaddr2hostname(sa);
149                 logger(DEBUG_ALWAYS, LOG_ERR, _("Can't bind to %s/tcp: %s"), addrstr,
150                            strerror(errno));
151                 free(addrstr);
152                 return -1;
153         }
154
155         if(listen(nfd, 3)) {
156                 close(nfd);
157                 logger(DEBUG_ALWAYS, LOG_ERR, _("System call `%s' failed: %s"), "listen",
158                            strerror(errno));
159                 return -1;
160         }
161
162         return nfd;
163 }
164
165 int setup_vpn_in_socket(sockaddr_t *sa)
166 {
167         int nfd, flags;
168         char *addrstr;
169         int option;
170 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
171         char *interface;
172         struct ifreq ifr;
173 #endif
174
175         cp();
176
177         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
178
179         if(nfd < 0) {
180                 logger(DEBUG_ALWAYS, LOG_ERR, _("Creating UDP socket failed: %s"), strerror(errno));
181                 return -1;
182         }
183
184         flags = fcntl(nfd, F_GETFL);
185         if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
186                 close(nfd);
187                 logger(DEBUG_ALWAYS, LOG_ERR, _("System call `%s' failed: %s"), "fcntl",
188                            strerror(errno));
189                 return -1;
190         }
191
192         option = 1;
193         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
194
195 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
196         if(get_config_string
197            (lookup_config(config_tree, "BindToInterface"), &interface)) {
198                 memset(&ifr, 0, sizeof(ifr));
199                 strncpy(ifr.ifr_ifrn.ifrn_name, interface, IFNAMSIZ);
200
201                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr))) {
202                         close(nfd);
203                         logger(DEBUG_ALWAYS, LOG_ERR, _("Can't bind to interface %s: %s"), interface,
204                                    strerror(errno));
205                         return -1;
206                 }
207         }
208 #endif
209
210         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
211                 close(nfd);
212                 addrstr = sockaddr2hostname(sa);
213                 logger(DEBUG_ALWAYS, LOG_ERR, _("Can't bind to %s/udp: %s"), addrstr,
214                            strerror(errno));
215                 free(addrstr);
216                 return -1;
217         }
218
219         return nfd;
220 }
221
222 void retry_outgoing(outgoing_t *outgoing)
223 {
224         event_t *event;
225
226         cp();
227
228         outgoing->timeout += 5;
229
230         if(outgoing->timeout > maxtimeout)
231                 outgoing->timeout = maxtimeout;
232
233         event = new_event();
234         event->handler = (event_handler_t) setup_outgoing_connection;
235         event->time = now + outgoing->timeout;
236         event->data = outgoing;
237         event_add(event);
238
239         logger(DEBUG_CONNECTIONS, LOG_NOTICE,
240                            _("Trying to re-establish outgoing connection in %d seconds"),
241                            outgoing->timeout);
242 }
243
244 void finish_connecting(connection_t *c)
245 {
246         cp();
247
248         logger(DEBUG_CONNECTIONS, LOG_INFO, _("Connected to %s (%s)"), c->name, c->hostname);
249
250         c->last_ping_time = now;
251
252         send_id(c);
253 }
254
255 void do_outgoing_connection(connection_t *c)
256 {
257         char *address, *port;
258         int option, result, flags;
259
260         cp();
261
262 begin:
263         if(!c->outgoing->ai) {
264                 if(!c->outgoing->cfg) {
265                         logger(DEBUG_CONNECTIONS, LOG_ERR, _("Could not set up a meta connection to %s"),
266                                            c->name);
267                         c->status.remove = 1;
268                         retry_outgoing(c->outgoing);
269                         return;
270                 }
271
272                 get_config_string(c->outgoing->cfg, &address);
273
274                 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
275                         asprintf(&port, "655");
276
277                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
278                 free(address);
279                 free(port);
280
281                 c->outgoing->aip = c->outgoing->ai;
282                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
283         }
284
285         if(!c->outgoing->aip) {
286                 freeaddrinfo(c->outgoing->ai);
287                 c->outgoing->ai = NULL;
288                 goto begin;
289         }
290
291         memcpy(&c->address, c->outgoing->aip->ai_addr,
292                    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         logger(DEBUG_CONNECTIONS, 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                 logger(DEBUG_CONNECTIONS, 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         flags = fcntl(c->socket, F_GETFL);
327
328         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
329                 logger(DEBUG_ALWAYS, LOG_ERR, _("fcntl for %s: %s"), c->hostname, strerror(errno));
330         }
331
332         /* Connect */
333
334         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
335
336         if(result == -1) {
337                 if(errno == EINPROGRESS) {
338                         c->status.connecting = 1;
339                         return;
340                 }
341
342                 close(c->socket);
343
344                 logger(DEBUG_CONNECTIONS, LOG_ERR, _("%s: %s"), c->hostname, strerror(errno));
345
346                 goto begin;
347         }
348
349         finish_connecting(c);
350
351         return;
352 }
353
354 void setup_outgoing_connection(outgoing_t *outgoing)
355 {
356         connection_t *c;
357         node_t *n;
358
359         cp();
360
361         n = lookup_node(outgoing->name);
362
363         if(n)
364                 if(n->connection) {
365                         logger(DEBUG_CONNECTIONS, LOG_INFO, _("Already connected to %s"), outgoing->name);
366
367                         n->connection->outgoing = outgoing;
368                         return;
369                 }
370
371         c = new_connection();
372         c->name = xstrdup(outgoing->name);
373         c->outcipher = myself->connection->outcipher;
374         c->outdigest = myself->connection->outdigest;
375         c->outmaclength = myself->connection->outmaclength;
376         c->outcompression = myself->connection->outcompression;
377
378         init_configuration(&c->config_tree);
379         read_connection_config(c);
380
381         outgoing->cfg = lookup_config(c->config_tree, "Address");
382
383         if(!outgoing->cfg) {
384                 logger(DEBUG_ALWAYS, LOG_ERR, _("No address specified for %s"), c->name);
385                 free_connection(c);
386                 free(outgoing->name);
387                 free(outgoing);
388                 return;
389         }
390
391         c->outgoing = outgoing;
392         c->last_ping_time = now;
393
394         connection_add(c);
395
396         do_outgoing_connection(c);
397 }
398
399 /*
400   accept a new tcp connect and create a
401   new connection
402 */
403 int handle_new_meta_connection(int sock)
404 {
405         connection_t *c;
406         sockaddr_t sa;
407         int fd, len = sizeof(sa);
408
409         cp();
410
411         fd = accept(sock, &sa.sa, &len);
412
413         if(fd < 0) {
414                 logger(DEBUG_ALWAYS, LOG_ERR, _("Accepting a new connection failed: %s"),
415                            strerror(errno));
416                 return -1;
417         }
418
419         sockaddrunmap(&sa);
420
421         c = new_connection();
422         c->outcipher = myself->connection->outcipher;
423         c->outdigest = myself->connection->outdigest;
424         c->outmaclength = myself->connection->outmaclength;
425         c->outcompression = myself->connection->outcompression;
426
427         c->address = sa;
428         c->hostname = sockaddr2hostname(&sa);
429         c->socket = fd;
430         c->last_ping_time = now;
431
432         logger(DEBUG_CONNECTIONS, LOG_NOTICE, _("Connection from %s"), c->hostname);
433
434         connection_add(c);
435
436         c->allow_request = ID;
437         send_id(c);
438
439         return 0;
440 }
441
442 void try_outgoing_connections(void)
443 {
444         static config_t *cfg = NULL;
445         char *name;
446         outgoing_t *outgoing;
447
448         cp();
449
450         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg;
451                 cfg = lookup_config_next(config_tree, cfg)) {
452                 get_config_string(cfg, &name);
453
454                 if(check_id(name)) {
455                         logger(DEBUG_ALWAYS, LOG_ERR,
456                                    _("Invalid name for outgoing connection in %s line %d"),
457                                    cfg->file, cfg->line);
458                         free(name);
459                         continue;
460                 }
461
462                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
463                 outgoing->name = name;
464                 setup_outgoing_connection(outgoing);
465         }
466 }