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