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