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