- Added meta.c which contains functions to send, receive and broadcast
[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.32 2000/09/26 14:06:04 guus 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 #include <cipher.h>
41 #include <utils.h>
42 #include <xalloc.h>
43
44 #include "conf.h"
45 #include "encr.h"
46 #include "net.h"
47 #include "netutl.h"
48 #include "protocol.h"
49 #include "meta.h"
50
51 #include "system.h"
52
53 int tap_fd = -1;
54
55 int total_tap_in = 0;
56 int total_tap_out = 0;
57 int total_socket_in = 0;
58 int total_socket_out = 0;
59
60 int upstreamindex = 0;
61 static int seconds_till_retry;
62
63 /* The global list of existing connections */
64 conn_list_t *conn_list = NULL;
65 conn_list_t *myself = NULL;
66
67 /*
68   strip off the MAC adresses of an ethernet frame
69 */
70 void strip_mac_addresses(vpn_packet_t *p)
71 {
72   unsigned char tmp[MAXSIZE];
73 cp
74   memcpy(tmp, p->data, p->len);
75   p->len -= 12;
76   memcpy(p->data, &tmp[12], p->len);
77 cp
78 }
79
80 /*
81   reassemble MAC addresses
82 */
83 void add_mac_addresses(vpn_packet_t *p)
84 {
85   unsigned char tmp[MAXSIZE];
86 cp
87   memcpy(&tmp[12], p->data, p->len);
88   p->len += 12;
89   tmp[0] = tmp[6] = 0xfe;
90   tmp[1] = tmp[7] = 0xfd;
91   *((ip_t*)(&tmp[2])) = (ip_t)(htonl(myself->vpn_ip));
92   *((ip_t*)(&tmp[8])) = *((ip_t*)(&tmp[26]));
93   memcpy(p->data, &tmp[0], p->len);
94 cp
95 }
96
97 int xsend(conn_list_t *cl, void *packet)
98 {
99   real_packet_t rp;
100 cp
101   do_encrypt((vpn_packet_t*)packet, &rp, cl->datakey);
102   rp.from = htonl(myself->vpn_ip);
103   rp.data.len = htons(rp.data.len);
104   rp.len = htons(rp.len);
105
106   if(debug_lvl > 3)
107     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
108            ntohs(rp.len), cl->name, cl->hostname);
109
110   total_socket_out += ntohs(rp.len);
111
112   cl->want_ping = 1;
113
114   if((cl->flags | myself->flags) & TCPONLY)
115       return send_tcppacket(cl, (void*)&rp, ntohs(rp.len));
116
117   if((send(cl->socket, (char*)&rp, ntohs(rp.len), 0)) < 0)
118     {
119       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
120              cl->name, cl->hostname);
121       return -1;
122     }
123 cp
124   return 0;
125 }
126
127 int xrecv(conn_list_t *cl, void *packet)
128 {
129   vpn_packet_t vp;
130   int lenin;
131 cp
132   do_decrypt((real_packet_t*)packet, &vp, cl->datakey);
133   add_mac_addresses(&vp);
134
135   if(debug_lvl > 3)
136     syslog(LOG_ERR, _("Receiving packet of %d bytes from %s (%s)"),
137            ((real_packet_t*)packet)->len, cl->name, cl->hostname);
138
139   if((lenin = write(tap_fd, &vp, vp.len + sizeof(vp.len))) < 0)
140     syslog(LOG_ERR, _("Can't write to tap device: %m"));
141   else
142     total_tap_out += lenin;
143
144   cl->want_ping = 0;
145   cl->last_ping_time = time(NULL);
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(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   /* The next few lines will be obsoleted, if we are going indirect, matching subnet_t
294      should point to only our uplink as the recepient
295   */
296
297   if(myself->flags & EXPORTINDIRECTDATA)
298     {
299       for(cl = conn_list; cl != NULL && !cl->status.outgoing; cl = cl->next);
300       if(!cl)
301         { /* No open outgoing connection has been found. */
302           if(debug_lvl > 3)
303             syslog(LOG_NOTICE, _("There is no remote host I can send this packet to!"));
304           return -1;
305         }
306     }
307   else
308
309   /* If indirectdata flag is set for the destination we just looked up,
310    * then real_ip is actually the vpn_ip of the gateway tincd
311    * it is behind.
312    */
313    
314   if(cl->flags & INDIRECTDATA)
315     {
316       if(debug_lvl > 3)
317         syslog(LOG_NOTICE, _("Indirect packet to %s via %s"),
318                cl->name, cl->hostname);
319       if((cl = lookup_conn(cl->real_ip)) == NULL)
320         {
321           if(debug_lvl > 3)
322               syslog(LOG_NOTICE, _("Indirect look up %d.%d.%d.%d in connection list failed!"), IP_ADDR_V(to));
323             
324           /* Gateway tincd dead? Should we kill it? (GS) */
325
326           return -1;
327         }
328       if(cl->flags & INDIRECTDATA)  /* This should not happen */
329         {
330           if(debug_lvl > 3)
331               syslog(LOG_NOTICE, _("Double indirection for %d.%d.%d.%d"), IP_ADDR_V(to));
332           return -1;        
333         }
334     }            
335
336   if(my_key_expiry <= time(NULL))
337     regenerate_keys();
338
339   if(!cl->status.dataopen)
340     if(setup_vpn_connection(cl) < 0)
341       {
342         syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
343                cl->name, cl->hostname);
344         return -1;
345       }
346       
347   if(!cl->status.validkey)
348     {
349       if(debug_lvl > 3)
350         syslog(LOG_INFO, _("%s (%s) has no valid key, queueing packet"),
351                cl->name, cl->hostname);
352       add_queue(&(cl->sq), packet, packet->len + 2);
353       if(!cl->status.waitingforkey)
354         send_key_request(cl->vpn_ip);                   /* Keys should be sent to the host running the tincd */
355       return 0;
356     }
357
358   if(!cl->status.active)
359     {
360       if(debug_lvl > 3)
361         syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
362                cl->name, cl->hostname);
363       add_queue(&(cl->sq), packet, packet->len + 2);
364       return 0; /* We don't want to mess up, do we? */
365     }
366
367   /* can we send it? can we? can we? huh? */
368 cp
369   return xsend(cl, packet);
370 }
371
372 /*
373   open the local ethertap device
374 */
375 int setup_tap_fd(void)
376 {
377   int nfd;
378   const char *tapfname;
379   config_t const *cfg;
380 cp  
381   if((cfg = get_config_val(tapdevice)) == NULL)
382     tapfname = "/dev/tap0";
383   else
384     tapfname = cfg->data.ptr;
385
386   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
387     {
388       syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
389       return -1;
390     }
391
392   tap_fd = nfd;
393 cp
394   return 0;
395 }
396
397 /*
398   set up the socket that we listen on for incoming
399   (tcp) connections
400 */
401 int setup_listen_meta_socket(int port)
402 {
403   int nfd, flags;
404   struct sockaddr_in a;
405   const int one = 1;
406   config_t const *cfg;
407 cp
408   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
409     {
410       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
411       return -1;
412     }
413
414   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
415     {
416       syslog(LOG_ERR, _("setsockopt: %m"));
417       return -1;
418     }
419
420   if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
421     {
422       syslog(LOG_ERR, _("setsockopt: %m"));
423       return -1;
424     }
425
426   flags = fcntl(nfd, F_GETFL);
427   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
428     {
429       syslog(LOG_ERR, _("fcntl: %m"));
430       return -1;
431     }
432
433   if((cfg = get_config_val(interface)))
434     {
435       if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
436         {
437           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
438           return -1;
439         }
440     }
441
442   memset(&a, 0, sizeof(a));
443   a.sin_family = AF_INET;
444   a.sin_port = htons(port);
445   
446   if((cfg = get_config_val(interfaceip)))
447     a.sin_addr.s_addr = htonl(cfg->data.ip->ip);
448   else
449     a.sin_addr.s_addr = htonl(INADDR_ANY);
450
451   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
452     {
453       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
454       return -1;
455     }
456
457   if(listen(nfd, 3))
458     {
459       syslog(LOG_ERR, _("listen: %m"));
460       return -1;
461     }
462 cp
463   return nfd;
464 }
465
466 /*
467   setup the socket for incoming encrypted
468   data (the udp part)
469 */
470 int setup_vpn_in_socket(int port)
471 {
472   int nfd, flags;
473   struct sockaddr_in a;
474   const int one = 1;
475 cp
476   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
477     {
478       syslog(LOG_ERR, _("Creating socket failed: %m"));
479       return -1;
480     }
481
482   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
483     {
484       syslog(LOG_ERR, _("setsockopt: %m"));
485       return -1;
486     }
487
488   flags = fcntl(nfd, F_GETFL);
489   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
490     {
491       syslog(LOG_ERR, _("fcntl: %m"));
492       return -1;
493     }
494
495   memset(&a, 0, sizeof(a));
496   a.sin_family = AF_INET;
497   a.sin_port = htons(port);
498   a.sin_addr.s_addr = htonl(INADDR_ANY);
499
500   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
501     {
502       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
503       return -1;
504     }
505 cp
506   return nfd;
507 }
508
509 /*
510   setup an outgoing meta (tcp) socket
511 */
512 int setup_outgoing_meta_socket(conn_list_t *cl)
513 {
514   int flags;
515   struct sockaddr_in a;
516   config_t const *cfg;
517 cp
518   if(debug_lvl > 0)
519     syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
520
521   if((cfg = get_config_val(upstreamport)) == NULL)
522     cl->port = 655;
523   else
524     cl->port = cfg->data.val;
525
526   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
527   if(cl->meta_socket == -1)
528     {
529       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
530              cl->hostname, cl->port);
531       return -1;
532     }
533
534   a.sin_family = AF_INET;
535   a.sin_port = htons(cl->port);
536   a.sin_addr.s_addr = htonl(cl->real_ip);
537
538   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
539     {
540       syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
541       return -1;
542     }
543
544   flags = fcntl(cl->meta_socket, F_GETFL);
545   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
546     {
547       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
548              cl->hostname, cl->port);
549       return -1;
550     }
551
552   if(debug_lvl > 0)
553     syslog(LOG_INFO, _("Connected to %s port %hd"),
554          cl->hostname, cl->port);
555 cp
556   return 0;
557 }
558
559 /*
560   setup an outgoing connection. It's not
561   necessary to also open an udp socket as
562   well, because the other host will initiate
563   an authentication sequence during which
564   we will do just that.
565 */
566 int setup_outgoing_connection(char *hostname)
567 {
568   conn_list_t *ncn;
569   struct hostent *h;
570 cp
571   if(!(h = gethostbyname(hostname)))
572     {
573       syslog(LOG_ERR, _("Error looking up `%s': %m"), hostname);
574       return -1;
575     }
576
577   ncn = new_conn_list();
578   ncn->real_ip = ntohl(*((ip_t*)(h->h_addr_list[0])));
579   ncn->hostname = hostlookup(htonl(ncn->real_ip));
580   
581   if(setup_outgoing_meta_socket(ncn) < 0)
582     {
583       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
584              ncn->hostname);
585       free_conn_element(ncn);
586       return -1;
587     }
588
589   ncn->status.meta = 1;
590   ncn->status.outgoing = 1;
591   ncn->next = conn_list;
592   conn_list = ncn;
593 cp
594   return 0;
595 }
596
597 /*
598   set up the local sockets (listen only)
599 */
600 int setup_myself(void)
601 {
602   config_t const *cfg;
603 cp
604   myself = new_conn_list();
605
606   if(!(cfg = get_config_val(myvpnip)))
607     {
608       syslog(LOG_ERR, _("No value for my VPN IP given"));
609       return -1;
610     }
611
612   myself->vpn_ip = cfg->data.ip->ip;
613   myself->hostname = hostlookup(htonl(myself->vpn_ip));
614   myself->vpn_mask = cfg->data.ip->mask;
615   myself->flags = 0;
616
617   if(!(cfg = get_config_val(tincname)))
618     asprintf(&(myself->name), IP_ADDR_S, IP_ADDR_V(myself->vpn_ip));
619   else
620     myself->name = (char*)cfg->data.val;
621   
622   if(!(cfg = get_config_val(listenport)))
623     myself->port = 655;
624   else
625     myself->port = cfg->data.val;
626
627   if((cfg = get_config_val(indirectdata)))
628     if(cfg->data.val == stupid_true)
629       myself->flags |= EXPORTINDIRECTDATA;
630
631   if((cfg = get_config_val(tcponly)))
632     if(cfg->data.val == stupid_true)
633       myself->flags |= TCPONLY;
634
635   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
636     {
637       syslog(LOG_ERR, _("Unable to set up a listening socket"));
638       return -1;
639     }
640
641   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
642     {
643       syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
644       close(myself->meta_socket);
645       return -1;
646     }
647
648   myself->status.active = 1;
649
650   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
651 cp
652   return 0;
653 }
654
655 RETSIGTYPE
656 sigalrm_handler(int a)
657 {
658   config_t const *cfg;
659 cp
660   cfg = get_next_config_val(upstreamip, upstreamindex++);
661
662   while(cfg)
663     {
664       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
665         {
666           signal(SIGALRM, SIG_IGN);
667           return;
668         }
669       cfg = get_next_config_val(upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
670     }
671
672   signal(SIGALRM, sigalrm_handler);
673   upstreamindex = 0;
674   seconds_till_retry += 5;
675   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
676     seconds_till_retry = MAXTIMEOUT;
677   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
678          seconds_till_retry);
679   alarm(seconds_till_retry);
680 cp
681 }
682
683 /*
684   setup all initial network connections
685 */
686 int setup_network_connections(void)
687 {
688   config_t const *cfg;
689 cp
690   if((cfg = get_config_val(pingtimeout)) == NULL)
691     timeout = 5;
692   else
693     timeout = cfg->data.val;
694
695   if(setup_tap_fd() < 0)
696     return -1;
697
698   if(setup_myself() < 0)
699     return -1;
700
701   if((cfg = get_next_config_val(upstreamip, upstreamindex++)) == NULL)
702     /* No upstream IP given, we're listen only. */
703     return 0;
704
705   while(cfg)
706     {
707       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
708         return 0;
709       cfg = get_next_config_val(upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
710     }
711     
712   signal(SIGALRM, sigalrm_handler);
713   upstreamindex = 0;
714   seconds_till_retry = MAXTIMEOUT;
715   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
716   alarm(seconds_till_retry);
717 cp
718   return 0;
719 }
720
721 /*
722   close all open network connections
723 */
724 void close_network_connections(void)
725 {
726   conn_list_t *p;
727 cp
728   for(p = conn_list; p != NULL; p = p->next)
729     {
730       if(p->status.dataopen)
731         {
732           shutdown(p->socket, 0); /* No more receptions */
733           close(p->socket);
734         }
735       if(p->status.meta)
736         {
737           send_termreq(p);
738           shutdown(p->meta_socket, 0); /* No more receptions */
739           close(p->meta_socket);
740         }
741     }
742
743   if(myself)
744     if(myself->status.active)
745       {
746         close(myself->meta_socket);
747         close(myself->socket);
748       }
749
750   close(tap_fd);
751   destroy_conn_list();
752
753   syslog(LOG_NOTICE, _("Terminating"));
754 cp
755   return;
756 }
757
758 /*
759   create a data (udp) socket
760 */
761 int setup_vpn_connection(conn_list_t *cl)
762 {
763   int nfd, flags;
764   struct sockaddr_in a;
765 cp
766   if(debug_lvl > 0)
767     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
768
769   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
770   if(nfd == -1)
771     {
772       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
773       return -1;
774     }
775
776   a.sin_family = AF_INET;
777   a.sin_port = htons(cl->port);
778   a.sin_addr.s_addr = htonl(cl->real_ip);
779
780   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
781     {
782       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
783              cl->hostname, cl->port);
784       return -1;
785     }
786
787   flags = fcntl(nfd, F_GETFL);
788   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
789     {
790       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
791              cl->name, cl->hostname);
792       return -1;
793     }
794
795   cl->socket = nfd;
796   cl->status.dataopen = 1;
797 cp
798   return 0;
799 }
800
801 /*
802   handle an incoming tcp connect call and open
803   a connection to it.
804 */
805 conn_list_t *create_new_connection(int sfd)
806 {
807   conn_list_t *p;
808   struct sockaddr_in ci;
809   int len = sizeof(ci);
810 cp
811   p = new_conn_list();
812
813   if(getpeername(sfd, &ci, &len) < 0)
814     {
815       syslog(LOG_ERR, _("Error: getpeername: %m"));
816       return NULL;
817     }
818
819   p->real_ip = ntohl(ci.sin_addr.s_addr);
820   p->hostname = hostlookup(ci.sin_addr.s_addr);
821   p->meta_socket = sfd;
822   p->status.meta = 1;
823   p->buflen = 0;
824   p->last_ping_time = time(NULL);
825   p->want_ping = 0;
826   
827   if(debug_lvl > 0)
828     syslog(LOG_NOTICE, _("Connection from %s port %d"),
829          p->hostname, htons(ci.sin_port));
830
831   if(send_basic_info(p) < 0)
832     {
833       free_conn_element(p);
834       return NULL;
835     }
836 cp
837   return p;
838 }
839
840 /*
841   put all file descriptors in an fd_set array
842 */
843 void build_fdset(fd_set *fs)
844 {
845   conn_list_t *p;
846 cp
847   FD_ZERO(fs);
848
849   for(p = conn_list; p != NULL; p = p->next)
850     {
851       if(p->status.meta)
852         FD_SET(p->meta_socket, fs);
853       if(p->status.dataopen)
854         FD_SET(p->socket, fs);
855     }
856
857   FD_SET(myself->meta_socket, fs);
858   FD_SET(myself->socket, fs);
859   FD_SET(tap_fd, fs);
860 cp
861 }
862
863 /*
864   receive incoming data from the listening
865   udp socket and write it to the ethertap
866   device after being decrypted
867 */
868 int handle_incoming_vpn_data(conn_list_t *cl)
869 {
870   real_packet_t rp;
871   int lenin;
872   int x, l = sizeof(x);
873   conn_list_t *f;
874 cp
875   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
876     {
877       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"),
878              __FILE__, __LINE__, cl->socket,
879              cl->name, cl->hostname);
880       return -1;
881     }
882   if(x)
883     {
884       syslog(LOG_ERR, _("Incoming data socket error for %s (%s): %s"),
885              cl->name, cl->hostname, strerror(x));
886       return -1;
887     }
888
889   rp.len = -1;
890   lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
891   if(lenin <= 0)
892     {
893       syslog(LOG_ERR, _("Receiving packet from %s (%s) failed: %m"),
894              cl->name, cl->hostname);
895       return -1;
896     }
897   total_socket_in += lenin;
898
899   rp.data.len = ntohs(rp.data.len);
900   rp.len = ntohs(rp.len);
901   rp.from = ntohl(rp.from);
902
903   if(rp.len >= 0)
904     {
905       f = lookup_conn(rp.from);
906       if(!f)
907         {
908           syslog(LOG_ERR, _("Got packet from %s (%s) with unknown origin %d.%d.%d.%d?"),
909                  cl->name, cl->hostname, IP_ADDR_V(rp.from));
910           return -1;
911         }
912
913       if(f->status.validkey)
914         xrecv(f, &rp);
915       else
916         {
917           add_queue(&(f->rq), &rp, rp.len);
918           if(!cl->status.waitingforkey)
919             send_key_request(rp.from);
920         }
921
922       if(my_key_expiry <= time(NULL))
923         regenerate_keys();
924     }
925 cp
926   return 0;
927 }
928
929 /*
930   terminate a connection and notify the other
931   end before closing the sockets
932 */
933 void terminate_connection(conn_list_t *cl)
934 {
935   conn_list_t *p;
936
937 cp
938   if(cl->status.remove)
939     return;
940
941   if(debug_lvl > 0)
942     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
943            cl->name, cl->hostname);
944
945   if(cl->status.timeout)
946     send_timeout(cl);
947 /*  else if(!cl->status.termreq)
948     send_termreq(cl);
949  */
950  
951   if(cl->socket)
952     close(cl->socket);
953   if(cl->status.meta)
954     close(cl->meta_socket);
955
956   cl->status.remove = 1;
957
958   /* If this cl isn't active, don't send any DEL_HOSTs. */
959   if(cl->status.active)
960     notify_others(cl,NULL,send_del_host);
961     
962 cp
963   /* Find all connections that were lost because they were behind cl
964      (the connection that was dropped). */
965   if(cl->status.meta)
966     for(p = conn_list; p != NULL; p = p->next)
967       {
968         if((p->nexthop == cl) && (p != cl))
969           {
970             if(cl->status.active && p->status.active)
971               notify_others(p,cl,send_del_host);
972            if(cl->socket)
973              close(cl->socket);
974             p->status.active = 0;
975             p->status.remove = 1;
976           }
977       }
978     
979   cl->status.active = 0;
980   
981   if(cl->status.outgoing)
982     {
983       signal(SIGALRM, sigalrm_handler);
984       seconds_till_retry = 5;
985       alarm(seconds_till_retry);
986       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
987     }
988 cp
989 }
990
991 /*
992   Check if the other end is active.
993   If we have sent packets, but didn't receive any,
994   then possibly the other end is dead. We send a
995   PING request over the meta connection. If the other
996   end does not reply in time, we consider them dead
997   and close the connection.
998 */
999 int check_dead_connections(void)
1000 {
1001   conn_list_t *p;
1002   time_t now;
1003 cp
1004   now = time(NULL);
1005   for(p = conn_list; p != NULL; p = p->next)
1006     {
1007       if(p->status.remove)
1008         continue;
1009       if(p->status.active && p->status.meta)
1010         {
1011           if(p->last_ping_time + timeout < now)
1012             {
1013               if(p->status.pinged && !p->status.got_pong)
1014                 {
1015                   if(debug_lvl > 1)
1016                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1017                            p->name, p->hostname);
1018                   p->status.timeout = 1;
1019                   terminate_connection(p);
1020                 }
1021               else if(p->want_ping)
1022                 {
1023                   send_ping(p);
1024                   p->last_ping_time = now;
1025                   p->status.pinged = 1;
1026                   p->status.got_pong = 0;
1027                 }
1028             }
1029         }
1030     }
1031 cp
1032   return 0;
1033 }
1034
1035 /*
1036   accept a new tcp connect and create a
1037   new connection
1038 */
1039 int handle_new_meta_connection(conn_list_t *cl)
1040 {
1041   conn_list_t *ncn;
1042   struct sockaddr client;
1043   int nfd, len = sizeof(client);
1044 cp
1045   if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
1046     {
1047       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1048       return -1;
1049     }
1050
1051   if(!(ncn = create_new_connection(nfd)))
1052     {
1053       shutdown(nfd, 2);
1054       close(nfd);
1055       syslog(LOG_NOTICE, _("Closed attempted connection"));
1056       return 0;
1057     }
1058
1059   ncn->status.meta = 1;
1060   ncn->next = conn_list;
1061   conn_list = ncn;
1062 cp
1063   return 0;
1064 }
1065
1066 /*
1067   check all connections to see if anything
1068   happened on their sockets
1069 */
1070 void check_network_activity(fd_set *f)
1071 {
1072   conn_list_t *p;
1073   int x, l = sizeof(x);
1074 cp
1075   for(p = conn_list; p != NULL; p = p->next)
1076     {
1077       if(p->status.remove)
1078         continue;
1079
1080       if(p->status.dataopen)
1081         if(FD_ISSET(p->socket, f))
1082           {
1083             /*
1084               The only thing that can happen to get us here is apparently an
1085               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1086               something that will not trigger an error directly on send()).
1087               I've once got here when it said `No route to host'.
1088             */
1089             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1090             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1091                    p->name, p->hostname, strerror(x));
1092             terminate_connection(p);
1093             return;
1094           }  
1095
1096       if(p->status.meta)
1097         if(FD_ISSET(p->meta_socket, f))
1098           if(receive_meta(p) < 0)
1099             {
1100               terminate_connection(p);
1101               return;
1102             } 
1103     }
1104   
1105   if(FD_ISSET(myself->socket, f))
1106     handle_incoming_vpn_data(myself);
1107
1108   if(FD_ISSET(myself->meta_socket, f))
1109     handle_new_meta_connection(myself);
1110 cp
1111 }
1112
1113 /*
1114   read, encrypt and send data that is
1115   available through the ethertap device
1116 */
1117 void handle_tap_input(void)
1118 {
1119   vpn_packet_t vp;
1120   ip_t from, to;
1121   int ether_type, lenin;
1122 cp  
1123   memset(&vp, 0, sizeof(vp));
1124   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1125     {
1126       syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1127       return;
1128     }
1129
1130   total_tap_in += lenin;
1131
1132   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1133   if(ether_type != 0x0800)
1134     {
1135       if(debug_lvl > 3)
1136         syslog(LOG_INFO, _("Non-IP ethernet frame %04x from %02x:%02x:%02x:%02x:%02x:%02x"), ether_type, MAC_ADDR_V(vp.data[6]));
1137       return;
1138     }
1139   
1140   if(lenin < 32)
1141     {
1142       if(debug_lvl > 3)
1143         syslog(LOG_INFO, _("Dropping short packet from %02x:%02x:%02x:%02x:%02x:%02x"), MAC_ADDR_V(vp.data[6]));
1144       return;
1145     }
1146
1147   from = ntohl(*((unsigned long*)(&vp.data[26])));
1148   to = ntohl(*((unsigned long*)(&vp.data[30])));
1149
1150   vp.len = (length_t)lenin - 2;
1151
1152   strip_mac_addresses(&vp);
1153
1154   send_packet(to, &vp);
1155 cp
1156 }
1157
1158 /*
1159   this is where it all happens...
1160 */
1161 void main_loop(void)
1162 {
1163   fd_set fset;
1164   struct timeval tv;
1165   int r;
1166   time_t last_ping_check;
1167 cp
1168   last_ping_check = time(NULL);
1169
1170   for(;;)
1171     {
1172       tv.tv_sec = timeout;
1173       tv.tv_usec = 0;
1174
1175       prune_conn_list();
1176       build_fdset(&fset);
1177
1178       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1179         {
1180           if(errno != EINTR) /* because of alarm */
1181             {
1182               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1183               return;
1184             }
1185         }
1186
1187       if(sighup)
1188         {
1189           sighup = 0;
1190           if(debug_lvl > 1)
1191             syslog(LOG_INFO, _("Rereading configuration file"));
1192           close_network_connections();
1193           clear_config();
1194           if(read_config_file(configfilename))
1195             {
1196               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1197               exit(0);
1198             }
1199           sleep(5);
1200           setup_network_connections();
1201           continue;
1202         }
1203
1204       if(last_ping_check + timeout < time(NULL))
1205         /* Let's check if everybody is still alive */
1206         {
1207           check_dead_connections();
1208           last_ping_check = time(NULL);
1209         }
1210
1211       if(r > 0)
1212         {
1213           check_network_activity(&fset);
1214
1215           /* local tap data */
1216           if(FD_ISSET(tap_fd, &fset))
1217             handle_tap_input();
1218         }
1219     }
1220 cp
1221 }