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