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