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