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