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