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