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.34 2000/10/11 22:00:58 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;
62 /* The global list of existing connections */
63 conn_list_t *conn_list = NULL;
64 conn_list_t *myself = NULL;
67 strip off the MAC adresses of an ethernet frame
69 void strip_mac_addresses(vpn_packet_t *p)
72 memmove(p->data, p->data + 12, p->len -= 12);
77 reassemble MAC addresses
79 void add_mac_addresses(vpn_packet_t *p)
82 memcpy(p->data + 12, p->data, p->len);
84 p->data[0] = p->data[6] = 0xfe;
85 p->data[1] = p->data[7] = 0xfd;
86 /* Really evil pointer stuff just below! */
87 *((ip_t*)(&p->data[2])) = (ip_t)(htonl(myself->address));
88 *((ip_t*)(&p->data[8])) = *((ip_t*)(&p->data[26]));
92 int xsend(conn_list_t *cl, vpn_packet_t *inpkt)
97 outpkt.len = inpkt->len;
98 EVP_EncryptInit(cl->cipher_pktctx, cl->cipher_pkttype, cl->cipher_pktkey, cl->cipher_pktiv);
99 EVP_EncryptUpdate(cl->cipher_pktctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
100 EVP_EncryptFinal(cl->cipher_pktctx, outpkt.data + outlen, &outpad);
104 syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
105 outlen, cl->name, cl->hostname);
107 total_socket_out += outlen;
111 if((send(cl->socket, (char *) &(outpkt.len), outlen + 2, 0)) < 0)
113 syslog(LOG_ERR, _("Error sending packet to %s (%s): %m"),
114 cl->name, cl->hostname);
121 int xrecv(vpn_packet_t *inpkt)
127 syslog(LOG_ERR, _("Receiving packet of %d bytes"),
130 outpkt.len = inpkt->len;
131 EVP_DecryptInit(myself->cipher_pktctx, myself->cipher_pkttype, myself->cipher_pktkey, myself->cipher_pktiv);
132 EVP_DecryptUpdate(myself->cipher_pktctx, outpkt.data, &outlen, inpkt->data, inpkt->len);
133 /* FIXME: grok DecryptFinal
134 EVP_DecryptFinal(myself->cipher_pktctx, outpkt.data + outlen, &outpad);
137 add_mac_addresses(&outpkt);
139 if(write(tap_fd, outpkt.data, outpkt.len) < 0)
140 syslog(LOG_ERR, _("Can't write to tap device: %m"));
142 total_tap_out += outpkt.len;
148 add the given packet of size s to the
149 queue q, be it the send or receive queue
151 void add_queue(packet_queue_t **q, void *packet, size_t s)
155 e = xmalloc(sizeof(*e));
156 e->packet = xmalloc(s);
157 memcpy(e->packet, packet, s);
161 *q = xmalloc(sizeof(**q));
162 (*q)->head = (*q)->tail = NULL;
165 e->next = NULL; /* We insert at the tail */
167 if((*q)->tail) /* Do we have a tail? */
169 (*q)->tail->next = e;
170 e->prev = (*q)->tail;
172 else /* No tail -> no head too */
182 /* Remove a queue element */
183 void del_queue(packet_queue_t **q, queue_element_t *e)
188 if(e->next) /* There is a successor, so we are not tail */
190 if(e->prev) /* There is a predecessor, so we are not head */
192 e->next->prev = e->prev;
193 e->prev->next = e->next;
195 else /* We are head */
197 e->next->prev = NULL;
198 (*q)->head = e->next;
201 else /* We are tail (or all alone!) */
203 if(e->prev) /* We are not alone :) */
205 e->prev->next = NULL;
206 (*q)->tail = e->prev;
220 flush a queue by calling function for
221 each packet, and removing it when that
222 returned a zero exit code
224 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
225 int (*function)(conn_list_t*,void*))
227 queue_element_t *p, *next = NULL;
229 for(p = (*pq)->head; p != NULL; )
233 if(!function(cl, p->packet))
240 syslog(LOG_DEBUG, _("Queue flushed"));
245 flush the send&recv queues
246 void because nothing goes wrong here, packets
247 remain in the queue if something goes wrong
249 void flush_queues(conn_list_t *cl)
255 syslog(LOG_DEBUG, _("Flushing send queue for %s (%s)"),
256 cl->name, cl->hostname);
257 flush_queue(cl, &(cl->sq), xsend);
263 syslog(LOG_DEBUG, _("Flushing receive queue for %s (%s)"),
264 cl->name, cl->hostname);
265 flush_queue(cl, &(cl->rq), xrecv);
271 send a packet to the given vpn ip.
273 int send_packet(ip_t to, vpn_packet_t *packet)
277 if((cl = lookup_conn_list_ipv4(to)) == NULL)
281 syslog(LOG_NOTICE, _("Trying to look up %d.%d.%d.%d in connection list failed!"),
288 /* If we ourselves have indirectdata flag set, we should send only to our uplink! */
290 /* FIXME - check for indirection and reprogram it The Right Way(tm) this time. */
292 if(my_key_expiry <= time(NULL))
295 if(!cl->status.dataopen)
296 if(setup_vpn_connection(cl) < 0)
298 syslog(LOG_ERR, _("Could not open UDP connection to %s (%s)"),
299 cl->name, cl->hostname);
303 if(!cl->status.validkey)
306 syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
307 cl->name, cl->hostname);
308 add_queue(&(cl->sq), packet, packet->len + 2);
309 if(!cl->status.waitingforkey)
310 send_req_key(myself, cl); /* Keys should be sent to the host running the tincd */
314 if(!cl->status.active)
317 syslog(LOG_INFO, _("%s (%s) is not ready, queueing packet"),
318 cl->name, cl->hostname);
319 add_queue(&(cl->sq), packet, packet->len + 2);
320 return 0; /* We don't want to mess up, do we? */
323 /* can we send it? can we? can we? huh? */
325 return xsend(cl, packet);
329 open the local ethertap device
331 int setup_tap_fd(void)
334 const char *tapfname;
337 if((cfg = get_config_val(config, tapdevice)) == NULL)
338 tapfname = "/dev/tap0";
340 tapfname = cfg->data.ptr;
342 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
344 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
354 set up the socket that we listen on for incoming
357 int setup_listen_meta_socket(int port)
360 struct sockaddr_in a;
364 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
366 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
370 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
372 syslog(LOG_ERR, _("setsockopt: %m"));
376 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)))
378 syslog(LOG_ERR, _("setsockopt: %m"));
382 flags = fcntl(nfd, F_GETFL);
383 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
385 syslog(LOG_ERR, _("fcntl: %m"));
389 if((cfg = get_config_val(config, interface)))
391 if(setsockopt(nfd, SOL_SOCKET, SO_KEEPALIVE, cfg->data.ptr, strlen(cfg->data.ptr)))
393 syslog(LOG_ERR, _("Unable to bind listen socket to interface %s: %m"), cfg->data.ptr);
398 memset(&a, 0, sizeof(a));
399 a.sin_family = AF_INET;
400 a.sin_port = htons(port);
402 if((cfg = get_config_val(config, interfaceip)))
403 a.sin_addr.s_addr = htonl(cfg->data.ip->ip);
405 a.sin_addr.s_addr = htonl(INADDR_ANY);
407 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
409 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
415 syslog(LOG_ERR, _("listen: %m"));
423 setup the socket for incoming encrypted
426 int setup_vpn_in_socket(int port)
429 struct sockaddr_in a;
432 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
434 syslog(LOG_ERR, _("Creating socket failed: %m"));
438 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
440 syslog(LOG_ERR, _("setsockopt: %m"));
444 flags = fcntl(nfd, F_GETFL);
445 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
447 syslog(LOG_ERR, _("fcntl: %m"));
451 memset(&a, 0, sizeof(a));
452 a.sin_family = AF_INET;
453 a.sin_port = htons(port);
454 a.sin_addr.s_addr = htonl(INADDR_ANY);
456 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
458 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
466 setup an outgoing meta (tcp) socket
468 int setup_outgoing_meta_socket(conn_list_t *cl)
471 struct sockaddr_in a;
475 syslog(LOG_INFO, _("Trying to connect to %s"), cl->hostname);
477 if((cfg = get_config_val(cl->config, port)) == NULL)
480 cl->port = cfg->data.val;
482 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
483 if(cl->meta_socket == -1)
485 syslog(LOG_ERR, _("Creating socket for %s port %d failed: %m"),
486 cl->hostname, cl->port);
490 a.sin_family = AF_INET;
491 a.sin_port = htons(cl->port);
492 a.sin_addr.s_addr = htonl(cl->address);
494 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
496 syslog(LOG_ERR, _("%s port %hd: %m"), cl->hostname, cl->port);
500 flags = fcntl(cl->meta_socket, F_GETFL);
501 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
503 syslog(LOG_ERR, _("fcntl for %s port %d: %m"),
504 cl->hostname, cl->port);
509 syslog(LOG_INFO, _("Connected to %s port %hd"),
510 cl->hostname, cl->port);
516 setup an outgoing connection. It's not
517 necessary to also open an udp socket as
518 well, because the other host will initiate
519 an authentication sequence during which
520 we will do just that.
522 int setup_outgoing_connection(char *hostname)
527 if(!(h = gethostbyname(hostname)))
529 syslog(LOG_ERR, _("Error looking up `%s': %m"), hostname);
533 ncn = new_conn_list();
534 ncn->address = ntohl(*((ip_t*)(h->h_addr_list[0])));
535 ncn->hostname = hostlookup(htonl(ncn->address));
537 if(setup_outgoing_meta_socket(ncn) < 0)
539 syslog(LOG_ERR, _("Could not set up a meta connection to %s"),
541 free_conn_element(ncn);
545 ncn->status.meta = 1;
546 ncn->status.outgoing = 1;
547 ncn->next = conn_list;
554 set up the local sockets (listen only)
556 int setup_myself(void)
560 myself = new_conn_list();
562 myself->hostname = "MYSELF"; /* FIXME? */
565 if(!(cfg = get_config_val(config, tincname))) /* Not acceptable */
567 syslog(LOG_ERR, _("Name for tinc daemon required!"));
571 myself->name = (char*)cfg->data.val;
573 if(!(cfg = get_config_val(myself, port)))
576 myself->port = cfg->data.val;
578 if((cfg = get_config_val(config, indirectdata)))
579 if(cfg->data.val == stupid_true)
580 myself->flags |= EXPORTINDIRECTDATA;
582 if((cfg = get_config_val(config, tcponly)))
583 if(cfg->data.val == stupid_true)
584 myself->flags |= TCPONLY;
586 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
588 syslog(LOG_ERR, _("Unable to set up a listening socket"));
592 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
594 syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
595 close(myself->meta_socket);
599 myself->status.active = 1;
601 syslog(LOG_NOTICE, _("Ready: listening on port %hd"), myself->port);
607 sigalrm_handler(int a)
611 /* FIXME! Use name instead of upstreamip.
612 cfg = get_next_config_val(config, upstreamip, upstreamindex++);
616 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
618 signal(SIGALRM, SIG_IGN);
621 // cfg = get_next_config_val(config, upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
624 signal(SIGALRM, sigalrm_handler);
626 seconds_till_retry += 5;
627 if(seconds_till_retry > MAXTIMEOUT) /* Don't wait more than MAXTIMEOUT seconds. */
628 seconds_till_retry = MAXTIMEOUT;
629 syslog(LOG_ERR, _("Still failed to connect to other, will retry in %d seconds"),
631 alarm(seconds_till_retry);
636 setup all initial network connections
638 int setup_network_connections(void)
642 if((cfg = get_config_val(config, pingtimeout)) == NULL)
645 timeout = cfg->data.val;
647 if(setup_tap_fd() < 0)
650 if(setup_myself() < 0)
653 // if((cfg = get_next_config_val(config, upstreamip, upstreamindex++)) == NULL)
654 /* No upstream IP given, we're listen only. */
659 if(!setup_outgoing_connection(cfg->data.ptr)) /* function returns 0 when there are no problems */
661 // cfg = get_next_config_val(config, upstreamip, upstreamindex++); /* Or else we try the next ConnectTo line */
664 signal(SIGALRM, sigalrm_handler);
666 seconds_till_retry = MAXTIMEOUT;
667 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in %d seconds"), seconds_till_retry);
668 alarm(seconds_till_retry);
674 close all open network connections
676 void close_network_connections(void)
680 for(p = conn_list; p != NULL; p = p->next)
682 if(p->status.dataopen)
684 shutdown(p->socket, 0); /* No more receptions */
690 shutdown(p->meta_socket, 0); /* No more receptions */
691 close(p->meta_socket);
696 if(myself->status.active)
698 close(myself->meta_socket);
699 close(myself->socket);
705 syslog(LOG_NOTICE, _("Terminating"));
711 create a data (udp) socket
713 int setup_vpn_connection(conn_list_t *cl)
716 struct sockaddr_in a;
719 syslog(LOG_DEBUG, _("Opening UDP socket to %s"), cl->hostname);
721 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
724 syslog(LOG_ERR, _("Creating UDP socket failed: %m"));
728 a.sin_family = AF_INET;
729 a.sin_port = htons(cl->port);
730 a.sin_addr.s_addr = htonl(cl->address);
732 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
734 syslog(LOG_ERR, _("Connecting to %s port %d failed: %m"),
735 cl->hostname, cl->port);
739 flags = fcntl(nfd, F_GETFL);
740 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
742 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m %s (%s)"), __FILE__, __LINE__, nfd,
743 cl->name, cl->hostname);
748 cl->status.dataopen = 1;
754 handle an incoming tcp connect call and open
757 conn_list_t *create_new_connection(int sfd)
760 struct sockaddr_in ci;
761 int len = sizeof(ci);
765 if(getpeername(sfd, &ci, &len) < 0)
767 syslog(LOG_ERR, _("Error: getpeername: %m"));
771 p->address = ntohl(ci.sin_addr.s_addr);
772 p->hostname = hostlookup(ci.sin_addr.s_addr);
773 p->meta_socket = sfd;
776 p->last_ping_time = time(NULL);
780 syslog(LOG_NOTICE, _("Connection from %s port %d"),
781 p->hostname, htons(ci.sin_port));
783 if(send_basic_info(p) < 0)
785 free_conn_element(p);
793 put all file descriptors in an fd_set array
795 void build_fdset(fd_set *fs)
801 for(p = conn_list; p != NULL; p = p->next)
804 FD_SET(p->meta_socket, fs);
805 if(p->status.dataopen)
806 FD_SET(p->socket, fs);
809 FD_SET(myself->meta_socket, fs);
810 FD_SET(myself->socket, fs);
816 receive incoming data from the listening
817 udp socket and write it to the ethertap
818 device after being decrypted
820 int handle_incoming_vpn_data()
824 int x, l = sizeof(x);
826 if(getsockopt(myself->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
828 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"),
829 __FILE__, __LINE__, myself->socket);
834 syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
838 if(recvfrom(myself->socket, (char *) &(pkt.len), MTU, 0, NULL, NULL) <= 0)
840 syslog(LOG_ERR, _("Receiving packet failed: %m"));
849 terminate a connection and notify the other
850 end before closing the sockets
852 void terminate_connection(conn_list_t *cl)
857 if(cl->status.remove)
861 syslog(LOG_NOTICE, _("Closing connection with %s (%s)"),
862 cl->name, cl->hostname);
864 if(cl->status.timeout)
866 /* else if(!cl->status.termreq)
873 close(cl->meta_socket);
875 cl->status.remove = 1;
877 /* If this cl isn't active, don't send any DEL_HOSTs. */
878 if(cl->status.active)
879 notify_others(cl,NULL,send_del_host);
882 /* Find all connections that were lost because they were behind cl
883 (the connection that was dropped). */
885 for(p = conn_list; p != NULL; p = p->next)
887 if((p->nexthop == cl) && (p != cl))
889 if(cl->status.active && p->status.active)
890 notify_others(p,cl,send_del_host);
893 p->status.active = 0;
894 p->status.remove = 1;
898 cl->status.active = 0;
900 if(cl->status.outgoing)
902 signal(SIGALRM, sigalrm_handler);
903 seconds_till_retry = 5;
904 alarm(seconds_till_retry);
905 syslog(LOG_NOTICE, _("Trying to re-establish outgoing connection in 5 seconds"));
911 Check if the other end is active.
912 If we have sent packets, but didn't receive any,
913 then possibly the other end is dead. We send a
914 PING request over the meta connection. If the other
915 end does not reply in time, we consider them dead
916 and close the connection.
918 int check_dead_connections(void)
924 for(p = conn_list; p != NULL; p = p->next)
928 if(p->status.active && p->status.meta)
930 if(p->last_ping_time + timeout < now)
932 if(p->status.pinged && !p->status.got_pong)
935 syslog(LOG_INFO, _("%s (%s) didn't respond to PING"),
936 p->name, p->hostname);
937 p->status.timeout = 1;
938 terminate_connection(p);
940 else if(p->want_ping)
943 p->last_ping_time = now;
944 p->status.pinged = 1;
945 p->status.got_pong = 0;
955 accept a new tcp connect and create a
958 int handle_new_meta_connection()
961 struct sockaddr client;
962 int nfd, len = sizeof(client);
964 if((nfd = accept(myself->meta_socket, &client, &len)) < 0)
966 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
970 if(!(ncn = create_new_connection(nfd)))
974 syslog(LOG_NOTICE, _("Closed attempted connection"));
978 ncn->status.meta = 1;
979 ncn->next = conn_list;
986 check all connections to see if anything
987 happened on their sockets
989 void check_network_activity(fd_set *f)
992 int x, l = sizeof(x);
994 for(p = conn_list; p != NULL; p = p->next)
999 if(p->status.dataopen)
1000 if(FD_ISSET(p->socket, f))
1003 The only thing that can happen to get us here is apparently an
1004 error on this outgoing(!) UDP socket that isn't immediate (i.e.
1005 something that will not trigger an error directly on send()).
1006 I've once got here when it said `No route to host'.
1008 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1009 syslog(LOG_ERR, _("Outgoing data socket error for %s (%s): %s"),
1010 p->name, p->hostname, strerror(x));
1011 terminate_connection(p);
1016 if(FD_ISSET(p->meta_socket, f))
1017 if(receive_meta(p) < 0)
1019 terminate_connection(p);
1024 if(FD_ISSET(myself->socket, f))
1025 handle_incoming_vpn_data();
1027 if(FD_ISSET(myself->meta_socket, f))
1028 handle_new_meta_connection();
1033 read, encrypt and send data that is
1034 available through the ethertap device
1036 void handle_tap_input(void)
1040 int ether_type, lenin;
1042 memset(&vp, 0, sizeof(vp));
1043 if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1045 syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1049 total_tap_in += lenin;
1051 ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1052 if(ether_type != 0x0800)
1055 syslog(LOG_INFO, _("Non-IP ethernet frame %04x from %02x:%02x:%02x:%02x:%02x:%02x"), ether_type, MAC_ADDR_V(vp.data[6]));
1062 syslog(LOG_INFO, _("Dropping short packet from %02x:%02x:%02x:%02x:%02x:%02x"), MAC_ADDR_V(vp.data[6]));
1066 from = ntohl(*((unsigned long*)(&vp.data[26])));
1067 to = ntohl(*((unsigned long*)(&vp.data[30])));
1069 vp.len = (length_t)lenin - 2;
1071 strip_mac_addresses(&vp);
1073 send_packet(to, &vp);
1078 this is where it all happens...
1080 void main_loop(void)
1085 time_t last_ping_check;
1087 last_ping_check = time(NULL);
1091 tv.tv_sec = timeout;
1097 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1099 if(errno != EINTR) /* because of alarm */
1101 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1110 syslog(LOG_INFO, _("Rereading configuration file"));
1111 close_network_connections();
1113 if(read_config_file(&config, configfilename))
1115 syslog(LOG_ERR, _("Unable to reread configuration file, exiting"));
1119 setup_network_connections();
1123 if(last_ping_check + timeout < time(NULL))
1124 /* Let's check if everybody is still alive */
1126 check_dead_connections();
1127 last_ping_check = time(NULL);
1132 check_network_activity(&fset);
1134 /* local tap data */
1135 if(FD_ISSET(tap_fd, &fset))