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>
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.
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.
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.
20 $Id: net.c,v 1.35.4.35 2000/10/14 17:04:13 guus Exp $
25 #include <arpa/inet.h>
29 #include <netinet/in.h>
33 #include <sys/signal.h>
34 #include <sys/socket.h>
36 #include <sys/types.h>
55 int total_tap_out = 0;
56 int total_socket_in = 0;
57 int total_socket_out = 0;
59 int upstreamindex = 0;
60 static int seconds_till_retry;
63 strip off the MAC adresses of an ethernet frame
65 void strip_mac_addresses(vpn_packet_t *p)
68 memmove(p->data, p->data + 12, p->len -= 12);
73 reassemble MAC addresses
75 void add_mac_addresses(vpn_packet_t *p)
78 memcpy(p->data + 12, p->data, p->len);
80 p->data[0] = p->data[6] = 0xfe;
81 p->data[1] = p->data[7] = 0xfd;
82 /* Really evil pointer stuff just below! */
83 *((ip_t*)(&p->data[2])) = (ip_t)(htonl(myself->address));
84 *((ip_t*)(&p->data[8])) = *((ip_t*)(&p->data[26]));
88 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
93 outpkt.len = inpkt->len;
94 EVP_EncryptInit(cl->cipher_pktctx, cl->cipher_pkttype, cl->cipher_pktkey, NULL);
95 EVP_EncryptUpdate(cl->cipher_pktctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
96 EVP_EncryptFinal(cl->cipher_pktctx, outpkt.data + outlen, &outpad);
100 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
101 outlen, cl->name, cl->hostname);
103 total_socket_out += outlen;
107 if((send(cl->socket, (char *) &(outpkt.len), outlen + 2, 0)) < 0)
109 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
110 cl->name, cl->hostname);
117 int xrecv(vpn_packet_t *inpkt)
123 syslog(LOG_ERR, _("Receiving packet of %d bytes"),
126 outpkt.len = inpkt->len;
127 EVP_DecryptInit(myself->cipher_pktctx, myself->cipher_pkttype, myself->cipher_pktkey, NULL);
128 EVP_DecryptUpdate(myself->cipher_pktctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
129 /* FIXME: grok DecryptFinal
130 EVP_DecryptFinal(myself->cipher_pktctx, outpkt.data + outlen, &outpad);
133 add_mac_addresses(&outpkt);
135 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
136 syslog(LOG_ERR, _("Can't write to tap device: %m"));
138 total_tap_out += outpkt.len;
144 add the given packet of size s to the
145 queue q, be it the send or receive queue
147 void add_queue(packet_queue_t **q, void *packet, size_t s)
151 e = xmalloc(sizeof(*e));
152 e->packet = xmalloc(s);
153 memcpy(e->packet, packet, s);
157 *q = xmalloc(sizeof(**q));
158 (*q)->head = (*q)->tail = NULL;
161 e->next = NULL; /* We insert at the tail */
163 if((*q)->tail) /* Do we have a tail? */
165 (*q)->tail->next = e;
166 e->prev = (*q)->tail;
168 else /* No tail -> no head too */
178 /* Remove a queue element */
179 void del_queue(packet_queue_t **q, queue_element_t *e)
184 if(e->next) /* There is a successor, so we are not tail */
186 if(e->prev) /* There is a predecessor, so we are not head */
188 e->next->prev = e->prev;
189 e->prev->next = e->next;
191 else /* We are head */
193 e->next->prev = NULL;
194 (*q)->head = e->next;
197 else /* We are tail (or all alone!) */
199 if(e->prev) /* We are not alone :) */
201 e->prev->next = NULL;
202 (*q)->tail = e->prev;
216 flush a queue by calling function for
217 each packet, and removing it when that
218 returned a zero exit code
220 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
221 int (*function)(conn_list_t*,void*))
223 queue_element_t *p, *next = NULL;
225 for(p = (*pq)->head; p != NULL; )
229 if(!function(cl, p->packet))
236 syslog(LOG_DEBUG, _("Queue flushed"));
241 flush the send&recv queues
242 void because nothing goes wrong here, packets
243 remain in the queue if something goes wrong
245 void flush_queues(conn_list_t *cl)
251 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
252 cl->name, cl->hostname);
253 flush_queue(cl, &(cl->sq), xsend);
259 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
260 cl->name, cl->hostname);
261 flush_queue(cl, &(cl->rq), xrecv);
267 send a packet to the given vpn ip.
269 int send_packet(ip_t to, vpn_packet_t *packet)
273 if((cl = lookup_conn_list_ipv4(to)) == NULL)
277 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
284 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
286 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
288 if(!cl->status.dataopen)
289 if(setup_vpn_connection(cl) < 0)
291 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
292 cl->name, cl->hostname);
296 if(!cl->status.validkey)
299 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
300 cl->name, cl->hostname);
301 add_queue(&(cl->sq), packet, packet->len + 2);
302 if(!cl->status.waitingforkey)
303 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
307 if(!cl->status.active)
310 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
311 cl->name, cl->hostname);
312 add_queue(&(cl->sq), packet, packet->len + 2);
313 return 0; /* We don't want to mess up, do we? */
316 /* can we send it? can we? can we? huh? */
318 return xsend(cl, packet);
322 open the local ethertap device
324 int setup_tap_fd(void)
327 const char *tapfname;
330 if((cfg = get_config_val(config, tapdevice)) == NULL)
331 tapfname = "/dev/tap0";
333 tapfname = cfg->data.ptr;
335 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
337 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
347 set up the socket that we listen on for incoming
350 int setup_listen_meta_socket(int port)
353 struct sockaddr_in a;
357 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
359 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
363 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
365 syslog(LOG_ERR, _("setsockopt: %m"));
369 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
371 syslog(LOG_ERR, _("setsockopt: %m"));
375 flags = fcntl(nfd, F_GETFL);
376 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
378 syslog(LOG_ERR, _("fcntl: %m"));
382 if((cfg = get_config_val(config, interface)))
384 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
386 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
391 memset(&a, 0, sizeof(a));
392 a.sin_family = AF_INET;
393 a.sin_port = htons(port);
395 if((cfg = get_config_val(config, interfaceip)))
396 a.sin_addr.s_addr = htonl(cfg->data.ip->ip);
398 a.sin_addr.s_addr = htonl(INADDR_ANY);
400 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
402 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
408 syslog(LOG_ERR, _("listen: %m"));
416 setup the socket for incoming encrypted
419 int setup_vpn_in_socket(int port)
422 struct sockaddr_in a;
425 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
427 syslog(LOG_ERR, _("Creating socket failed: %m"));
431 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
433 syslog(LOG_ERR, _("setsockopt: %m"));
437 flags = fcntl(nfd, F_GETFL);
438 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
440 syslog(LOG_ERR, _("fcntl: %m"));
444 memset(&a, 0, sizeof(a));
445 a.sin_family = AF_INET;
446 a.sin_port = htons(port);
447 a.sin_addr.s_addr = htonl(INADDR_ANY);
449 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
451 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
459 setup an outgoing meta (tcp) socket
461 int setup_outgoing_meta_socket(conn_list_t *cl)
464 struct sockaddr_in a;
468 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
470 if((cfg = get_config_val(cl->config, port)) == NULL)
473 cl->port = cfg->data.val;
475 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
476 if(cl->meta_socket == -1)
478 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
479 cl->hostname, cl->port);
483 a.sin_family = AF_INET;
484 a.sin_port = htons(cl->port);
485 a.sin_addr.s_addr = htonl(cl->address);
487 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
489 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
493 flags = fcntl(cl->meta_socket, F_GETFL);
494 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
496 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
497 cl->hostname, cl->port);
502 syslog(LOG_INFO, _("Connected to %s port %hd"),
503 cl->hostname, cl->port);
509 setup an outgoing connection. It's not
510 necessary to also open an udp socket as
511 well, because the other host will initiate
512 an authentication sequence during which
513 we will do just that.
515 int setup_outgoing_connection(char *hostname)
520 if(!(h = gethostbyname(hostname)))
522 syslog(LOG_ERR, _("Error looking up `%s': %m"), hostname);
526 ncn = new_conn_list();
527 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
528 ncn->hostname = hostlookup(htonl(ncn->address));
530 if(setup_outgoing_meta_socket(ncn) < 0)
532 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
538 ncn->status.meta = 1;
539 ncn->status.outgoing = 1;
540 ncn->next = conn_list;
547 set up the local sockets (listen only)
549 int setup_myself(void)
553 myself = new_conn_list();
555 asprintf(&myself->hostname, "MYSELF"); /* FIXME? Do hostlookup on ourselves? */
558 if(!(cfg = get_config_val(config, tincname))) /* Not acceptable */
560 syslog(LOG_ERR, _("Name for tinc daemon required!"));
564 myself->name = (char*)cfg->data.val;
566 if(check_id(myself->name))
568 syslog(LOG_ERR, _("Invalid name for myself!"));
572 if(read_host_config(myself))
574 syslog(LOG_ERR, _("Cannot open host configuration file for myself!"));
578 if(!(cfg = get_config_val(myself->config, port)))
581 myself->port = cfg->data.val;
583 if((cfg = get_config_val(myself->config, indirectdata)))
584 if(cfg->data.val == stupid_true)
585 myself->flags |= EXPORTINDIRECTDATA;
587 if((cfg = get_config_val(myself->config, tcponly)))
588 if(cfg->data.val == stupid_true)
589 myself->flags |= TCPONLY;
591 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
593 syslog(LOG_ERR, _("Unable to set up a listening socket"));
597 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
599 syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
600 close(myself->meta_socket);
604 myself->status.active = 1;
606 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
612 sigalrm_handler(int a)
616 /* FIXME! Use name instead of upstreamip.
617 cfg = get_next_config_val(config, upstreamip, upstreamindex++);
621 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
623 signal(SIGALRM, SIG_IGN);
626 // cfg = get_next_config_val(config, upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
629 signal(SIGALRM, sigalrm_handler);
631 seconds_till_retry += 5;
632 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
633 seconds_till_retry = MAXTIMEOUT;
634 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
636 alarm(seconds_till_retry);
641 setup all initial network connections
643 int setup_network_connections(void)
647 if((cfg = get_config_val(config, pingtimeout)) == NULL)
650 timeout = cfg->data.val;
652 if(setup_tap_fd() < 0)
655 if(setup_myself() < 0)
658 // if((cfg = get_next_config_val(config, upstreamip, upstreamindex++)) == NULL)
659 /* No upstream IP given, we're listen only. */
664 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
666 // cfg = get_next_config_val(config, upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
669 signal(SIGALRM, sigalrm_handler);
671 seconds_till_retry = MAXTIMEOUT;
672 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
673 alarm(seconds_till_retry);
679 close all open network connections
681 void close_network_connections(void)
685 for(p = conn_list; p != NULL; p = p->next)
687 if(p->status.dataopen)
689 shutdown(p->socket, 0); /* No more receptions */
695 shutdown(p->meta_socket, 0); /* No more receptions */
696 close(p->meta_socket);
701 if(myself->status.active)
703 close(myself->meta_socket);
704 close(myself->socket);
710 syslog(LOG_NOTICE, _("Terminating"));
716 create a data (udp) socket
718 int setup_vpn_connection(conn_list_t *cl)
721 struct sockaddr_in a;
724 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
726 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
729 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
733 a.sin_family = AF_INET;
734 a.sin_port = htons(cl->port);
735 a.sin_addr.s_addr = htonl(cl->address);
737 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
739 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
740 cl->hostname, cl->port);
744 flags = fcntl(nfd, F_GETFL);
745 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
747 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
748 cl->name, cl->hostname);
753 cl->status.dataopen = 1;
759 handle an incoming tcp connect call and open
762 conn_list_t *create_new_connection(int sfd)
765 struct sockaddr_in ci;
766 int len = sizeof(ci);
770 if(getpeername(sfd, &ci, &len) < 0)
772 syslog(LOG_ERR, _("Error: getpeername: %m"));
776 p->address = ntohl(ci.sin_addr.s_addr);
777 p->hostname = hostlookup(ci.sin_addr.s_addr);
778 p->meta_socket = sfd;
781 p->last_ping_time = time(NULL);
785 syslog(LOG_NOTICE, _("Connection from %s port %d"),
786 p->hostname, htons(ci.sin_port));
798 put all file descriptors in an fd_set array
800 void build_fdset(fd_set *fs)
806 for(p = conn_list; p != NULL; p = p->next)
809 FD_SET(p->meta_socket, fs);
810 if(p->status.dataopen)
811 FD_SET(p->socket, fs);
814 FD_SET(myself->meta_socket, fs);
815 FD_SET(myself->socket, fs);
821 receive incoming data from the listening
822 udp socket and write it to the ethertap
823 device after being decrypted
825 int handle_incoming_vpn_data()
829 int x, l = sizeof(x);
831 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
833 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
834 __FILE__, __LINE__, myself->socket);
839 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
843 if(recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, NULL, NULL) <= 0)
845 syslog(LOG_ERR, _("Receiving packet failed: %m"));
854 terminate a connection and notify the other
855 end before closing the sockets
857 void terminate_connection(conn_list_t *cl)
862 if(cl->status.remove)
866 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
867 cl->name, cl->hostname);
872 close(cl->meta_socket);
874 cl->status.remove = 1;
876 /* If this cl isn't active, don't send any DEL_HOSTs. */
878 /* FIXME: reprogram this.
879 if(cl->status.active)
880 notify_others(cl,NULL,send_del_host);
884 /* Find all connections that were lost because they were behind cl
885 (the connection that was dropped). */
887 for(p = conn_list; p != NULL; p = p->next)
889 if((p->nexthop == cl) && (p != cl))
891 if(cl->status.active && p->status.active)
892 /* FIXME: reprogram this
893 notify_others(p,cl,send_del_host);
897 p->status.active = 0;
898 p->status.remove = 1;
902 cl->status.active = 0;
904 if(cl->status.outgoing)
906 signal(SIGALRM, sigalrm_handler);
907 seconds_till_retry = 5;
908 alarm(seconds_till_retry);
909 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
915 Check if the other end is active.
916 If we have sent packets, but didn't receive any,
917 then possibly the other end is dead. We send a
918 PING request over the meta connection. If the other
919 end does not reply in time, we consider them dead
920 and close the connection.
922 int check_dead_connections(void)
928 for(p = conn_list; p != NULL; p = p->next)
932 if(p->status.active && p->status.meta)
934 if(p->last_ping_time + timeout < now)
936 if(p->status.pinged && !p->status.got_pong)
939 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
940 p->name, p->hostname);
941 p->status.timeout = 1;
942 terminate_connection(p);
944 else if(p->want_ping)
947 p->last_ping_time = now;
948 p->status.pinged = 1;
949 p->status.got_pong = 0;
959 accept a new tcp connect and create a
962 int handle_new_meta_connection()
965 struct sockaddr client;
966 int nfd, len = sizeof(client);
968 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
970 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
974 if(!(ncn = create_new_connection(nfd)))
978 syslog(LOG_NOTICE, _("Closed attempted connection"));
982 ncn->status.meta = 1;
983 ncn->next = conn_list;
990 check all connections to see if anything
991 happened on their sockets
993 void check_network_activity(fd_set *f)
996 int x, l = sizeof(x);
998 for(p = conn_list; p != NULL; p = p->next)
1000 if(p->status.remove)
1003 if(p->status.dataopen)
1004 if(FD_ISSET(p->socket, f))
1007 The only thing that can happen to get us here is apparently an
1008 error on this outgoing(!) UDP socket that isn't immediate (i.e.
1009 something that will not trigger an error directly on send()).
1010 I've once got here when it said `No route to host'.
1012 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1013 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1014 p->name, p->hostname, strerror(x));
1015 terminate_connection(p);
1020 if(FD_ISSET(p->meta_socket, f))
1021 if(receive_meta(p) < 0)
1023 terminate_connection(p);
1028 if(FD_ISSET(myself->socket, f))
1029 handle_incoming_vpn_data();
1031 if(FD_ISSET(myself->meta_socket, f))
1032 handle_new_meta_connection();
1037 read, encrypt and send data that is
1038 available through the ethertap device
1040 void handle_tap_input(void)
1044 int ether_type, lenin;
1046 memset(&vp, 0, sizeof(vp));
1047 if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1049 syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1053 total_tap_in += lenin;
1055 ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1056 if(ether_type != 0x0800)
1059 syslog(LOG_INFO, _("Non-IP ethernet frame %04x from %02x:%02x:%02x:%02x:%02x:%02x"), ether_type, MAC_ADDR_V(vp.data[6]));
1066 syslog(LOG_INFO, _("Dropping short packet from %02x:%02x:%02x:%02x:%02x:%02x"), MAC_ADDR_V(vp.data[6]));
1070 from = ntohl(*((unsigned long*)(&vp.data[26])));
1071 to = ntohl(*((unsigned long*)(&vp.data[30])));
1073 vp.len = (length_t)lenin - 2;
1075 strip_mac_addresses(&vp);
1077 send_packet(to, &vp);
1082 this is where it all happens...
1084 void main_loop(void)
1089 time_t last_ping_check;
1091 last_ping_check = time(NULL);
1095 tv.tv_sec = timeout;
1101 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1103 if(errno != EINTR) /* because of alarm */
1105 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1113 /* FIXME: reprogram this.
1115 syslog(LOG_INFO, _("Rereading configuration file"));
1116 close_network_connections();
1118 if(read_config_file(&config, configfilename))
1120 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1124 setup_network_connections();
1129 if(last_ping_check + timeout < time(NULL))
1130 /* Let's check if everybody is still alive */
1132 check_dead_connections();
1133 last_ping_check = time(NULL);
1138 check_network_activity(&fset);
1140 /* local tap data */
1141 if(FD_ISSET(tap_fd, &fset))