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