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