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.33 2000/05/30 12:31:41 zarq 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 static int seconds_till_retry;
61 /* The global list of existing connections */
62 conn_list_t *conn_list = NULL;
63 conn_list_t *myself = NULL;
66 strip off the MAC adresses of an ethernet frame
68 void strip_mac_addresses(vpn_packet_t *p)
70 unsigned char tmp[MAXSIZE];
72 memcpy(tmp, p->data, p->len);
74 memcpy(p->data, &tmp[12], p->len);
79 reassemble MAC addresses
81 void add_mac_addresses(vpn_packet_t *p)
83 unsigned char tmp[MAXSIZE];
85 memcpy(&tmp[12], p->data, p->len);
87 tmp[0] = tmp[6] = 0xfe;
88 tmp[1] = tmp[7] = 0xfd;
89 *((ip_t*)(&tmp[2])) = (ip_t)(htonl(myself->vpn_ip));
90 *((ip_t*)(&tmp[8])) = *((ip_t*)(&tmp[26]));
91 memcpy(p->data, &tmp[0], p->len);
95 int xsend(conn_list_t *cl, void *packet)
100 do_encrypt((vpn_packet_t*)packet, &rp, cl->key);
101 rp.from = htonl(myself->vpn_ip);
102 rp.data.len = htons(rp.data.len);
103 rp.len = htons(rp.len);
106 syslog(LOG_ERR, _("Sent %d bytes to %lx"), ntohs(rp.len), cl->vpn_ip);
108 if((r = send(cl->socket, (char*)&rp, ntohs(rp.len), 0)) < 0)
110 syslog(LOG_ERR, _("Error sending data: %m"));
114 total_socket_out += r;
121 int xrecv(conn_list_t *cl, void *packet)
126 do_decrypt((real_packet_t*)packet, &vp, cl->key);
127 add_mac_addresses(&vp);
129 if((lenin = write(tap_fd, &vp, vp.len + sizeof(vp.len))) < 0)
130 syslog(LOG_ERR, _("Can't write to tap device: %m"));
132 total_tap_out += lenin;
135 cl->last_ping_time = time(NULL);
141 add the given packet of size s to the
142 queue q, be it the send or receive queue
144 void add_queue(packet_queue_t **q, void *packet, size_t s)
149 syslog(LOG_DEBUG, _("packet to queue: %d"), 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 " IP_ADDR_S),
252 IP_ADDR_V(cl->vpn_ip));
253 flush_queue(cl, &(cl->sq), xsend);
259 syslog(LOG_DEBUG, _("Flushing receive queue for " IP_ADDR_S),
260 IP_ADDR_V(cl->vpn_ip));
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(to)) == NULL)
277 syslog(LOG_NOTICE, _("trying to look up " IP_ADDR_S " in connection list failed."),
280 for(cl = conn_list; cl != NULL && !cl->status.outgoing; cl = cl->next);
282 { /* No open outgoing connection has been found. */
284 syslog(LOG_NOTICE, _("There is no remote host I can send this packet to."));
289 if(my_key_expiry <= time(NULL))
292 if(!cl->status.dataopen)
293 if(setup_vpn_connection(cl) < 0)
296 if(!cl->status.validkey)
298 add_queue(&(cl->sq), packet, packet->len + 2);
299 if(!cl->status.waitingforkey)
300 send_key_request(cl->vpn_ip); /* Keys should be sent to the host running the tincd */
304 if(!cl->status.active)
306 add_queue(&(cl->sq), packet, packet->len + 2);
308 syslog(LOG_INFO, _(IP_ADDR_S " is not ready, queueing packet."), IP_ADDR_V(cl->vpn_ip));
309 return 0; /* We don't want to mess up, do we? */
312 /* can we send it? can we? can we? huh? */
314 return xsend(cl, packet);
318 open the local ethertap device
320 int setup_tap_fd(void)
323 const char *tapfname;
326 if((cfg = get_config_val(tapdevice)) == NULL)
327 tapfname = "/dev/tap0";
329 tapfname = cfg->data.ptr;
331 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
333 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
343 set up the socket that we listen on for incoming
346 int setup_listen_meta_socket(int port)
349 struct sockaddr_in a;
352 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
354 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
358 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
360 syslog(LOG_ERR, _("setsockopt: %m"));
364 flags = fcntl(nfd, F_GETFL);
365 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
367 syslog(LOG_ERR, _("fcntl: %m"));
371 memset(&a, 0, sizeof(a));
372 a.sin_family = AF_INET;
373 a.sin_port = htons(port);
374 a.sin_addr.s_addr = htonl(INADDR_ANY);
376 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
378 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
384 syslog(LOG_ERR, _("listen: %m"));
392 setup the socket for incoming encrypted
395 int setup_vpn_in_socket(int port)
398 struct sockaddr_in a;
401 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
403 syslog(LOG_ERR, _("Creating socket failed: %m"));
407 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
409 syslog(LOG_ERR, _("setsockopt: %m"));
413 flags = fcntl(nfd, F_GETFL);
414 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
416 syslog(LOG_ERR, _("fcntl: %m"));
420 memset(&a, 0, sizeof(a));
421 a.sin_family = AF_INET;
422 a.sin_port = htons(port);
423 a.sin_addr.s_addr = htonl(INADDR_ANY);
425 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
427 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
435 setup an outgoing meta (tcp) socket
437 int setup_outgoing_meta_socket(conn_list_t *cl)
440 struct sockaddr_in a;
443 if((cfg = get_config_val(upstreamport)) == NULL)
446 cl->port = cfg->data.val;
448 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
449 if(cl->meta_socket == -1)
451 syslog(LOG_ERR, _("Creating socket failed: %m"));
455 a.sin_family = AF_INET;
456 a.sin_port = htons(cl->port);
457 a.sin_addr.s_addr = htonl(cl->real_ip);
459 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
461 syslog(LOG_ERR, _(IP_ADDR_S ":%d: %m"), IP_ADDR_V(cl->real_ip), cl->port);
465 flags = fcntl(cl->meta_socket, F_GETFL);
466 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
468 syslog(LOG_ERR, _("fcntl: %m"));
472 cl->hostname = hostlookup(htonl(cl->real_ip));
474 syslog(LOG_INFO, _("Connected to %s:%hd"), cl->hostname, cl->port);
480 setup an outgoing connection. It's not
481 necessary to also open an udp socket as
482 well, because the other host will initiate
483 an authentication sequence during which
484 we will do just that.
486 int setup_outgoing_connection(ip_t ip)
490 ncn = new_conn_list();
493 if(setup_outgoing_meta_socket(ncn) < 0)
495 syslog(LOG_ERR, _("Could not set up a meta connection."));
496 free_conn_element(ncn);
500 ncn->status.meta = 1;
501 ncn->status.outgoing = 1;
502 ncn->next = conn_list;
509 set up the local sockets (listen only)
511 int setup_myself(void)
515 myself = new_conn_list();
517 if(!(cfg = get_config_val(myvpnip)))
519 syslog(LOG_ERR, _("No value for my VPN IP given"));
523 myself->vpn_ip = cfg->data.ip->ip;
524 myself->vpn_mask = cfg->data.ip->mask;
526 if(!(cfg = get_config_val(listenport)))
529 myself->port = cfg->data.val;
531 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
533 syslog(LOG_ERR, _("Unable to set up a listening socket"));
537 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
539 syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
540 close(myself->meta_socket);
544 myself->status.active = 1;
546 syslog(LOG_NOTICE, _("Ready: listening on port %d."), myself->port);
552 sigalrm_handler(int a)
556 cfg = get_config_val(upstreamip);
558 if(!setup_outgoing_connection(cfg->data.ip->ip))
560 signal(SIGALRM, SIG_IGN);
564 signal(SIGALRM, sigalrm_handler);
565 seconds_till_retry += 5;
566 if(seconds_till_retry>300) /* Don't wait more than 5 minutes. */
567 seconds_till_retry = 300;
568 alarm(seconds_till_retry);
569 syslog(LOG_ERR, _("Still failed to connect to other. Will retry in %d seconds."),
576 setup all initial network connections
578 int setup_network_connections(void)
582 if((cfg = get_config_val(pingtimeout)) == NULL)
585 timeout = cfg->data.val;
587 if(setup_tap_fd() < 0)
590 if(setup_myself() < 0)
593 if((cfg = get_config_val(upstreamip)) == NULL)
594 /* No upstream IP given, we're listen only. */
597 if(setup_outgoing_connection(cfg->data.ip->ip))
599 signal(SIGALRM, sigalrm_handler);
600 seconds_till_retry = 300;
601 alarm(seconds_till_retry);
602 syslog(LOG_NOTICE, _("Try to re-establish outgoing connection in 5 minutes."));
609 close all open network connections
611 void close_network_connections(void)
615 for(p = conn_list; p != NULL; p = p->next)
617 if(p->status.dataopen)
619 shutdown(p->socket, 0); /* No more receptions */
625 shutdown(p->meta_socket, 0); /* No more receptions */
626 close(p->meta_socket);
631 if(myself->status.active)
633 close(myself->meta_socket);
634 close(myself->socket);
640 syslog(LOG_NOTICE, _("Terminating."));
646 create a data (udp) socket
648 int setup_vpn_connection(conn_list_t *cl)
651 struct sockaddr_in a;
654 syslog(LOG_DEBUG, _("Opening UDP socket to " IP_ADDR_S), IP_ADDR_V(cl->real_ip));
656 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
659 syslog(LOG_ERR, _("Creating data socket failed: %m"));
663 a.sin_family = AF_INET;
664 a.sin_port = htons(cl->port);
665 a.sin_addr.s_addr = htonl(cl->real_ip);
667 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
669 syslog(LOG_ERR, _("Connecting to " IP_ADDR_S ":%d failed: %m"),
670 IP_ADDR_V(cl->real_ip), cl->port);
674 flags = fcntl(nfd, F_GETFL);
675 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
677 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, nfd);
682 cl->status.dataopen = 1;
688 handle an incoming tcp connect call and open
691 conn_list_t *create_new_connection(int sfd)
694 struct sockaddr_in ci;
695 int len = sizeof(ci);
699 if(getpeername(sfd, &ci, &len) < 0)
701 syslog(LOG_ERR, _("Error: getpeername: %m"));
705 p->hostname = hostlookup(ci.sin_addr.s_addr);
706 p->real_ip = ntohl(ci.sin_addr.s_addr);
707 p->meta_socket = sfd;
710 p->last_ping_time = time(NULL);
713 syslog(LOG_NOTICE, _("Connection from %s:%d"), p->hostname, htons(ci.sin_port));
715 if(send_basic_info(p) < 0)
725 put all file descriptors in an fd_set array
727 void build_fdset(fd_set *fs)
733 for(p = conn_list; p != NULL; p = p->next)
736 FD_SET(p->meta_socket, fs);
737 if(p->status.dataopen)
738 FD_SET(p->socket, fs);
741 FD_SET(myself->meta_socket, fs);
742 FD_SET(myself->socket, fs);
748 receive incoming data from the listening
749 udp socket and write it to the ethertap
750 device after being decrypted
752 int handle_incoming_vpn_data(conn_list_t *cl)
756 int x, l = sizeof(x);
759 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
761 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->socket);
766 syslog(LOG_ERR, _("Incoming data socket error: %s"), sys_errlist[x]);
771 lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
774 syslog(LOG_ERR, _("Receiving data failed: %m"));
777 total_socket_in += lenin;
779 rp.data.len = ntohs(rp.data.len);
780 rp.len = ntohs(rp.len);
781 rp.from = ntohl(rp.from);
785 f = lookup_conn(rp.from);
787 syslog(LOG_DEBUG, _("packet from " IP_ADDR_S " (len %d)"),
788 IP_ADDR_V(rp.from), rp.len);
791 syslog(LOG_ERR, _("Got packet from unknown source " IP_ADDR_S),
796 if(f->status.validkey)
800 add_queue(&(f->rq), &rp, rp.len);
801 if(!cl->status.waitingforkey)
802 send_key_request(rp.from);
805 if(my_key_expiry <= time(NULL))
813 terminate a connection and notify the other
814 end before closing the sockets
816 void terminate_connection(conn_list_t *cl)
821 if(cl->status.remove)
825 syslog(LOG_NOTICE, _("Closing connection with %s."), cl->hostname);
827 if(cl->status.timeout)
829 else if(!cl->status.termreq)
834 close(cl->meta_socket);
836 if(cl->status.outgoing)
838 signal(SIGALRM, sigalrm_handler);
839 seconds_till_retry = 5;
840 alarm(seconds_till_retry);
841 syslog(LOG_NOTICE, _("Try to re-establish outgoing connection in 5 seconds."));
844 cl->status.active = 0;
845 cl->status.remove = 1;
848 /* Find all connections that were lost because they were behind cl
849 (the connection that was dropped). */
850 for(p = conn_list; p != NULL; p = p->next)
854 p->status.active = 0;
855 p->status.remove = 1;
860 /* Then send a notification about all these connections to all hosts
861 that are still connected to us. */
862 for(p = conn_list; p != NULL; p = p->next)
864 if(!p->status.remove)
865 for(q = conn_list; q != NULL; q = q->next)
873 Check if the other end is active.
874 If we have sent packets, but didn't receive any,
875 then possibly the other end is dead. We send a
876 PING request over the meta connection. If the other
877 end does not reply in time, we consider them dead
878 and close the connection.
880 int check_dead_connections(void)
886 for(p = conn_list; p != NULL; p = p->next)
890 if(p->status.active && p->status.meta)
892 if(p->last_ping_time + timeout < now)
894 if(p->status.pinged && !p->status.got_pong)
896 syslog(LOG_INFO, _("%s (" IP_ADDR_S ") didn't respond to ping"),
897 p->hostname, IP_ADDR_V(p->vpn_ip));
898 p->status.timeout = 1;
899 terminate_connection(p);
901 else if(p->want_ping)
904 p->last_ping_time = now;
905 p->status.pinged = 1;
906 p->status.got_pong = 0;
916 accept a new tcp connect and create a
919 int handle_new_meta_connection(conn_list_t *cl)
922 struct sockaddr client;
923 int nfd, len = sizeof(client);
925 if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
927 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
931 if((ncn = create_new_connection(nfd)) == NULL)
935 syslog(LOG_NOTICE, _("Closed attempted connection."));
939 ncn->status.meta = 1;
940 ncn->next = conn_list;
947 dispatch any incoming meta requests
949 int handle_incoming_meta_data(conn_list_t *cl)
951 int x, l = sizeof(x);
952 int request, oldlen, i;
955 if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
957 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->meta_socket);
962 syslog(LOG_ERR, _("Metadata socket error: %s"), sys_errlist[x]);
966 if(cl->buflen >= MAXBUFSIZE)
968 syslog(LOG_ERR, _("Metadata read buffer overflow."));
972 lenin = read(cl->meta_socket, cl->buffer, MAXBUFSIZE-cl->buflen);
976 syslog(LOG_ERR, _("Metadata socket read error: %m"));
987 for(i = oldlen; i < cl->buflen; i++)
989 if(cl->buffer[i] == '\n')
991 cl->buffer[i] = 0; /* replace end-of-line by end-of-string so we can use sscanf */
999 if(sscanf(cl->buffer, "%d", &request) == 1)
1001 if((request < 0) || (request > 255) || (request_handlers[request] == NULL))
1003 syslog(LOG_ERR, _("Unknown request: %s"), cl->buffer);
1008 syslog(LOG_DEBUG, _("Got request: %s"), cl->buffer);
1010 if(request_handlers[request](cl)) /* Something went wrong. Probably scriptkiddies. Terminate. */
1012 syslog(LOG_ERR, _("Error while processing request from " IP_ADDR_S), IP_ADDR_V(cl->real_ip));
1018 syslog(LOG_ERR, _("Bogus data received."));
1022 cl->buflen -= cl->reqlen;
1023 memmove(cl->buffer, cl->buffer + cl->reqlen, cl->buflen);
1032 cl->last_ping_time = time(NULL);
1039 check all connections to see if anything
1040 happened on their sockets
1042 void check_network_activity(fd_set *f)
1045 int x, l = sizeof(x);
1047 for(p = conn_list; p != NULL; p = p->next)
1049 if(p->status.remove)
1052 if(p->status.dataopen)
1053 if(FD_ISSET(p->socket, f))
1056 The only thing that can happen to get us here is apparently an
1057 error on this outgoing(!) UDP socket that isn't immediate (i.e.
1058 something that will not trigger an error directly on send()).
1059 I've once got here when it said `No route to host'.
1061 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1062 syslog(LOG_ERR, _("Outgoing data socket error: %s"), sys_errlist[x]);
1063 terminate_connection(p);
1068 if(FD_ISSET(p->meta_socket, f))
1069 if(handle_incoming_meta_data(p) < 0)
1071 terminate_connection(p);
1076 if(FD_ISSET(myself->socket, f))
1077 handle_incoming_vpn_data(myself);
1079 if(FD_ISSET(myself->meta_socket, f))
1080 handle_new_meta_connection(myself);
1085 read, encrypt and send data that is
1086 available through the ethertap device
1088 void handle_tap_input(void)
1092 int ether_type, lenin;
1094 memset(&vp, 0, sizeof(vp));
1095 if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1097 syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1101 total_tap_in += lenin;
1103 ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1104 if(ether_type != 0x0800)
1107 syslog(LOG_INFO, _("Non-IP ethernet frame %04x from " MAC_ADDR_S),
1108 ether_type, MAC_ADDR_V(vp.data[6]));
1115 syslog(LOG_INFO, _("Dropping short packet"));
1119 from = ntohl(*((unsigned long*)(&vp.data[26])));
1120 to = ntohl(*((unsigned long*)(&vp.data[30])));
1123 syslog(LOG_DEBUG, _("An IP packet (%04x) for " IP_ADDR_S " from " IP_ADDR_S),
1124 ether_type, IP_ADDR_V(to), IP_ADDR_V(from));
1126 syslog(LOG_DEBUG, _(MAC_ADDR_S " to " MAC_ADDR_S),
1127 MAC_ADDR_V(vp.data[0]), MAC_ADDR_V(vp.data[6]));
1129 vp.len = (length_t)lenin - 2;
1131 strip_mac_addresses(&vp);
1133 send_packet(to, &vp);
1138 this is where it all happens...
1140 void main_loop(void)
1145 time_t last_ping_check;
1147 last_ping_check = time(NULL);
1151 tv.tv_sec = timeout;
1157 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1159 if(errno == EINTR) /* because of alarm */
1161 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1165 if(last_ping_check + timeout < time(NULL))
1166 /* Let's check if everybody is still alive */
1168 check_dead_connections();
1169 last_ping_check = time(NULL);
1173 check_network_activity(&fset);
1175 /* local tap data */
1176 if(FD_ISSET(tap_fd, &fset))