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