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