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