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