Second round of fixes
[oweals/tinc.git] / src / net.c
1 /*
2     net.c -- most of the network code
3     Copyright (C) 1998,1999,2000 Ivo Timmermans <itimmermans@bigfoot.com>,
4                             2000 Guus Sliepen <guus@sliepen.warande.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: net.c,v 1.35.4.30 2000/09/15 12:58:39 zarq Exp $
21 */
22
23 #include "config.h"
24
25 #include <arpa/inet.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <netdb.h>
29 #include <netinet/in.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/signal.h>
34 #include <sys/socket.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <syslog.h>
38 #include <unistd.h>
39
40 #include <cipher.h>
41 #include <utils.h>
42 #include <xalloc.h>
43
44 #include "conf.h"
45 #include "encr.h"
46 #include "net.h"
47 #include "netutl.h"
48 #include "protocol.h"
49
50 #include "system.h"
51
52 int tap_fd = -1;
53
54 int total_tap_in = 0;
55 int total_tap_out = 0;
56 int total_socket_in = 0;
57 int total_socket_out = 0;
58
59 int upstreamindex = 0;
60 static int seconds_till_retry;
61
62 /* The global list of existing connections */
63 conn_list_t *conn_list = NULL;
64 conn_list_t *myself = NULL;
65
66 /*
67   strip off the MAC adresses of an ethernet frame
68 */
69 void strip_mac_addresses(vpn_packet_t *p)
70 {
71   unsigned char tmp[MAXSIZE];
72 cp
73   memcpy(tmp, p->data, p->len);
74   p->len -= 12;
75   memcpy(p->data, &tmp[12], p->len);
76 cp
77 }
78
79 /*
80   reassemble MAC addresses
81 */
82 void add_mac_addresses(vpn_packet_t *p)
83 {
84   unsigned char tmp[MAXSIZE];
85 cp
86   memcpy(&tmp[12], p->data, p->len);
87   p->len += 12;
88   tmp[0] = tmp[6] = 0xfe;
89   tmp[1] = tmp[7] = 0xfd;
90   *((ip_t*)(&tmp[2])) = (ip_t)(htonl(myself->vpn_ip));
91   *((ip_t*)(&tmp[8])) = *((ip_t*)(&tmp[26]));
92   memcpy(p->data, &tmp[0], p->len);
93 cp
94 }
95
96 int str2opt(const char *str) {
97   int r;
98
99   r = 0;
100   return r;
101 }
102
103 char *opt2str(int opt) {
104   static char s[50];
105
106   snprintf(s, 49, "%d", opt);
107   return &s;
108 }
109
110 int xsend(conn_list_t *cl, void *packet)
111 {
112   real_packet_t rp;
113 cp
114   do_encrypt((vpn_packet_t*)packet, &rp, cl->datakey);
115   rp.from = htonl(myself->vpn_ip);
116   rp.data.len = htons(rp.data.len);
117   rp.len = htons(rp.len);
118
119   if(debug_lvl > 3)
120     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
121            ntohs(rp.len), cl->name, cl->hostname);
122
123   total_socket_out += ntohs(rp.len);
124
125   cl->want_ping = 1;
126
127   if((cl->flags | myself->flags) & TCPONLY)
128       return send_tcppacket(cl, (void*)&rp, ntohs(rp.len));
129
130   if((send(cl->socket, (char*)&rp, ntohs(rp.len), 0)) < 0)
131     {
132       syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
133              cl->name, cl->hostname);
134       return -1;
135     }
136 cp
137   return 0;
138 }
139
140 int xrecv(conn_list_t *cl, void *packet)
141 {
142   vpn_packet_t vp;
143   int lenin;
144 cp
145   do_decrypt((real_packet_t*)packet, &vp, cl->datakey);
146   add_mac_addresses(&vp);
147
148   if(debug_lvl > 3)
149     syslog(LOG_ERR, _("Receiving packet of %d bytes from %s (%s)"),
150            ((real_packet_t*)packet)->len, cl->name, cl->hostname);
151
152   if((lenin = write(tap_fd, &vp, vp.len + sizeof(vp.len))) < 0)
153     syslog(LOG_ERR, _("Can't write to tap device: %m"));
154   else
155     total_tap_out += lenin;
156
157   cl->want_ping = 0;
158   cl->last_ping_time = time(NULL);
159 cp
160   return 0;
161 }
162
163 /*
164   add the given packet of size s to the
165   queue q, be it the send or receive queue
166 */
167 void add_queue(packet_queue_t **q, void *packet, size_t s)
168 {
169   queue_element_t *e;
170 cp
171   e = xmalloc(sizeof(*e));
172   e->packet = xmalloc(s);
173   memcpy(e->packet, packet, s);
174
175   if(!*q)
176     {
177       *q = xmalloc(sizeof(**q));
178       (*q)->head = (*q)->tail = NULL;
179     }
180
181   e->next = NULL;                       /* We insert at the tail */
182
183   if((*q)->tail)                        /* Do we have a tail? */
184     {
185       (*q)->tail->next = e;
186       e->prev = (*q)->tail;
187     }
188   else                                  /* No tail -> no head too */
189     {
190       (*q)->head = e;
191       e->prev = NULL;
192     }
193
194   (*q)->tail = e;
195 cp
196 }
197
198 /* Remove a queue element */
199 void del_queue(packet_queue_t **q, queue_element_t *e)
200 {
201 cp
202   free(e->packet);
203
204   if(e->next)                           /* There is a successor, so we are not tail */
205     {
206       if(e->prev)                       /* There is a predecessor, so we are not head */
207         {
208           e->next->prev = e->prev;
209           e->prev->next = e->next;
210         }
211       else                              /* We are head */
212         {
213           e->next->prev = NULL;
214           (*q)->head = e->next;
215         }
216     }
217   else                                  /* We are tail (or all alone!) */
218     {          
219       if(e->prev)                       /* We are not alone :) */
220         {
221           e->prev->next = NULL;
222           (*q)->tail = e->prev;
223         }
224       else                              /* Adieu */
225         {
226           free(*q);
227           *q = NULL;
228         }
229     }
230     
231   free(e);
232 cp
233 }
234
235 /*
236   flush a queue by calling function for
237   each packet, and removing it when that
238   returned a zero exit code
239 */
240 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
241                  int (*function)(conn_list_t*,void*))
242 {
243   queue_element_t *p, *next = NULL;
244 cp
245   for(p = (*pq)->head; p != NULL; )
246     {
247       next = p->next;
248
249       if(!function(cl, p->packet))
250         del_queue(pq, p);
251         
252       p = next;
253     }
254
255   if(debug_lvl > 3)
256     syslog(LOG_DEBUG, _("Queue flushed"));
257 cp
258 }
259
260 /*
261   flush the send&recv queues
262   void because nothing goes wrong here, packets
263   remain in the queue if something goes wrong
264 */
265 void flush_queues(conn_list_t *cl)
266 {
267 cp
268   if(cl->sq)
269     {
270       if(debug_lvl > 3)
271         syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
272                cl->name, cl->hostname);
273       flush_queue(cl, &(cl->sq), xsend);
274     }
275
276   if(cl->rq)
277     {
278       if(debug_lvl > 3)
279         syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
280                cl->name, cl->hostname);
281       flush_queue(cl, &(cl->rq), xrecv);
282     }
283 cp
284 }
285
286 /*
287   send a packet to the given vpn ip.
288 */
289 int send_packet(ip_t to, vpn_packet_t *packet)
290 {
291   conn_list_t *cl;
292 cp
293   if((cl = lookup_conn(to)) == NULL)
294     {
295       if(debug_lvl > 3)
296         {
297           syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
298                  IP_ADDR_V(to));
299         }
300
301       return -1;
302    }
303     
304   /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
305   
306   /* The next few lines will be obsoleted, if we are going indirect, matching subnet_t
307      should point to only our uplink as the recepient
308   */
309
310   if(myself->flags & EXPORTINDIRECTDATA)
311     {
312       for(cl = conn_list; cl != NULL && !cl->status.outgoing; cl = cl->next);
313       if(!cl)
314         { /* No open outgoing connection has been found. */
315           if(debug_lvl > 3)
316             syslog(LOG_NOTICE, _("There is no remote host I can send this packet to!"));
317           return -1;
318         }
319     }
320   else
321
322   /* If indirectdata flag is set for the destination we just looked up,
323    * then real_ip is actually the vpn_ip of the gateway tincd
324    * it is behind.
325    */
326    
327   if(cl->flags & INDIRECTDATA)
328     {
329       if(debug_lvl > 3)
330         syslog(LOG_NOTICE, _("Indirect packet to %s via %s"),
331                cl->name, cl->hostname);
332       if((cl = lookup_conn(cl->real_ip)) == NULL)
333         {
334           if(debug_lvl > 3)
335               syslog(LOG_NOTICE, _("Indirect look up %d.%d.%d.%d in connection list failed!"), IP_ADDR_V(to));
336             
337           /* Gateway tincd dead? Should we kill it? (GS) */
338
339           return -1;
340         }
341       if(cl->flags & INDIRECTDATA)  /* This should not happen */
342         {
343           if(debug_lvl > 3)
344               syslog(LOG_NOTICE, _("Double indirection for %d.%d.%d.%d"), IP_ADDR_V(to));
345           return -1;        
346         }
347     }            
348
349   if(my_key_expiry <= time(NULL))
350     regenerate_keys();
351
352   if(!cl->status.dataopen)
353     if(setup_vpn_connection(cl) < 0)
354       {
355         syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
356                cl->name, cl->hostname);
357         return -1;
358       }
359       
360   if(!cl->status.validkey)
361     {
362       if(debug_lvl > 3)
363         syslog(LOG_INFO, _("%s (%s) has no valid key, queueing packet"),
364                cl->name, cl->hostname);
365       add_queue(&(cl->sq), packet, packet->len + 2);
366       if(!cl->status.waitingforkey)
367         send_key_request(cl->vpn_ip);                   /* Keys should be sent to the host running the tincd */
368       return 0;
369     }
370
371   if(!cl->status.active)
372     {
373       if(debug_lvl > 3)
374         syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
375                cl->name, cl->hostname);
376       add_queue(&(cl->sq), packet, packet->len + 2);
377       return 0; /* We don't want to mess up, do we? */
378     }
379
380   /* can we send it? can we? can we? huh? */
381 cp
382   return xsend(cl, packet);
383 }
384
385 /*
386   open the local ethertap device
387 */
388 int setup_tap_fd(void)
389 {
390   int nfd;
391   const char *tapfname;
392   config_t const *cfg;
393 cp  
394   if((cfg = get_config_val(tapdevice)) == NULL)
395     tapfname = "/dev/tap0";
396   else
397     tapfname = cfg->data.ptr;
398
399   if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
400     {
401       syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
402       return -1;
403     }
404
405   tap_fd = nfd;
406 cp
407   return 0;
408 }
409
410 /*
411   set up the socket that we listen on for incoming
412   (tcp) connections
413 */
414 int setup_listen_meta_socket(int port)
415 {
416   int nfd, flags;
417   struct sockaddr_in a;
418   const int one = 1;
419   config_t const *cfg;
420 cp
421   if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
422     {
423       syslog(LOG_ERR, _("Creating metasocket failed: %m"));
424       return -1;
425     }
426
427   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
428     {
429       syslog(LOG_ERR, _("setsockopt: %m"));
430       return -1;
431     }
432
433   if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
434     {
435       syslog(LOG_ERR, _("setsockopt: %m"));
436       return -1;
437     }
438
439   flags = fcntl(nfd, F_GETFL);
440   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
441     {
442       syslog(LOG_ERR, _("fcntl: %m"));
443       return -1;
444     }
445
446   if((cfg = get_config_val(interface)))
447     {
448       if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
449         {
450           syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
451           return -1;
452         }
453     }
454
455   memset(&a, 0, sizeof(a));
456   a.sin_family = AF_INET;
457   a.sin_port = htons(port);
458   
459   if((cfg = get_config_val(interfaceip)))
460     a.sin_addr.s_addr = htonl(cfg->data.ip->ip);
461   else
462     a.sin_addr.s_addr = htonl(INADDR_ANY);
463
464   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
465     {
466       syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
467       return -1;
468     }
469
470   if(listen(nfd, 3))
471     {
472       syslog(LOG_ERR, _("listen: %m"));
473       return -1;
474     }
475 cp
476   return nfd;
477 }
478
479 /*
480   setup the socket for incoming encrypted
481   data (the udp part)
482 */
483 int setup_vpn_in_socket(int port)
484 {
485   int nfd, flags;
486   struct sockaddr_in a;
487   const int one = 1;
488 cp
489   if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
490     {
491       syslog(LOG_ERR, _("Creating socket failed: %m"));
492       return -1;
493     }
494
495   if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
496     {
497       syslog(LOG_ERR, _("setsockopt: %m"));
498       return -1;
499     }
500
501   flags = fcntl(nfd, F_GETFL);
502   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
503     {
504       syslog(LOG_ERR, _("fcntl: %m"));
505       return -1;
506     }
507
508   memset(&a, 0, sizeof(a));
509   a.sin_family = AF_INET;
510   a.sin_port = htons(port);
511   a.sin_addr.s_addr = htonl(INADDR_ANY);
512
513   if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
514     {
515       syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
516       return -1;
517     }
518 cp
519   return nfd;
520 }
521
522 /*
523   setup an outgoing meta (tcp) socket
524 */
525 int setup_outgoing_meta_socket(conn_list_t *cl)
526 {
527   int flags;
528   struct sockaddr_in a;
529   config_t const *cfg;
530 cp
531   if(debug_lvl > 0)
532     syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
533
534   if((cfg = get_config_val(upstreamport)) == NULL)
535     cl->port = 655;
536   else
537     cl->port = cfg->data.val;
538
539   cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
540   if(cl->meta_socket == -1)
541     {
542       syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
543              cl->hostname, cl->port);
544       return -1;
545     }
546
547   a.sin_family = AF_INET;
548   a.sin_port = htons(cl->port);
549   a.sin_addr.s_addr = htonl(cl->real_ip);
550
551   if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
552     {
553       syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
554       return -1;
555     }
556
557   flags = fcntl(cl->meta_socket, F_GETFL);
558   if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
559     {
560       syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
561              cl->hostname, cl->port);
562       return -1;
563     }
564
565   if(debug_lvl > 0)
566     syslog(LOG_INFO, _("Connected to %s port %hd"),
567          cl->hostname, cl->port);
568 cp
569   return 0;
570 }
571
572 /*
573   setup an outgoing connection. It's not
574   necessary to also open an udp socket as
575   well, because the other host will initiate
576   an authentication sequence during which
577   we will do just that.
578 */
579 int setup_outgoing_connection(char *hostname)
580 {
581   conn_list_t *ncn;
582   struct hostent *h;
583 cp
584   if(!(h = gethostbyname(hostname)))
585     {
586       syslog(LOG_ERR, _("Error looking up `%s': %m"), hostname);
587       return -1;
588     }
589
590   ncn = new_conn_list();
591   ncn->real_ip = ntohl(*((ip_t*)(h->h_addr_list[0])));
592   ncn->hostname = hostlookup(htonl(ncn->real_ip));
593   
594   if(setup_outgoing_meta_socket(ncn) < 0)
595     {
596       syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
597              ncn->hostname);
598       free_conn_element(ncn);
599       return -1;
600     }
601
602   ncn->status.meta = 1;
603   ncn->status.outgoing = 1;
604   ncn->next = conn_list;
605   conn_list = ncn;
606 cp
607   return 0;
608 }
609
610 /*
611   set up the local sockets (listen only)
612 */
613 int setup_myself(void)
614 {
615   config_t const *cfg;
616 cp
617   myself = new_conn_list();
618
619   if(!(cfg = get_config_val(myvpnip)))
620     {
621       syslog(LOG_ERR, _("No value for my VPN IP given"));
622       return -1;
623     }
624
625   myself->vpn_ip = cfg->data.ip->ip;
626   myself->hostname = hostlookup(htonl(myself->vpn_ip));
627   myself->vpn_mask = cfg->data.ip->mask;
628   myself->flags = 0;
629
630   if(!(cfg = get_config_val(tincname)))
631     asprintf(&(myself->name), IP_ADDR_S, IP_ADDR_V(myself->vpn_ip));
632   else
633     myself->name = (char*)cfg->data.val;
634   
635   if(!(cfg = get_config_val(listenport)))
636     myself->port = 655;
637   else
638     myself->port = cfg->data.val;
639
640   if((cfg = get_config_val(indirectdata)))
641     if(cfg->data.val == stupid_true)
642       myself->flags |= EXPORTINDIRECTDATA;
643
644   if((cfg = get_config_val(tcponly)))
645     if(cfg->data.val == stupid_true)
646       myself->flags |= TCPONLY;
647
648   if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
649     {
650       syslog(LOG_ERR, _("Unable to set up a listening socket"));
651       return -1;
652     }
653
654   if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
655     {
656       syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
657       close(myself->meta_socket);
658       return -1;
659     }
660
661   myself->status.active = 1;
662
663   syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
664 cp
665   return 0;
666 }
667
668 RETSIGTYPE
669 sigalrm_handler(int a)
670 {
671   config_t const *cfg;
672 cp
673   cfg = get_next_config_val(upstreamip, upstreamindex++);
674
675   while(cfg)
676     {
677       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
678         {
679           signal(SIGALRM, SIG_IGN);
680           return;
681         }
682       cfg = get_next_config_val(upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
683     }
684
685   signal(SIGALRM, sigalrm_handler);
686   upstreamindex = 0;
687   seconds_till_retry += 5;
688   if(seconds_till_retry > MAXTIMEOUT)    /* Don't wait more than MAXTIMEOUT seconds. */
689     seconds_till_retry = MAXTIMEOUT;
690   syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
691          seconds_till_retry);
692   alarm(seconds_till_retry);
693 cp
694 }
695
696 /*
697   setup all initial network connections
698 */
699 int setup_network_connections(void)
700 {
701   config_t const *cfg;
702 cp
703   if((cfg = get_config_val(pingtimeout)) == NULL)
704     timeout = 5;
705   else
706     timeout = cfg->data.val;
707
708   if(setup_tap_fd() < 0)
709     return -1;
710
711   if(setup_myself() < 0)
712     return -1;
713
714   if((cfg = get_next_config_val(upstreamip, upstreamindex++)) == NULL)
715     /* No upstream IP given, we're listen only. */
716     return 0;
717
718   while(cfg)
719     {
720       if(!setup_outgoing_connection(cfg->data.ptr))   /* function returns 0 when there are no problems */
721         return 0;
722       cfg = get_next_config_val(upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
723     }
724     
725   signal(SIGALRM, sigalrm_handler);
726   upstreamindex = 0;
727   seconds_till_retry = MAXTIMEOUT;
728   syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
729   alarm(seconds_till_retry);
730 cp
731   return 0;
732 }
733
734 /*
735   close all open network connections
736 */
737 void close_network_connections(void)
738 {
739   conn_list_t *p;
740 cp
741   for(p = conn_list; p != NULL; p = p->next)
742     {
743       if(p->status.dataopen)
744         {
745           shutdown(p->socket, 0); /* No more receptions */
746           close(p->socket);
747         }
748       if(p->status.meta)
749         {
750           send_termreq(p);
751           shutdown(p->meta_socket, 0); /* No more receptions */
752           close(p->meta_socket);
753         }
754     }
755
756   if(myself)
757     if(myself->status.active)
758       {
759         close(myself->meta_socket);
760         close(myself->socket);
761       }
762
763   close(tap_fd);
764   destroy_conn_list();
765
766   syslog(LOG_NOTICE, _("Terminating"));
767 cp
768   return;
769 }
770
771 /*
772   create a data (udp) socket
773 */
774 int setup_vpn_connection(conn_list_t *cl)
775 {
776   int nfd, flags;
777   struct sockaddr_in a;
778 cp
779   if(debug_lvl > 0)
780     syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
781
782   nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
783   if(nfd == -1)
784     {
785       syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
786       return -1;
787     }
788
789   a.sin_family = AF_INET;
790   a.sin_port = htons(cl->port);
791   a.sin_addr.s_addr = htonl(cl->real_ip);
792
793   if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
794     {
795       syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
796              cl->hostname, cl->port);
797       return -1;
798     }
799
800   flags = fcntl(nfd, F_GETFL);
801   if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
802     {
803       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
804              cl->name, cl->hostname);
805       return -1;
806     }
807
808   cl->socket = nfd;
809   cl->status.dataopen = 1;
810 cp
811   return 0;
812 }
813
814 /*
815   handle an incoming tcp connect call and open
816   a connection to it.
817 */
818 conn_list_t *create_new_connection(int sfd)
819 {
820   conn_list_t *p;
821   struct sockaddr_in ci;
822   int len = sizeof(ci);
823 cp
824   p = new_conn_list();
825
826   if(getpeername(sfd, &ci, &len) < 0)
827     {
828       syslog(LOG_ERR, _("Error: getpeername: %m"));
829       return NULL;
830     }
831
832   p->real_ip = ntohl(ci.sin_addr.s_addr);
833   p->hostname = hostlookup(ci.sin_addr.s_addr);
834   p->meta_socket = sfd;
835   p->status.meta = 1;
836   p->buflen = 0;
837   p->last_ping_time = time(NULL);
838   p->want_ping = 0;
839   
840   if(debug_lvl > 0)
841     syslog(LOG_NOTICE, _("Connection from %s port %d"),
842          p->hostname, htons(ci.sin_port));
843
844   if(send_basic_info(p) < 0)
845     {
846       free_conn_element(p);
847       return NULL;
848     }
849 cp
850   return p;
851 }
852
853 /*
854   put all file descriptors in an fd_set array
855 */
856 void build_fdset(fd_set *fs)
857 {
858   conn_list_t *p;
859 cp
860   FD_ZERO(fs);
861
862   for(p = conn_list; p != NULL; p = p->next)
863     {
864       if(p->status.meta)
865         FD_SET(p->meta_socket, fs);
866       if(p->status.dataopen)
867         FD_SET(p->socket, fs);
868     }
869
870   FD_SET(myself->meta_socket, fs);
871   FD_SET(myself->socket, fs);
872   FD_SET(tap_fd, fs);
873 cp
874 }
875
876 /*
877   receive incoming data from the listening
878   udp socket and write it to the ethertap
879   device after being decrypted
880 */
881 int handle_incoming_vpn_data(conn_list_t *cl)
882 {
883   real_packet_t rp;
884   int lenin;
885   int x, l = sizeof(x);
886   conn_list_t *f;
887 cp
888   if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
889     {
890       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"),
891              __FILE__, __LINE__, cl->socket,
892              cl->name, cl->hostname);
893       return -1;
894     }
895   if(x)
896     {
897       syslog(LOG_ERR, _("Incoming data socket error for %s (%s): %s"),
898              cl->name, cl->hostname, strerror(x));
899       return -1;
900     }
901
902   rp.len = -1;
903   lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
904   if(lenin <= 0)
905     {
906       syslog(LOG_ERR, _("Receiving packet from %s (%s) failed: %m"),
907              cl->name, cl->hostname);
908       return -1;
909     }
910   total_socket_in += lenin;
911
912   rp.data.len = ntohs(rp.data.len);
913   rp.len = ntohs(rp.len);
914   rp.from = ntohl(rp.from);
915
916   if(rp.len >= 0)
917     {
918       f = lookup_conn(rp.from);
919       if(!f)
920         {
921           syslog(LOG_ERR, _("Got packet from %s (%s) with unknown origin %d.%d.%d.%d?"),
922                  cl->name, cl->hostname, IP_ADDR_V(rp.from));
923           return -1;
924         }
925
926       if(f->status.validkey)
927         xrecv(f, &rp);
928       else
929         {
930           add_queue(&(f->rq), &rp, rp.len);
931           if(!cl->status.waitingforkey)
932             send_key_request(rp.from);
933         }
934
935       if(my_key_expiry <= time(NULL))
936         regenerate_keys();
937     }
938 cp
939   return 0;
940 }
941
942 /*
943   terminate a connection and notify the other
944   end before closing the sockets
945 */
946 void terminate_connection(conn_list_t *cl)
947 {
948   conn_list_t *p;
949
950 cp
951   if(cl->status.remove)
952     return;
953
954   if(debug_lvl > 0)
955     syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
956            cl->name, cl->hostname);
957
958   if(cl->status.timeout)
959     send_timeout(cl);
960 /*  else if(!cl->status.termreq)
961     send_termreq(cl);
962  */
963  
964   if(cl->socket)
965     close(cl->socket);
966   if(cl->status.meta)
967     close(cl->meta_socket);
968
969   cl->status.remove = 1;
970
971   /* If this cl isn't active, don't send any DEL_HOSTs. */
972   if(cl->status.active)
973     notify_others(cl,NULL,send_del_host);
974     
975 cp
976   /* Find all connections that were lost because they were behind cl
977      (the connection that was dropped). */
978   if(cl->status.meta)
979     for(p = conn_list; p != NULL; p = p->next)
980       {
981         if((p->nexthop == cl) && (p != cl))
982           {
983             if(cl->status.active && p->status.active)
984               notify_others(p,cl,send_del_host);
985            if(cl->socket)
986              close(cl->socket);
987             p->status.active = 0;
988             p->status.remove = 1;
989           }
990       }
991     
992   cl->status.active = 0;
993   
994   if(cl->status.outgoing)
995     {
996       signal(SIGALRM, sigalrm_handler);
997       seconds_till_retry = 5;
998       alarm(seconds_till_retry);
999       syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
1000     }
1001 cp
1002 }
1003
1004 /*
1005   Check if the other end is active.
1006   If we have sent packets, but didn't receive any,
1007   then possibly the other end is dead. We send a
1008   PING request over the meta connection. If the other
1009   end does not reply in time, we consider them dead
1010   and close the connection.
1011 */
1012 int check_dead_connections(void)
1013 {
1014   conn_list_t *p;
1015   time_t now;
1016 cp
1017   now = time(NULL);
1018   for(p = conn_list; p != NULL; p = p->next)
1019     {
1020       if(p->status.remove)
1021         continue;
1022       if(p->status.active && p->status.meta)
1023         {
1024           if(p->last_ping_time + timeout < now)
1025             {
1026               if(p->status.pinged && !p->status.got_pong)
1027                 {
1028                   if(debug_lvl > 1)
1029                     syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
1030                            p->name, p->hostname);
1031                   p->status.timeout = 1;
1032                   terminate_connection(p);
1033                 }
1034               else if(p->want_ping)
1035                 {
1036                   send_ping(p);
1037                   p->last_ping_time = now;
1038                   p->status.pinged = 1;
1039                   p->status.got_pong = 0;
1040                 }
1041             }
1042         }
1043     }
1044 cp
1045   return 0;
1046 }
1047
1048 /*
1049   accept a new tcp connect and create a
1050   new connection
1051 */
1052 int handle_new_meta_connection(conn_list_t *cl)
1053 {
1054   conn_list_t *ncn;
1055   struct sockaddr client;
1056   int nfd, len = sizeof(client);
1057 cp
1058   if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
1059     {
1060       syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
1061       return -1;
1062     }
1063
1064   if(!(ncn = create_new_connection(nfd)))
1065     {
1066       shutdown(nfd, 2);
1067       close(nfd);
1068       syslog(LOG_NOTICE, _("Closed attempted connection"));
1069       return 0;
1070     }
1071
1072   ncn->status.meta = 1;
1073   ncn->next = conn_list;
1074   conn_list = ncn;
1075 cp
1076   return 0;
1077 }
1078
1079 /*
1080   dispatch any incoming meta requests
1081 */
1082 int handle_incoming_meta_data(conn_list_t *cl)
1083 {
1084   int x, l = sizeof(x);
1085   int request, oldlen, i;
1086   int lenin = 0;
1087 cp
1088   if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
1089     {
1090       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, cl->meta_socket,
1091              cl->name, cl->hostname);
1092       return -1;
1093     }
1094   if(x)
1095     {
1096       syslog(LOG_ERR, _("Metadata socket error for %s (%s): %s"),
1097              cl->name, cl->hostname, strerror(x));
1098       return -1;
1099     }
1100
1101   lenin = read(cl->meta_socket, cl->buffer+cl->buflen, MAXBUFSIZE - cl->buflen);
1102
1103   if(lenin<=0)
1104     {
1105       if(errno==EINTR)
1106         return 0;      
1107       if(errno==0)
1108         {
1109           if(debug_lvl>DEBUG_CONNECTIONS)
1110             syslog(LOG_NOTICE, _("Connection closed by %s (%s)"),
1111                 cl->name, cl->hostname);
1112         }
1113       else
1114         syslog(LOG_ERR, _("Metadata socket read error for %s (%s): %m"),
1115                cl->name, cl->hostname);
1116       return -1;
1117     }
1118
1119   if(cl->status.encryptin)
1120     {
1121       /* FIXME: do decryption. */
1122     }
1123
1124   oldlen = cl->buflen;
1125   cl->buflen += lenin;
1126
1127   for(;;)
1128     {
1129       cl->reqlen = 0;
1130
1131       for(i = oldlen; i < cl->buflen; i++)
1132         {
1133           if(cl->buffer[i] == '\n')
1134             {
1135               cl->buffer[i] = 0;  /* replace end-of-line by end-of-string so we can use sscanf */
1136               cl->reqlen = i + 1;
1137               break;
1138             }
1139         }
1140
1141       if(cl->reqlen)
1142         {
1143           if(debug_lvl > DEBUG_PROTOCOL)
1144             syslog(LOG_DEBUG, _("Got request from %s (%s): %s"),
1145                    cl->name, cl->hostname, cl->buffer);
1146           if(sscanf(cl->buffer, "%d", &request) == 1)
1147             {
1148               if((request < 0) || (request > 255) || (request_handlers[request] == NULL))
1149                 {
1150                   syslog(LOG_ERR, _("Unknown request from %s (%s)"),
1151                          cl->name, cl->hostname);
1152                   return -1;
1153                 }
1154               else
1155                 {
1156                   if(debug_lvl > DEBUG_PROTOCOL)
1157                     syslog(LOG_DEBUG, _("Got %s from %s (%s)"),
1158                            request_name[request], cl->name, cl->hostname);
1159                 }
1160               if(request_handlers[request](cl))
1161                 /* Something went wrong. Probably scriptkiddies. Terminate. */
1162                 {
1163                   syslog(LOG_ERR, _("Error while processing %s from %s (%s)"),
1164                          request_name[request], cl->name, cl->hostname);
1165                   return -1;
1166                 }
1167             }
1168           else
1169             {
1170               syslog(LOG_ERR, _("Bogus data received from %s (%s)"),
1171                      cl->name, cl->hostname);
1172               return -1;
1173             }
1174
1175           cl->buflen -= cl->reqlen;
1176           memmove(cl->buffer, cl->buffer + cl->reqlen, cl->buflen);
1177           oldlen = 0;
1178         }
1179       else
1180         {
1181           break;
1182         }
1183     }
1184
1185   if(cl->buflen >= MAXBUFSIZE)
1186     {
1187       syslog(LOG_ERR, _("Metadata read buffer overflow for %s (%s)"),
1188              cl->name, cl->hostname);
1189       return -1;
1190     }
1191
1192   cl->last_ping_time = time(NULL);
1193   cl->want_ping = 0;
1194 cp  
1195   return 0;
1196 }
1197
1198 /*
1199   check all connections to see if anything
1200   happened on their sockets
1201 */
1202 void check_network_activity(fd_set *f)
1203 {
1204   conn_list_t *p;
1205   int x, l = sizeof(x);
1206 cp
1207   for(p = conn_list; p != NULL; p = p->next)
1208     {
1209       if(p->status.remove)
1210         continue;
1211
1212       if(p->status.dataopen)
1213         if(FD_ISSET(p->socket, f))
1214           {
1215             /*
1216               The only thing that can happen to get us here is apparently an
1217               error on this outgoing(!) UDP socket that isn't immediate (i.e.
1218               something that will not trigger an error directly on send()).
1219               I've once got here when it said `No route to host'.
1220             */
1221             getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1222             syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1223                    p->name, p->hostname, strerror(x));
1224             terminate_connection(p);
1225             return;
1226           }  
1227
1228       if(p->status.meta)
1229         if(FD_ISSET(p->meta_socket, f))
1230           if(handle_incoming_meta_data(p) < 0)
1231             {
1232               terminate_connection(p);
1233               return;
1234             } 
1235     }
1236   
1237   if(FD_ISSET(myself->socket, f))
1238     handle_incoming_vpn_data(myself);
1239
1240   if(FD_ISSET(myself->meta_socket, f))
1241     handle_new_meta_connection(myself);
1242 cp
1243 }
1244
1245 /*
1246   read, encrypt and send data that is
1247   available through the ethertap device
1248 */
1249 void handle_tap_input(void)
1250 {
1251   vpn_packet_t vp;
1252   ip_t from, to;
1253   int ether_type, lenin;
1254 cp  
1255   memset(&vp, 0, sizeof(vp));
1256   if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1257     {
1258       syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1259       return;
1260     }
1261
1262   total_tap_in += lenin;
1263
1264   ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1265   if(ether_type != 0x0800)
1266     {
1267       if(debug_lvl > 3)
1268         syslog(LOG_INFO, _("Non-IP ethernet frame %04x from %02x:%02x:%02x:%02x:%02x:%02x"), ether_type, MAC_ADDR_V(vp.data[6]));
1269       return;
1270     }
1271   
1272   if(lenin < 32)
1273     {
1274       if(debug_lvl > 3)
1275         syslog(LOG_INFO, _("Dropping short packet from %02x:%02x:%02x:%02x:%02x:%02x"), MAC_ADDR_V(vp.data[6]));
1276       return;
1277     }
1278
1279   from = ntohl(*((unsigned long*)(&vp.data[26])));
1280   to = ntohl(*((unsigned long*)(&vp.data[30])));
1281
1282   vp.len = (length_t)lenin - 2;
1283
1284   strip_mac_addresses(&vp);
1285
1286   send_packet(to, &vp);
1287 cp
1288 }
1289
1290 /*
1291   this is where it all happens...
1292 */
1293 void main_loop(void)
1294 {
1295   fd_set fset;
1296   struct timeval tv;
1297   int r;
1298   time_t last_ping_check;
1299 cp
1300   last_ping_check = time(NULL);
1301
1302   for(;;)
1303     {
1304       tv.tv_sec = timeout;
1305       tv.tv_usec = 0;
1306
1307       prune_conn_list();
1308       build_fdset(&fset);
1309
1310       if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1311         {
1312           if(errno != EINTR) /* because of alarm */
1313             {
1314               syslog(LOG_ERR, _("Error while waiting for input: %m"));
1315               return;
1316             }
1317         }
1318
1319       if(sighup)
1320         {
1321           sighup = 0;
1322           if(debug_lvl > 1)
1323             syslog(LOG_INFO, _("Rereading configuration file"));
1324           close_network_connections();
1325           clear_config();
1326           if(read_config_file(configfilename))
1327             {
1328               syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1329               exit(0);
1330             }
1331           sleep(5);
1332           setup_network_connections();
1333           continue;
1334         }
1335
1336       if(last_ping_check + timeout < time(NULL))
1337         /* Let's check if everybody is still alive */
1338         {
1339           check_dead_connections();
1340           last_ping_check = time(NULL);
1341         }
1342
1343       if(r > 0)
1344         {
1345           check_network_activity(&fset);
1346
1347           /* local tap data */
1348           if(FD_ISSET(tap_fd, &fset))
1349             handle_tap_input();
1350         }
1351     }
1352 cp
1353 }