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