Another big & bad commit:
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998,1999,2000 Ivo Timmermans <itimmermans@bigfoot.com>,
4                             2000 Guus Sliepen <guus@sliepen.warande.net>
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.c,v 1.35.4.81 2000/11/24 23:13:02 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/signal.h>
33 #include <sys/time.h>
34 #include <sys/types.h>
35 #include <syslog.h>
36 #include <unistd.h>
37 #include <sys/ioctl.h>
38 /* SunOS really wants sys/socket.h BEFORE net/if.h,
39    and FreeBSD wants these lines below the rest. */
40 #include <arpa/inet.h>
41 #include <sys/socket.h>
42 #include <net/if.h>
43
44 #ifdef HAVE_OPENSSL_RAND_H
45 # include <openssl/rand.h>
46 #else
47 # include <rand.h>
48 #endif
49
50 #ifdef HAVE_OPENSSL_EVP_H
51 # include <openssl/evp.h>
52 #else
53 # include <evp.h>
54 #endif
55
56 #ifdef HAVE_OPENSSL_ERR_H
57 # include <openssl/err.h>
58 #else
59 # include <err.h>
60 #endif
61
62 #ifdef HAVE_TUNTAP
63 #include LINUX_IF_TUN_H
64 #endif
65
66 #include <utils.h>
67 #include <xalloc.h>
68
69 #include "conf.h"
70 #include "connection.h"
71 #include "list.h"
72 #include "meta.h"
73 #include "net.h"
74 #include "netutl.h"
75 #include "process.h"
76 #include "protocol.h"
77 #include "subnet.h"
78
79 #include "system.h"
80
81 int tap_fd = -1;
82 int taptype = TAP_TYPE_ETHERTAP;
83 int total_tap_in = 0;
84 int total_tap_out = 0;
85 int total_socket_in = 0;
86 int total_socket_out = 0;
87
88 config_t *upstreamcfg;
89 static int seconds_till_retry;
90
91 int keylifetime = 0;
92 int keyexpires = 0;
93
94 char *unknown = NULL;
95
96 subnet_t mymac;
97
98 int xsend(connection_t *cl, vpn_packet_t *inpkt)
99 {
100   vpn_packet_t outpkt;
101   int outlen, outpad;
102   EVP_CIPHER_CTX ctx;
103 cp
104   outpkt.len = inpkt->len;
105   
106   /* Encrypt the packet */
107   
108   EVP_EncryptInit(&ctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktkey + cl->cipher_pkttype->key_len);
109   EVP_EncryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
110   EVP_EncryptFinal(&ctx, outpkt.data + outlen, &outpad);
111   outlen += outpad + 2;
112
113 /* Bypass
114   outlen = outpkt.len + 2;
115   memcpy(&outpkt, inpkt, outlen);
116 */  
117
118   if(debug_lvl >= DEBUG_TRAFFIC)
119     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
120            outlen, cl->name, cl->hostname);
121
122   total_socket_out += outlen;
123
124   if((send(cl->socket, (char *) &(outpkt.len), outlen, 0)) < 0)
125     {
126       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
127              cl->name, cl->hostname);
128       return -1;
129     }
130 cp
131   return 0;
132 }
133
134 int xrecv(connection_t *cl, vpn_packet_t *inpkt)
135 {
136   vpn_packet_t outpkt;
137   int outlen, outpad;
138   EVP_CIPHER_CTX ctx;
139 cp
140   outpkt.len = inpkt->len;
141
142   /* Decrypt the packet */
143
144   EVP_DecryptInit(&ctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktkey + myself->cipher_pkttype->key_len);
145   EVP_DecryptUpdate(&ctx, outpkt.data, &outlen, inpkt->data, inpkt->len + 8);
146   EVP_DecryptFinal(&ctx, outpkt.data + outlen, &outpad);
147   outlen += outpad;
148
149 /* Bypass
150   outlen = outpkt.len+2;
151   memcpy(&outpkt, inpkt, outlen);
152 */
153      
154   if(debug_lvl >= DEBUG_TRAFFIC)
155     syslog(LOG_ERR, _("Writing packet of %d bytes to tap device"),
156            outpkt.len, outlen);
157
158   /* Fix mac address */
159
160   memcpy(outpkt.data, mymac.net.mac.address.x, 6);
161
162   if(taptype == TAP_TYPE_TUNTAP)
163     {
164       if(write(tap_fd, outpkt.data, outpkt.len) < 0)
165         syslog(LOG_ERR, _("Can't write to tun/tap device: %m"));
166       else
167         total_tap_out += outpkt.len;
168     }
169   else  /* ethertap */
170     {
171       if(write(tap_fd, outpkt.data - 2, outpkt.len + 2) < 0)
172         syslog(LOG_ERR, _("Can't write to ethertap device: %m"));
173       else
174         total_tap_out += outpkt.len + 2;
175     }
176 cp
177   return 0;
178 }
179
180 /*
181   add the given packet of size s to the
182   queue q, be it the send or receive queue
183 */
184 void add_queue(packet_queue_t **q, void *packet, size_t s)
185 {
186   queue_element_t *e;
187 cp
188   e = xmalloc(sizeof(*e));
189   e->packet = xmalloc(s);
190   memcpy(e->packet, packet, s);
191
192   if(!*q)
193     {
194       *q = xmalloc(sizeof(**q));
195       (*q)->head = (*q)->tail = NULL;
196     }
197
198   e->next = NULL;                       /* We insert at the tail */
199
200   if((*q)->tail)                        /* Do we have a tail? */
201     {
202       (*q)->tail->next = e;
203       e->prev = (*q)->tail;
204     }
205   else                                  /* No tail -> no head too */
206     {
207       (*q)->head = e;
208       e->prev = NULL;
209     }
210
211   (*q)->tail = e;
212 cp
213 }
214
215 /* Remove a queue element */
216 void del_queue(packet_queue_t **q, queue_element_t *e)
217 {
218 cp
219   free(e->packet);
220
221   if(e->next)                           /* There is a successor, so we are not tail */
222     {
223       if(e->prev)                       /* There is a predecessor, so we are not head */
224         {
225           e->next->prev = e->prev;
226           e->prev->next = e->next;
227         }
228       else                              /* We are head */
229         {
230           e->next->prev = NULL;
231           (*q)->head = e->next;
232         }
233     }
234   else                                  /* We are tail (or all alone!) */
235     {          
236       if(e->prev)                       /* We are not alone :) */
237         {
238           e->prev->next = NULL;
239           (*q)->tail = e->prev;
240         }
241       else                              /* Adieu */
242         {
243           free(*q);
244           *q = NULL;
245         }
246     }
247     
248   free(e);
249 cp
250 }
251
252 /*
253   flush a queue by calling function for
254   each packet, and removing it when that
255   returned a zero exit code
256 */
257 void flush_queue(connection_t *cl, packet_queue_t **pq,
258                  int (*function)(connection_t*,vpn_packet_t*))
259 {
260   queue_element_t *p, *next = NULL;
261 cp
262   for(p = (*pq)->head; p != NULL; )
263     {
264       next = p->next;
265
266       if(!function(cl, p->packet))
267         del_queue(pq, p);
268         
269       p = next;
270     }
271
272   if(debug_lvl >= DEBUG_TRAFFIC)
273     syslog(LOG_DEBUG, _("Queue flushed"));
274 cp
275 }
276
277 /*
278   flush the send&recv queues
279   void because nothing goes wrong here, packets
280   remain in the queue if something goes wrong
281 */
282 void flush_queues(connection_t *cl)
283 {
284 cp
285   if(cl->sq)
286     {
287       if(debug_lvl >= DEBUG_TRAFFIC)
288         syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
289                cl->name, cl->hostname);
290       flush_queue(cl, &(cl->sq), xsend);
291     }
292
293   if(cl->rq)
294     {
295       if(debug_lvl >=  DEBUG_TRAFFIC)
296         syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
297                cl->name, cl->hostname);
298       flush_queue(cl, &(cl->rq), xrecv);
299     }
300 cp
301 }
302
303 /*
304   send a packet to the given vpn ip.
305 */
306 int send_packet(ip_t to, vpn_packet_t *packet)
307 {
308   connection_t *cl;
309   subnet_t *subnet;
310 cp
311   if((subnet = lookup_subnet_ipv4(to)) == NULL)
312     {
313       if(debug_lvl >= DEBUG_TRAFFIC)
314         {
315           syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
316                  IP_ADDR_V(to));
317         }
318
319       return -1;
320     }
321
322   cl = subnet->owner;
323     
324   if(cl == myself)
325     {
326       if(debug_lvl >= DEBUG_TRAFFIC)
327         {
328           syslog(LOG_NOTICE, _("Packet with destination %d.%d.%d.%d is looping back to us!"),
329                  IP_ADDR_V(to));
330         }
331
332       return -1;
333     }
334
335   /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
336
337   /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
338   
339   /* Connections are now opened beforehand...
340
341   if(!cl->status.dataopen)
342     if(setup_vpn_connection(cl) < 0)
343       {
344         syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
345                cl->name, cl->hostname);
346         return -1;
347       }
348   */
349       
350   if(!cl->status.validkey)
351     {
352 /* FIXME: Don't queue until everything else is fixed.
353       if(debug_lvl >= DEBUG_TRAFFIC)
354         syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
355                cl->name, cl->hostname);
356       add_queue(&(cl->sq), packet, packet->len + 2);
357 */
358       if(!cl->status.waitingforkey)
359         send_req_key(myself, cl);                       /* Keys should be sent to the host running the tincd */
360       return 0;
361     }
362
363   if(!cl->status.active)
364     {
365 /* FIXME: Don't queue until everything else is fixed.
366       if(debug_lvl >= DEBUG_TRAFFIC)
367         syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
368                cl->name, cl->hostname);
369       add_queue(&(cl->sq), packet, packet->len + 2);
370 */
371       return 0; /* We don't want to mess up, do we? */
372     }
373
374   /* can we send it? can we? can we? huh? */
375 cp
376   return xsend(cl, packet);
377 }
378
379 /*
380   open the local ethertap device
381 */
382 int setup_tap_fd(void)
383 {
384   int nfd;
385   const char *tapfname;
386   config_t const *cfg;
387 #ifdef HAVE_TUNTAP
388   struct ifreq ifr;
389 #endif
390
391 cp  
392   if((cfg = get_config_val(config, config_tapdevice)))
393     tapfname = cfg->data.ptr;
394   else
395 #ifdef HAVE_TUNTAP
396     tapfname = "/dev/misc/net/tun";
397 #else
398     tapfname = "/dev/tap0";
399 #endif
400 cp
401   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
402     {
403       syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
404       return -1;
405     }
406 cp
407   tap_fd = nfd;
408
409   /* Set default MAC address for ethertap devices */
410   
411   taptype = TAP_TYPE_ETHERTAP;
412   mymac.type = SUBNET_MAC;
413   mymac.net.mac.address.x[0] = 0xfe;
414   mymac.net.mac.address.x[1] = 0xfd;
415   mymac.net.mac.address.x[2] = 0x00;
416   mymac.net.mac.address.x[3] = 0x00;
417   mymac.net.mac.address.x[4] = 0x00;
418   mymac.net.mac.address.x[5] = 0x00;
419
420 #ifdef HAVE_TUNTAP
421   /* Ok now check if this is an old ethertap or a new tun/tap thingie */
422   memset(&ifr, 0, sizeof(ifr));
423 cp
424   ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
425   if (netname)
426     strncpy(ifr.ifr_name, netname, IFNAMSIZ);
427 cp
428   if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
429   {
430     syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
431     taptype = TAP_TYPE_TUNTAP;
432   }
433 #endif
434 cp
435   return 0;
436 }
437
438 /*
439   set up the socket that we listen on for incoming
440   (tcp) connections
441 */
442 int setup_listen_meta_socket(int port)
443 {
444   int nfd, flags;
445   struct sockaddr_in a;
446   const int one = 1;
447   config_t const *cfg;
448 cp
449   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
450     {
451       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
452       return -1;
453     }
454
455   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
456     {
457       close(nfd);
458       syslog(LOG_ERR, _("System call `%s' failed: %m"),
459              "setsockopt");
460       return -1;
461     }
462
463   if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
464     {
465       close(nfd);
466       syslog(LOG_ERR, _("System call `%s' failed: %m"),
467              "setsockopt");
468       return -1;
469     }
470
471   flags = fcntl(nfd, F_GETFL);
472   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
473     {
474       close(nfd);
475       syslog(LOG_ERR, _("System call `%s' failed: %m"),
476              "fcntl");
477       return -1;
478     }
479
480   if((cfg = get_config_val(config, config_interface)))
481     {
482       if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
483         {
484           close(nfd);
485           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
486           return -1;
487         }
488     }
489
490   memset(&a, 0, sizeof(a));
491   a.sin_family = AF_INET;
492   a.sin_port = htons(port);
493   
494   if((cfg = get_config_val(config, config_interfaceip)))
495     a.sin_addr.s_addr = htonl(cfg->data.ip->address);
496   else
497     a.sin_addr.s_addr = htonl(INADDR_ANY);
498
499   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
500     {
501       close(nfd);
502       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
503       return -1;
504     }
505
506   if(listen(nfd, 3))
507     {
508       close(nfd);
509       syslog(LOG_ERR, _("System call `%s' failed: %m"),
510              "listen");
511       return -1;
512     }
513 cp
514   return nfd;
515 }
516
517 /*
518   setup the socket for incoming encrypted
519   data (the udp part)
520 */
521 int setup_vpn_in_socket(int port)
522 {
523   int nfd, flags;
524   struct sockaddr_in a;
525   const int one = 1;
526 cp
527   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
528     {
529       close(nfd);
530       syslog(LOG_ERR, _("Creating socket failed: %m"));
531       return -1;
532     }
533
534   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
535     {
536       close(nfd);
537       syslog(LOG_ERR, _("System call `%s' failed: %m"),
538              "setsockopt");
539       return -1;
540     }
541
542   flags = fcntl(nfd, F_GETFL);
543   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
544     {
545       close(nfd);
546       syslog(LOG_ERR, _("System call `%s' failed: %m"),
547              "fcntl");
548       return -1;
549     }
550
551   memset(&a, 0, sizeof(a));
552   a.sin_family = AF_INET;
553   a.sin_port = htons(port);
554   a.sin_addr.s_addr = htonl(INADDR_ANY);
555
556   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
557     {
558       close(nfd);
559       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
560       return -1;
561     }
562 cp
563   return nfd;
564 }
565
566 /*
567   setup an outgoing meta (tcp) socket
568 */
569 int setup_outgoing_meta_socket(connection_t *cl)
570 {
571   int flags;
572   struct sockaddr_in a;
573   config_t const *cfg;
574 cp
575   if(debug_lvl >= DEBUG_CONNECTIONS)
576     syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
577
578   if((cfg = get_config_val(cl->config, config_port)) == NULL)
579     cl->port = 655;
580   else
581     cl->port = cfg->data.val;
582
583   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
584   if(cl->meta_socket == -1)
585     {
586       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
587              cl->hostname, cl->port);
588       return -1;
589     }
590
591   a.sin_family = AF_INET;
592   a.sin_port = htons(cl->port);
593   a.sin_addr.s_addr = htonl(cl->address);
594
595   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
596     {
597       close(cl->meta_socket);
598       syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
599       return -1;
600     }
601
602   flags = fcntl(cl->meta_socket, F_GETFL);
603   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
604     {
605       close(cl->meta_socket);
606       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
607              cl->hostname, cl->port);
608       return -1;
609     }
610
611   if(debug_lvl >= DEBUG_CONNECTIONS)
612     syslog(LOG_INFO, _("Connected to %s port %hd"),
613          cl->hostname, cl->port);
614
615   cl->status.meta = 1;
616 cp
617   return 0;
618 }
619
620 /*
621   setup an outgoing connection. It's not
622   necessary to also open an udp socket as
623   well, because the other host will initiate
624   an authentication sequence during which
625   we will do just that.
626 */
627 int setup_outgoing_connection(char *name)
628 {
629   connection_t *ncn;
630   struct hostent *h;
631   config_t const *cfg;
632 cp
633   if(check_id(name))
634     {
635       syslog(LOG_ERR, _("Invalid name for outgoing connection"));
636       return -1;
637     }
638
639   ncn = new_connection();
640   asprintf(&ncn->name, "%s", name);
641     
642   if(read_host_config(ncn))
643     {
644       syslog(LOG_ERR, _("Error reading host configuration file for %s"));
645       free_connection(ncn);
646       return -1;
647     }
648     
649   if(!(cfg = get_config_val(ncn->config, config_address)))
650     {
651       syslog(LOG_ERR, _("No address specified for %s"));
652       free_connection(ncn);
653       return -1;
654     }
655     
656   if(!(h = gethostbyname(cfg->data.ptr)))
657     {
658       syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
659       free_connection(ncn);
660       return -1;
661     }
662
663   ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
664   ncn->hostname = hostlookup(htonl(ncn->address));
665   
666   if(setup_outgoing_meta_socket(ncn) < 0)
667     {
668       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
669              ncn->hostname);
670       free_connection(ncn);
671       return -1;
672     }
673
674   ncn->status.outgoing = 1;
675   ncn->buffer = xmalloc(MAXBUFSIZE);
676   ncn->buflen = 0;
677   ncn->last_ping_time = time(NULL);
678
679   connection_add(ncn);
680
681   send_id(ncn);
682 cp
683   return 0;
684 }
685
686 /*
687   Configure connection_t myself and set up the local sockets (listen only)
688 */
689 int setup_myself(void)
690 {
691   config_t const *cfg;
692   config_t *next;
693   subnet_t *net;
694 cp
695   myself = new_connection();
696
697   asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
698   myself->flags = 0;
699   myself->protocol_version = PROT_CURRENT;
700
701   if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
702     {
703       syslog(LOG_ERR, _("Name for tinc daemon required!"));
704       return -1;
705     }
706   else
707     asprintf(&myself->name, "%s", (char*)cfg->data.val);
708
709   if(check_id(myself->name))
710     {
711       syslog(LOG_ERR, _("Invalid name for myself!"));
712       return -1;
713     }
714 cp
715   if(!(cfg = get_config_val(config, config_privatekey)))
716     {
717       syslog(LOG_ERR, _("Private key for tinc daemon required!"));
718       return -1;
719     }
720   else
721     {
722       myself->rsa_key = RSA_new();
723       BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
724       BN_hex2bn(&myself->rsa_key->e, "FFFF");
725     }
726
727   if(read_host_config(myself))
728     {
729       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
730       return -1;
731     }
732 cp  
733   if(!(cfg = get_config_val(myself->config, config_publickey)))
734     {
735       syslog(LOG_ERR, _("Public key for tinc daemon required!"));
736       return -1;
737     }
738   else
739     {
740       BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
741     }
742 /*
743   if(RSA_check_key(myself->rsa_key) != 1)
744     {
745       syslog(LOG_ERR, _("Invalid public/private keypair!"));
746       return -1;
747     }
748 */
749   if(!(cfg = get_config_val(myself->config, config_port)))
750     myself->port = 655;
751   else
752     myself->port = cfg->data.val;
753
754   if((cfg = get_config_val(myself->config, config_indirectdata)))
755     if(cfg->data.val == stupid_true)
756       myself->flags |= EXPORTINDIRECTDATA;
757
758   if((cfg = get_config_val(myself->config, config_tcponly)))
759     if(cfg->data.val == stupid_true)
760       myself->flags |= TCPONLY;
761
762 /* Read in all the subnets specified in the host configuration file */
763
764   for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
765     {
766       net = new_subnet();
767       net->type = SUBNET_IPV4;
768       net->net.ipv4.address = cfg->data.ip->address;
769       net->net.ipv4.mask = cfg->data.ip->mask;
770       
771       /* Teach newbies what subnets are... */
772       
773       if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
774         {
775           syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
776           return -1;
777         }        
778       
779       subnet_add(myself, net);
780     }
781     
782   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
783     {
784       syslog(LOG_ERR, _("Unable to set up a listening socket!"));
785       return -1;
786     }
787
788   /* Generate packet encryption key */
789
790   myself->cipher_pkttype = EVP_bf_cfb();
791
792   myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
793
794   myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
795   RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
796
797   if(!(cfg = get_config_val(config, config_keyexpire)))
798     keylifetime = 3600;
799   else
800     keylifetime = cfg->data.val;
801     
802   keyexpires = time(NULL) + keylifetime;
803
804   /* Activate ourselves */
805   
806   myself->status.active = 1;
807
808   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
809 cp
810   return 0;
811 }
812
813 RETSIGTYPE
814 sigalrm_handler(int a)
815 {
816   config_t const *cfg;
817 cp
818   cfg = get_config_val(upstreamcfg, config_connectto);
819
820   if(!cfg && upstreamcfg == config)
821     /* No upstream IP given, we're listen only. */
822     return;
823
824   while(cfg)
825     {
826       upstreamcfg = cfg->next;
827       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
828         {
829           signal(SIGALRM, SIG_IGN);
830           return;
831         }
832       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
833     }
834
835   signal(SIGALRM, sigalrm_handler);
836   upstreamcfg = config;
837   seconds_till_retry += 5;
838   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
839     seconds_till_retry = MAXTIMEOUT;
840   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
841          seconds_till_retry);
842   alarm(seconds_till_retry);
843 cp
844 }
845
846 /*
847   setup all initial network connections
848 */
849 int setup_network_connections(void)
850 {
851   config_t const *cfg;
852 cp
853   init_connections();
854   init_subnets();
855
856   if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
857     timeout = 60;
858   else
859     {
860       timeout = cfg->data.val;
861       if(timeout < 1)
862         {
863           timeout = 86400;
864         }
865      }
866
867   if(setup_tap_fd() < 0)
868     return -1;
869
870   /* Run tinc-up script to further initialize the tap interface */
871   execute_script("tinc-up");
872   
873   if(setup_myself() < 0)
874     return -1;
875
876   if(!(cfg = get_config_val(config, config_connectto)))
877     /* No upstream IP given, we're listen only. */
878     return 0;
879
880   while(cfg)
881     {
882       upstreamcfg = cfg->next;
883       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
884         return 0;
885       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
886     }
887     
888   signal(SIGALRM, sigalrm_handler);
889   upstreamcfg = config;
890   seconds_till_retry = MAXTIMEOUT;
891   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
892   alarm(seconds_till_retry);
893 cp
894   return 0;
895 }
896
897 /*
898   close all open network connections
899 */
900 void close_network_connections(void)
901 {
902   rbl_t *rbl;
903   connection_t *p;
904 cp
905   RBL_FOREACH(connection_tree, rbl)
906     {
907       p = (connection_t *)rbl->data;
908       p->status.active = 0;
909       terminate_connection(p);
910     }
911
912   if(myself)
913     if(myself->status.active)
914       {
915         close(myself->meta_socket);
916         free_connection(myself);
917         myself = NULL;
918       }
919
920   close(tap_fd);
921
922   /* Execute tinc-down script right after shutting down the interface */
923   execute_script("tinc-down");
924
925   destroy_connection_tree();
926 cp
927   return;
928 }
929
930 /*
931   create a data (udp) socket
932 */
933 int setup_vpn_connection(connection_t *cl)
934 {
935   int nfd, flags;
936   struct sockaddr_in a;
937   const int one = 1;
938 cp
939   if(debug_lvl >= DEBUG_TRAFFIC)
940     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
941
942   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
943   if(nfd == -1)
944     {
945       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
946       return -1;
947     }
948
949   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
950     {
951       close(nfd);
952       syslog(LOG_ERR, _("System call `%s' failed: %m"),
953              "setsockopt");
954       return -1;
955     }
956
957   flags = fcntl(nfd, F_GETFL);
958   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
959     {
960       close(nfd);
961       syslog(LOG_ERR, _("System call `%s' failed: %m"),
962              "fcntl");
963       return -1;
964     }
965
966   memset(&a, 0, sizeof(a));
967   a.sin_family = AF_INET;
968   a.sin_port = htons(myself->port);
969   a.sin_addr.s_addr = htonl(INADDR_ANY);
970
971   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
972     {
973       close(nfd);
974       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
975       return -1;
976     }
977
978   a.sin_family = AF_INET;
979   a.sin_port = htons(cl->port);
980   a.sin_addr.s_addr = htonl(cl->address);
981
982   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
983     {
984       close(nfd);
985       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
986              cl->hostname, cl->port);
987       return -1;
988     }
989
990   flags = fcntl(nfd, F_GETFL);
991   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
992     {
993       close(nfd);
994       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
995              cl->name, cl->hostname);
996       return -1;
997     }
998
999   cl->socket = nfd;
1000   cl->status.dataopen = 1;
1001 cp
1002   return 0;
1003 }
1004
1005 /*
1006   handle an incoming tcp connect call and open
1007   a connection to it.
1008 */
1009 connection_t *create_new_connection(int sfd)
1010 {
1011   connection_t *p;
1012   struct sockaddr_in ci;
1013   int len = sizeof(ci);
1014 cp
1015   p = new_connection();
1016
1017   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1018     {
1019       syslog(LOG_ERR, _("System call `%s' failed: %m"),
1020              "getpeername");
1021       return NULL;
1022     }
1023
1024   p->name = unknown;
1025   p->address = ntohl(ci.sin_addr.s_addr);
1026   p->hostname = hostlookup(ci.sin_addr.s_addr);
1027   p->meta_socket = sfd;
1028   p->status.meta = 1;
1029   p->buffer = xmalloc(MAXBUFSIZE);
1030   p->buflen = 0;
1031   p->last_ping_time = time(NULL);
1032   
1033   if(debug_lvl >= DEBUG_CONNECTIONS)
1034     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1035          p->hostname, htons(ci.sin_port));
1036
1037   p->allow_request = ID;
1038 cp
1039   return p;
1040 }
1041
1042 /*
1043   put all file descriptors in an fd_set array
1044 */
1045 void build_fdset(fd_set *fs)
1046 {
1047   rbl_t *rbl;
1048   connection_t *p;
1049 cp
1050   FD_ZERO(fs);
1051
1052   RBL_FOREACH(connection_tree, rbl)
1053     {
1054       p = (connection_t *)rbl->data;
1055       if(p->status.meta)
1056         FD_SET(p->meta_socket, fs);
1057       if(p->status.dataopen)
1058         FD_SET(p->socket, fs);
1059     }
1060
1061   FD_SET(myself->meta_socket, fs);
1062   FD_SET(tap_fd, fs);
1063 cp
1064 }
1065
1066 /*
1067   receive incoming data from the listening
1068   udp socket and write it to the ethertap
1069   device after being decrypted
1070 */
1071 int handle_incoming_vpn_data(connection_t *cl)
1072 {
1073   vpn_packet_t pkt;
1074   int x, l = sizeof(x);
1075   int lenin;
1076 cp
1077   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1078     {
1079       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1080              __FILE__, __LINE__, cl->socket);
1081       return -1;
1082     }
1083   if(x)
1084     {
1085       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1086       return -1;
1087     }
1088
1089   if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1090     {
1091       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1092       return -1;
1093     }
1094
1095   if(debug_lvl >= DEBUG_TRAFFIC)
1096     {
1097       syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1098              cl->name, cl->hostname);
1099     }
1100
1101 cp
1102   return xrecv(cl, &pkt);
1103 }
1104
1105 /*
1106   terminate a connection and notify the other
1107   end before closing the sockets
1108 */
1109 void terminate_connection(connection_t *cl)
1110 {
1111   connection_t *p;
1112   subnet_t *subnet;
1113   rbl_t *rbl;
1114 cp
1115   if(cl->status.remove)
1116     return;
1117
1118   cl->status.remove = 1;
1119
1120   if(debug_lvl >= DEBUG_CONNECTIONS)
1121     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1122            cl->name, cl->hostname);
1123  
1124   if(cl->socket)
1125     close(cl->socket);
1126   if(cl->status.meta)
1127     close(cl->meta_socket);
1128
1129   /* Find all connections that were lost because they were behind cl
1130      (the connection that was dropped). */
1131
1132   if(cl->status.meta)
1133     RBL_FOREACH(connection_tree, rbl)
1134       {
1135         p = (connection_t *)rbl->data;
1136         if(p->nexthop == cl && p != cl)
1137           terminate_connection(p);
1138       }
1139
1140   /* Inform others of termination if it was still active */
1141
1142   if(cl->status.active)
1143     RBL_FOREACH(connection_tree, rbl)
1144       {
1145         p = (connection_t *)rbl->data;
1146         if(p->status.meta && p->status.active && p!=cl)
1147           send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1148       }
1149
1150   /* Remove the associated subnets */
1151
1152   RBL_FOREACH(cl->subnet_tree, rbl)
1153     {
1154       subnet = (subnet_t *)rbl->data;
1155       subnet_del(subnet);
1156     }
1157
1158   /* Check if this was our outgoing connection */
1159     
1160   if(cl->status.outgoing && cl->status.active)
1161     {
1162       signal(SIGALRM, sigalrm_handler);
1163       seconds_till_retry = 5;
1164       alarm(seconds_till_retry);
1165       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1166     }
1167
1168   /* Inactivate */
1169
1170   cl->status.active = 0;
1171 cp
1172 }
1173
1174 /*
1175   Check if the other end is active.
1176   If we have sent packets, but didn't receive any,
1177   then possibly the other end is dead. We send a
1178   PING request over the meta connection. If the other
1179   end does not reply in time, we consider them dead
1180   and close the connection.
1181 */
1182 void check_dead_connections(void)
1183 {
1184   time_t now;
1185   rbl_t *rbl;
1186   connection_t *cl;
1187 cp
1188   now = time(NULL);
1189
1190   RBL_FOREACH(connection_tree, rbl)
1191     {
1192       cl = (connection_t *)rbl->data;
1193       if(cl->status.active && cl->status.meta)
1194         {
1195           if(cl->last_ping_time + timeout < now)
1196             {
1197               if(cl->status.pinged)
1198                 {
1199                   if(debug_lvl >= DEBUG_PROTOCOL)
1200                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1201                            cl->name, cl->hostname);
1202                   cl->status.timeout = 1;
1203                   terminate_connection(cl);
1204                 }
1205               else
1206                 {
1207                   send_ping(cl);
1208                 }
1209             }
1210         }
1211     }
1212 cp
1213 }
1214
1215 /*
1216   accept a new tcp connect and create a
1217   new connection
1218 */
1219 int handle_new_meta_connection()
1220 {
1221   connection_t *ncn;
1222   struct sockaddr client;
1223   int nfd, len = sizeof(client);
1224 cp
1225   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1226     {
1227       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1228       return -1;
1229     }
1230
1231   if(!(ncn = create_new_connection(nfd)))
1232     {
1233       shutdown(nfd, 2);
1234       close(nfd);
1235       syslog(LOG_NOTICE, _("Closed attempted connection"));
1236       return 0;
1237     }
1238
1239   connection_add(ncn);
1240 cp
1241   return 0;
1242 }
1243
1244 /*
1245   check all connections to see if anything
1246   happened on their sockets
1247 */
1248 void check_network_activity(fd_set *f)
1249 {
1250   connection_t *p;
1251   rbl_t *rbl;
1252 cp
1253   RBL_FOREACH(connection_tree, rbl)
1254     {
1255       p = (connection_t *)rbl->data;
1256
1257       if(p->status.remove)
1258         return;
1259
1260       if(p->status.dataopen)
1261         if(FD_ISSET(p->socket, f))
1262           {
1263             handle_incoming_vpn_data(p);
1264
1265             /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1266             
1267             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1268             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1269                    p->name, p->hostname, strerror(x));
1270             terminate_connection(p);
1271             */
1272             return;
1273           }  
1274
1275       if(p->status.meta)
1276         if(FD_ISSET(p->meta_socket, f))
1277           if(receive_meta(p) < 0)
1278             {
1279               terminate_connection(p);
1280               return;
1281             } 
1282     }
1283     
1284   if(FD_ISSET(myself->meta_socket, f))
1285     handle_new_meta_connection();
1286 cp
1287 }
1288
1289 /*
1290   read, encrypt and send data that is
1291   available through the ethertap device
1292 */
1293 void handle_tap_input(void)
1294 {
1295   vpn_packet_t vp;
1296   int lenin;
1297 cp  
1298   if(taptype == TAP_TYPE_TUNTAP)
1299     {
1300       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1301         {
1302           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1303           return;
1304         }
1305       vp.len = lenin;
1306     }
1307   else                  /* ethertap */
1308     {
1309       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1310         {
1311           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1312           return;
1313         }
1314       vp.len = lenin - 2;
1315     }
1316
1317   total_tap_in += lenin;
1318
1319   if(lenin < 32)
1320     {
1321       if(debug_lvl >= DEBUG_TRAFFIC)
1322         syslog(LOG_WARNING, _("Received short packet from tap device"));
1323       return;
1324     }
1325
1326   if(debug_lvl >= DEBUG_TRAFFIC)
1327     {
1328       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1329     }
1330
1331   send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1332 cp
1333 }
1334
1335 /*
1336   this is where it all happens...
1337 */
1338 void main_loop(void)
1339 {
1340   fd_set fset;
1341   struct timeval tv;
1342   int r;
1343   time_t last_ping_check;
1344   int t;
1345 cp
1346   last_ping_check = time(NULL);
1347
1348   for(;;)
1349     {
1350       tv.tv_sec = timeout;
1351       tv.tv_usec = 0;
1352
1353       prune_connection_tree();
1354       build_fdset(&fset);
1355
1356       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1357         {
1358           if(errno != EINTR) /* because of alarm */
1359             {
1360               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1361               return;
1362             }
1363         }
1364
1365       if(sighup)
1366         {
1367           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1368           sighup = 0;
1369           close_network_connections();
1370           clear_config(&config);
1371
1372           if(read_server_config())
1373             {
1374               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1375               exit(0);
1376             }
1377
1378           sleep(5);
1379           
1380           if(setup_network_connections())
1381             return;
1382             
1383           continue;
1384         }
1385
1386       t = time(NULL);
1387
1388       /* Let's check if everybody is still alive */
1389
1390       if(last_ping_check + timeout < t)
1391         {
1392           check_dead_connections();
1393           last_ping_check = time(NULL);
1394
1395           /* Should we regenerate our key? */
1396
1397           if(keyexpires < t)
1398             {
1399               if(debug_lvl >= DEBUG_STATUS)
1400                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1401                 
1402               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1403               send_key_changed(myself, NULL);
1404               keyexpires = time(NULL) + keylifetime;
1405             }
1406         }
1407
1408       if(r > 0)
1409         {
1410           check_network_activity(&fset);
1411
1412           /* local tap data */
1413           if(FD_ISSET(tap_fd, &fset))
1414             handle_tap_input();
1415         }
1416     }
1417 cp
1418 }