Revert Martin Kihlgren's patch, it doesn't work the way it should.
[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.38 2003/12/22 11:04:16 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(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice) {
167                         option = IP_PMTUDISC_DO;
168                         setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, &option, sizeof(option));
169                 }
170         }
171 #endif
172
173 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
174         {
175                 bool choice;
176
177                 if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice) {
178                         option = IPV6_PMTUDISC_DO;
179                         setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, &option, sizeof(option));
180                 }
181         }
182 #endif
183
184 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
185         {
186                 char *iface;
187                 struct ifreq ifr;
188
189                 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
190                         memset(&ifr, 0, sizeof(ifr));
191                         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
192
193                         if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr))) {
194                                 closesocket(nfd);
195                                 logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
196                                            strerror(errno));
197                                 return -1;
198                         }
199                 }
200         }
201 #endif
202
203         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
204                 closesocket(nfd);
205                 addrstr = sockaddr2hostname(sa);
206                 logger(LOG_ERR, _("Can't bind to %s/udp: %s"), addrstr,
207                            strerror(errno));
208                 free(addrstr);
209                 return -1;
210         }
211
212         return nfd;
213 }
214
215 void retry_outgoing(outgoing_t *outgoing)
216 {
217         event_t *event;
218
219         cp();
220
221         outgoing->timeout += 5;
222
223         if(outgoing->timeout > maxtimeout)
224                 outgoing->timeout = maxtimeout;
225
226         event = new_event();
227         event->handler = (event_handler_t) setup_outgoing_connection;
228         event->time = now + outgoing->timeout;
229         event->data = outgoing;
230         event_add(event);
231
232         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
233                            _("Trying to re-establish outgoing connection in %d seconds"),
234                            outgoing->timeout);
235 }
236
237 void finish_connecting(connection_t *c)
238 {
239         cp();
240
241         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Connected to %s (%s)"), c->name, c->hostname);
242
243         c->last_ping_time = now;
244
245         send_id(c);
246 }
247
248 void do_outgoing_connection(connection_t *c)
249 {
250         char *address, *port;
251         int option, result, flags;
252
253         cp();
254
255 begin:
256         if(!c->outgoing->ai) {
257                 if(!c->outgoing->cfg) {
258                         ifdebug(CONNECTIONS) logger(LOG_ERR, _("Could not set up a meta connection to %s"),
259                                            c->name);
260                         c->status.remove = true;
261                         retry_outgoing(c->outgoing);
262                         return;
263                 }
264
265                 get_config_string(c->outgoing->cfg, &address);
266
267                 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
268                         asprintf(&port, "655");
269
270                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
271                 free(address);
272                 free(port);
273
274                 c->outgoing->aip = c->outgoing->ai;
275                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
276         }
277
278         if(!c->outgoing->aip) {
279                 freeaddrinfo(c->outgoing->ai);
280                 c->outgoing->ai = NULL;
281                 goto begin;
282         }
283
284         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
285         c->outgoing->aip = c->outgoing->aip->ai_next;
286
287         if(c->hostname)
288                 free(c->hostname);
289
290         c->hostname = sockaddr2hostname(&c->address);
291
292         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Trying to connect to %s (%s)"), c->name,
293                            c->hostname);
294
295         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
296
297         if(c->socket == -1) {
298                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("Creating socket for %s failed: %s"), c->hostname,
299                                    strerror(errno));
300
301                 goto begin;
302         }
303
304         /* Optimize TCP settings */
305
306 #if defined(SOL_TCP) && defined(TCP_NODELAY)
307         option = 1;
308         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
309 #endif
310
311 #if defined(SOL_IP) && defined(IP_TOS)
312         option = IPTOS_LOWDELAY;
313         setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
314 #endif
315
316         /* Non-blocking */
317
318 #ifdef O_NONBLOCK
319         flags = fcntl(c->socket, F_GETFL);
320
321         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
322                 logger(LOG_ERR, _("fcntl for %s: %s"), c->hostname, strerror(errno));
323         }
324 #endif
325
326         /* Connect */
327
328         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
329
330         if(result == -1) {
331                 if(errno == EINPROGRESS) {
332                         c->status.connecting = true;
333                         return;
334                 }
335
336                 closesocket(c->socket);
337
338                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("%s: %s"), c->hostname, strerror(errno));
339
340                 goto begin;
341         }
342
343         finish_connecting(c);
344
345         return;
346 }
347
348 void setup_outgoing_connection(outgoing_t *outgoing)
349 {
350         connection_t *c;
351         node_t *n;
352
353         cp();
354
355         n = lookup_node(outgoing->name);
356
357         if(n)
358                 if(n->connection) {
359                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Already connected to %s"), outgoing->name);
360
361                         n->connection->outgoing = outgoing;
362                         return;
363                 }
364
365         c = new_connection();
366         c->name = xstrdup(outgoing->name);
367         c->outcipher = myself->connection->outcipher;
368         c->outdigest = myself->connection->outdigest;
369         c->outmaclength = myself->connection->outmaclength;
370         c->outcompression = myself->connection->outcompression;
371
372         init_configuration(&c->config_tree);
373         read_connection_config(c);
374
375         outgoing->cfg = lookup_config(c->config_tree, "Address");
376
377         if(!outgoing->cfg) {
378                 logger(LOG_ERR, _("No address specified for %s"), c->name);
379                 free_connection(c);
380                 free(outgoing->name);
381                 free(outgoing);
382                 return;
383         }
384
385         c->outgoing = outgoing;
386         c->last_ping_time = now;
387
388         connection_add(c);
389
390         do_outgoing_connection(c);
391 }
392
393 /*
394   accept a new tcp connect and create a
395   new connection
396 */
397 bool handle_new_meta_connection(int sock)
398 {
399         connection_t *c;
400         sockaddr_t sa;
401         int fd, len = sizeof(sa);
402
403         cp();
404
405         fd = accept(sock, &sa.sa, &len);
406
407         if(fd < 0) {
408                 logger(LOG_ERR, _("Accepting a new connection failed: %s"),
409                            strerror(errno));
410                 return false;
411         }
412
413         sockaddrunmap(&sa);
414
415         c = new_connection();
416         c->outcipher = myself->connection->outcipher;
417         c->outdigest = myself->connection->outdigest;
418         c->outmaclength = myself->connection->outmaclength;
419         c->outcompression = myself->connection->outcompression;
420
421         c->address = sa;
422         c->hostname = sockaddr2hostname(&sa);
423         c->socket = fd;
424         c->last_ping_time = now;
425
426         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection from %s"), c->hostname);
427
428         connection_add(c);
429
430         c->allow_request = ID;
431         send_id(c);
432
433         return true;
434 }
435
436 void try_outgoing_connections(void)
437 {
438         static config_t *cfg = NULL;
439         char *name;
440         outgoing_t *outgoing;
441
442         cp();
443
444         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg;
445                 cfg = lookup_config_next(config_tree, cfg)) {
446                 get_config_string(cfg, &name);
447
448                 if(!check_id(name)) {
449                         logger(LOG_ERR,
450                                    _("Invalid name for outgoing connection in %s line %d"),
451                                    cfg->file, cfg->line);
452                         free(name);
453                         continue;
454                 }
455
456                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
457                 outgoing->name = name;
458                 setup_outgoing_connection(outgoing);
459         }
460 }