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