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