1130fa99650d595860709c7d38270348d90eb587
[tinc] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998,99 Ivo Timmermans <zarq@iname.com>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include "config.h"
21
22 #include <arpa/inet.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <netdb.h>
26 #include <netinet/in.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/signal.h>
31 #include <sys/socket.h>
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <syslog.h>
35 #include <unistd.h>
36
37 #include <cipher.h>
38 #include <utils.h>
39 #include <xalloc.h>
40
41 #include "conf.h"
42 #include "encr.h"
43 #include "net.h"
44 #include "netutl.h"
45 #include "protocol.h"
46
47 int tap_fd = -1;
48
49 int total_tap_in = 0;
50 int total_tap_out = 0;
51 int total_socket_in = 0;
52 int total_socket_out = 0;
53
54 time_t last_ping_time = 0;
55
56 /* The global list of existing connections */
57 conn_list_t *conn_list = NULL;
58 conn_list_t *myself = NULL;
59
60 /*
61   strip off the MAC adresses of an ethernet frame
62 */
63 void strip_mac_addresses(vpn_packet_t *p)
64 {
65   unsigned char tmp[MAXSIZE];
66 cp
67   memcpy(tmp, p->data, p->len);
68   p->len -= 12;
69   memcpy(p->data, &tmp[12], p->len);
70 cp
71 }
72
73 /*
74   reassemble MAC addresses
75 */
76 void add_mac_addresses(vpn_packet_t *p)
77 {
78   unsigned char tmp[MAXSIZE];
79 cp
80   memcpy(&tmp[12], p->data, p->len);
81   p->len += 12;
82   tmp[0] = tmp[6] = 0xfe;
83   tmp[1] = tmp[7] = 0xfd;
84   *((ip_t*)(&tmp[2])) = (ip_t)(htonl(myself->vpn_ip));
85   *((ip_t*)(&tmp[8])) = *((ip_t*)(&tmp[26]));
86   memcpy(p->data, &tmp[0], p->len);
87 cp
88 }
89
90 int xsend(conn_list_t *cl, void *packet)
91 {
92   int r;
93   real_packet_t rp;
94 cp
95   do_encrypt((vpn_packet_t*)packet, &rp, cl->key);
96   rp.from = myself->vpn_ip;
97
98   if(debug_lvl > 3)
99     syslog(LOG_ERR, "Sent %d bytes to %lx", rp.len, cl->vpn_ip);
100
101   if((r = send(cl->socket, (char*)&rp, rp.len, 0)) < 0)
102     {
103       syslog(LOG_ERR, "Error sending data: %m");
104       return -1;
105     }
106
107   total_socket_out += r;
108 cp
109   return 0;
110 }
111
112 /*
113   write as many bytes as possible to the tap
114   device, possibly in multiple turns.
115 */
116 int write_n(int fd, void *buf, size_t len)
117 {
118   int r, done = 0;
119 cp  
120   do
121     {
122       if((r = write(fd, buf, len)) < 0)
123         return -1;
124       len -= r;
125       buf += r;
126       done += r;
127     } while(len > 0);
128
129   return done;
130 cp
131 }
132
133 int xrecv(conn_list_t *cl, void *packet)
134 {
135   vpn_packet_t vp;
136   int lenin;
137 cp
138   do_decrypt((real_packet_t*)packet, &vp, cl->key);
139   add_mac_addresses(&vp);
140
141   if((lenin = write_n(tap_fd, &vp, vp.len + 2)) < 0)
142     syslog(LOG_ERR, "Can't write to tap device: %m");
143   else
144     total_tap_out += lenin;
145 cp
146   return 0;
147 }
148
149 /*
150   add the given packet of size s to the
151   queue q, be it the send or receive queue
152 */
153 void add_queue(packet_queue_t **q, void *packet, size_t s)
154 {
155   queue_element_t *e;
156 cp
157   if(debug_lvl > 3)
158     syslog(LOG_DEBUG, "packet to queue: %d", s);
159
160   e = xmalloc(sizeof(queue_element_t));
161   e->packet = xmalloc(s);
162   memcpy(e->packet, packet, s);
163
164   if(!*q)
165     {
166       *q = xmalloc(sizeof(packet_queue_t));
167       (*q)->head = (*q)->tail = NULL;
168     }
169
170   e->next = NULL;                       /* We insert at the tail */
171
172   if((*q)->tail)                        /* Do we have a tail? */
173     {
174       (*q)->tail->next = e;
175       e->prev = (*q)->tail;
176     }
177   else                                  /* No tail -> no head too */
178     {
179       (*q)->head = e;
180       e->prev = NULL;
181     }
182
183   (*q)->tail = e;
184 cp
185 }
186
187 /* Remove a queue element */
188 void del_queue(packet_queue_t **q, packet_element_t *e)
189 {
190   queue_element_t *p, *n;
191 cp
192   free(e->packet);
193
194   if(e->next)                           /* There is a successor, so we are not tail */
195     {
196       if(e->prev)                       /* There is a predecessor, so we are not head */
197         {
198           e->next->prev = e->prev;
199           e->prev->next = e->next;
200         }
201       else                              /* We are head */
202         {
203           e->next->prev = NULL;
204           (*q)->head = e->next;
205         }
206     }
207   else                                  /* We are tail (or all alone!) */
208     {          
209       if(e->prev)                       /* We are not alone :) */
210         {
211           e->prev->next = NULL;
212           (*q)->tail = e->prev;
213         }
214       else                              /* Adieu */
215         {
216           free(*q);
217           *q = NULL;
218         }
219     }
220     
221   free(e);
222 cp
223 }
224
225 /*
226   flush a queue by calling function for
227   each packet, and removing it when that
228   returned a zero exit code
229 */
230 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
231                  int (*function)(conn_list_t*,void*))
232 {
233   queue_element_t *p, *prev = NULL, *next = NULL;
234 cp
235   for(p = (*pq)->head; p != NULL; )
236     {
237       next = p->next;
238
239       if(!function(cl, p->packet))
240         del_queue(pq, p);
241         
242       p = next;
243     }
244
245   if(debug_lvl > 3)
246     syslog(LOG_DEBUG, "queue flushed");
247 cp
248 }
249
250 /*
251   flush the send&recv queues
252   void because nothing goes wrong here, packets
253   remain in the queue if something goes wrong
254 */
255 void flush_queues(conn_list_t *cl)
256 {
257 cp
258   if(cl->sq)
259     {
260       if(debug_lvl > 1)
261         syslog(LOG_DEBUG, "Flushing send queue for " IP_ADDR_S,
262                IP_ADDR_V(cl->vpn_ip));
263       flush_queue(cl, &(cl->sq), xsend);
264     }
265
266   if(cl->rq)
267     {
268       if(debug_lvl > 1)
269         syslog(LOG_DEBUG, "Flushing receive queue for " IP_ADDR_S,
270                IP_ADDR_V(cl->vpn_ip));
271       flush_queue(cl, &(cl->rq), xrecv);
272     }
273 cp
274 }
275
276 /*
277   send a packet to the given vpn ip.
278 */
279 int send_packet(ip_t to, vpn_packet_t *packet)
280 {
281   conn_list_t *cl;
282 cp
283   if((cl = lookup_conn(to)) == NULL)
284     {
285       if(debug_lvl > 2)
286         {
287           syslog(LOG_NOTICE, "trying to look up " IP_ADDR_S " in connection list failed.",
288                  IP_ADDR_V(to));
289         }
290       for(cl = conn_list; cl != NULL && !cl->status.outgoing; cl = cl->next);
291       if(!cl)
292         { /* No open outgoing connection has been found. */
293           if(debug_lvl > 2)
294             syslog(LOG_NOTICE, "There is no remote host I can send this packet to.");
295           return -1;
296         }
297     }
298
299   if(my_key_expiry <= time(NULL))
300     regenerate_keys();
301
302   if(!cl->status.dataopen)
303     if(setup_vpn_connection(cl) < 0)
304       return -1;
305
306   if(!cl->status.validkey)
307     {
308       add_queue(&(cl->sq), packet, packet->len + 2);
309       if(!cl->status.waitingforkey)
310         send_key_request(to);
311       return 0;
312     }
313
314   if(!cl->status.active)
315     {
316       add_queue(&(cl->sq), packet, packet->len + 2);
317       if(debug_lvl > 1)
318         syslog(LOG_INFO, IP_ADDR_S " is not ready, queueing packet.", IP_ADDR_V(cl->vpn_ip));
319       return 0; /* We don't want to mess up, do we? */
320     }
321
322   /* can we send it? can we? can we? huh? */
323 cp
324   return xsend(cl, packet);
325 }
326
327 int send_broadcast(conn_list_t *cl, vpn_packet_t *packet)
328 {
329   conn_list_t *p;
330 cp
331   for(p = cl; p != NULL; p = p->next)
332     if(send_packet(p->real_ip, packet) < 0)
333       {
334         syslog(LOG_ERR, "Could not send a broadcast packet to %08lx (%08lx): %m",
335                p->vpn_ip, p->real_ip);
336         break; /* FIXME: should retry later, and send a ping over the metaconnection. */
337       }
338 cp
339   return 0;
340 }
341
342 /*
343   open the local ethertap device
344 */
345 int setup_tap_fd(void)
346 {
347   int nfd;
348   const char *tapfname;
349   config_t const *cfg;
350 cp  
351   if((cfg = get_config_val(tapdevice)) == NULL)
352     tapfname = "/dev/tap0";
353   else
354     tapfname = cfg->data.ptr;
355
356   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
357     {
358       syslog(LOG_ERR, "Could not open %s: %m", tapfname);
359       return -1;
360     }
361
362   tap_fd = nfd;
363 cp
364   return 0;
365 }
366
367 /*
368   set up the socket that we listen on for incoming
369   (tcp) connections
370 */
371 int setup_listen_meta_socket(int port)
372 {
373   int nfd, flags;
374   struct sockaddr_in a;
375   const int one = 1;
376 cp
377   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
378     {
379       syslog(LOG_ERR, "Creating metasocket failed: %m");
380       return -1;
381     }
382
383   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
384     {
385       syslog(LOG_ERR, "setsockopt: %m");
386       return -1;
387     }
388
389   flags = fcntl(nfd, F_GETFL);
390   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
391     {
392       syslog(LOG_ERR, "fcntl: %m");
393       return -1;
394     }
395
396   memset(&a, 0, sizeof(a));
397   a.sin_family = AF_INET;
398   a.sin_port = htons(port);
399   a.sin_addr.s_addr = htonl(INADDR_ANY);
400
401   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
402     {
403       syslog(LOG_ERR, "Can't bind to port %hd/tcp: %m", port);
404       return -1;
405     }
406
407   if(listen(nfd, 3))
408     {
409       syslog(LOG_ERR, "listen: %m");
410       return -1;
411     }
412 cp
413   return nfd;
414 }
415
416 /*
417   setup the socket for incoming encrypted
418   data (the udp part)
419 */
420 int setup_vpn_in_socket(int port)
421 {
422   int nfd, flags;
423   struct sockaddr_in a;
424   const int one = 1;
425 cp
426   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
427     {
428       syslog(LOG_ERR, "Creating socket failed: %m");
429       return -1;
430     }
431
432   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
433     {
434       syslog(LOG_ERR, "setsockopt: %m");
435       return -1;
436     }
437
438   flags = fcntl(nfd, F_GETFL);
439   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
440     {
441       syslog(LOG_ERR, "fcntl: %m");
442       return -1;
443     }
444
445   memset(&a, 0, sizeof(a));
446   a.sin_family = AF_INET;
447   a.sin_port = htons(port);
448   a.sin_addr.s_addr = htonl(INADDR_ANY);
449
450   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
451     {
452       syslog(LOG_ERR, "Can't bind to port %hd/udp: %m", port);
453       return -1;
454     }
455 cp
456   return nfd;
457 }
458
459 /*
460   setup an outgoing meta (tcp) socket
461 */
462 int setup_outgoing_meta_socket(conn_list_t *cl)
463 {
464   int flags;
465   struct sockaddr_in a;
466   config_t const *cfg;
467 cp
468   if((cfg = get_config_val(upstreamport)) == NULL)
469     cl->port = 655;
470   else
471     cl->port = cfg->data.val;
472
473   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
474   if(cl->meta_socket == -1)
475     {
476       syslog(LOG_ERR, "Creating socket failed: %m");
477       return -1;
478     }
479
480   a.sin_family = AF_INET;
481   a.sin_port = htons(cl->port);
482   a.sin_addr.s_addr = htonl(cl->real_ip);
483
484   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
485     {
486       syslog(LOG_ERR, IP_ADDR_S ":%d: %m", IP_ADDR_V(cl->real_ip), cl->port);
487       return -1;
488     }
489
490   flags = fcntl(cl->meta_socket, F_GETFL);
491   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
492     {
493       syslog(LOG_ERR, "fcntl: %m");
494       return -1;
495     }
496
497   cl->hostname = hostlookup(htonl(cl->real_ip));
498
499   syslog(LOG_INFO, "Connected to %s:%hd" , cl->hostname, cl->port);
500 cp
501   return 0;
502 }
503
504 /*
505   setup an outgoing connection. It's not
506   necessary to also open an udp socket as
507   well, because the other host will initiate
508   an authentication sequence during which
509   we will do just that.
510 */
511 int setup_outgoing_connection(ip_t ip)
512 {
513   conn_list_t *ncn;
514 cp
515   ncn = new_conn_list();
516   ncn->real_ip = ip;
517
518   if(setup_outgoing_meta_socket(ncn) < 0)
519     {
520       syslog(LOG_ERR, "Could not set up a meta connection.");
521       free_conn_element(ncn);
522       return -1;
523     }
524
525   ncn->status.meta = 1;
526   ncn->status.outgoing = 1;
527   ncn->next = conn_list;
528   conn_list = ncn;
529 cp
530   return 0;
531 }
532
533 /*
534   set up the local sockets (listen only)
535 */
536 int setup_myself(void)
537 {
538   config_t const *cfg;
539 cp
540   myself = new_conn_list();
541
542   if(!(cfg = get_config_val(myvpnip)))
543     {
544       syslog(LOG_ERR, "No value for my VPN IP given");
545       return -1;
546     }
547
548   myself->vpn_ip = cfg->data.ip->ip;
549   myself->vpn_mask = cfg->data.ip->mask;
550
551   if(!(cfg = get_config_val(listenport)))
552     myself->port = 655;
553   else
554     myself->port = cfg->data.val;
555
556   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
557     {
558       syslog(LOG_ERR, "Unable to set up a listening socket");
559       return -1;
560     }
561
562   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
563     {
564       syslog(LOG_ERR, "Unable to set up an incoming vpn data socket");
565       close(myself->meta_socket);
566       return -1;
567     }
568
569   myself->status.active = 1;
570
571   syslog(LOG_NOTICE, "Ready: listening on port %d.", myself->port);
572 cp
573   return 0;
574 }
575
576 /*
577   setup all initial network connections
578 */
579 int setup_network_connections(void)
580 {
581   config_t const *cfg;
582 cp
583   if((cfg = get_config_val(pingtimeout)) == NULL)
584     timeout = 10;
585   else
586     timeout = cfg->data.val;
587
588   if(setup_tap_fd() < 0)
589     return -1;
590
591   if(setup_myself() < 0)
592     return -1;
593
594   if((cfg = get_config_val(upstreamip)) == NULL)
595     /* No upstream IP given, we're listen only. */
596     return 0;
597
598   if(setup_outgoing_connection(cfg->data.ip->ip))
599     return -1;
600 cp
601   return 0;
602 }
603
604 RETSIGTYPE
605 sigalrm_handler(int a)
606 {
607   config_t const *cfg;
608   static int seconds_till_retry;
609 cp
610   cfg = get_config_val(upstreamip);
611
612   if(!setup_outgoing_connection(cfg->data.ip->ip))
613     {
614       signal(SIGALRM, SIG_IGN);
615       seconds_till_retry = 5;
616     }
617   else
618     {
619       signal(SIGALRM, sigalrm_handler);
620       seconds_till_retry += 5;
621       alarm(seconds_till_retry);
622       syslog(LOG_ERR, "Still failed to connect to other. Will retry in %d seconds.",
623              seconds_till_retry);
624     }
625 cp
626 }
627
628 /*
629   close all open network connections
630 */
631 void close_network_connections(void)
632 {
633   conn_list_t *p;
634 cp
635   for(p = conn_list; p != NULL; p = p->next)
636     {
637       if(p->status.dataopen)
638         {
639           shutdown(p->socket, 0); /* No more receptions */
640           close(p->socket);
641         }
642       if(p->status.meta)
643         {
644           send_termreq(p);
645           shutdown(p->meta_socket, 0); /* No more receptions */
646           close(p->meta_socket);
647         }
648     }
649
650   if(myself)
651     if(myself->status.active)
652       {
653         close(myself->meta_socket);
654         close(myself->socket);
655       }
656
657   close(tap_fd);
658   destroy_conn_list();
659
660   syslog(LOG_NOTICE, "Terminating.");
661 cp
662   return;
663 }
664
665 /*
666   create a data (udp) socket
667 */
668 int setup_vpn_connection(conn_list_t *cl)
669 {
670   int nfd, flags;
671   struct sockaddr_in a;
672 cp
673   if(debug_lvl > 1)
674     syslog(LOG_DEBUG, "Opening UDP socket to " IP_ADDR_S, IP_ADDR_V(cl->real_ip));
675
676   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
677   if(nfd == -1)
678     {
679       syslog(LOG_ERR, "Creating data socket failed: %m");
680       return -1;
681     }
682
683   a.sin_family = AF_INET;
684   a.sin_port = htons(cl->port);
685   a.sin_addr.s_addr = htonl(cl->real_ip);
686
687   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
688     {
689       syslog(LOG_ERR, "Create connection to %08lx:%d failed: %m", ntohs(cl->real_ip),
690              cl->port);
691       return -1;
692     }
693
694   flags = fcntl(nfd, F_GETFL);
695   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
696     {
697       syslog(LOG_ERR, "This is a bug: %s:%d: %d:%m", __FILE__, __LINE__, nfd);
698       return -1;
699     }
700
701   cl->socket = nfd;
702   cl->status.dataopen = 1;
703 cp
704   return 0;
705 }
706
707 /*
708   handle an incoming tcp connect call and open
709   a connection to it.
710 */
711 conn_list_t *create_new_connection(int sfd)
712 {
713   conn_list_t *p;
714   struct sockaddr_in ci;
715   int len = sizeof(ci);
716 cp
717   p = new_conn_list();
718
719   if(getpeername(sfd, &ci, &len) < 0)
720     {
721       syslog(LOG_ERR, "Error: getpeername: %m");
722       return NULL;
723     }
724
725   p->hostname = hostlookup(ci.sin_addr.s_addr);
726   p->real_ip = ntohl(ci.sin_addr.s_addr);
727   p->meta_socket = sfd;
728   p->status.meta = 1;
729
730   syslog(LOG_NOTICE, "Connection from %s:%d", p->hostname, htons(ci.sin_port));
731
732   if(send_basic_info(p) < 0)
733     {
734       free(p);
735       return NULL;
736     }
737 cp
738   return p;
739 }
740
741 /*
742   put all file descriptors in an fd_set array
743 */
744 void build_fdset(fd_set *fs)
745 {
746   conn_list_t *p;
747 cp
748   FD_ZERO(fs);
749
750   for(p = conn_list; p != NULL; p = p->next)
751     {
752       if(p->status.meta)
753         FD_SET(p->meta_socket, fs);
754       if(p->status.dataopen)
755         FD_SET(p->socket, fs);
756     }
757
758   FD_SET(myself->meta_socket, fs);
759   FD_SET(myself->socket, fs);
760   FD_SET(tap_fd, fs);
761 cp
762 }
763
764 /*
765   receive incoming data from the listening
766   udp socket and write it to the ethertap
767   device after being decrypted
768 */
769 int handle_incoming_vpn_data(conn_list_t *cl)
770 {
771   real_packet_t rp;
772   int lenin;
773   int x, l = sizeof(x);
774   conn_list_t *f;
775 cp
776   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
777     {
778       syslog(LOG_ERR, "This is a bug: %s:%d: %d:%m", __FILE__, __LINE__, cl->socket);
779       return -1;
780     }
781   if(x)
782     {
783       syslog(LOG_ERR, "Incoming data socket error: %s", sys_errlist[x]);
784       return -1;
785     }
786
787   rp.len = -1;
788   lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
789   if(lenin <= 0)
790     {
791       syslog(LOG_ERR, "Receiving data failed: %m");
792       return -1;
793     }
794   total_socket_in += lenin;
795   if(rp.len >= 0)
796     {
797       f = lookup_conn(rp.from);
798       if(debug_lvl > 2)
799         syslog(LOG_DEBUG, "packet from " IP_ADDR_S " (len %d)",
800                IP_ADDR_V(rp.from), rp.len);
801       if(!f)
802         {
803           syslog(LOG_ERR, "Got packet from unknown source " IP_ADDR_S,
804                  IP_ADDR_V(rp.from));
805           return -1;
806         }
807
808       if(f->status.validkey)
809         xrecv(f, &rp);
810       else
811         {
812           add_queue(&(f->rq), &rp, rp.len);
813           if(!cl->status.waitingforkey)
814             send_key_request(rp.from);
815         }
816
817       if(my_key_expiry <= time(NULL))
818         regenerate_keys();
819     }
820 cp
821   return 0;
822 }
823
824 /*
825   terminate a connection and notify the other
826   end before closing the sockets
827 */
828 void terminate_connection(conn_list_t *cl)
829 {
830 cp
831   if(cl->status.remove)
832     return;
833
834   if(debug_lvl > 0)
835     syslog(LOG_NOTICE, "Closing connection with %s.", cl->hostname);
836
837   if(cl->status.timeout)
838     send_timeout(cl);
839   else if(!cl->status.termreq)
840     send_termreq(cl);
841
842   close(cl->socket);
843   if(cl->status.meta)
844     close(cl->meta_socket);
845
846   if(cl->status.outgoing)
847     {
848       alarm(5);
849       signal(SIGALRM, sigalrm_handler);
850       syslog(LOG_NOTICE, "Try to re-establish outgoing connection in 5 seconds.");
851     }
852   
853   cl->status.remove = 1;
854 cp
855 }
856
857 /*
858   send out a ping request to all active
859   connections
860 */
861 int send_broadcast_ping(void)
862 {
863   conn_list_t *p;
864 cp
865   for(p = conn_list; p != NULL; p = p->next)
866     {
867       if(p->status.remove)
868         continue;
869       if(p->status.active && p->status.meta)
870         {
871           if(send_ping(p))
872             terminate_connection(p);
873           else
874             {
875               p->status.pinged = 1;
876               p->status.got_pong = 0;
877             }
878         }
879     }
880
881   last_ping_time = time(NULL);
882 cp
883   return 0;
884 }
885
886 /*
887   end all connections that did not respond
888   to the ping probe in time
889 */
890 int check_dead_connections(void)
891 {
892   conn_list_t *p;
893 cp
894   for(p = conn_list; p != NULL; p = p->next)
895     {
896       if(p->status.remove)
897         continue;
898       if(p->status.active && p->status.meta && p->status.pinged && !p->status.got_pong)
899         {
900           syslog(LOG_INFO, "%s (" IP_ADDR_S ") didn't respond to ping",
901                  p->hostname, IP_ADDR_V(p->vpn_ip));
902           p->status.timeout = 1;
903           terminate_connection(p);
904         }
905     }
906 cp
907   return 0;
908 }
909
910 /*
911   accept a new tcp connect and create a
912   new connection
913 */
914 int handle_new_meta_connection(conn_list_t *cl)
915 {
916   conn_list_t *ncn;
917   struct sockaddr client;
918   int nfd, len = sizeof(struct sockaddr);
919 cp
920   if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
921     {
922       syslog(LOG_ERR, "Accepting a new connection failed: %m");
923       return -1;
924     }
925
926   if((ncn = create_new_connection(nfd)) == NULL)
927     {
928       shutdown(nfd, 2);
929       close(nfd);
930       syslog(LOG_NOTICE, "Closed attempted connection.");
931       return 0;
932     }
933
934   ncn->status.meta = 1;
935   ncn->next = conn_list;
936   conn_list = ncn;
937 cp
938   return 0;
939 }
940
941 /*
942   dispatch any incoming meta requests
943 */
944 int handle_incoming_meta_data(conn_list_t *cl)
945 {
946   int x, l = sizeof(x), lenin;
947   unsigned char tmp[1600];
948   int request;
949 cp
950   if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
951     {
952       syslog(LOG_ERR, "This is a bug: %s:%d: %d:%m", __FILE__, __LINE__, cl->meta_socket);
953       return -1;
954     }
955   if(x)
956     {
957       syslog(LOG_ERR, "Metadata socket error: %s", sys_errlist[x]);
958       return -1;
959     }
960
961   if((lenin = recv(cl->meta_socket, &tmp, sizeof(tmp), 0)) <= 0)
962     {
963       syslog(LOG_ERR, "Receive failed: %m");
964       return -1;
965     }
966
967   request = (int)(tmp[0]);
968
969   if(debug_lvl > 3)
970     syslog(LOG_DEBUG, "got request %d", request);
971
972   if(request_handlers[request] == NULL)
973     syslog(LOG_ERR, "Unknown request %d.", request);
974   else
975     if(request_handlers[request](cl, tmp, lenin) < 0)
976       return -1;
977 cp  
978   return 0;
979 }
980
981 /*
982   check all connections to see if anything
983   happened on their sockets
984 */
985 void check_network_activity(fd_set *f)
986 {
987   conn_list_t *p;
988   int x, l = sizeof(x);
989 cp
990   for(p = conn_list; p != NULL; p = p->next)
991     {
992       if(p->status.remove)
993         continue;
994
995       if(p->status.active)
996         if(FD_ISSET(p->socket, f))
997           {
998             /*
999               The only thing that can happen to get us here is apparently an
1000               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1001               something that will not trigger an error directly on send()).
1002               I've once got here when it said `No route to host'.
1003             */
1004             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1005             syslog(LOG_ERR, "Outgoing data socket error: %s", sys_errlist[x]);
1006             terminate_connection(p);
1007             return;
1008           }  
1009
1010       if(p->status.meta)
1011         if(FD_ISSET(p->meta_socket, f))
1012           if(handle_incoming_meta_data(p) < 0)
1013             {
1014               terminate_connection(p);
1015               return;
1016             } 
1017     }
1018   
1019   if(FD_ISSET(myself->socket, f))
1020     handle_incoming_vpn_data(myself);
1021
1022   if(FD_ISSET(myself->meta_socket, f))
1023     handle_new_meta_connection(myself);
1024 cp
1025 }
1026
1027 /*
1028   read, encrypt and send data that is
1029   available through the ethertap device
1030 */
1031 void handle_tap_input(void)
1032 {
1033   vpn_packet_t vp;
1034   ip_t from, to;
1035   int ether_type, lenin;
1036 cp  
1037   memset(&vp, 0, sizeof(vp));
1038   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1039     {
1040       syslog(LOG_ERR, "Error while reading from tapdevice: %m");
1041       return;
1042     }
1043
1044   total_tap_in += lenin;
1045
1046   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1047   if(ether_type != 0x0800)
1048     {
1049       if(debug_lvl > 0)
1050         syslog(LOG_INFO, "Non-IP ethernet frame %04x from " MAC_ADDR_S,
1051                ether_type, MAC_ADDR_V(vp.data[6]));
1052       return;
1053     }
1054   
1055   if(lenin < 32)
1056     {
1057       if(debug_lvl > 0)
1058         syslog(LOG_INFO, "Dropping short packet");
1059       return;
1060     }
1061
1062   from = ntohl(*((unsigned long*)(&vp.data[26])));
1063   to = ntohl(*((unsigned long*)(&vp.data[30])));
1064
1065   if(debug_lvl > 2)
1066     syslog(LOG_DEBUG, "An IP packet (%04x) for " IP_ADDR_S " from " IP_ADDR_S,
1067            ether_type, IP_ADDR_V(to), IP_ADDR_V(from));
1068   if(debug_lvl > 3)
1069     syslog(LOG_DEBUG, MAC_ADDR_S " to " MAC_ADDR_S,
1070            MAC_ADDR_V(vp.data[0]), MAC_ADDR_V(vp.data[6]));
1071   
1072   vp.len = (length_t)lenin - 2;
1073
1074   strip_mac_addresses(&vp);
1075
1076   send_packet(to, &vp);
1077 cp
1078 }
1079
1080 /*
1081   this is where it al happens...
1082 */
1083 void main_loop(void)
1084 {
1085   fd_set fset;
1086   struct timeval tv;
1087   int r;
1088 cp
1089   last_ping_time = time(NULL);
1090
1091   for(;;)
1092     {
1093       tv.tv_sec = timeout;
1094       tv.tv_usec = 0;
1095
1096       prune_conn_list();
1097       build_fdset(&fset);
1098
1099       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1100         {
1101           if(errno == EINTR) /* because of alarm */
1102             continue;
1103           syslog(LOG_ERR, "Error while waiting for input: %m");
1104           return;
1105         }
1106
1107       if(r == 0 || last_ping_time + timeout < time(NULL))
1108         /* Timeout... hm... something might be wrong. */
1109         {
1110           check_dead_connections();
1111           send_broadcast_ping();
1112           continue;
1113         }
1114
1115       check_network_activity(&fset);
1116
1117       /* local tap data */
1118       if(FD_ISSET(tap_fd, &fset))
1119         handle_tap_input();
1120     }
1121 cp
1122 }