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