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