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