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