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