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