Imported gnutls based branch.
[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 <gnutls/gnutls.h>
26
27 #include "avl_tree.h"
28 #include "conf.h"
29 #include "connection.h"
30 #include "event.h"
31 #include "logger.h"
32 #include "meta.h"
33 #include "net.h"
34 #include "netutl.h"
35 #include "protocol.h"
36 #include "utils.h"
37 #include "xalloc.h"
38
39 #ifdef WSAEINPROGRESS
40 #define EINPROGRESS WSAEINPROGRESS
41 #endif
42
43 int addressfamily = AF_UNSPEC;
44 int maxtimeout = 900;
45 int seconds_till_retry = 5;
46
47 listen_socket_t listen_socket[MAXSOCKETS];
48 int listen_sockets;
49
50 int certselfunc(gnutls_session session,  const gnutls_datum *client_cert, int ncerts, const gnutls_datum* req_ca_cert, int nreqs) {
51         logger(LOG_DEBUG, "Client certificate select function called with %d certs, %d requests\n", ncerts, nreqs);
52         return 0;
53 }
54
55 int scertselfunc(gnutls_session session,  const gnutls_datum *server_cert, int ncerts) {
56         logger(LOG_DEBUG, "Server certificate select function called with %d certs\n", ncerts);
57         return 0;
58 }
59
60 /* Setup sockets */
61
62 int setup_listen_socket(const sockaddr_t *sa)
63 {
64         int nfd;
65         char *addrstr;
66         int option;
67         char *iface;
68
69         cp();
70
71         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
72
73         if(nfd < 0) {
74                 ifdebug(STATUS) logger(LOG_ERR, _("Creating metasocket failed: %s"), strerror(errno));
75                 return -1;
76         }
77
78 #ifdef O_NONBLOCK
79         {
80                 int flags = fcntl(nfd, F_GETFL);
81
82                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
83                         closesocket(nfd);
84                         logger(LOG_ERR, _("System call `%s' failed: %s"), "fcntl",
85                                    strerror(errno));
86                         return -1;
87                 }
88         }
89 #endif
90
91         /* Optimize TCP settings */
92
93         option = 1;
94         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
95
96 #if defined(SOL_TCP) && defined(TCP_NODELAY)
97         setsockopt(nfd, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
98 #endif
99
100 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
101         option = IPTOS_LOWDELAY;
102         setsockopt(nfd, SOL_IP, IP_TOS, &option, sizeof(option));
103 #endif
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 #endif
170
171         option = 1;
172         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
173
174 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
175         {
176                 bool choice;
177
178                 if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice) {
179                         option = IP_PMTUDISC_DO;
180                         setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, &option, sizeof(option));
181                 }
182         }
183 #endif
184
185 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
186         {
187                 bool choice;
188
189                 if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice) {
190                         option = IPV6_PMTUDISC_DO;
191                         setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, &option, sizeof(option));
192                 }
193         }
194 #endif
195
196 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
197         {
198                 char *iface;
199                 struct ifreq ifr;
200
201                 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
202                         memset(&ifr, 0, sizeof(ifr));
203                         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
204
205                         if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr))) {
206                                 closesocket(nfd);
207                                 logger(LOG_ERR, _("Can't bind to interface %s: %s"), iface,
208                                            strerror(errno));
209                                 return -1;
210                         }
211                 }
212         }
213 #endif
214
215         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
216                 closesocket(nfd);
217                 addrstr = sockaddr2hostname(sa);
218                 logger(LOG_ERR, _("Can't bind to %s/udp: %s"), addrstr,
219                            strerror(errno));
220                 free(addrstr);
221                 return -1;
222         }
223
224         return nfd;
225 }
226
227 void retry_outgoing(outgoing_t *outgoing)
228 {
229         event_t *event;
230
231         cp();
232
233         outgoing->timeout += 5;
234
235         if(outgoing->timeout > maxtimeout)
236                 outgoing->timeout = maxtimeout;
237
238         event = new_event();
239         event->handler = (event_handler_t) setup_outgoing_connection;
240         event->time = now + outgoing->timeout;
241         event->data = outgoing;
242         event_add(event);
243
244         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
245                            _("Trying to re-establish outgoing connection in %d seconds"),
246                            outgoing->timeout);
247 }
248
249 void finish_connecting(connection_t *c)
250 {
251         int result;
252
253         cp();
254
255         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Connected to %s (%s)"), c->name, c->hostname);
256
257         c->last_ping_time = now;
258
259         gnutls_init(&c->session, GNUTLS_SERVER);
260         gnutls_set_default_priority(c->session);
261         gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, myself->connection->credentials);
262         gnutls_certificate_server_set_request(c->session, GNUTLS_CERT_REQUEST);
263 //      gnutls_certificate_client_set_select_function(c->session, certselfunc);
264 //      gnutls_certificate_server_set_select_function(c->session, scertselfunc);
265         gnutls_transport_set_ptr(c->session, c->socket);
266 }
267
268 void do_outgoing_connection(connection_t *c)
269 {
270         char *address, *port;
271         int option, result, flags;
272
273         cp();
274
275 begin:
276         if(!c->outgoing->ai) {
277                 if(!c->outgoing->cfg) {
278                         ifdebug(CONNECTIONS) logger(LOG_ERR, _("Could not set up a meta connection to %s"),
279                                            c->name);
280                         c->status.remove = true;
281                         retry_outgoing(c->outgoing);
282                         return;
283                 }
284
285                 get_config_string(c->outgoing->cfg, &address);
286
287                 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
288                         asprintf(&port, "655");
289
290                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
291                 free(address);
292                 free(port);
293
294                 c->outgoing->aip = c->outgoing->ai;
295                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
296         }
297
298         if(!c->outgoing->aip) {
299                 freeaddrinfo(c->outgoing->ai);
300                 c->outgoing->ai = NULL;
301                 goto begin;
302         }
303
304         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
305         c->outgoing->aip = c->outgoing->aip->ai_next;
306
307         if(c->hostname)
308                 free(c->hostname);
309
310         c->hostname = sockaddr2hostname(&c->address);
311
312         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Trying to connect to %s (%s)"), c->name,
313                            c->hostname);
314
315         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
316
317         if(c->socket == -1) {
318                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("Creating socket for %s failed: %s"), c->hostname,
319                                    strerror(errno));
320
321                 goto begin;
322         }
323
324         /* Optimize TCP settings */
325
326 #if defined(SOL_TCP) && defined(TCP_NODELAY)
327         option = 1;
328         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof(option));
329 #endif
330
331 #if defined(SOL_IP) && defined(IP_TOS)
332         option = IPTOS_LOWDELAY;
333         setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof(option));
334 #endif
335
336         /* Non-blocking */
337
338 #ifdef O_NONBLOCK
339         flags = fcntl(c->socket, F_GETFL);
340
341         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
342                 logger(LOG_ERR, _("fcntl for %s: %s"), c->hostname, strerror(errno));
343         }
344 #endif
345
346         /* Connect */
347
348         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
349
350         if(result == -1) {
351                 if(errno == EINPROGRESS) {
352                         c->status.connecting = true;
353                         return;
354                 }
355
356                 closesocket(c->socket);
357
358                 ifdebug(CONNECTIONS) logger(LOG_ERR, _("%s: %s"), c->hostname, strerror(errno));
359
360                 goto begin;
361         }
362
363         logger(LOG_DEBUG, _("finishing connection"));
364         finish_connecting(c);
365
366         return;
367 }
368
369 void setup_outgoing_connection(outgoing_t *outgoing)
370 {
371         connection_t *c;
372         node_t *n;
373
374         cp();
375
376         n = lookup_node(outgoing->name);
377
378         if(n)
379                 if(n->connection) {
380                         ifdebug(CONNECTIONS) logger(LOG_INFO, _("Already connected to %s"), outgoing->name);
381
382                         n->connection->outgoing = outgoing;
383                         return;
384                 }
385
386         c = new_connection();
387         c->name = xstrdup(outgoing->name);
388
389         init_configuration(&c->config_tree);
390         read_connection_config(c);
391
392         outgoing->cfg = lookup_config(c->config_tree, "Address");
393
394         if(!outgoing->cfg) {
395                 logger(LOG_ERR, _("No address specified for %s"), c->name);
396                 free_connection(c);
397                 free(outgoing->name);
398                 free(outgoing);
399                 return;
400         }
401
402         c->outgoing = outgoing;
403         c->last_ping_time = now;
404
405         connection_add(c);
406
407         do_outgoing_connection(c);
408 }
409
410 /*
411   accept a new tcp connect and create a
412   new connection
413 */
414 bool handle_new_meta_connection(int sock)
415 {
416         connection_t *c;
417         sockaddr_t sa;
418         int fd, len = sizeof(sa);
419         int result;
420
421         cp();
422
423         fd = accept(sock, &sa.sa, &len);
424
425         if(fd < 0) {
426                 logger(LOG_ERR, _("Accepting a new connection failed: %s"),
427                            strerror(errno));
428                 return false;
429         }
430
431 #ifdef O_NONBLOCK
432         {
433                 int flags = fcntl(fd, F_GETFL);
434
435                 if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
436                         closesocket(fd);
437                         logger(LOG_ERR, _("System call `%s' failed: %s"), "fcntl",
438                                    strerror(errno));
439                         return -1;
440                 }
441         }
442 #endif
443
444         sockaddrunmap(&sa);
445
446         c = new_connection();
447
448         c->address = sa;
449         c->hostname = sockaddr2hostname(&sa);
450         c->socket = fd;
451         c->last_ping_time = now;
452
453         ifdebug(CONNECTIONS) logger(LOG_NOTICE, _("Connection from %s"), c->hostname);
454
455         connection_add(c);
456
457         c->allow_request = ID;
458         gnutls_init(&c->session, GNUTLS_CLIENT);
459         gnutls_set_default_priority(c->session);
460         gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, myself->connection->credentials);
461         gnutls_certificate_server_set_request(c->session, GNUTLS_CERT_REQUEST);
462 //      gnutls_certificate_client_set_select_function(c->session, certselfunc);
463 //      gnutls_certificate_server_set_select_function(c->session, scertselfunc);
464         gnutls_transport_set_ptr(c->session, c->socket);
465         gnutls_handshake(c->session);
466
467         return true;
468 }
469
470 void try_outgoing_connections(void)
471 {
472         static config_t *cfg = NULL;
473         char *name;
474         outgoing_t *outgoing;
475
476         cp();
477
478         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg;
479                 cfg = lookup_config_next(config_tree, cfg)) {
480                 get_config_string(cfg, &name);
481
482                 if(!check_id(name)) {
483                         logger(LOG_ERR,
484                                    _("Invalid name for outgoing connection in %s line %d"),
485                                    cfg->file, cfg->line);
486                         free(name);
487                         continue;
488                 }
489
490                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
491                 outgoing->name = name;
492                 setup_outgoing_connection(outgoing);
493         }
494 }