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