Prevent freeing a NULL pointer when a hostname is unresolvable.
[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                 if(c->outgoing->ai)
304                         freeaddrinfo(c->outgoing->ai);
305                 c->outgoing->ai = NULL;
306                 goto begin;
307         }
308
309         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
310         c->outgoing->aip = c->outgoing->aip->ai_next;
311
312         if(c->hostname)
313                 free(c->hostname);
314
315         c->hostname = sockaddr2hostname(&c->address);
316
317         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Trying to connect to %s (%s)"), c->name,
318                            c->hostname);
319
320         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
321
322         if(c->socket == -1) {
323                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("Creating socket for %s failed: %s"), c->hostname,
324                                    strerror(errno));
325
326                 goto begin;
327         }
328
329         /* Optimize TCP settings */
330
331         configure_tcp(c);
332
333         /* Connect */
334
335         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
336
337         if(result == -1) {
338                 if(errno == EINPROGRESS
339 #if defined(WIN32) && !defined(O_NONBLOCK)
340                    || WSAGetLastError() == WSAEWOULDBLOCK
341 #endif
342                 ) {
343                         c->status.connecting = true;
344                         return;
345                 }
346
347                 closesocket(c->socket);
348
349                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("%s: %s"), c->hostname, strerror(errno));
350
351                 goto begin;
352         }
353
354         finish_connecting(c);
355
356         return;
357 }
358
359 void setup_outgoing_connection(outgoing_t *outgoing)
360 {
361         connection_t *c;
362         node_t *n;
363
364         cp();
365
366         n = lookup_node(outgoing->name);
367
368         if(n)
369                 if(n->connection) {
370                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Already connected to %s"), outgoing->name);
371
372                         n->connection->outgoing = outgoing;
373                         return;
374                 }
375
376         c = new_connection();
377         c->name = xstrdup(outgoing->name);
378         c->outcipher = myself->connection->outcipher;
379         c->outdigest = myself->connection->outdigest;
380         c->outmaclength = myself->connection->outmaclength;
381         c->outcompression = myself->connection->outcompression;
382
383         init_configuration(&c->config_tree);
384         read_connection_config(c);
385
386         outgoing->cfg = lookup_config(c->config_tree, "Address");
387
388         if(!outgoing->cfg) {
389                 logger(LOG_ERR, _("No address specified for %s"), c->name);
390                 free_connection(c);
391                 free(outgoing->name);
392                 free(outgoing);
393                 return;
394         }
395
396         c->outgoing = outgoing;
397         c->last_ping_time = now;
398
399         connection_add(c);
400
401         do_outgoing_connection(c);
402 }
403
404 /*
405   accept a new tcp connect and create a
406   new connection
407 */
408 bool handle_new_meta_connection(int sock)
409 {
410         connection_t *c;
411         sockaddr_t sa;
412         int fd;
413         socklen_t len = sizeof(sa);
414
415         cp();
416
417         fd = accept(sock, &sa.sa, &len);
418
419         if(fd < 0) {
420                 logger(LOG_ERR, _("Accepting a new connection failed: %s"),
421                            strerror(errno));
422                 return false;
423         }
424
425         sockaddrunmap(&sa);
426
427         c = new_connection();
428         c->name = xstrdup("<unknown>");
429         c->outcipher = myself->connection->outcipher;
430         c->outdigest = myself->connection->outdigest;
431         c->outmaclength = myself->connection->outmaclength;
432         c->outcompression = myself->connection->outcompression;
433
434         c->address = sa;
435         c->hostname = sockaddr2hostname(&sa);
436         c->socket = fd;
437         c->last_ping_time = now;
438
439         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection from %s"), c->hostname);
440
441         configure_tcp(c);
442
443         connection_add(c);
444
445         c->allow_request = ID;
446         send_id(c);
447
448         return true;
449 }
450
451 void try_outgoing_connections(void)
452 {
453         static config_t *cfg = NULL;
454         char *name;
455         outgoing_t *outgoing;
456
457         cp();
458
459         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
460                 get_config_string(cfg, &name);
461
462                 if(!check_id(name)) {
463                         logger(LOG_ERR,
464                                    _("Invalid name for outgoing connection in %s line %d"),
465                                    cfg->file, cfg->line);
466                         free(name);
467                         continue;
468                 }
469
470                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
471                 outgoing->name = name;
472                 setup_outgoing_connection(outgoing);
473         }
474 }