- Use strerror() instead of sys_errlist[] for increased portability
[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.27 2000/09/06 11:49:03 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   config_t const *cfg;
464 cp
465   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
466     {
467       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
468       return -1;
469     }
470
471   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
472     {
473       syslog(LOG_ERR, _("setsockopt: %m"));
474       return -1;
475     }
476
477   if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
478     {
479       syslog(LOG_ERR, _("setsockopt: %m"));
480       return -1;
481     }
482
483   flags = fcntl(nfd, F_GETFL);
484   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
485     {
486       syslog(LOG_ERR, _("fcntl: %m"));
487       return -1;
488     }
489
490   if((cfg = get_config_val(interface)))
491     {
492       if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
493         {
494           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
495           return -1;
496         }
497     }
498
499   memset(&a, 0, sizeof(a));
500   a.sin_family = AF_INET;
501   a.sin_port = htons(port);
502   
503   if((cfg = get_config_val(interfaceip)))
504     a.sin_addr.s_addr = htonl(cfg->data.ip->ip);
505   else
506     a.sin_addr.s_addr = htonl(INADDR_ANY);
507
508   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
509     {
510       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
511       return -1;
512     }
513
514   if(listen(nfd, 3))
515     {
516       syslog(LOG_ERR, _("listen: %m"));
517       return -1;
518     }
519 cp
520   return nfd;
521 }
522
523 /*
524   setup the socket for incoming encrypted
525   data (the udp part)
526 */
527 int setup_vpn_in_socket(int port)
528 {
529   int nfd, flags;
530   struct sockaddr_in a;
531   const int one = 1;
532 cp
533   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
534     {
535       syslog(LOG_ERR, _("Creating socket failed: %m"));
536       return -1;
537     }
538
539   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
540     {
541       syslog(LOG_ERR, _("setsockopt: %m"));
542       return -1;
543     }
544
545   flags = fcntl(nfd, F_GETFL);
546   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
547     {
548       syslog(LOG_ERR, _("fcntl: %m"));
549       return -1;
550     }
551
552   memset(&a, 0, sizeof(a));
553   a.sin_family = AF_INET;
554   a.sin_port = htons(port);
555   a.sin_addr.s_addr = htonl(INADDR_ANY);
556
557   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
558     {
559       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
560       return -1;
561     }
562 cp
563   return nfd;
564 }
565
566 /*
567   setup an outgoing meta (tcp) socket
568 */
569 int setup_outgoing_meta_socket(conn_list_t *cl)
570 {
571   int flags;
572   struct sockaddr_in a;
573   config_t const *cfg;
574 cp
575   if(debug_lvl > 0)
576     syslog(LOG_INFO, _("Trying to connect to %s"), cl->real_hostname);
577
578   if((cfg = get_config_val(upstreamport)) == NULL)
579     cl->port = 655;
580   else
581     cl->port = cfg->data.val;
582
583   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
584   if(cl->meta_socket == -1)
585     {
586       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
587              cl->real_hostname, cl->port);
588       return -1;
589     }
590
591   a.sin_family = AF_INET;
592   a.sin_port = htons(cl->port);
593   a.sin_addr.s_addr = htonl(cl->real_ip);
594
595   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
596     {
597       syslog(LOG_ERR, _("%s port %hd: %m"), cl->real_hostname, cl->port);
598       return -1;
599     }
600
601   flags = fcntl(cl->meta_socket, F_GETFL);
602   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
603     {
604       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
605              cl->real_hostname, cl->port);
606       return -1;
607     }
608
609   if(debug_lvl > 0)
610     syslog(LOG_INFO, _("Connected to %s port %hd"),
611          cl->real_hostname, cl->port);
612 cp
613   return 0;
614 }
615
616 /*
617   setup an outgoing connection. It's not
618   necessary to also open an udp socket as
619   well, because the other host will initiate
620   an authentication sequence during which
621   we will do just that.
622 */
623 int setup_outgoing_connection(char *hostname)
624 {
625   conn_list_t *ncn;
626   struct hostent *h;
627 cp
628   if(!(h = gethostbyname(hostname)))
629     {
630       syslog(LOG_ERR, _("Error looking up `%s': %m"), hostname);
631       return -1;
632     }
633
634   ncn = new_conn_list();
635   ncn->real_ip = ntohl(*((ip_t*)(h->h_addr_list[0])));
636   ncn->real_hostname = hostlookup(htonl(ncn->real_ip));
637   
638   if(setup_outgoing_meta_socket(ncn) < 0)
639     {
640       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
641              ncn->real_hostname);
642       free_conn_element(ncn);
643       return -1;
644     }
645
646   ncn->status.meta = 1;
647   ncn->status.outgoing = 1;
648   ncn->next = conn_list;
649   conn_list = ncn;
650 cp
651   return 0;
652 }
653
654 /*
655   set up the local sockets (listen only)
656 */
657 int setup_myself(void)
658 {
659   config_t const *cfg;
660 cp
661   myself = new_conn_list();
662
663   if(!(cfg = get_config_val(myvpnip)))
664     {
665       syslog(LOG_ERR, _("No value for my VPN IP given"));
666       return -1;
667     }
668
669   myself->vpn_ip = cfg->data.ip->ip;
670   myself->vpn_hostname = hostlookup(htonl(myself->vpn_ip));
671   myself->real_hostname = hostlookup(htonl(myself->vpn_ip));
672   myself->vpn_mask = cfg->data.ip->mask;
673   myself->flags = 0;
674
675   if(!(cfg = get_config_val(listenport)))
676     myself->port = 655;
677   else
678     myself->port = cfg->data.val;
679
680   if((cfg = get_config_val(indirectdata)))
681     if(cfg->data.val == stupid_true)
682       myself->flags |= EXPORTINDIRECTDATA;
683
684   if((cfg = get_config_val(tcponly)))
685     if(cfg->data.val == stupid_true)
686       myself->flags |= TCPONLY;
687
688   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
689     {
690       syslog(LOG_ERR, _("Unable to set up a listening socket"));
691       return -1;
692     }
693
694   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
695     {
696       syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
697       close(myself->meta_socket);
698       return -1;
699     }
700
701   myself->status.active = 1;
702
703   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
704 cp
705   return 0;
706 }
707
708 RETSIGTYPE
709 sigalrm_handler(int a)
710 {
711   config_t const *cfg;
712 cp
713   cfg = get_next_config_val(upstreamip, upstreamindex++);
714
715   while(cfg)
716     {
717       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
718         {
719           signal(SIGALRM, SIG_IGN);
720           return;
721         }
722       cfg = get_next_config_val(upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
723     }
724
725   signal(SIGALRM, sigalrm_handler);
726   upstreamindex = 0;
727   seconds_till_retry += 5;
728   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
729     seconds_till_retry = MAXTIMEOUT;
730   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
731          seconds_till_retry);
732   alarm(seconds_till_retry);
733 cp
734 }
735
736 /*
737   setup all initial network connections
738 */
739 int setup_network_connections(void)
740 {
741   config_t const *cfg;
742 cp
743   if((cfg = get_config_val(pingtimeout)) == NULL)
744     timeout = 5;
745   else
746     timeout = cfg->data.val;
747
748   if(setup_tap_fd() < 0)
749     return -1;
750
751   if(setup_myself() < 0)
752     return -1;
753
754   if((cfg = get_next_config_val(upstreamip, upstreamindex++)) == NULL)
755     /* No upstream IP given, we're listen only. */
756     return 0;
757
758   while(cfg)
759     {
760       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
761         return 0;
762       cfg = get_next_config_val(upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
763     }
764     
765   signal(SIGALRM, sigalrm_handler);
766   upstreamindex = 0;
767   seconds_till_retry = MAXTIMEOUT;
768   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
769   alarm(seconds_till_retry);
770 cp
771   return 0;
772 }
773
774 /*
775   close all open network connections
776 */
777 void close_network_connections(void)
778 {
779   conn_list_t *p;
780 cp
781   for(p = conn_list; p != NULL; p = p->next)
782     {
783       if(p->status.dataopen)
784         {
785           shutdown(p->socket, 0); /* No more receptions */
786           close(p->socket);
787         }
788       if(p->status.meta)
789         {
790           send_termreq(p);
791           shutdown(p->meta_socket, 0); /* No more receptions */
792           close(p->meta_socket);
793         }
794     }
795
796   if(myself)
797     if(myself->status.active)
798       {
799         close(myself->meta_socket);
800         close(myself->socket);
801       }
802
803   close(tap_fd);
804   destroy_conn_list();
805
806   syslog(LOG_NOTICE, _("Terminating"));
807 cp
808   return;
809 }
810
811 /*
812   create a data (udp) socket
813 */
814 int setup_vpn_connection(conn_list_t *cl)
815 {
816   int nfd, flags;
817   struct sockaddr_in a;
818 cp
819   if(debug_lvl > 0)
820     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->real_hostname);
821
822   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
823   if(nfd == -1)
824     {
825       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
826       return -1;
827     }
828
829   a.sin_family = AF_INET;
830   a.sin_port = htons(cl->port);
831   a.sin_addr.s_addr = htonl(cl->real_ip);
832
833   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
834     {
835       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
836              cl->real_hostname, cl->port);
837       return -1;
838     }
839
840   flags = fcntl(nfd, F_GETFL);
841   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
842     {
843       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
844              cl->vpn_hostname, cl->real_hostname);
845       return -1;
846     }
847
848   cl->socket = nfd;
849   cl->status.dataopen = 1;
850 cp
851   return 0;
852 }
853
854 /*
855   handle an incoming tcp connect call and open
856   a connection to it.
857 */
858 conn_list_t *create_new_connection(int sfd)
859 {
860   conn_list_t *p;
861   struct sockaddr_in ci;
862   int len = sizeof(ci);
863 cp
864   p = new_conn_list();
865
866   if(getpeername(sfd, &ci, &len) < 0)
867     {
868       syslog(LOG_ERR, _("Error: getpeername: %m"));
869       return NULL;
870     }
871
872   p->real_ip = ntohl(ci.sin_addr.s_addr);
873   p->real_hostname = hostlookup(ci.sin_addr.s_addr);
874   p->meta_socket = sfd;
875   p->status.meta = 1;
876   p->buflen = 0;
877   p->last_ping_time = time(NULL);
878   p->want_ping = 0;
879   
880   if(debug_lvl > 0)
881     syslog(LOG_NOTICE, _("Connection from %s port %d"),
882          p->real_hostname, htons(ci.sin_port));
883
884   if(send_basic_info(p) < 0)
885     {
886       free_conn_element(p);
887       return NULL;
888     }
889 cp
890   return p;
891 }
892
893 /*
894   put all file descriptors in an fd_set array
895 */
896 void build_fdset(fd_set *fs)
897 {
898   conn_list_t *p;
899 cp
900   FD_ZERO(fs);
901
902   for(p = conn_list; p != NULL; p = p->next)
903     {
904       if(p->status.meta)
905         FD_SET(p->meta_socket, fs);
906       if(p->status.dataopen)
907         FD_SET(p->socket, fs);
908     }
909
910   FD_SET(myself->meta_socket, fs);
911   FD_SET(myself->socket, fs);
912   FD_SET(tap_fd, fs);
913 cp
914 }
915
916 /*
917   receive incoming data from the listening
918   udp socket and write it to the ethertap
919   device after being decrypted
920 */
921 int handle_incoming_vpn_data(conn_list_t *cl)
922 {
923   real_packet_t rp;
924   int lenin;
925   int x, l = sizeof(x);
926   conn_list_t *f;
927 cp
928   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
929     {
930       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, cl->socket,
931              cl->vpn_hostname, cl->real_hostname);
932       return -1;
933     }
934   if(x)
935     {
936       syslog(LOG_ERR, _("Incoming data socket error for %s (%s): %s"),
937              cl->vpn_hostname, cl->real_hostname, strerror(x));
938       return -1;
939     }
940
941   rp.len = -1;
942   lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
943   if(lenin <= 0)
944     {
945       syslog(LOG_ERR, _("Receiving packet from %s (%s) failed: %m"), cl->vpn_hostname, cl->real_hostname);
946       return -1;
947     }
948   total_socket_in += lenin;
949
950   rp.data.len = ntohs(rp.data.len);
951   rp.len = ntohs(rp.len);
952   rp.from = ntohl(rp.from);
953
954   if(rp.len >= 0)
955     {
956       f = lookup_conn(rp.from);
957       if(!f)
958         {
959           syslog(LOG_ERR, _("Got packet from %s (%s) with unknown origin %d.%d.%d.%d?"),
960                  cl->vpn_hostname, cl->real_hostname, IP_ADDR_V(rp.from));
961           return -1;
962         }
963
964       if(f->status.validkey)
965         xrecv(f, &rp);
966       else
967         {
968           add_queue(&(f->rq), &rp, rp.len);
969           if(!cl->status.waitingforkey)
970             send_key_request(rp.from);
971         }
972
973       if(my_key_expiry <= time(NULL))
974         regenerate_keys();
975     }
976 cp
977   return 0;
978 }
979
980 /*
981   terminate a connection and notify the other
982   end before closing the sockets
983 */
984 void terminate_connection(conn_list_t *cl)
985 {
986   conn_list_t *p;
987
988 cp
989   if(cl->status.remove)
990     return;
991
992   if(debug_lvl > 0)
993     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
994            cl->vpn_hostname, cl->real_hostname);
995
996   if(cl->status.timeout)
997     send_timeout(cl);
998 /*  else if(!cl->status.termreq)
999     send_termreq(cl);
1000  */
1001  
1002   if(cl->socket)
1003     close(cl->socket);
1004   if(cl->status.meta)
1005     close(cl->meta_socket);
1006
1007   cl->status.remove = 1;
1008
1009   /* If this cl isn't active, don't send any DEL_HOSTs. */
1010   if(cl->status.active)
1011     notify_others(cl,NULL,send_del_host);
1012     
1013 cp
1014   /* Find all connections that were lost because they were behind cl
1015      (the connection that was dropped). */
1016   if(cl->status.meta)
1017     for(p = conn_list; p != NULL; p = p->next)
1018       {
1019         if((p->nexthop == cl) && (p != cl))
1020           {
1021             if(cl->status.active && p->status.active)
1022               notify_others(p,cl,send_del_host);
1023            if(cl->socket)
1024              close(cl->socket);
1025             p->status.active = 0;
1026             p->status.remove = 1;
1027           }
1028       }
1029     
1030   cl->status.active = 0;
1031   
1032   if(cl->status.outgoing)
1033     {
1034       signal(SIGALRM, sigalrm_handler);
1035       seconds_till_retry = 5;
1036       alarm(seconds_till_retry);
1037       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1038     }
1039 cp
1040 }
1041
1042 /*
1043   Check if the other end is active.
1044   If we have sent packets, but didn't receive any,
1045   then possibly the other end is dead. We send a
1046   PING request over the meta connection. If the other
1047   end does not reply in time, we consider them dead
1048   and close the connection.
1049 */
1050 int check_dead_connections(void)
1051 {
1052   conn_list_t *p;
1053   time_t now;
1054 cp
1055   now = time(NULL);
1056   for(p = conn_list; p != NULL; p = p->next)
1057     {
1058       if(p->status.remove)
1059         continue;
1060       if(p->status.active && p->status.meta)
1061         {
1062           if(p->last_ping_time + timeout < now)
1063             {
1064               if(p->status.pinged && !p->status.got_pong)
1065                 {
1066                   if(debug_lvl > 1)
1067                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1068                            p->vpn_hostname, p->real_hostname);
1069                   p->status.timeout = 1;
1070                   terminate_connection(p);
1071                 }
1072               else if(p->want_ping)
1073                 {
1074                   send_ping(p);
1075                   p->last_ping_time = now;
1076                   p->status.pinged = 1;
1077                   p->status.got_pong = 0;
1078                 }
1079             }
1080         }
1081     }
1082 cp
1083   return 0;
1084 }
1085
1086 /*
1087   accept a new tcp connect and create a
1088   new connection
1089 */
1090 int handle_new_meta_connection(conn_list_t *cl)
1091 {
1092   conn_list_t *ncn;
1093   struct sockaddr client;
1094   int nfd, len = sizeof(client);
1095 cp
1096   if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
1097     {
1098       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1099       return -1;
1100     }
1101
1102   if(!(ncn = create_new_connection(nfd)))
1103     {
1104       shutdown(nfd, 2);
1105       close(nfd);
1106       syslog(LOG_NOTICE, _("Closed attempted connection"));
1107       return 0;
1108     }
1109
1110   ncn->status.meta = 1;
1111   ncn->next = conn_list;
1112   conn_list = ncn;
1113 cp
1114   return 0;
1115 }
1116
1117 /*
1118   dispatch any incoming meta requests
1119 */
1120 int handle_incoming_meta_data(conn_list_t *cl)
1121 {
1122   int x, l = sizeof(x);
1123   int request, oldlen, i;
1124   int lenin = 0;
1125 cp
1126   if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1127     {
1128       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, cl->meta_socket,
1129              cl->vpn_hostname, cl->real_hostname);
1130       return -1;
1131     }
1132   if(x)
1133     {
1134       syslog(LOG_ERR, _("Metadata socket error for %s (%s): %s"),
1135              cl->vpn_hostname, cl->real_hostname, strerror(x));
1136       return -1;
1137     }
1138
1139   lenin = read(cl->meta_socket, cl->buffer, MAXBUFSIZE - cl->buflen);
1140
1141   if(lenin<=0)
1142     {
1143       if(errno==EINTR)
1144         return 0;      
1145       if(errno==0)
1146         {
1147           if(debug_lvl>0)
1148             syslog(LOG_NOTICE, _("Connection closed by %s (%s)"),
1149                 cl->vpn_hostname, cl->real_hostname);
1150         }
1151       else
1152         syslog(LOG_ERR, _("Metadata socket read error for %s (%s): %m"),
1153                cl->vpn_hostname, cl->real_hostname);
1154       return -1;
1155     }
1156
1157   oldlen = cl->buflen;
1158   cl->buflen += lenin;
1159
1160   for(;;)
1161     {
1162       if(cl->tcppacket)
1163         {
1164           if(cl->buflen >= cl->tcppacket)
1165             {
1166               tcprecv(cl, (real_packet_t *)cl->buffer);
1167               cl->buflen -= cl->tcppacket;
1168               memmove(cl->buffer, cl->buffer + cl->tcppacket, cl->buflen);
1169               oldlen = 0;
1170               cl->tcppacket=0;
1171             }
1172           else
1173             {
1174               break;
1175             }
1176         }
1177       else
1178         {
1179           cl->reqlen = 0;
1180
1181           for(i = oldlen; i < cl->buflen; i++)
1182             {
1183               if(cl->buffer[i] == '\n')
1184                 {
1185                   cl->buffer[i] = 0;  /* replace end-of-line by end-of-string so we can use sscanf */
1186                   cl->reqlen = i + 1;
1187                   break;
1188                 }
1189             }
1190
1191           if(cl->reqlen)
1192             {
1193               if(debug_lvl > 2)
1194                 syslog(LOG_DEBUG, _("Got request from %s (%s): %s"),
1195                              cl->vpn_hostname, cl->real_hostname, cl->buffer);
1196               if(sscanf(cl->buffer, "%d", &request) == 1)
1197                 {
1198                   if((request < 0) || (request > 255) || (request_handlers[request] == NULL))
1199                     {
1200                       syslog(LOG_ERR, _("Unknown request from %s (%s)"),
1201                              cl->vpn_hostname, cl->real_hostname);
1202                       return -1;
1203                     }
1204
1205                   if(request_handlers[request](cl))  /* Something went wrong. Probably scriptkiddies. Terminate. */
1206                     {
1207                       syslog(LOG_ERR, _("Error while processing request from %s (%s)"),
1208                              cl->vpn_hostname, cl->real_hostname);
1209                       return -1;
1210                     }
1211                 }
1212               else
1213                 {
1214                   syslog(LOG_ERR, _("Bogus data received from %s (%s)"),
1215                              cl->vpn_hostname, cl->real_hostname);
1216                   return -1;
1217                 }
1218
1219               cl->buflen -= cl->reqlen;
1220               memmove(cl->buffer, cl->buffer + cl->reqlen, cl->buflen);
1221               oldlen = 0;
1222             }
1223           else
1224             {
1225               break;
1226             }
1227         }
1228     }
1229
1230   if(cl->buflen >= MAXBUFSIZE)
1231     {
1232       syslog(LOG_ERR, _("Metadata read buffer overflow!"));
1233       return -1;
1234     }
1235
1236   cl->last_ping_time = time(NULL);
1237   cl->want_ping = 0;
1238 cp  
1239   return 0;
1240 }
1241
1242 /*
1243   check all connections to see if anything
1244   happened on their sockets
1245 */
1246 void check_network_activity(fd_set *f)
1247 {
1248   conn_list_t *p;
1249   int x, l = sizeof(x);
1250 cp
1251   for(p = conn_list; p != NULL; p = p->next)
1252     {
1253       if(p->status.remove)
1254         continue;
1255
1256       if(p->status.dataopen)
1257         if(FD_ISSET(p->socket, f))
1258           {
1259             /*
1260               The only thing that can happen to get us here is apparently an
1261               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1262               something that will not trigger an error directly on send()).
1263               I've once got here when it said `No route to host'.
1264             */
1265             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1266             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1267                    p->vpn_hostname, p->real_hostname, strerror(x));
1268             terminate_connection(p);
1269             return;
1270           }  
1271
1272       if(p->status.meta)
1273         if(FD_ISSET(p->meta_socket, f))
1274           if(handle_incoming_meta_data(p) < 0)
1275             {
1276               terminate_connection(p);
1277               return;
1278             } 
1279     }
1280   
1281   if(FD_ISSET(myself->socket, f))
1282     handle_incoming_vpn_data(myself);
1283
1284   if(FD_ISSET(myself->meta_socket, f))
1285     handle_new_meta_connection(myself);
1286 cp
1287 }
1288
1289 /*
1290   read, encrypt and send data that is
1291   available through the ethertap device
1292 */
1293 void handle_tap_input(void)
1294 {
1295   vpn_packet_t vp;
1296   ip_t from, to;
1297   int ether_type, lenin;
1298 cp  
1299   memset(&vp, 0, sizeof(vp));
1300   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1301     {
1302       syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1303       return;
1304     }
1305
1306   total_tap_in += lenin;
1307
1308   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1309   if(ether_type != 0x0800)
1310     {
1311       if(debug_lvl > 3)
1312         syslog(LOG_INFO, _("Non-IP ethernet frame %04x from " MAC_ADDR_S),
1313                ether_type, MAC_ADDR_V(vp.data[6]));
1314       return;
1315     }
1316   
1317   if(lenin < 32)
1318     {
1319       if(debug_lvl > 3)
1320         syslog(LOG_INFO, _("Dropping short packet"));
1321       return;
1322     }
1323
1324   from = ntohl(*((unsigned long*)(&vp.data[26])));
1325   to = ntohl(*((unsigned long*)(&vp.data[30])));
1326
1327   vp.len = (length_t)lenin - 2;
1328
1329   strip_mac_addresses(&vp);
1330
1331   send_packet(to, &vp);
1332 cp
1333 }
1334
1335 /*
1336   this is where it all happens...
1337 */
1338 void main_loop(void)
1339 {
1340   fd_set fset;
1341   struct timeval tv;
1342   int r;
1343   time_t last_ping_check;
1344 cp
1345   last_ping_check = time(NULL);
1346
1347   for(;;)
1348     {
1349       tv.tv_sec = timeout;
1350       tv.tv_usec = 0;
1351
1352       prune_conn_list();
1353       build_fdset(&fset);
1354
1355       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1356         {
1357           if(errno != EINTR) /* because of alarm */
1358             {
1359               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1360               return;
1361             }
1362         }
1363
1364       if(sighup)
1365         {
1366           sighup = 0;
1367           close_network_connections();
1368           clear_config();
1369           if(read_config_file(configfilename))
1370             {
1371               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1372               exit(0);
1373             }
1374           sleep(5);
1375           setup_network_connections();
1376           continue;
1377         }
1378
1379       if(last_ping_check + timeout < time(NULL))
1380         /* Let's check if everybody is still alive */
1381         {
1382           check_dead_connections();
1383           last_ping_check = time(NULL);
1384         }
1385
1386       if(r > 0)
1387         {
1388           check_network_activity(&fset);
1389
1390           /* local tap data */
1391           if(FD_ISSET(tap_fd, &fset))
1392             handle_tap_input();
1393         }
1394     }
1395 cp
1396 }