- Integrate rbl trees into tinc.
[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.77 2000/11/20 19:12:12 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
810   child_pids = list_new();
811 cp
812   return 0;
813 }
814
815 RETSIGTYPE
816 sigalrm_handler(int a)
817 {
818   config_t const *cfg;
819 cp
820   cfg = get_config_val(upstreamcfg, config_connectto);
821
822   if(!cfg && upstreamcfg == config)
823     /* No upstream IP given, we're listen only. */
824     return;
825
826   while(cfg)
827     {
828       upstreamcfg = cfg->next;
829       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
830         {
831           signal(SIGALRM, SIG_IGN);
832           return;
833         }
834       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
835     }
836
837   signal(SIGALRM, sigalrm_handler);
838   upstreamcfg = config;
839   seconds_till_retry += 5;
840   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
841     seconds_till_retry = MAXTIMEOUT;
842   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
843          seconds_till_retry);
844   alarm(seconds_till_retry);
845 cp
846 }
847
848 /*
849   setup all initial network connections
850 */
851 int setup_network_connections(void)
852 {
853   config_t const *cfg;
854 cp
855   if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
856     timeout = 60;
857   else
858     {
859       timeout = cfg->data.val;
860       if(timeout < 1)
861         {
862           timeout = 86400;
863         }
864      }
865
866   if(setup_tap_fd() < 0)
867     return -1;
868
869   if(setup_myself() < 0)
870     return -1;
871
872   /* Run tinc-up script to further initialize the tap interface */
873   execute_script("tinc-up");
874   
875   if(!(cfg = get_config_val(config, config_connectto)))
876     /* No upstream IP given, we're listen only. */
877     return 0;
878
879   while(cfg)
880     {
881       upstreamcfg = cfg->next;
882       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
883         return 0;
884       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
885     }
886     
887   signal(SIGALRM, sigalrm_handler);
888   upstreamcfg = config;
889   seconds_till_retry = MAXTIMEOUT;
890   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
891   alarm(seconds_till_retry);
892 cp
893   return 0;
894 }
895
896 /*
897   close all open network connections
898 */
899 void close_network_connections(void)
900 {
901   rbl_t *rbl;
902   connection_t *p;
903 cp
904   RBL_FOREACH(connection_tree, rbl)
905     {
906       p = (connection_t *)rbl->data;
907       p->status.active = 0;
908       terminate_connection(p);
909     }
910
911   if(myself)
912     if(myself->status.active)
913       {
914         close(myself->meta_socket);
915         free_connection(myself);
916         myself = NULL;
917       }
918
919   close(tap_fd);
920
921   /* Execute tinc-down script right after shutting down the interface */
922   execute_script("tinc-down");
923
924   destroy_connection_tree();
925
926   syslog(LOG_NOTICE, _("Terminating"));
927 cp
928   return;
929 }
930
931 /*
932   create a data (udp) socket
933 */
934 int setup_vpn_connection(connection_t *cl)
935 {
936   int nfd, flags;
937   struct sockaddr_in a;
938   const int one = 1;
939 cp
940   if(debug_lvl >= DEBUG_TRAFFIC)
941     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
942
943   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
944   if(nfd == -1)
945     {
946       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
947       return -1;
948     }
949
950   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
951     {
952       close(nfd);
953       syslog(LOG_ERR, _("System call `%s' failed: %m"),
954              "setsockopt");
955       return -1;
956     }
957
958   flags = fcntl(nfd, F_GETFL);
959   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
960     {
961       close(nfd);
962       syslog(LOG_ERR, _("System call `%s' failed: %m"),
963              "fcntl");
964       return -1;
965     }
966
967   memset(&a, 0, sizeof(a));
968   a.sin_family = AF_INET;
969   a.sin_port = htons(myself->port);
970   a.sin_addr.s_addr = htonl(INADDR_ANY);
971
972   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
973     {
974       close(nfd);
975       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
976       return -1;
977     }
978
979   a.sin_family = AF_INET;
980   a.sin_port = htons(cl->port);
981   a.sin_addr.s_addr = htonl(cl->address);
982
983   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
984     {
985       close(nfd);
986       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
987              cl->hostname, cl->port);
988       return -1;
989     }
990
991   flags = fcntl(nfd, F_GETFL);
992   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
993     {
994       close(nfd);
995       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
996              cl->name, cl->hostname);
997       return -1;
998     }
999
1000   cl->socket = nfd;
1001   cl->status.dataopen = 1;
1002 cp
1003   return 0;
1004 }
1005
1006 /*
1007   handle an incoming tcp connect call and open
1008   a connection to it.
1009 */
1010 connection_t *create_new_connection(int sfd)
1011 {
1012   connection_t *p;
1013   struct sockaddr_in ci;
1014   int len = sizeof(ci);
1015 cp
1016   p = new_connection();
1017
1018   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1019     {
1020       syslog(LOG_ERR, _("System call `%s' failed: %m"),
1021              "getpeername");
1022       return NULL;
1023     }
1024
1025   p->name = unknown;
1026   p->address = ntohl(ci.sin_addr.s_addr);
1027   p->hostname = hostlookup(ci.sin_addr.s_addr);
1028   p->meta_socket = sfd;
1029   p->status.meta = 1;
1030   p->buffer = xmalloc(MAXBUFSIZE);
1031   p->buflen = 0;
1032   p->last_ping_time = time(NULL);
1033   
1034   if(debug_lvl >= DEBUG_CONNECTIONS)
1035     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1036          p->hostname, htons(ci.sin_port));
1037
1038   p->allow_request = ID;
1039 cp
1040   return p;
1041 }
1042
1043 /*
1044   put all file descriptors in an fd_set array
1045 */
1046 void build_fdset(fd_set *fs)
1047 {
1048   rbl_t *rbl;
1049   connection_t *p;
1050 cp
1051   FD_ZERO(fs);
1052
1053   RBL_FOREACH(connection_tree, rbl)
1054     {
1055       p = (connection_t *)rbl->data;
1056       if(p->status.meta)
1057         FD_SET(p->meta_socket, fs);
1058       if(p->status.dataopen)
1059         FD_SET(p->socket, fs);
1060     }
1061
1062   FD_SET(myself->meta_socket, fs);
1063   FD_SET(tap_fd, fs);
1064 cp
1065 }
1066
1067 /*
1068   receive incoming data from the listening
1069   udp socket and write it to the ethertap
1070   device after being decrypted
1071 */
1072 int handle_incoming_vpn_data(connection_t *cl)
1073 {
1074   vpn_packet_t pkt;
1075   int x, l = sizeof(x);
1076   int lenin;
1077 cp
1078   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1079     {
1080       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1081              __FILE__, __LINE__, cl->socket);
1082       return -1;
1083     }
1084   if(x)
1085     {
1086       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1087       return -1;
1088     }
1089
1090   if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1091     {
1092       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1093       return -1;
1094     }
1095
1096   if(debug_lvl >= DEBUG_TRAFFIC)
1097     {
1098       syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1099              cl->name, cl->hostname);
1100     }
1101
1102 cp
1103   return xrecv(cl, &pkt);
1104 }
1105
1106 /*
1107   terminate a connection and notify the other
1108   end before closing the sockets
1109 */
1110 void terminate_connection(connection_t *cl)
1111 {
1112   connection_t *p;
1113   subnet_t *s;
1114   rbl_t *rbl;
1115
1116 cp
1117   if(cl->status.remove)
1118     return;
1119
1120   cl->status.remove = 1;
1121
1122   if(debug_lvl >= DEBUG_CONNECTIONS)
1123     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1124            cl->name, cl->hostname);
1125  
1126   if(cl->socket)
1127     close(cl->socket);
1128   if(cl->status.meta)
1129     close(cl->meta_socket);
1130
1131 cp
1132   /* Find all connections that were lost because they were behind cl
1133      (the connection that was dropped). */
1134
1135   if(cl->status.meta)
1136     RBL_FOREACH(connection_tree, rbl)
1137       {
1138         p = (connection_t *)rbl->data;
1139         if(p->nexthop == cl && p != cl)
1140           terminate_connection(p);
1141       }
1142
1143   /* Inform others of termination if it was still active */
1144
1145   if(cl->status.active)
1146     RBL_FOREACH(connection_tree, rbl)
1147       {
1148         p = (connection_t *)rbl->data;
1149         if(p->status.meta && p->status.active && p!=cl)
1150           send_del_host(p, cl); /* Sounds like recursion, but p does not have a meta connection :) */
1151       }
1152
1153   /* Remove the associated subnets */
1154
1155   rbl_delete_rbltree(cl->subnet_tree);
1156
1157   /* Check if this was our outgoing connection */
1158     
1159   if(cl->status.outgoing && cl->status.active)
1160     {
1161       signal(SIGALRM, sigalrm_handler);
1162       seconds_till_retry = 5;
1163       alarm(seconds_till_retry);
1164       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1165     }
1166
1167   /* Inactivate */
1168
1169   cl->status.active = 0;
1170 cp
1171 }
1172
1173 /*
1174   Check if the other end is active.
1175   If we have sent packets, but didn't receive any,
1176   then possibly the other end is dead. We send a
1177   PING request over the meta connection. If the other
1178   end does not reply in time, we consider them dead
1179   and close the connection.
1180 */
1181 void check_dead_connections(void)
1182 {
1183   time_t now;
1184   rbl_t *rbl;
1185   connection_t *cl;
1186 cp
1187   now = time(NULL);
1188
1189   RBL_FOREACH(connection_tree, rbl)
1190     {
1191       cl = (connection_t *)rbl->data;
1192       if(cl->status.active && cl->status.meta)
1193         {
1194           if(cl->last_ping_time + timeout < now)
1195             {
1196               if(cl->status.pinged)
1197                 {
1198                   if(debug_lvl >= DEBUG_PROTOCOL)
1199                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1200                            cl->name, cl->hostname);
1201                   cl->status.timeout = 1;
1202                   terminate_connection(cl);
1203                 }
1204               else
1205                 {
1206                   send_ping(cl);
1207                 }
1208             }
1209         }
1210     }
1211 cp
1212 }
1213
1214 /*
1215   accept a new tcp connect and create a
1216   new connection
1217 */
1218 int handle_new_meta_connection()
1219 {
1220   connection_t *ncn;
1221   struct sockaddr client;
1222   int nfd, len = sizeof(client);
1223 cp
1224   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1225     {
1226       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1227       return -1;
1228     }
1229
1230   if(!(ncn = create_new_connection(nfd)))
1231     {
1232       shutdown(nfd, 2);
1233       close(nfd);
1234       syslog(LOG_NOTICE, _("Closed attempted connection"));
1235       return 0;
1236     }
1237
1238   connection_add(ncn);
1239 cp
1240   return 0;
1241 }
1242
1243 /*
1244   check all connections to see if anything
1245   happened on their sockets
1246 */
1247 void check_network_activity(fd_set *f)
1248 {
1249   connection_t *p;
1250   rbl_t *rbl;
1251 cp
1252   RBL_FOREACH(connection_tree, rbl)
1253     {
1254       p = (connection_t *)rbl->data;
1255
1256       if(p->status.remove)
1257         return;
1258
1259       if(p->status.dataopen)
1260         if(FD_ISSET(p->socket, f))
1261           {
1262             handle_incoming_vpn_data(p);
1263
1264             /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1265             
1266             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1267             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1268                    p->name, p->hostname, strerror(x));
1269             terminate_connection(p);
1270             */
1271             return;
1272           }  
1273
1274       if(p->status.meta)
1275         if(FD_ISSET(p->meta_socket, f))
1276           if(receive_meta(p) < 0)
1277             {
1278               terminate_connection(p);
1279               return;
1280             } 
1281     }
1282     
1283   if(FD_ISSET(myself->meta_socket, f))
1284     handle_new_meta_connection();
1285 cp
1286 }
1287
1288 /*
1289   read, encrypt and send data that is
1290   available through the ethertap device
1291 */
1292 void handle_tap_input(void)
1293 {
1294   vpn_packet_t vp;
1295   int lenin;
1296 cp  
1297   if(taptype == TAP_TYPE_TUNTAP)
1298     {
1299       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1300         {
1301           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1302           return;
1303         }
1304       vp.len = lenin;
1305     }
1306   else                  /* ethertap */
1307     {
1308       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1309         {
1310           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1311           return;
1312         }
1313       vp.len = lenin - 2;
1314     }
1315
1316   total_tap_in += lenin;
1317
1318   if(lenin < 32)
1319     {
1320       if(debug_lvl >= DEBUG_TRAFFIC)
1321         syslog(LOG_WARNING, _("Received short packet from tap device"));
1322       return;
1323     }
1324
1325   if(debug_lvl >= DEBUG_TRAFFIC)
1326     {
1327       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1328     }
1329
1330   send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1331 cp
1332 }
1333
1334 /*
1335   this is where it all happens...
1336 */
1337 void main_loop(void)
1338 {
1339   fd_set fset;
1340   struct timeval tv;
1341   int r;
1342   time_t last_ping_check;
1343   int t;
1344 cp
1345   last_ping_check = time(NULL);
1346
1347   for(;;)
1348     {
1349       tv.tv_sec = timeout;
1350       tv.tv_usec = 0;
1351
1352       prune_connection_tree();
1353       build_fdset(&fset);
1354
1355       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1356         {
1357           if(errno != EINTR) /* because of alarm */
1358             {
1359               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1360               return;
1361             }
1362         }
1363
1364       if(sighup)
1365         {
1366           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1367           sighup = 0;
1368           close_network_connections();
1369           clear_config(&config);
1370
1371           if(read_server_config())
1372             {
1373               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1374               exit(0);
1375             }
1376
1377           sleep(5);
1378           
1379           if(setup_network_connections())
1380             return;
1381             
1382           continue;
1383         }
1384
1385       t = time(NULL);
1386
1387       /* Let's check if everybody is still alive */
1388
1389       if(last_ping_check + timeout < t)
1390         {
1391           check_dead_connections();
1392           last_ping_check = time(NULL);
1393
1394           /* Should we regenerate our key? */
1395
1396           if(keyexpires < t)
1397             {
1398               if(debug_lvl >= DEBUG_STATUS)
1399                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1400                 
1401               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1402               send_key_changed(myself, NULL);
1403               keyexpires = time(NULL) + keylifetime;
1404             }
1405         }
1406
1407       if(r > 0)
1408         {
1409           check_network_activity(&fset);
1410
1411           /* local tap data */
1412           if(FD_ISSET(tap_fd, &fset))
1413             handle_tap_input();
1414         }
1415
1416       check_children();
1417     }
1418 cp
1419 }