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