2 net.c -- most of the network code
3 Copyright (C) 1998,1999,2000 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>
52 int total_tap_out = 0;
53 int total_socket_in = 0;
54 int total_socket_out = 0;
56 static int seconds_till_retry;
58 /* The global list of existing connections */
59 conn_list_t *conn_list = NULL;
60 conn_list_t *myself = NULL;
63 strip off the MAC adresses of an ethernet frame
65 void strip_mac_addresses(vpn_packet_t *p)
67 unsigned char tmp[MAXSIZE];
69 memcpy(tmp, p->data, p->len);
71 memcpy(p->data, &tmp[12], p->len);
76 reassemble MAC addresses
78 void add_mac_addresses(vpn_packet_t *p)
80 unsigned char tmp[MAXSIZE];
82 memcpy(&tmp[12], p->data, p->len);
84 tmp[0] = tmp[6] = 0xfe;
85 tmp[1] = tmp[7] = 0xfd;
86 *((ip_t*)(&tmp[2])) = (ip_t)(htonl(myself->vpn_ip));
87 *((ip_t*)(&tmp[8])) = *((ip_t*)(&tmp[26]));
88 memcpy(p->data, &tmp[0], p->len);
92 int xsend(conn_list_t *cl, void *packet)
97 do_encrypt((vpn_packet_t*)packet, &rp, cl->key);
98 rp.from = htonl(myself->vpn_ip);
99 rp.data.len = htons(rp.data.len);
100 rp.len = htons(rp.len);
103 syslog(LOG_ERR, _("Sent %d bytes to %lx"), ntohs(rp.len), cl->vpn_ip);
105 if((r = send(cl->socket, (char*)&rp, ntohs(rp.len), 0)) < 0)
107 syslog(LOG_ERR, _("Error sending data: %m"));
111 total_socket_out += r;
118 int xrecv(conn_list_t *cl, void *packet)
123 do_decrypt((real_packet_t*)packet, &vp, cl->key);
124 add_mac_addresses(&vp);
126 if((lenin = write(tap_fd, &vp, vp.len + sizeof(vp.len))) < 0)
127 syslog(LOG_ERR, _("Can't write to tap device: %m"));
129 total_tap_out += lenin;
132 cl->last_ping_time = time(NULL);
138 add the given packet of size s to the
139 queue q, be it the send or receive queue
141 void add_queue(packet_queue_t **q, void *packet, size_t s)
146 syslog(LOG_DEBUG, _("packet to queue: %d"), s);
148 e = xmalloc(sizeof(*e));
149 e->packet = xmalloc(s);
150 memcpy(e->packet, packet, s);
154 *q = xmalloc(sizeof(**q));
155 (*q)->head = (*q)->tail = NULL;
158 e->next = NULL; /* We insert at the tail */
160 if((*q)->tail) /* Do we have a tail? */
162 (*q)->tail->next = e;
163 e->prev = (*q)->tail;
165 else /* No tail -> no head too */
175 /* Remove a queue element */
176 void del_queue(packet_queue_t **q, queue_element_t *e)
181 if(e->next) /* There is a successor, so we are not tail */
183 if(e->prev) /* There is a predecessor, so we are not head */
185 e->next->prev = e->prev;
186 e->prev->next = e->next;
188 else /* We are head */
190 e->next->prev = NULL;
191 (*q)->head = e->next;
194 else /* We are tail (or all alone!) */
196 if(e->prev) /* We are not alone :) */
198 e->prev->next = NULL;
199 (*q)->tail = e->prev;
213 flush a queue by calling function for
214 each packet, and removing it when that
215 returned a zero exit code
217 void flush_queue(conn_list_t *cl, packet_queue_t **pq,
218 int (*function)(conn_list_t*,void*))
220 queue_element_t *p, *next = NULL;
222 for(p = (*pq)->head; p != NULL; )
226 if(!function(cl, p->packet))
233 syslog(LOG_DEBUG, _("queue flushed"));
238 flush the send&recv queues
239 void because nothing goes wrong here, packets
240 remain in the queue if something goes wrong
242 void flush_queues(conn_list_t *cl)
248 syslog(LOG_DEBUG, _("Flushing send queue for " IP_ADDR_S),
249 IP_ADDR_V(cl->vpn_ip));
250 flush_queue(cl, &(cl->sq), xsend);
256 syslog(LOG_DEBUG, _("Flushing receive queue for " IP_ADDR_S),
257 IP_ADDR_V(cl->vpn_ip));
258 flush_queue(cl, &(cl->rq), xrecv);
264 send a packet to the given vpn ip.
266 int send_packet(ip_t to, vpn_packet_t *packet)
270 if((cl = lookup_conn(to)) == NULL)
274 syslog(LOG_NOTICE, _("trying to look up " IP_ADDR_S " in connection list failed."),
277 for(cl = conn_list; cl != NULL && !cl->status.outgoing; cl = cl->next);
279 { /* No open outgoing connection has been found. */
281 syslog(LOG_NOTICE, _("There is no remote host I can send this packet to."));
286 if(my_key_expiry <= time(NULL))
289 if(!cl->status.dataopen)
290 if(setup_vpn_connection(cl) < 0)
293 if(!cl->status.validkey)
295 add_queue(&(cl->sq), packet, packet->len + 2);
296 if(!cl->status.waitingforkey)
297 send_key_request(cl->vpn_ip); /* Keys should be sent to the host running the tincd */
301 if(!cl->status.active)
303 add_queue(&(cl->sq), packet, packet->len + 2);
305 syslog(LOG_INFO, _(IP_ADDR_S " is not ready, queueing packet."), IP_ADDR_V(cl->vpn_ip));
306 return 0; /* We don't want to mess up, do we? */
309 /* can we send it? can we? can we? huh? */
311 return xsend(cl, packet);
315 open the local ethertap device
317 int setup_tap_fd(void)
320 const char *tapfname;
323 if((cfg = get_config_val(tapdevice)) == NULL)
324 tapfname = "/dev/tap0";
326 tapfname = cfg->data.ptr;
328 if((nfd = open(tapfname, O_RDWR | O_NONBLOCK)) < 0)
330 syslog(LOG_ERR, _("Could not open %s: %m"), tapfname);
340 set up the socket that we listen on for incoming
343 int setup_listen_meta_socket(int port)
346 struct sockaddr_in a;
349 if((nfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
351 syslog(LOG_ERR, _("Creating metasocket failed: %m"));
355 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
357 syslog(LOG_ERR, _("setsockopt: %m"));
361 flags = fcntl(nfd, F_GETFL);
362 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
364 syslog(LOG_ERR, _("fcntl: %m"));
368 memset(&a, 0, sizeof(a));
369 a.sin_family = AF_INET;
370 a.sin_port = htons(port);
371 a.sin_addr.s_addr = htonl(INADDR_ANY);
373 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
375 syslog(LOG_ERR, _("Can't bind to port %hd/tcp: %m"), port);
381 syslog(LOG_ERR, _("listen: %m"));
389 setup the socket for incoming encrypted
392 int setup_vpn_in_socket(int port)
395 struct sockaddr_in a;
398 if((nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
400 syslog(LOG_ERR, _("Creating socket failed: %m"));
404 if(setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
406 syslog(LOG_ERR, _("setsockopt: %m"));
410 flags = fcntl(nfd, F_GETFL);
411 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
413 syslog(LOG_ERR, _("fcntl: %m"));
417 memset(&a, 0, sizeof(a));
418 a.sin_family = AF_INET;
419 a.sin_port = htons(port);
420 a.sin_addr.s_addr = htonl(INADDR_ANY);
422 if(bind(nfd, (struct sockaddr *)&a, sizeof(struct sockaddr)))
424 syslog(LOG_ERR, _("Can't bind to port %hd/udp: %m"), port);
432 setup an outgoing meta (tcp) socket
434 int setup_outgoing_meta_socket(conn_list_t *cl)
437 struct sockaddr_in a;
440 if((cfg = get_config_val(upstreamport)) == NULL)
443 cl->port = cfg->data.val;
445 cl->meta_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
446 if(cl->meta_socket == -1)
448 syslog(LOG_ERR, _("Creating socket failed: %m"));
452 a.sin_family = AF_INET;
453 a.sin_port = htons(cl->port);
454 a.sin_addr.s_addr = htonl(cl->real_ip);
456 if(connect(cl->meta_socket, (struct sockaddr *)&a, sizeof(a)) == -1)
458 syslog(LOG_ERR, _(IP_ADDR_S ":%d: %m"), IP_ADDR_V(cl->real_ip), cl->port);
462 flags = fcntl(cl->meta_socket, F_GETFL);
463 if(fcntl(cl->meta_socket, F_SETFL, flags | O_NONBLOCK) < 0)
465 syslog(LOG_ERR, _("fcntl: %m"));
469 cl->hostname = hostlookup(htonl(cl->real_ip));
471 syslog(LOG_INFO, _("Connected to %s:%hd"), cl->hostname, cl->port);
477 setup an outgoing connection. It's not
478 necessary to also open an udp socket as
479 well, because the other host will initiate
480 an authentication sequence during which
481 we will do just that.
483 int setup_outgoing_connection(ip_t ip)
487 ncn = new_conn_list();
490 if(setup_outgoing_meta_socket(ncn) < 0)
492 syslog(LOG_ERR, _("Could not set up a meta connection."));
493 free_conn_element(ncn);
497 ncn->status.meta = 1;
498 ncn->status.outgoing = 1;
499 ncn->next = conn_list;
506 set up the local sockets (listen only)
508 int setup_myself(void)
512 myself = new_conn_list();
514 if(!(cfg = get_config_val(myvpnip)))
516 syslog(LOG_ERR, _("No value for my VPN IP given"));
520 myself->vpn_ip = cfg->data.ip->ip;
521 myself->vpn_mask = cfg->data.ip->mask;
523 if(!(cfg = get_config_val(listenport)))
526 myself->port = cfg->data.val;
528 if((myself->meta_socket = setup_listen_meta_socket(myself->port)) < 0)
530 syslog(LOG_ERR, _("Unable to set up a listening socket"));
534 if((myself->socket = setup_vpn_in_socket(myself->port)) < 0)
536 syslog(LOG_ERR, _("Unable to set up an incoming vpn data socket"));
537 close(myself->meta_socket);
541 myself->status.active = 1;
543 syslog(LOG_NOTICE, _("Ready: listening on port %d."), myself->port);
549 sigalrm_handler(int a)
553 cfg = get_config_val(upstreamip);
555 if(!setup_outgoing_connection(cfg->data.ip->ip))
557 signal(SIGALRM, SIG_IGN);
561 signal(SIGALRM, sigalrm_handler);
562 seconds_till_retry += 5;
563 if(seconds_till_retry>300) /* Don't wait more than 5 minutes. */
564 seconds_till_retry = 300;
565 alarm(seconds_till_retry);
566 syslog(LOG_ERR, _("Still failed to connect to other. Will retry in %d seconds."),
573 setup all initial network connections
575 int setup_network_connections(void)
579 if((cfg = get_config_val(pingtimeout)) == NULL)
582 timeout = cfg->data.val;
584 if(setup_tap_fd() < 0)
587 if(setup_myself() < 0)
590 if((cfg = get_config_val(upstreamip)) == NULL)
591 /* No upstream IP given, we're listen only. */
594 if(setup_outgoing_connection(cfg->data.ip->ip))
596 signal(SIGALRM, sigalrm_handler);
597 seconds_till_retry = 300;
598 alarm(seconds_till_retry);
599 syslog(LOG_NOTICE, _("Try to re-establish outgoing connection in 5 minutes."));
606 close all open network connections
608 void close_network_connections(void)
612 for(p = conn_list; p != NULL; p = p->next)
614 if(p->status.dataopen)
616 shutdown(p->socket, 0); /* No more receptions */
622 shutdown(p->meta_socket, 0); /* No more receptions */
623 close(p->meta_socket);
628 if(myself->status.active)
630 close(myself->meta_socket);
631 close(myself->socket);
637 syslog(LOG_NOTICE, _("Terminating."));
643 create a data (udp) socket
645 int setup_vpn_connection(conn_list_t *cl)
648 struct sockaddr_in a;
651 syslog(LOG_DEBUG, _("Opening UDP socket to " IP_ADDR_S), IP_ADDR_V(cl->real_ip));
653 nfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
656 syslog(LOG_ERR, _("Creating data socket failed: %m"));
660 a.sin_family = AF_INET;
661 a.sin_port = htons(cl->port);
662 a.sin_addr.s_addr = htonl(cl->real_ip);
664 if(connect(nfd, (struct sockaddr *)&a, sizeof(a)) == -1)
666 syslog(LOG_ERR, _("Connecting to " IP_ADDR_S ":%d failed: %m"),
667 IP_ADDR_V(cl->real_ip), cl->port);
671 flags = fcntl(nfd, F_GETFL);
672 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0)
674 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, nfd);
679 cl->status.dataopen = 1;
685 handle an incoming tcp connect call and open
688 conn_list_t *create_new_connection(int sfd)
691 struct sockaddr_in ci;
692 int len = sizeof(ci);
696 if(getpeername(sfd, &ci, &len) < 0)
698 syslog(LOG_ERR, _("Error: getpeername: %m"));
702 p->hostname = hostlookup(ci.sin_addr.s_addr);
703 p->real_ip = ntohl(ci.sin_addr.s_addr);
704 p->meta_socket = sfd;
707 p->last_ping_time = time(NULL);
710 syslog(LOG_NOTICE, _("Connection from %s:%d"), p->hostname, htons(ci.sin_port));
712 if(send_basic_info(p) < 0)
722 put all file descriptors in an fd_set array
724 void build_fdset(fd_set *fs)
730 for(p = conn_list; p != NULL; p = p->next)
733 FD_SET(p->meta_socket, fs);
734 if(p->status.dataopen)
735 FD_SET(p->socket, fs);
738 FD_SET(myself->meta_socket, fs);
739 FD_SET(myself->socket, fs);
745 receive incoming data from the listening
746 udp socket and write it to the ethertap
747 device after being decrypted
749 int handle_incoming_vpn_data(conn_list_t *cl)
753 int x, l = sizeof(x);
756 if(getsockopt(cl->socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
758 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->socket);
763 syslog(LOG_ERR, _("Incoming data socket error: %s"), sys_errlist[x]);
768 lenin = recvfrom(cl->socket, &rp, MTU, 0, NULL, NULL);
771 syslog(LOG_ERR, _("Receiving data failed: %m"));
774 total_socket_in += lenin;
776 rp.data.len = ntohs(rp.data.len);
777 rp.len = ntohs(rp.len);
778 rp.from = ntohl(rp.from);
782 f = lookup_conn(rp.from);
784 syslog(LOG_DEBUG, _("packet from " IP_ADDR_S " (len %d)"),
785 IP_ADDR_V(rp.from), rp.len);
788 syslog(LOG_ERR, _("Got packet from unknown source " IP_ADDR_S),
793 if(f->status.validkey)
797 add_queue(&(f->rq), &rp, rp.len);
798 if(!cl->status.waitingforkey)
799 send_key_request(rp.from);
802 if(my_key_expiry <= time(NULL))
810 terminate a connection and notify the other
811 end before closing the sockets
813 void terminate_connection(conn_list_t *cl)
816 if(cl->status.remove)
820 syslog(LOG_NOTICE, _("Closing connection with %s."), cl->hostname);
822 if(cl->status.timeout)
824 else if(!cl->status.termreq)
829 close(cl->meta_socket);
831 if(cl->status.outgoing)
833 signal(SIGALRM, sigalrm_handler);
834 seconds_till_retry = 5;
835 alarm(seconds_till_retry);
836 syslog(LOG_NOTICE, _("Try to re-establish outgoing connection in 5 seconds."));
839 cl->status.active = 0;
840 cl->status.remove = 1;
845 Check if the other end is active.
846 If we have sent packets, but didn't receive any,
847 then possibly the other end is dead. We send a
848 PING request over the meta connection. If the other
849 end does not reply in time, we consider them dead
850 and close the connection.
852 int check_dead_connections(void)
858 for(p = conn_list; p != NULL; p = p->next)
862 if(p->status.active && p->status.meta)
864 if(p->last_ping_time + timeout < now)
866 if(p->status.pinged && !p->status.got_pong)
868 syslog(LOG_INFO, _("%s (" IP_ADDR_S ") didn't respond to ping"),
869 p->hostname, IP_ADDR_V(p->vpn_ip));
870 p->status.timeout = 1;
871 terminate_connection(p);
873 else if(p->want_ping)
876 p->last_ping_time = now;
877 p->status.pinged = 1;
878 p->status.got_pong = 0;
888 accept a new tcp connect and create a
891 int handle_new_meta_connection(conn_list_t *cl)
894 struct sockaddr client;
895 int nfd, len = sizeof(client);
897 if((nfd = accept(cl->meta_socket, &client, &len)) < 0)
899 syslog(LOG_ERR, _("Accepting a new connection failed: %m"));
903 if((ncn = create_new_connection(nfd)) == NULL)
907 syslog(LOG_NOTICE, _("Closed attempted connection."));
911 ncn->status.meta = 1;
912 ncn->next = conn_list;
919 dispatch any incoming meta requests
921 int handle_incoming_meta_data(conn_list_t *cl)
923 int x, l = sizeof(x);
924 int request, oldlen, i;
927 if(getsockopt(cl->meta_socket, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
929 syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%m"), __FILE__, __LINE__, cl->meta_socket);
934 syslog(LOG_ERR, _("Metadata socket error: %s"), sys_errlist[x]);
938 if(cl->buflen >= MAXBUFSIZE)
940 syslog(LOG_ERR, _("Metadata read buffer overflow."));
944 lenin = read(cl->meta_socket, cl->buffer, MAXBUFSIZE-cl->buflen);
948 syslog(LOG_ERR, _("Metadata socket read error: %m"));
959 for(i = oldlen; i < cl->buflen; i++)
961 if(cl->buffer[i] == '\n')
963 cl->buffer[i] = 0; /* replace end-of-line by end-of-string so we can use sscanf */
971 if(sscanf(cl->buffer, "%d", &request) == 1)
973 if(request_handlers[request] == NULL)
975 syslog(LOG_ERR, _("Unknown request: %s"), cl->buffer);
980 syslog(LOG_DEBUG, _("Got request: %s"), cl->buffer);
982 if(request_handlers[request](cl)) /* Something went wrong. Probably scriptkiddies. Terminate. */
984 syslog(LOG_ERR, _("Error while processing request from " IP_ADDR_S), IP_ADDR_V(cl->real_ip));
990 syslog(LOG_ERR, _("Bogus data received."));
994 cl->buflen -= cl->reqlen;
995 memmove(cl->buffer, cl->buffer + cl->reqlen, cl->buflen);
1004 cl->last_ping_time = time(NULL);
1011 check all connections to see if anything
1012 happened on their sockets
1014 void check_network_activity(fd_set *f)
1017 int x, l = sizeof(x);
1019 for(p = conn_list; p != NULL; p = p->next)
1021 if(p->status.remove)
1024 if(p->status.dataopen)
1025 if(FD_ISSET(p->socket, f))
1028 The only thing that can happen to get us here is apparently an
1029 error on this outgoing(!) UDP socket that isn't immediate (i.e.
1030 something that will not trigger an error directly on send()).
1031 I've once got here when it said `No route to host'.
1033 getsockopt(p->socket, SOL_SOCKET, SO_ERROR, &x, &l);
1034 syslog(LOG_ERR, _("Outgoing data socket error: %s"), sys_errlist[x]);
1035 terminate_connection(p);
1040 if(FD_ISSET(p->meta_socket, f))
1041 if(handle_incoming_meta_data(p) < 0)
1043 terminate_connection(p);
1048 if(FD_ISSET(myself->socket, f))
1049 handle_incoming_vpn_data(myself);
1051 if(FD_ISSET(myself->meta_socket, f))
1052 handle_new_meta_connection(myself);
1057 read, encrypt and send data that is
1058 available through the ethertap device
1060 void handle_tap_input(void)
1064 int ether_type, lenin;
1066 memset(&vp, 0, sizeof(vp));
1067 if((lenin = read(tap_fd, &vp, MTU)) <= 0)
1069 syslog(LOG_ERR, _("Error while reading from tapdevice: %m"));
1073 total_tap_in += lenin;
1075 ether_type = ntohs(*((unsigned short*)(&vp.data[12])));
1076 if(ether_type != 0x0800)
1079 syslog(LOG_INFO, _("Non-IP ethernet frame %04x from " MAC_ADDR_S),
1080 ether_type, MAC_ADDR_V(vp.data[6]));
1087 syslog(LOG_INFO, _("Dropping short packet"));
1091 from = ntohl(*((unsigned long*)(&vp.data[26])));
1092 to = ntohl(*((unsigned long*)(&vp.data[30])));
1095 syslog(LOG_DEBUG, _("An IP packet (%04x) for " IP_ADDR_S " from " IP_ADDR_S),
1096 ether_type, IP_ADDR_V(to), IP_ADDR_V(from));
1098 syslog(LOG_DEBUG, _(MAC_ADDR_S " to " MAC_ADDR_S),
1099 MAC_ADDR_V(vp.data[0]), MAC_ADDR_V(vp.data[6]));
1101 vp.len = (length_t)lenin - 2;
1103 strip_mac_addresses(&vp);
1105 send_packet(to, &vp);
1110 this is where it all happens...
1112 void main_loop(void)
1117 time_t last_ping_check;
1119 last_ping_check = time(NULL);
1123 tv.tv_sec = timeout;
1129 if((r = select(FD_SETSIZE, &fset, NULL, NULL, &tv)) < 0)
1131 if(errno == EINTR) /* because of alarm */
1133 syslog(LOG_ERR, _("Error while waiting for input: %m"));
1137 if(last_ping_check + timeout < time(NULL))
1138 /* Let's check if everybody is still alive */
1140 check_dead_connections();
1141 last_ping_check = time(NULL);
1145 check_network_activity(&fset);
1147 /* local tap data */
1148 if(FD_ISSET(tap_fd, &fset))