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