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