287d68887fde45ecaa6e4d9b4aa1b6beed054861
[tinc] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2007 Guus Sliepen <guus@tinc-vpn.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$
21 */
22
23 #include "system.h"
24
25 #include "avl_tree.h"
26 #include "conf.h"
27 #include "connection.h"
28 #include "logger.h"
29 #include "meta.h"
30 #include "net.h"
31 #include "netutl.h"
32 #include "protocol.h"
33 #include "utils.h"
34 #include "xalloc.h"
35
36 #ifdef WSAEINPROGRESS
37 #define EINPROGRESS WSAEINPROGRESS
38 #endif
39
40 /* Needed on Mac OS/X */
41 #ifndef SOL_TCP
42 #define SOL_TCP IPPROTO_TCP
43 #endif
44
45 int addressfamily = AF_UNSPEC;
46 int maxtimeout = 900;
47 int seconds_till_retry = 5;
48
49 listen_socket_t listen_socket[MAXSOCKETS];
50 int listen_sockets;
51
52 /* Setup sockets */
53
54 static void configure_tcp(connection_t *c)
55 {
56         int option;
57
58 #ifdef O_NONBLOCK
59         int flags = fcntl(c->socket, F_GETFL);
60
61         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
62                 logger(LOG_ERR, _("fcntl for %s: %s"), c->hostname, strerror(errno));
63         }
64 #elif defined(WIN32)
65         unsigned long arg = 1;
66
67         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
68                 logger(LOG_ERR, _("ioctlsocket for %s: WSA error %d"), c->hostname, WSAGetLastError());
69         }
70 #endif
71
72 #if defined(SOL_TCP) && defined(TCP_NODELAY)
73         option = 1;
74         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
75 #endif
76
77 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
78         option = IPTOS_LOWDELAY;
79         setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
80 #endif
81 }
82
83 int setup_listen_socket(const sockaddr_t *sa)
84 {
85         int nfd;
86         char *addrstr;
87         int option;
88         char *iface;
89
90         cp();
91
92         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
93
94         if(nfd < 0) {
95                 ifdebug(STATUS) logger(LOG_ERR, _("Creating metasocket failed: %s"), strerror(errno));
96                 return -1;
97         }
98
99         /* Optimize TCP settings */
100
101         option = 1;
102         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
103
104         if(get_config_string
105            (lookup_config(config_tree, "BindToInterface"), &iface)) {
106 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
107                 struct ifreq ifr;
108
109                 memset(&ifr, 0, sizeof(ifr));
110                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
111
112                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr))) {
113                         closesocket(nfd);
114                         logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
115                                    strerror(errno));
116                         return -1;
117                 }
118 #else
119                 logger(LOG_WARNING, _("BindToInterface not supported on this platform"));
120 #endif
121         }
122
123         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
124                 closesocket(nfd);
125                 addrstr = sockaddr2hostname(sa);
126                 logger(LOG_ERR, _("Can't bind to %s/tcp: %s"), addrstr,
127                            strerror(errno));
128                 free(addrstr);
129                 return -1;
130         }
131
132         if(listen(nfd, 3)) {
133                 closesocket(nfd);
134                 logger(LOG_ERR, _("System call `%s' failed: %s"), "listen",
135                            strerror(errno));
136                 return -1;
137         }
138
139         return nfd;
140 }
141
142 int setup_vpn_in_socket(const sockaddr_t *sa)
143 {
144         int nfd;
145         char *addrstr;
146         int option;
147
148         cp();
149
150         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
151
152         if(nfd < 0) {
153                 logger(LOG_ERR, _("Creating UDP socket failed: %s"), strerror(errno));
154                 return -1;
155         }
156
157 #ifdef O_NONBLOCK
158         {
159                 int flags = fcntl(nfd, F_GETFL);
160
161                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
162                         closesocket(nfd);
163                         logger(LOG_ERR, _("System call `%s' failed: %s"), "fcntl",
164                                    strerror(errno));
165                         return -1;
166                 }
167         }
168 #elif defined(WIN32)
169         {
170                 unsigned long arg = 1;
171                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
172                         closesocket(nfd);
173                         logger(LOG_ERR, _("Call to `%s' failed: WSA error %d"), "ioctlsocket",
174                                 WSAGetLastError());
175                         return -1;
176                 }
177         }
178 #endif
179
180         option = 1;
181         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
182
183 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
184         {
185                 bool choice;
186
187                 if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice) {
188                         option = IP_PMTUDISC_DO;
189                         setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, &option, sizeof(option));
190                 }
191         }
192 #endif
193
194 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
195         {
196                 bool choice;
197
198                 if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice) {
199                         option = IPV6_PMTUDISC_DO;
200                         setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, &option, sizeof(option));
201                 }
202         }
203 #endif
204
205 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
206         {
207                 char *iface;
208                 struct ifreq ifr;
209
210                 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
211                         memset(&ifr, 0, sizeof(ifr));
212                         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
213
214                         if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr))) {
215                                 closesocket(nfd);
216                                 logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
217                                            strerror(errno));
218                                 return -1;
219                         }
220                 }
221         }
222 #endif
223
224         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
225                 closesocket(nfd);
226                 addrstr = sockaddr2hostname(sa);
227                 logger(LOG_ERR, _("Can't bind to %s/udp: %s"), addrstr,
228                            strerror(errno));
229                 free(addrstr);
230                 return -1;
231         }
232
233         return nfd;
234 }
235
236 static void retry_outgoing_handler(int fd, short events, void *data) {
237         do_outgoing_connection(data);
238 }
239
240 void retry_outgoing(outgoing_t *outgoing) {
241         cp();
242
243         outgoing->timeout += 5;
244
245         if(outgoing->timeout > maxtimeout)
246                 outgoing->timeout = maxtimeout;
247
248         timeout_set(&outgoing->ev, retry_outgoing_handler, outgoing);
249         event_add(&outgoing->ev, &(struct timeval){outgoing->timeout, 0});
250
251         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
252                            _("Trying to re-establish outgoing connection in %d seconds"),
253                            outgoing->timeout);
254 }
255
256 void finish_connecting(connection_t *c)
257 {
258         cp();
259
260         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Connected to %s (%s)"), c->name, c->hostname);
261
262         configure_tcp(c);
263
264         c->last_ping_time = time(NULL);
265         c->status.connecting = false;
266
267         send_id(c);
268 }
269
270 void do_outgoing_connection(connection_t *c)
271 {
272         char *address, *port;
273         int result;
274
275         cp();
276
277 begin:
278         if(!c->outgoing->ai) {
279                 if(!c->outgoing->cfg) {
280                         ifdebug(CONNECTIONS) logger(LOG_ERR, _("Could not set up a meta connection to %s"),
281                                            c->name);
282                         c->status.remove = true;
283                         retry_outgoing(c->outgoing);
284                         return;
285                 }
286
287                 get_config_string(c->outgoing->cfg, &address);
288
289                 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
290                         asprintf(&port, "655");
291
292                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
293                 free(address);
294                 free(port);
295
296                 c->outgoing->aip = c->outgoing->ai;
297                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
298         }
299
300         if(!c->outgoing->aip) {
301                 freeaddrinfo(c->outgoing->ai);
302                 c->outgoing->ai = NULL;
303                 goto begin;
304         }
305
306         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
307         c->outgoing->aip = c->outgoing->aip->ai_next;
308
309         if(c->hostname)
310                 free(c->hostname);
311
312         c->hostname = sockaddr2hostname(&c->address);
313
314         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Trying to connect to %s (%s)"), c->name,
315                            c->hostname);
316
317         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
318
319         if(c->socket == -1) {
320                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("Creating socket for %s failed: %s"), c->hostname,
321                                    strerror(errno));
322
323                 goto begin;
324         }
325
326         /* Optimize TCP settings */
327
328         configure_tcp(c);
329
330         /* Connect */
331
332         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
333
334         if(result == -1) {
335                 if(errno == EINPROGRESS
336 #if defined(WIN32) && !defined(O_NONBLOCK)
337                    || WSAGetLastError() == WSAEWOULDBLOCK
338 #endif
339                 ) {
340                         c->status.connecting = true;
341                         return;
342                 }
343
344                 closesocket(c->socket);
345
346                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("%s: %s"), c->hostname, strerror(errno));
347
348                 goto begin;
349         }
350
351         finish_connecting(c);
352
353         return;
354 }
355
356 void setup_outgoing_connection(outgoing_t *outgoing)
357 {
358         connection_t *c;
359         node_t *n;
360
361         cp();
362
363         n = lookup_node(outgoing->name);
364
365         if(n)
366                 if(n->connection) {
367                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Already connected to %s"), outgoing->name);
368
369                         n->connection->outgoing = outgoing;
370                         return;
371                 }
372
373         c = new_connection();
374         c->name = xstrdup(outgoing->name);
375         c->outcipher = myself->connection->outcipher;
376         c->outdigest = myself->connection->outdigest;
377         c->outmaclength = myself->connection->outmaclength;
378         c->outcompression = myself->connection->outcompression;
379
380         init_configuration(&c->config_tree);
381         read_connection_config(c);
382
383         outgoing->cfg = lookup_config(c->config_tree, "Address");
384
385         if(!outgoing->cfg) {
386                 logger(LOG_ERR, _("No address specified for %s"), c->name);
387                 free_connection(c);
388                 free(outgoing->name);
389                 free(outgoing);
390                 return;
391         }
392
393         c->outgoing = outgoing;
394         c->last_ping_time = time(NULL);
395
396         connection_add(c);
397
398         do_outgoing_connection(c);
399
400         event_set(&c->ev, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
401         event_set(&c->outev, c->socket, EV_WRITE | EV_PERSIST, flush_meta, c);
402         if(event_add(&c->ev, NULL) < 0) {
403                 logger(LOG_EMERG, _("event_add failed: %s"), strerror(errno));
404                 abort();
405         }
406 }
407
408 /*
409   accept a new tcp connect and create a
410   new connection
411 */
412 void handle_new_meta_connection(int sock, short events, void *data)
413 {
414         connection_t *c;
415         sockaddr_t sa;
416         int fd;
417         socklen_t len = sizeof(sa);
418
419         cp();
420
421         fd = accept(sock, &sa.sa, &len);
422
423         if(fd < 0) {
424                 logger(LOG_ERR, _("Accepting a new connection failed: %s"), strerror(errno));
425                 return;
426         }
427
428         sockaddrunmap(&sa);
429
430         c = new_connection();
431         c->name = xstrdup("<unknown>");
432         c->outcipher = myself->connection->outcipher;
433         c->outdigest = myself->connection->outdigest;
434         c->outmaclength = myself->connection->outmaclength;
435         c->outcompression = myself->connection->outcompression;
436
437         c->address = sa;
438         c->hostname = sockaddr2hostname(&sa);
439         c->socket = fd;
440         c->last_ping_time = time(NULL);
441
442         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection from %s"), c->hostname);
443
444         event_set(&c->ev, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
445         event_set(&c->outev, c->socket, EV_WRITE | EV_PERSIST, flush_meta, c);
446         if(event_add(&c->ev, NULL) < 0) {
447                 logger(LOG_ERR, _("event_add failed: %s"), strerror(errno));
448                 connection_del(c);
449                 return;
450         }
451                 
452         configure_tcp(c);
453
454         connection_add(c);
455
456         c->allow_request = ID;
457         send_id(c);
458 }
459
460 void try_outgoing_connections(void)
461 {
462         static config_t *cfg = NULL;
463         char *name;
464         outgoing_t *outgoing;
465
466         cp();
467
468         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
469                 get_config_string(cfg, &name);
470
471                 if(!check_id(name)) {
472                         logger(LOG_ERR,
473                                    _("Invalid name for outgoing connection in %s line %d"),
474                                    cfg->file, cfg->line);
475                         free(name);
476                         continue;
477                 }
478
479                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
480                 outgoing->name = name;
481                 setup_outgoing_connection(outgoing);
482         }
483 }