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