2 net.c -- most of the network code
3 Copyright (C) 1998,99 Ivo Timmermans <zarq@iname.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include <arpa/inet.h>
26 #include <netinet/in.h>
30 #include <sys/signal.h>
31 #include <sys/socket.h>
33 #include <sys/types.h>
50 int total_tap_out = 0;
51 int total_socket_in = 0;
52 int total_socket_out = 0;
54 time_t last_ping_time = 0;
56 /* The global list of existing connections */
57 conn_list_t *conn_list = NULL;
58 conn_list_t *myself = NULL;
61 strip off the MAC adresses of an ethernet frame
63 void strip_mac_addresses(vpn_packet_t *p)
65 unsigned char tmp[MAXSIZE];
67 memcpy(tmp, p->data, p->len);
69 memcpy(p->data, &tmp[12], p->len);
74 reassemble MAC addresses
76 void add_mac_addresses(vpn_packet_t *p)
78 unsigned char tmp[MAXSIZE];
80 memcpy(&tmp[12], p->data, p->len);
82 tmp[0] = tmp[6] = 0xfe;
83 tmp[1] = tmp[7] = 0xfd;
84 *((ip_t*)(&tmp[2])) = (ip_t)(htonl(myself->vpn_ip));
85 *((ip_t*)(&tmp[8])) = *((ip_t*)(&tmp[26]));
86 memcpy(p->data, &tmp[0], p->len);
90 int xsend(conn_list_t *cl, void *packet)
95 do_encrypt((vpn_packet_t*)packet, &rp, cl->key);
96 rp.from = myself->vpn_ip;
99 syslog(LOG_ERR, "Sent %d bytes to %lx", rp.len, cl->vpn_ip);
101 if((r = send(cl->socket, (char*)&rp, rp.len, 0)) < 0)
103 syslog(LOG_ERR, "Error sending data: %m");
107 total_socket_out += r;
113 write as many bytes as possible to the tap
114 device, possibly in multiple turns.
116 int write_n(int fd, void *buf, size_t len)
122 if((r = write(fd, buf, len)) < 0)
133 int xrecv(conn_list_t *cl, void *packet)
138 do_decrypt((real_packet_t*)packet, &vp, cl->key);
139 add_mac_addresses(&vp);
141 if((lenin = write_n(tap_fd, &vp, vp.len + 2)) < 0)
142 syslog(LOG_ERR, "Can't write to tap device: %m");
144 total_tap_out += lenin;
150 add the given packet of size s to the
151 queue q, be it the send or receive queue
153 void add_queue(packet_queue_t **q, void *packet, size_t s)
158 syslog(LOG_DEBUG, "packet to queue: %d", s);
160 e = xmalloc(sizeof(queue_element_t));
161 e->packet = xmalloc(s);
162 memcpy(e->packet, packet, s);
166 *q = xmalloc(sizeof(packet_queue_t));
167 (*q)->head = (*q)->tail = NULL;
170 e->next = NULL; /* We insert at the tail */
172 if((*q)->tail) /* Do we have a tail? */
174 (*q)->tail->next = e;
175 e->prev = (*q)->tail;
177 else /* No tail -> no head too */
187 /* Remove a queue element */
188 void del_queue(packet_queue_t **q, packet_element_t *e)
190 queue_element_t *p, *n;
194 if(e->next) /* There is a successor, so we are not tail */
196 if(e->prev) /* There is a predecessor, so we are not head */
198 e->next->prev = e->prev;
199 e->prev->next = e->next;
201 else /* We are head */
203 e->next->prev = NULL;
204 (*q)->head = e->next;
207 else /* We are tail (or all alone!) */
209 if(e->prev) /* We are not alone :) */
211 e->prev->next = NULL;
212 (*q)->tail = e->prev;
226 flush a queue by calling function for
227 each packet, and removing it when that
228 returned a zero exit code
230 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
231 int (*function)(conn_list_t*,void*))
233 queue_element_t *p, *prev = NULL, *next = NULL;
235 for(p = (*pq)->head; p != NULL; )
239 if(!function(cl, p->packet))
246 syslog(LOG_DEBUG, "queue flushed");
251 flush the send&recv queues
252 void because nothing goes wrong here, packets
253 remain in the queue if something goes wrong
255 void flush_queues(conn_list_t *cl)
261 syslog(LOG_DEBUG, "Flushing send queue for " IP_ADDR_S,
262 IP_ADDR_V(cl->vpn_ip));
263 flush_queue(cl, &(cl->sq), xsend);
269 syslog(LOG_DEBUG, "Flushing receive queue for " IP_ADDR_S,
270 IP_ADDR_V(cl->vpn_ip));
271 flush_queue(cl, &(cl->rq), xrecv);
277 send a packet to the given vpn ip.
279 int send_packet(ip_t to, vpn_packet_t *packet)
283 if((cl = lookup_conn(to)) == NULL)
287 syslog(LOG_NOTICE, "trying to look up " IP_ADDR_S " in connection list failed.",
290 for(cl = conn_list; cl != NULL && !cl->status.outgoing; cl = cl->next);
292 { /* No open outgoing connection has been found. */
294 syslog(LOG_NOTICE, "There is no remote host I can send this packet to.");
299 if(my_key_expiry <= time(NULL))
302 if(!cl->status.dataopen)
303 if(setup_vpn_connection(cl) < 0)
306 if(!cl->status.validkey)
308 add_queue(&(cl->sq), packet, packet->len + 2);
309 if(!cl->status.waitingforkey)
310 send_key_request(to);
314 if(!cl->status.active)
316 add_queue(&(cl->sq), packet, packet->len + 2);
318 syslog(LOG_INFO, IP_ADDR_S " is not ready, queueing packet.", IP_ADDR_V(cl->vpn_ip));
319 return 0; /* We don't want to mess up, do we? */
322 /* can we send it? can we? can we? huh? */
324 return xsend(cl, packet);
327 int send_broadcast(conn_list_t *cl, vpn_packet_t *packet)
331 for(p = cl; p != NULL; p = p->next)
332 if(send_packet(p->real_ip, packet) < 0)
334 syslog(LOG_ERR, "Could not send a broadcast packet to %08lx (%08lx): %m",
335 p->vpn_ip, p->real_ip);
336 break; /* FIXME: should retry later, and send a ping over the metaconnection. */
343 open the local ethertap device
345 int setup_tap_fd(void)
348 const char *tapfname;
351 if((cfg = get_config_val(tapdevice)) == NULL)
352 tapfname = "/dev/tap0";
354 tapfname = cfg->data.ptr;
356 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
358 syslog(LOG_ERR, "Could not open %s: %m", tapfname);
368 set up the socket that we listen on for incoming
371 int setup_listen_meta_socket(int port)
374 struct sockaddr_in a;
377 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
379 syslog(LOG_ERR, "Creating metasocket failed: %m");
383 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
385 syslog(LOG_ERR, "setsockopt: %m");
389 flags = fcntl(nfd, F_GETFL);
390 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
392 syslog(LOG_ERR, "fcntl: %m");
396 memset(&a, 0, sizeof(a));
397 a.sin_family = AF_INET;
398 a.sin_port = htons(port);
399 a.sin_addr.s_addr = htonl(INADDR_ANY);
401 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
403 syslog(LOG_ERR, "Can't bind to port %hd/tcp: %m", port);
409 syslog(LOG_ERR, "listen: %m");
417 setup the socket for incoming encrypted
420 int setup_vpn_in_socket(int port)
423 struct sockaddr_in a;
426 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
428 syslog(LOG_ERR, "Creating socket failed: %m");
432 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
434 syslog(LOG_ERR, "setsockopt: %m");
438 flags = fcntl(nfd, F_GETFL);
439 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
441 syslog(LOG_ERR, "fcntl: %m");
445 memset(&a, 0, sizeof(a));
446 a.sin_family = AF_INET;
447 a.sin_port = htons(port);
448 a.sin_addr.s_addr = htonl(INADDR_ANY);
450 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
452 syslog(LOG_ERR, "Can't bind to port %hd/udp: %m", port);
460 setup an outgoing meta (tcp) socket
462 int setup_outgoing_meta_socket(conn_list_t *cl)
465 struct sockaddr_in a;
468 if((cfg = get_config_val(upstreamport)) == NULL)
471 cl->port = cfg->data.val;
473 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
474 if(cl->meta_socket == -1)
476 syslog(LOG_ERR, "Creating socket failed: %m");
480 a.sin_family = AF_INET;
481 a.sin_port = htons(cl->port);
482 a.sin_addr.s_addr = htonl(cl->real_ip);
484 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
486 syslog(LOG_ERR, IP_ADDR_S ":%d: %m", IP_ADDR_V(cl->real_ip), cl->port);
490 flags = fcntl(cl->meta_socket, F_GETFL);
491 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
493 syslog(LOG_ERR, "fcntl: %m");
497 cl->hostname = hostlookup(htonl(cl->real_ip));
499 syslog(LOG_INFO, "Connected to %s:%hd" , cl->hostname, cl->port);
505 setup an outgoing connection. It's not
506 necessary to also open an udp socket as
507 well, because the other host will initiate
508 an authentication sequence during which
509 we will do just that.
511 int setup_outgoing_connection(ip_t ip)
515 ncn = new_conn_list();
518 if(setup_outgoing_meta_socket(ncn) < 0)
520 syslog(LOG_ERR, "Could not set up a meta connection.");
521 free_conn_element(ncn);
525 ncn->status.meta = 1;
526 ncn->status.outgoing = 1;
527 ncn->next = conn_list;
534 set up the local sockets (listen only)
536 int setup_myself(void)
540 myself = new_conn_list();
542 if(!(cfg = get_config_val(myvpnip)))
544 syslog(LOG_ERR, "No value for my VPN IP given");
548 myself->vpn_ip = cfg->data.ip->ip;
549 myself->vpn_mask = cfg->data.ip->mask;
551 if(!(cfg = get_config_val(listenport)))
554 myself->port = cfg->data.val;
556 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
558 syslog(LOG_ERR, "Unable to set up a listening socket");
562 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
564 syslog(LOG_ERR, "Unable to set up an incoming vpn data socket");
565 close(myself->meta_socket);
569 myself->status.active = 1;
571 syslog(LOG_NOTICE, "Ready: listening on port %d.", myself->port);
577 setup all initial network connections
579 int setup_network_connections(void)
583 if((cfg = get_config_val(pingtimeout)) == NULL)
586 timeout = cfg->data.val;
588 if(setup_tap_fd() < 0)
591 if(setup_myself() < 0)
594 if((cfg = get_config_val(upstreamip)) == NULL)
595 /* No upstream IP given, we're listen only. */
598 if(setup_outgoing_connection(cfg->data.ip->ip))
605 sigalrm_handler(int a)
608 static int seconds_till_retry;
610 cfg = get_config_val(upstreamip);
612 if(!setup_outgoing_connection(cfg->data.ip->ip))
614 signal(SIGALRM, SIG_IGN);
615 seconds_till_retry = 5;
619 signal(SIGALRM, sigalrm_handler);
620 seconds_till_retry += 5;
621 alarm(seconds_till_retry);
622 syslog(LOG_ERR, "Still failed to connect to other. Will retry in %d seconds.",
629 close all open network connections
631 void close_network_connections(void)
635 for(p = conn_list; p != NULL; p = p->next)
637 if(p->status.dataopen)
639 shutdown(p->socket, 0); /* No more receptions */
645 shutdown(p->meta_socket, 0); /* No more receptions */
646 close(p->meta_socket);
651 if(myself->status.active)
653 close(myself->meta_socket);
654 close(myself->socket);
660 syslog(LOG_NOTICE, "Terminating.");
666 create a data (udp) socket
668 int setup_vpn_connection(conn_list_t *cl)
671 struct sockaddr_in a;
674 syslog(LOG_DEBUG, "Opening UDP socket to " IP_ADDR_S, IP_ADDR_V(cl->real_ip));
676 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
679 syslog(LOG_ERR, "Creating data socket failed: %m");
683 a.sin_family = AF_INET;
684 a.sin_port = htons(cl->port);
685 a.sin_addr.s_addr = htonl(cl->real_ip);
687 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
689 syslog(LOG_ERR, "Create connection to %08lx:%d failed: %m", ntohs(cl->real_ip),
694 flags = fcntl(nfd, F_GETFL);
695 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
697 syslog(LOG_ERR, "This is a bug: %s:%d: %d:%m", __FILE__, __LINE__, nfd);
702 cl->status.dataopen = 1;
708 handle an incoming tcp connect call and open
711 conn_list_t *create_new_connection(int sfd)
714 struct sockaddr_in ci;
715 int len = sizeof(ci);
719 if(getpeername(sfd, &ci, &len) < 0)
721 syslog(LOG_ERR, "Error: getpeername: %m");
725 p->hostname = hostlookup(ci.sin_addr.s_addr);
726 p->real_ip = ntohl(ci.sin_addr.s_addr);
727 p->meta_socket = sfd;
730 syslog(LOG_NOTICE, "Connection from %s:%d", p->hostname, htons(ci.sin_port));
732 if(send_basic_info(p) < 0)
742 put all file descriptors in an fd_set array
744 void build_fdset(fd_set *fs)
750 for(p = conn_list; p != NULL; p = p->next)
753 FD_SET(p->meta_socket, fs);
754 if(p->status.dataopen)
755 FD_SET(p->socket, fs);
758 FD_SET(myself->meta_socket, fs);
759 FD_SET(myself->socket, fs);
765 receive incoming data from the listening
766 udp socket and write it to the ethertap
767 device after being decrypted
769 int handle_incoming_vpn_data(conn_list_t *cl)
773 int x, l = sizeof(x);
776 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
778 syslog(LOG_ERR, "This is a bug: %s:%d: %d:%m", __FILE__, __LINE__, cl->socket);
783 syslog(LOG_ERR, "Incoming data socket error: %s", sys_errlist[x]);
788 lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
791 syslog(LOG_ERR, "Receiving data failed: %m");
794 total_socket_in += lenin;
797 f = lookup_conn(rp.from);
799 syslog(LOG_DEBUG, "packet from " IP_ADDR_S " (len %d)",
800 IP_ADDR_V(rp.from), rp.len);
803 syslog(LOG_ERR, "Got packet from unknown source " IP_ADDR_S,
808 if(f->status.validkey)
812 add_queue(&(f->rq), &rp, rp.len);
813 if(!cl->status.waitingforkey)
814 send_key_request(rp.from);
817 if(my_key_expiry <= time(NULL))
825 terminate a connection and notify the other
826 end before closing the sockets
828 void terminate_connection(conn_list_t *cl)
831 if(cl->status.remove)
835 syslog(LOG_NOTICE, "Closing connection with %s.", cl->hostname);
837 if(cl->status.timeout)
839 else if(!cl->status.termreq)
844 close(cl->meta_socket);
846 if(cl->status.outgoing)
849 signal(SIGALRM, sigalrm_handler);
850 syslog(LOG_NOTICE, "Try to re-establish outgoing connection in 5 seconds.");
853 cl->status.remove = 1;
858 send out a ping request to all active
861 int send_broadcast_ping(void)
865 for(p = conn_list; p != NULL; p = p->next)
869 if(p->status.active && p->status.meta)
872 terminate_connection(p);
875 p->status.pinged = 1;
876 p->status.got_pong = 0;
881 last_ping_time = time(NULL);
887 end all connections that did not respond
888 to the ping probe in time
890 int check_dead_connections(void)
894 for(p = conn_list; p != NULL; p = p->next)
898 if(p->status.active && p->status.meta && p->status.pinged && !p->status.got_pong)
900 syslog(LOG_INFO, "%s (" IP_ADDR_S ") didn't respond to ping",
901 p->hostname, IP_ADDR_V(p->vpn_ip));
902 p->status.timeout = 1;
903 terminate_connection(p);
911 accept a new tcp connect and create a
914 int handle_new_meta_connection(conn_list_t *cl)
917 struct sockaddr client;
918 int nfd, len = sizeof(struct sockaddr);
920 if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
922 syslog(LOG_ERR, "Accepting a new connection failed: %m");
926 if((ncn = create_new_connection(nfd)) == NULL)
930 syslog(LOG_NOTICE, "Closed attempted connection.");
934 ncn->status.meta = 1;
935 ncn->next = conn_list;
942 dispatch any incoming meta requests
944 int handle_incoming_meta_data(conn_list_t *cl)
946 int x, l = sizeof(x), lenin;
947 unsigned char tmp[1600];
950 if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
952 syslog(LOG_ERR, "This is a bug: %s:%d: %d:%m", __FILE__, __LINE__, cl->meta_socket);
957 syslog(LOG_ERR, "Metadata socket error: %s", sys_errlist[x]);
961 if((lenin = recv(cl->meta_socket, &tmp, sizeof(tmp), 0)) <= 0)
963 syslog(LOG_ERR, "Receive failed: %m");
967 request = (int)(tmp[0]);
970 syslog(LOG_DEBUG, "got request %d", request);
972 if(request_handlers[request] == NULL)
973 syslog(LOG_ERR, "Unknown request %d.", request);
975 if(request_handlers[request](cl, tmp, lenin) < 0)
982 check all connections to see if anything
983 happened on their sockets
985 void check_network_activity(fd_set *f)
988 int x, l = sizeof(x);
990 for(p = conn_list; p != NULL; p = p->next)
996 if(FD_ISSET(p->socket, f))
999 The only thing that can happen to get us here is apparently an
1000 error on this outgoing(!) UDP socket that isn't immediate (i.e.
1001 something that will not trigger an error directly on send()).
1002 I've once got here when it said `No route to host'.
1004 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1005 syslog(LOG_ERR, "Outgoing data socket error: %s", sys_errlist[x]);
1006 terminate_connection(p);
1011 if(FD_ISSET(p->meta_socket, f))
1012 if(handle_incoming_meta_data(p) < 0)
1014 terminate_connection(p);
1019 if(FD_ISSET(myself->socket, f))
1020 handle_incoming_vpn_data(myself);
1022 if(FD_ISSET(myself->meta_socket, f))
1023 handle_new_meta_connection(myself);
1028 read, encrypt and send data that is
1029 available through the ethertap device
1031 void handle_tap_input(void)
1035 int ether_type, lenin;
1037 memset(&vp, 0, sizeof(vp));
1038 if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1040 syslog(LOG_ERR, "Error while reading from tapdevice: %m");
1044 total_tap_in += lenin;
1046 ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1047 if(ether_type != 0x0800)
1050 syslog(LOG_INFO, "Non-IP ethernet frame %04x from " MAC_ADDR_S,
1051 ether_type, MAC_ADDR_V(vp.data[6]));
1058 syslog(LOG_INFO, "Dropping short packet");
1062 from = ntohl(*((unsigned long*)(&vp.data[26])));
1063 to = ntohl(*((unsigned long*)(&vp.data[30])));
1066 syslog(LOG_DEBUG, "An IP packet (%04x) for " IP_ADDR_S " from " IP_ADDR_S,
1067 ether_type, IP_ADDR_V(to), IP_ADDR_V(from));
1069 syslog(LOG_DEBUG, MAC_ADDR_S " to " MAC_ADDR_S,
1070 MAC_ADDR_V(vp.data[0]), MAC_ADDR_V(vp.data[6]));
1072 vp.len = (length_t)lenin - 2;
1074 strip_mac_addresses(&vp);
1076 send_packet(to, &vp);
1081 this is where it al happens...
1083 void main_loop(void)
1089 last_ping_time = time(NULL);
1093 tv.tv_sec = timeout;
1099 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1101 if(errno == EINTR) /* because of alarm */
1103 syslog(LOG_ERR, "Error while waiting for input: %m");
1107 if(r == 0 || last_ping_time + timeout < time(NULL))
1108 /* Timeout... hm... something might be wrong. */
1110 check_dead_connections();
1111 send_broadcast_ping();
1115 check_network_activity(&fset);
1117 /* local tap data */
1118 if(FD_ISSET(tap_fd, &fset))