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