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