7d81176a76d2cda89fd57f853305c1a1b1ca4bdd
[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.75 2000/11/16 17:54:27 zarq 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 "connlist.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(conn_list_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(conn_list_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(conn_list_t *cl, packet_queue_t **pq,
258                  int (*function)(conn_list_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(conn_list_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   conn_list_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   struct ifreq ifr;
388
389 cp  
390   if((cfg = get_config_val(config, config_tapdevice)))
391     tapfname = cfg->data.ptr;
392   else
393 #ifdef HAVE_TUNTAP
394     tapfname = "/dev/misc/net/tun";
395 #else
396     tapfname = "/dev/tap0";
397 #endif
398 cp
399   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
400     {
401       syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
402       return -1;
403     }
404 cp
405   tap_fd = nfd;
406
407   /* Set default MAC address for ethertap devices */
408   
409   taptype = TAP_TYPE_ETHERTAP;
410   mymac.type = SUBNET_MAC;
411   mymac.net.mac.address.x[0] = 0xfe;
412   mymac.net.mac.address.x[1] = 0xfd;
413   mymac.net.mac.address.x[2] = 0x00;
414   mymac.net.mac.address.x[3] = 0x00;
415   mymac.net.mac.address.x[4] = 0x00;
416   mymac.net.mac.address.x[5] = 0x00;
417
418 #ifdef HAVE_TUNTAP
419   /* Ok now check if this is an old ethertap or a new tun/tap thingie */
420   memset(&ifr, 0, sizeof(ifr));
421 cp
422   ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
423   if (netname)
424     strncpy(ifr.ifr_name, netname, IFNAMSIZ);
425 cp
426   if (!ioctl(tap_fd, TUNSETIFF, (void *) &ifr))
427   {
428     syslog(LOG_INFO, _("%s is a new style tun/tap device"), tapfname);
429     taptype = TAP_TYPE_TUNTAP;
430   }
431 #endif
432 cp
433   return 0;
434 }
435
436 /*
437   set up the socket that we listen on for incoming
438   (tcp) connections
439 */
440 int setup_listen_meta_socket(int port)
441 {
442   int nfd, flags;
443   struct sockaddr_in a;
444   const int one = 1;
445   config_t const *cfg;
446 cp
447   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
448     {
449       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
450       return -1;
451     }
452
453   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
454     {
455       close(nfd);
456       syslog(LOG_ERR, _("System call `%s' failed: %m"),
457              "setsockopt");
458       return -1;
459     }
460
461   if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
462     {
463       close(nfd);
464       syslog(LOG_ERR, _("System call `%s' failed: %m"),
465              "setsockopt");
466       return -1;
467     }
468
469   flags = fcntl(nfd, F_GETFL);
470   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
471     {
472       close(nfd);
473       syslog(LOG_ERR, _("System call `%s' failed: %m"),
474              "fcntl");
475       return -1;
476     }
477
478   if((cfg = get_config_val(config, config_interface)))
479     {
480       if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
481         {
482           close(nfd);
483           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
484           return -1;
485         }
486     }
487
488   memset(&a, 0, sizeof(a));
489   a.sin_family = AF_INET;
490   a.sin_port = htons(port);
491   
492   if((cfg = get_config_val(config, config_interfaceip)))
493     a.sin_addr.s_addr = htonl(cfg->data.ip->address);
494   else
495     a.sin_addr.s_addr = htonl(INADDR_ANY);
496
497   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
498     {
499       close(nfd);
500       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
501       return -1;
502     }
503
504   if(listen(nfd, 3))
505     {
506       close(nfd);
507       syslog(LOG_ERR, _("System call `%s' failed: %m"),
508              "listen");
509       return -1;
510     }
511 cp
512   return nfd;
513 }
514
515 /*
516   setup the socket for incoming encrypted
517   data (the udp part)
518 */
519 int setup_vpn_in_socket(int port)
520 {
521   int nfd, flags;
522   struct sockaddr_in a;
523   const int one = 1;
524 cp
525   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
526     {
527       close(nfd);
528       syslog(LOG_ERR, _("Creating socket failed: %m"));
529       return -1;
530     }
531
532   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
533     {
534       close(nfd);
535       syslog(LOG_ERR, _("System call `%s' failed: %m"),
536              "setsockopt");
537       return -1;
538     }
539
540   flags = fcntl(nfd, F_GETFL);
541   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
542     {
543       close(nfd);
544       syslog(LOG_ERR, _("System call `%s' failed: %m"),
545              "fcntl");
546       return -1;
547     }
548
549   memset(&a, 0, sizeof(a));
550   a.sin_family = AF_INET;
551   a.sin_port = htons(port);
552   a.sin_addr.s_addr = htonl(INADDR_ANY);
553
554   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
555     {
556       close(nfd);
557       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
558       return -1;
559     }
560 cp
561   return nfd;
562 }
563
564 /*
565   setup an outgoing meta (tcp) socket
566 */
567 int setup_outgoing_meta_socket(conn_list_t *cl)
568 {
569   int flags;
570   struct sockaddr_in a;
571   config_t const *cfg;
572 cp
573   if(debug_lvl >= DEBUG_CONNECTIONS)
574     syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
575
576   if((cfg = get_config_val(cl->config, config_port)) == NULL)
577     cl->port = 655;
578   else
579     cl->port = cfg->data.val;
580
581   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
582   if(cl->meta_socket == -1)
583     {
584       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
585              cl->hostname, cl->port);
586       return -1;
587     }
588
589   a.sin_family = AF_INET;
590   a.sin_port = htons(cl->port);
591   a.sin_addr.s_addr = htonl(cl->address);
592
593   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
594     {
595       close(cl->meta_socket);
596       syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
597       return -1;
598     }
599
600   flags = fcntl(cl->meta_socket, F_GETFL);
601   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
602     {
603       close(cl->meta_socket);
604       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
605              cl->hostname, cl->port);
606       return -1;
607     }
608
609   if(debug_lvl >= DEBUG_CONNECTIONS)
610     syslog(LOG_INFO, _("Connected to %s port %hd"),
611          cl->hostname, cl->port);
612
613   cl->status.meta = 1;
614 cp
615   return 0;
616 }
617
618 /*
619   setup an outgoing connection. It's not
620   necessary to also open an udp socket as
621   well, because the other host will initiate
622   an authentication sequence during which
623   we will do just that.
624 */
625 int setup_outgoing_connection(char *name)
626 {
627   conn_list_t *ncn;
628   struct hostent *h;
629   config_t const *cfg;
630 cp
631   if(check_id(name))
632     {
633       syslog(LOG_ERR, _("Invalid name for outgoing connection"));
634       return -1;
635     }
636
637   ncn = new_conn_list();
638   asprintf(&ncn->name, "%s", name);
639     
640   if(read_host_config(ncn))
641     {
642       syslog(LOG_ERR, _("Error reading host configuration file for %s"));
643       free_conn_list(ncn);
644       return -1;
645     }
646     
647   if(!(cfg = get_config_val(ncn->config, config_address)))
648     {
649       syslog(LOG_ERR, _("No address specified for %s"));
650       free_conn_list(ncn);
651       return -1;
652     }
653     
654   if(!(h = gethostbyname(cfg->data.ptr)))
655     {
656       syslog(LOG_ERR, _("Error looking up `%s': %m"), cfg->data.ptr);
657       free_conn_list(ncn);
658       return -1;
659     }
660
661   ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
662   ncn->hostname = hostlookup(htonl(ncn->address));
663   
664   if(setup_outgoing_meta_socket(ncn) < 0)
665     {
666       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
667              ncn->hostname);
668       free_conn_list(ncn);
669       return -1;
670     }
671
672   ncn->status.outgoing = 1;
673   ncn->buffer = xmalloc(MAXBUFSIZE);
674   ncn->buflen = 0;
675   ncn->last_ping_time = time(NULL);
676
677   conn_list_add(ncn);
678
679   send_id(ncn);
680 cp
681   return 0;
682 }
683
684 /*
685   Configure conn_list_t myself and set up the local sockets (listen only)
686 */
687 int setup_myself(void)
688 {
689   config_t const *cfg;
690   config_t *next;
691   subnet_t *net;
692 cp
693   myself = new_conn_list();
694
695   asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
696   myself->flags = 0;
697   myself->protocol_version = PROT_CURRENT;
698
699   if(!(cfg = get_config_val(config, config_name))) /* Not acceptable */
700     {
701       syslog(LOG_ERR, _("Name for tinc daemon required!"));
702       return -1;
703     }
704   else
705     asprintf(&myself->name, "%s", (char*)cfg->data.val);
706
707   if(check_id(myself->name))
708     {
709       syslog(LOG_ERR, _("Invalid name for myself!"));
710       return -1;
711     }
712 cp
713   if(!(cfg = get_config_val(config, config_privatekey)))
714     {
715       syslog(LOG_ERR, _("Private key for tinc daemon required!"));
716       return -1;
717     }
718   else
719     {
720       myself->rsa_key = RSA_new();
721       BN_hex2bn(&myself->rsa_key->d, cfg->data.ptr);
722       BN_hex2bn(&myself->rsa_key->e, "FFFF");
723     }
724
725   if(read_host_config(myself))
726     {
727       syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
728       return -1;
729     }
730 cp  
731   if(!(cfg = get_config_val(myself->config, config_publickey)))
732     {
733       syslog(LOG_ERR, _("Public key for tinc daemon required!"));
734       return -1;
735     }
736   else
737     {
738       BN_hex2bn(&myself->rsa_key->n, cfg->data.ptr);
739     }
740 /*
741   if(RSA_check_key(myself->rsa_key) != 1)
742     {
743       syslog(LOG_ERR, _("Invalid public/private keypair!"));
744       return -1;
745     }
746 */
747   if(!(cfg = get_config_val(myself->config, config_port)))
748     myself->port = 655;
749   else
750     myself->port = cfg->data.val;
751
752   if((cfg = get_config_val(myself->config, config_indirectdata)))
753     if(cfg->data.val == stupid_true)
754       myself->flags |= EXPORTINDIRECTDATA;
755
756   if((cfg = get_config_val(myself->config, config_tcponly)))
757     if(cfg->data.val == stupid_true)
758       myself->flags |= TCPONLY;
759
760 /* Read in all the subnets specified in the host configuration file */
761
762   for(next = myself->config; (cfg = get_config_val(next, config_subnet)); next = cfg->next)
763     {
764       net = new_subnet();
765       net->type = SUBNET_IPV4;
766       net->net.ipv4.address = cfg->data.ip->address;
767       net->net.ipv4.mask = cfg->data.ip->mask;
768       
769       /* Teach newbies what subnets are... */
770       
771       if((net->net.ipv4.address & net->net.ipv4.mask) != net->net.ipv4.address)
772         {
773           syslog(LOG_ERR, _("Network address and subnet mask do not match!"));
774           return -1;
775         }        
776       
777       subnet_add(myself, net);
778     }
779     
780   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
781     {
782       syslog(LOG_ERR, _("Unable to set up a listening socket!"));
783       return -1;
784     }
785
786   /* Generate packet encryption key */
787
788   myself->cipher_pkttype = EVP_bf_cfb();
789
790   myself->cipher_pktkeylength = myself->cipher_pkttype->key_len + myself->cipher_pkttype->iv_len;
791
792   myself->cipher_pktkey = (char *)xmalloc(myself->cipher_pktkeylength);
793   RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
794
795   if(!(cfg = get_config_val(config, config_keyexpire)))
796     keylifetime = 3600;
797   else
798     keylifetime = cfg->data.val;
799     
800   keyexpires = time(NULL) + keylifetime;
801
802   /* Activate ourselves */
803   
804   myself->status.active = 1;
805
806   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
807
808   child_pids = list_new();
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   if((cfg = get_config_val(config, config_pingtimeout)) == NULL)
854     timeout = 60;
855   else
856     {
857       timeout = cfg->data.val;
858       if(timeout < 1)
859         {
860           timeout = 86400;
861         }
862      }
863
864   if(setup_tap_fd() < 0)
865     return -1;
866
867   if(setup_myself() < 0)
868     return -1;
869
870   /* Run tinc-up script to further initialize the tap interface */
871   execute_script("tinc-up");
872   
873   if(!(cfg = get_config_val(config, config_connectto)))
874     /* No upstream IP given, we're listen only. */
875     return 0;
876
877   while(cfg)
878     {
879       upstreamcfg = cfg->next;
880       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
881         return 0;
882       cfg = get_config_val(upstreamcfg, config_connectto); /* Or else we try the next ConnectTo line */
883     }
884     
885   signal(SIGALRM, sigalrm_handler);
886   upstreamcfg = config;
887   seconds_till_retry = MAXTIMEOUT;
888   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
889   alarm(seconds_till_retry);
890 cp
891   return 0;
892 }
893
894 /*
895   close all open network connections
896 */
897 void close_network_connections(void)
898 {
899   conn_list_t *p;
900 cp
901   for(p = conn_list; p != NULL; p = p->next)
902     {
903       p->status.active = 0;
904       terminate_connection(p);
905     }
906
907   if(myself)
908     if(myself->status.active)
909       {
910         close(myself->meta_socket);
911         free_conn_list(myself);
912         myself = NULL;
913       }
914
915   close(tap_fd);
916
917   /* Execute tinc-down script right after shutting down the interface */
918   execute_script("tinc-down");
919
920   destroy_conn_list();
921
922   syslog(LOG_NOTICE, _("Terminating"));
923 cp
924   return;
925 }
926
927 /*
928   create a data (udp) socket
929 */
930 int setup_vpn_connection(conn_list_t *cl)
931 {
932   int nfd, flags;
933   struct sockaddr_in a;
934   const int one = 1;
935 cp
936   if(debug_lvl >= DEBUG_TRAFFIC)
937     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
938
939   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
940   if(nfd == -1)
941     {
942       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
943       return -1;
944     }
945
946   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
947     {
948       close(nfd);
949       syslog(LOG_ERR, _("System call `%s' failed: %m"),
950              "setsockopt");
951       return -1;
952     }
953
954   flags = fcntl(nfd, F_GETFL);
955   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
956     {
957       close(nfd);
958       syslog(LOG_ERR, _("System call `%s' failed: %m"),
959              "fcntl");
960       return -1;
961     }
962
963   memset(&a, 0, sizeof(a));
964   a.sin_family = AF_INET;
965   a.sin_port = htons(myself->port);
966   a.sin_addr.s_addr = htonl(INADDR_ANY);
967
968   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
969     {
970       close(nfd);
971       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), myself->port);
972       return -1;
973     }
974
975   a.sin_family = AF_INET;
976   a.sin_port = htons(cl->port);
977   a.sin_addr.s_addr = htonl(cl->address);
978
979   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
980     {
981       close(nfd);
982       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
983              cl->hostname, cl->port);
984       return -1;
985     }
986
987   flags = fcntl(nfd, F_GETFL);
988   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
989     {
990       close(nfd);
991       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
992              cl->name, cl->hostname);
993       return -1;
994     }
995
996   cl->socket = nfd;
997   cl->status.dataopen = 1;
998 cp
999   return 0;
1000 }
1001
1002 /*
1003   handle an incoming tcp connect call and open
1004   a connection to it.
1005 */
1006 conn_list_t *create_new_connection(int sfd)
1007 {
1008   conn_list_t *p;
1009   struct sockaddr_in ci;
1010   int len = sizeof(ci);
1011 cp
1012   p = new_conn_list();
1013
1014   if(getpeername(sfd, (struct sockaddr *) &ci, (socklen_t *) &len) < 0)
1015     {
1016       syslog(LOG_ERR, _("System call `%s' failed: %m"),
1017              "getpeername");
1018       return NULL;
1019     }
1020
1021   p->name = unknown;
1022   p->address = ntohl(ci.sin_addr.s_addr);
1023   p->hostname = hostlookup(ci.sin_addr.s_addr);
1024   p->meta_socket = sfd;
1025   p->status.meta = 1;
1026   p->buffer = xmalloc(MAXBUFSIZE);
1027   p->buflen = 0;
1028   p->last_ping_time = time(NULL);
1029   
1030   if(debug_lvl >= DEBUG_CONNECTIONS)
1031     syslog(LOG_NOTICE, _("Connection from %s port %d"),
1032          p->hostname, htons(ci.sin_port));
1033
1034   p->allow_request = ID;
1035 cp
1036   return p;
1037 }
1038
1039 /*
1040   put all file descriptors in an fd_set array
1041 */
1042 void build_fdset(fd_set *fs)
1043 {
1044   conn_list_t *p;
1045 cp
1046   FD_ZERO(fs);
1047
1048   for(p = conn_list; p != NULL; p = p->next)
1049     {
1050       if(p->status.meta)
1051         FD_SET(p->meta_socket, fs);
1052       if(p->status.dataopen)
1053         FD_SET(p->socket, fs);
1054     }
1055
1056   FD_SET(myself->meta_socket, fs);
1057   FD_SET(tap_fd, fs);
1058 cp
1059 }
1060
1061 /*
1062   receive incoming data from the listening
1063   udp socket and write it to the ethertap
1064   device after being decrypted
1065 */
1066 int handle_incoming_vpn_data(conn_list_t *cl)
1067 {
1068   vpn_packet_t pkt;
1069   int x, l = sizeof(x);
1070   int lenin;
1071 cp
1072   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1073     {
1074       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
1075              __FILE__, __LINE__, cl->socket);
1076       return -1;
1077     }
1078   if(x)
1079     {
1080       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
1081       return -1;
1082     }
1083
1084   if((lenin = recv(cl->socket, (char *) &(pkt.len), MTU, 0)) <= 0)
1085     {
1086       syslog(LOG_ERR, _("Receiving packet failed: %m"));
1087       return -1;
1088     }
1089
1090   if(debug_lvl >= DEBUG_TRAFFIC)
1091     {
1092       syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), lenin,
1093              cl->name, cl->hostname);
1094     }
1095
1096 cp
1097   return xrecv(cl, &pkt);
1098 }
1099
1100 /*
1101   terminate a connection and notify the other
1102   end before closing the sockets
1103 */
1104 void terminate_connection(conn_list_t *cl)
1105 {
1106   conn_list_t *p;
1107   subnet_t *s;
1108 cp
1109   if(cl->status.remove)
1110     return;
1111
1112   cl->status.remove = 1;
1113
1114   if(debug_lvl >= DEBUG_CONNECTIONS)
1115     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
1116            cl->name, cl->hostname);
1117  
1118   if(cl->socket)
1119     close(cl->socket);
1120   if(cl->status.meta)
1121     close(cl->meta_socket);
1122
1123 cp
1124   /* Find all connections that were lost because they were behind cl
1125      (the connection that was dropped). */
1126
1127   if(cl->status.meta)
1128     for(p = conn_list; p != NULL; p = p->next)
1129       if((p->nexthop == cl) && (p != cl))
1130         terminate_connection(p);        /* Sounds like recursion, but p does not have a meta connection :) */
1131
1132   /* Inform others of termination if it was still active */
1133
1134   if(cl->status.active)
1135     for(p = conn_list; p != NULL; p = p->next)
1136       if(p->status.meta && p->status.active && p!=cl)
1137         send_del_host(p, cl);
1138
1139   /* Remove the associated subnets */
1140
1141   for(s = cl->subnets; s; s = s->next)
1142     subnet_del(s);
1143
1144   /* Check if this was our outgoing connection */
1145     
1146   if(cl->status.outgoing && cl->status.active)
1147     {
1148       signal(SIGALRM, sigalrm_handler);
1149       seconds_till_retry = 5;
1150       alarm(seconds_till_retry);
1151       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1152     }
1153
1154   /* Inactivate */
1155
1156   cl->status.active = 0;
1157 cp
1158 }
1159
1160 /*
1161   Check if the other end is active.
1162   If we have sent packets, but didn't receive any,
1163   then possibly the other end is dead. We send a
1164   PING request over the meta connection. If the other
1165   end does not reply in time, we consider them dead
1166   and close the connection.
1167 */
1168 int check_dead_connections(void)
1169 {
1170   conn_list_t *p;
1171   time_t now;
1172 cp
1173   now = time(NULL);
1174   for(p = conn_list; p != NULL; p = p->next)
1175     {
1176       if(p->status.active && p->status.meta)
1177         {
1178           if(p->last_ping_time + timeout < now)
1179             {
1180               if(p->status.pinged)
1181                 {
1182                   if(debug_lvl >= DEBUG_PROTOCOL)
1183                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1184                            p->name, p->hostname);
1185                   p->status.timeout = 1;
1186                   terminate_connection(p);
1187                 }
1188               else
1189                 {
1190                   send_ping(p);
1191                 }
1192             }
1193         }
1194     }
1195 cp
1196   return 0;
1197 }
1198
1199 /*
1200   accept a new tcp connect and create a
1201   new connection
1202 */
1203 int handle_new_meta_connection()
1204 {
1205   conn_list_t *ncn;
1206   struct sockaddr client;
1207   int nfd, len = sizeof(client);
1208 cp
1209   if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
1210     {
1211       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1212       return -1;
1213     }
1214
1215   if(!(ncn = create_new_connection(nfd)))
1216     {
1217       shutdown(nfd, 2);
1218       close(nfd);
1219       syslog(LOG_NOTICE, _("Closed attempted connection"));
1220       return 0;
1221     }
1222
1223   conn_list_add(ncn);
1224 cp
1225   return 0;
1226 }
1227
1228 /*
1229   check all connections to see if anything
1230   happened on their sockets
1231 */
1232 void check_network_activity(fd_set *f)
1233 {
1234   conn_list_t *p;
1235 cp
1236   for(p = conn_list; p != NULL; p = p->next)
1237     {
1238       if(p->status.remove)
1239         continue;
1240
1241       if(p->status.dataopen)
1242         if(FD_ISSET(p->socket, f))
1243           {
1244             handle_incoming_vpn_data(p);
1245
1246             /* Old error stuff (FIXME: copy this to handle_incoming_vpn_data()
1247             
1248             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1249             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1250                    p->name, p->hostname, strerror(x));
1251             terminate_connection(p);
1252             */
1253             return;
1254           }  
1255
1256       if(p->status.meta)
1257         if(FD_ISSET(p->meta_socket, f))
1258           if(receive_meta(p) < 0)
1259             {
1260               terminate_connection(p);
1261               return;
1262             } 
1263     }
1264   
1265   if(FD_ISSET(myself->meta_socket, f))
1266     handle_new_meta_connection();
1267 cp
1268 }
1269
1270 /*
1271   read, encrypt and send data that is
1272   available through the ethertap device
1273 */
1274 void handle_tap_input(void)
1275 {
1276   vpn_packet_t vp;
1277   int lenin;
1278 cp  
1279   if(taptype == TAP_TYPE_TUNTAP)
1280     {
1281       if((lenin = read(tap_fd, vp.data, MTU)) <= 0)
1282         {
1283           syslog(LOG_ERR, _("Error while reading from tun/tap device: %m"));
1284           return;
1285         }
1286       vp.len = lenin;
1287     }
1288   else                  /* ethertap */
1289     {
1290       if((lenin = read(tap_fd, vp.data - 2, MTU)) <= 0)
1291         {
1292           syslog(LOG_ERR, _("Error while reading from ethertap device: %m"));
1293           return;
1294         }
1295       vp.len = lenin - 2;
1296     }
1297
1298   total_tap_in += lenin;
1299
1300   if(lenin < 32)
1301     {
1302       if(debug_lvl >= DEBUG_TRAFFIC)
1303         syslog(LOG_WARNING, _("Received short packet from tap device"));
1304       return;
1305     }
1306
1307   if(debug_lvl >= DEBUG_TRAFFIC)
1308     {
1309       syslog(LOG_DEBUG, _("Read packet of length %d from tap device"), vp.len);
1310     }
1311
1312   send_packet(ntohl(*((unsigned long*)(&vp.data[30]))), &vp);
1313 cp
1314 }
1315
1316 /*
1317   this is where it all happens...
1318 */
1319 void main_loop(void)
1320 {
1321   fd_set fset;
1322   struct timeval tv;
1323   int r;
1324   time_t last_ping_check;
1325   int t;
1326 cp
1327   last_ping_check = time(NULL);
1328
1329   for(;;)
1330     {
1331       tv.tv_sec = timeout;
1332       tv.tv_usec = 0;
1333
1334       prune_conn_list();
1335       build_fdset(&fset);
1336
1337       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1338         {
1339           if(errno != EINTR) /* because of alarm */
1340             {
1341               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1342               return;
1343             }
1344         }
1345
1346       if(sighup)
1347         {
1348           syslog(LOG_INFO, _("Rereading configuration file and restarting in 5 seconds"));
1349           sighup = 0;
1350           close_network_connections();
1351           clear_config(&config);
1352
1353           if(read_server_config())
1354             {
1355               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1356               exit(0);
1357             }
1358
1359           sleep(5);
1360           
1361           if(setup_network_connections())
1362             return;
1363             
1364           continue;
1365         }
1366
1367       t = time(NULL);
1368
1369       /* Let's check if everybody is still alive */
1370
1371       if(last_ping_check + timeout < t)
1372         {
1373           check_dead_connections();
1374           last_ping_check = time(NULL);
1375
1376           /* Should we regenerate our key? */
1377
1378           if(keyexpires < t)
1379             {
1380               if(debug_lvl >= DEBUG_STATUS)
1381                 syslog(LOG_INFO, _("Regenerating symmetric key"));
1382                 
1383               RAND_bytes(myself->cipher_pktkey, myself->cipher_pktkeylength);
1384               send_key_changed(myself, NULL);
1385               keyexpires = time(NULL) + keylifetime;
1386             }
1387         }
1388
1389       if(r > 0)
1390         {
1391           check_network_activity(&fset);
1392
1393           /* local tap data */
1394           if(FD_ISSET(tap_fd, &fset))
1395             handle_tap_input();
1396         }
1397
1398       check_children();
1399     }
1400 cp
1401 }