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