From: Guus Sliepen Date: Wed, 16 Sep 2009 17:55:47 +0000 (+0200) Subject: Merge branch 'master' into 1.1 X-Git-Tag: import-tinc-1.1~592 X-Git-Url: http://git.meshlink.io/?p=meshlink;a=commitdiff_plain;h=075e6828a7533e7daa790225f17aa6bb39703278 Merge branch 'master' into 1.1 Conflicts: have.h lib/dropin.c lib/fake-getaddrinfo.c lib/pidfile.c src/Makefile.am src/bsd/device.c src/conf.c src/connection.c src/connection.h src/graph.c src/mingw/device.c src/net.c src/net_setup.c src/node.c src/protocol_key.c src/protocol_misc.c src/tincd.c --- 075e6828a7533e7daa790225f17aa6bb39703278 diff --cc lib/fake-getaddrinfo.c index 0c27025b,10672b7e..df3d3476 --- a/lib/fake-getaddrinfo.c +++ b/lib/fake-getaddrinfo.c @@@ -16,8 -16,9 +16,9 @@@ #include "fake-getaddrinfo.h" #include "xalloc.h" - #ifndef HAVE_GAI_STRERROR ++ + #if !HAVE_DECL_GAI_STRERROR -char *gai_strerror(int ecode) -{ +char *gai_strerror(int ecode) { switch (ecode) { case EAI_NODATA: return "No address associated with hostname"; @@@ -31,8 -32,9 +32,8 @@@ } #endif /* !HAVE_GAI_STRERROR */ - #ifndef HAVE_FREEADDRINFO + #if !HAVE_DECL_FREEADDRINFO -void freeaddrinfo(struct addrinfo *ai) -{ +void freeaddrinfo(struct addrinfo *ai) { struct addrinfo *next; while(ai) { @@@ -43,8 -45,9 +44,8 @@@ } #endif /* !HAVE_FREEADDRINFO */ - #ifndef HAVE_GETADDRINFO + #if !HAVE_DECL_GETADDRINFO -static struct addrinfo *malloc_ai(uint16_t port, uint32_t addr) -{ +static struct addrinfo *malloc_ai(uint16_t port, uint32_t addr) { struct addrinfo *ai; ai = xmalloc_and_zero(sizeof(struct addrinfo) + sizeof(struct sockaddr_in)); diff --cc lib/fake-getnameinfo.c index 05f0875a,80471730..1eba4925 --- a/lib/fake-getnameinfo.c +++ b/lib/fake-getnameinfo.c @@@ -14,9 -14,10 +14,9 @@@ #include "fake-getnameinfo.h" #include "fake-getaddrinfo.h" - #ifndef HAVE_GETNAMEINFO + #if !HAVE_DECL_GETNAMEINFO -int getnameinfo(const struct sockaddr *sa, size_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) -{ +int getnameinfo(const struct sockaddr *sa, size_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) { struct sockaddr_in *sin = (struct sockaddr_in *)sa; struct hostent *hp; int len; diff --cc src/Makefile.am index ed110e9f,501fdf66..db90897f --- a/src/Makefile.am +++ b/src/Makefile.am @@@ -5,23 -5,29 +5,31 @@@ sbin_PROGRAMS = tincd tincct EXTRA_DIST = linux/device.c bsd/device.c solaris/device.c cygwin/device.c mingw/device.c mingw/common.h raw_socket/device.c uml_socket/device.c -tincd_SOURCES = conf.c connection.c edge.c event.c graph.c logger.c meta.c net.c net_packet.c net_setup.c \ +tincd_SOURCES = cipher.c conf.c connection.c control.c crypto.c digest.c edge.c graph.c logger.c meta.c net.c net_packet.c net_setup.c \ net_socket.c netutl.c node.c process.c protocol.c protocol_auth.c protocol_edge.c protocol_misc.c \ - protocol_key.c protocol_subnet.c route.c subnet.c tincd.c + protocol_key.c protocol_subnet.c route.c rsa.c subnet.c tincd.c + +tincctl_SOURCES = tincctl.c rsagen.c + if TUNEMU + tincd_SOURCES += bsd/tunemu.c + endif + nodist_tincd_SOURCES = device.c DEFAULT_INCLUDES = INCLUDES = @INCLUDES@ -I$(top_builddir) -I$(top_srcdir)/lib -noinst_HEADERS = conf.h connection.h device.h edge.h event.h graph.h logger.h meta.h net.h netutl.h node.h process.h \ - protocol.h route.h subnet.h bsd/tunemu.h +noinst_HEADERS = cipher.h conf.h connection.h control.h crypto.h device.h digest.h edge.h graph.h logger.h meta.h net.h netutl.h node.h process.h \ - protocol.h route.h rsa.h rsagen.h subnet.h ++ protocol.h route.h rsa.h rsagen.h subnet.h bsd/tunemu.h -LIBS = @LIBS@ @LIBINTL@ +LIBS = @LIBS@ @LIBGCRYPT_LIBS@ @LIBINTL@ + if TUNEMU + LIBS += -lpcap + endif + tincd_LDADD = \ $(top_builddir)/lib/libvpn.a diff --cc src/bsd/device.c index 1066858b,fe85d10f..872ad92f --- a/src/bsd/device.c +++ b/src/bsd/device.c @@@ -152,7 -190,16 +190,16 @@@ bool read_packet(vpn_packet_t *packet) switch(device_type) { case DEVICE_TYPE_TUN: - if((inlen = read(device_fd, packet->data + 14, MTU - 14)) <= 0) { + #ifdef HAVE_TUNEMU + case DEVICE_TYPE_TUNEMU: + if(device_type == DEVICE_TYPE_TUNEMU) - lenin = tunemu_read(device_fd, packet->data + 14, MTU - 14); ++ inlen = tunemu_read(device_fd, packet->data + 14, MTU - 14); + else + #else - lenin = read(device_fd, packet->data + 14, MTU - 14); ++ inlen = read(device_fd, packet->data + 14, MTU - 14); + #endif + - if(lenin <= 0) { ++ if(inlen <= 0) { logger(LOG_ERR, _("Error while reading from %s %s: %s"), device_info, device, strerror(errno)); return false; diff --cc src/connection.c index 230ec4ed,283ebd71..4a2ba4c0 --- a/src/connection.c +++ b/src/connection.c @@@ -33,17 -32,19 +33,17 @@@ #include "utils.h" #include "xalloc.h" -avl_tree_t *connection_tree; /* Meta connections */ +splay_tree_t *connection_tree; /* Meta connections */ connection_t *broadcast; -static int connection_compare(const connection_t *a, const connection_t *b) -{ +static int connection_compare(const connection_t *a, const connection_t *b) { - return (void *)a - (void *)b; + return a < b ? -1 : a == b ? 0 : 1; } -void init_connections(void) -{ +void init_connections(void) { cp(); - connection_tree = avl_alloc_tree((avl_compare_t) connection_compare, (avl_action_t) free_connection); + connection_tree = splay_alloc_tree((splay_compare_t) connection_compare, (splay_action_t) free_connection); broadcast = new_connection(); broadcast->name = xstrdup(_("everyone")); broadcast->hostname = xstrdup(_("BROADCAST")); @@@ -110,19 -139,20 +110,19 @@@ int dump_connections(struct evbuffer *o cp(); - logger(LOG_DEBUG, _("Connections:")); - for(node = connection_tree->head; node; node = node->next) { c = node->data; - logger(LOG_DEBUG, _(" %s at %s options %lx socket %d status %04x outbuf %d/%d/%d"), - c->name, c->hostname, c->options, c->socket, bitfield_to_int(&c->status, sizeof c->status), - c->outbufsize, c->outbufstart, c->outbuflen); + if(evbuffer_add_printf(out, + _(" %s at %s options %lx socket %d status %04x\n"), + c->name, c->hostname, c->options, c->socket, - c->status.value) == -1) ++ bitfield_to_int(&c->status, sizeof c->status)) == -1) + return errno; } - logger(LOG_DEBUG, _("End of connections.")); + return 0; } -bool read_connection_config(connection_t *c) -{ +bool read_connection_config(connection_t *c) { char *fname; int x; diff --cc src/connection.h index 08778bf3,8948d4fa..e44af0b0 --- a/src/connection.h +++ b/src/connection.h @@@ -32,20 -32,17 +32,17 @@@ #define OPTION_TCPONLY 0x0002 #define OPTION_PMTU_DISCOVERY 0x0004 - typedef union connection_status_t { - struct { + typedef struct connection_status_t { - int pinged:1; /* sent ping */ - int active:1; /* 1 if active.. */ - int connecting:1; /* 1 if we are waiting for a non-blocking connect() to finish */ - int termreq:1; /* the termination of this connection was requested */ - int remove:1; /* Set to 1 if you want this connection removed */ - int timeout:1; /* 1 if gotten timeout */ - int encryptout:1; /* 1 if we can encrypt outgoing traffic */ - int decryptin:1; /* 1 if we have to decrypt incoming traffic */ - int mst:1; /* 1 if this connection is part of a minimum spanning tree */ - int unused:23; + int pinged:1; /* sent ping */ + int active:1; /* 1 if active.. */ + int connecting:1; /* 1 if we are waiting for a non-blocking connect() to finish */ + int termreq:1; /* the termination of this connection was requested */ + int remove_unused:1; /* Set to 1 if you want this connection removed */ + int timeout_unused:1; /* 1 if gotten timeout */ + int encryptout:1; /* 1 if we can encrypt outgoing traffic */ + int decryptin:1; /* 1 if we have to decrypt incoming traffic */ + int mst:1; /* 1 if this connection is part of a minimum spanning tree */ + int unused:23; - }; - uint32_t value; } connection_status_t; #include "edge.h" diff --cc src/graph.c index 4e060b7f,a267f052..f2e546ee --- a/src/graph.c +++ b/src/graph.c @@@ -57,9 -57,12 +57,10 @@@ #include "process.h" #include "subnet.h" #include "utils.h" + #include "xalloc.h" -static bool graph_changed = true; - /* Implementation of Kruskal's algorithm. - Running time: O(EN) + Running time: O(E) Please note that sorting on weight is already done by add_edge(). */ @@@ -359,13 -265,18 +360,15 @@@ void check_reachability() n->minmtu = 0; n->mtuprobes = 0; - asprintf(&envp[0], "NETNAME=%s", netname ? : ""); - asprintf(&envp[1], "DEVICE=%s", device ? : ""); - asprintf(&envp[2], "INTERFACE=%s", iface ? : ""); - asprintf(&envp[3], "NODE=%s", n->name); - if(n->mtuevent) { - event_del(n->mtuevent); - n->mtuevent = NULL; - } ++ event_del(&n->mtuevent); + + xasprintf(&envp[0], "NETNAME=%s", netname ? : ""); + xasprintf(&envp[1], "DEVICE=%s", device ? : ""); + xasprintf(&envp[2], "INTERFACE=%s", iface ? : ""); + xasprintf(&envp[3], "NODE=%s", n->name); sockaddr2str(&n->address, &address, &port); - asprintf(&envp[4], "REMOTEADDRESS=%s", address); - asprintf(&envp[5], "REMOTEPORT=%s", port); + xasprintf(&envp[4], "REMOTEADDRESS=%s", address); + xasprintf(&envp[5], "REMOTEPORT=%s", port); envp[6] = NULL; execute_script(n->status.reachable ? "host-up" : "host-down", envp); diff --cc src/meta.c index 82dde3a5,b59f15b0..6054427c --- a/src/meta.c +++ b/src/meta.c @@@ -32,9 -34,18 +32,14 @@@ #include "utils.h" #include "xalloc.h" -bool send_meta(connection_t *c, const char *buffer, int length) -{ - int outlen; - int result; - +bool send_meta(connection_t *c, const char *buffer, int length) { cp(); + if(!c) { + logger(LOG_ERR, _("send_meta() called with NULL pointer!")); + abort(); + } + ifdebug(META) logger(LOG_DEBUG, _("Sending %d bytes of metadata to %s (%s)"), length, c->name, c->hostname); diff --cc src/mingw/device.c index 915256f5,fa134332..2334af39 --- a/src/mingw/device.c +++ b/src/mingw/device.c @@@ -316,30 -232,14 +230,12 @@@ void close_device(void) free(iface); } -bool read_packet(vpn_packet_t *packet) -{ +bool read_packet(vpn_packet_t *packet) { - unsigned char bufno; - - cp(); - - if((recv(device_fd, &bufno, 1, 0)) <= 0) { - logger(LOG_ERR, _("Error while reading from %s %s: %s"), device_info, - device, strerror(errno)); - return false; - } - - packet->len = bufs[bufno].len; - memcpy(packet->data, bufs[bufno].data, bufs[bufno].len); - - device_total_in += packet->len; - - ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Read packet of %d bytes from %s"), packet->len, - device_info); - - return true; + return false; } -bool write_packet(vpn_packet_t *packet) -{ - long lenout; +bool write_packet(vpn_packet_t *packet) { + long outlen; OVERLAPPED overlapped = {0}; cp(); diff --cc src/net_packet.c index 8bf41c39,aca84683..77e29c0a --- a/src/net_packet.c +++ b/src/net_packet.c @@@ -64,7 -68,13 +64,12 @@@ static void send_mtu_probe_handler(int cp(); n->mtuprobes++; - n->mtuevent = NULL; + if(!n->status.reachable) { + logger(LOG_DEBUG, _("Trying to send MTU probe to unreachable node %s (%s)"), n->name, n->hostname); + return; + } + if(n->mtuprobes >= 10 && !n->minmtu) { ifdebug(TRAFFIC) logger(LOG_INFO, _("No response to MTU probes from %s (%s)"), n->name, n->hostname); return; diff --cc src/net_setup.c index 224bdf61,3c4bf48c..623eb185 --- a/src/net_setup.c +++ b/src/net_setup.c @@@ -105,10 -170,8 +105,10 @@@ bool read_rsa_private_key() return true; } + /* Else, check for PrivateKeyFile statement and read it */ + if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname)) - asprintf(&fname, "%s/rsa_key.priv", confbase); + xasprintf(&fname, "%s/rsa_key.priv", confbase); fp = fopen(fname, "r"); @@@ -296,36 -349,65 +299,36 @@@ bool setup_myself(void) /* Generate packet encryption key */ - if(get_config_string - (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) { - if(!strcasecmp(cipher, "none")) { - myself->incipher = NULL; - } else { - myself->incipher = EVP_get_cipherbyname(cipher); - - if(!myself->incipher) { - logger(LOG_ERR, _("Unrecognized cipher type!")); - return false; - } - } - } else - myself->incipher = EVP_aes_256_cbc(); + if(!get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) - cipher = xstrdup("blowfish"); ++ cipher = xstrdup("aes256"); - if(myself->incipher) - myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len; - else - myself->inkeylength = 1; - - myself->connection->outcipher = EVP_aes_256_ofb(); + if(!cipher_open_by_name(&myself->incipher, cipher)) { + logger(LOG_ERR, _("Unrecognized cipher type!")); + return false; + } if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime)) keylifetime = 3600; - keyexpires = now + keylifetime; - + regenerate_key(); + /* Check if we want to use message authentication codes... */ - if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest)) { - if(!strcasecmp(digest, "none")) { - myself->indigest = NULL; - } else { - myself->indigest = EVP_get_digestbyname(digest); + if(!get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest)) - digest = xstrdup("sha1"); ++ digest = xstrdup("sha256"); - if(!myself->indigest) { - logger(LOG_ERR, _("Unrecognized digest type!")); - return false; - } - } - } else - myself->indigest = EVP_sha256(); - - myself->connection->outdigest = EVP_sha256(); - - if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->inmaclength)) { - if(myself->indigest) { - if(myself->inmaclength > myself->indigest->md_size) { - logger(LOG_ERR, _("MAC length exceeds size of digest!")); - return false; - } else if(myself->inmaclength < 0) { - logger(LOG_ERR, _("Bogus MAC length!")); - return false; - } - } - } else - myself->inmaclength = 4; + int maclength = 4; + get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &maclength); - myself->connection->outmaclength = 0; + if(maclength < 0) { + logger(LOG_ERR, _("Bogus MAC length!")); + return false; + } + + if(!digest_open_by_name(&myself->indigest, digest, maclength)) { + logger(LOG_ERR, _("Unrecognized digest type!")); + return false; + } /* Compression */ @@@ -353,19 -435,11 +356,19 @@@ if(!setup_device()) return false; + event_set(&device_ev, device_fd, EV_READ|EV_PERSIST, handle_device_data, NULL); + + if (event_add(&device_ev, NULL) < 0) { + logger(LOG_ERR, _("event_add failed: %s"), strerror(errno)); + close_device(); + return false; + } + /* Run tinc-up script to further initialize the tap interface */ - asprintf(&envp[0], "NETNAME=%s", netname ? : ""); - asprintf(&envp[1], "DEVICE=%s", device ? : ""); - asprintf(&envp[2], "INTERFACE=%s", iface ? : ""); - asprintf(&envp[3], "NAME=%s", myself->name); + xasprintf(&envp[0], "NETNAME=%s", netname ? : ""); + xasprintf(&envp[1], "DEVICE=%s", device ? : ""); + xasprintf(&envp[2], "INTERFACE=%s", iface ? : ""); + xasprintf(&envp[3], "NAME=%s", myself->name); envp[4] = NULL; execute_script("tinc-up", envp); diff --cc src/node.c index 6df236a1,4fbec08f..ebd2c7c2 --- a/src/node.c +++ b/src/node.c @@@ -131,11 -137,12 +131,11 @@@ void node_del(node_t *n) edge_del(e); } - splay_delete(node_tree, n); - avl_delete(node_udp_tree, n); - avl_delete(node_tree, n); + splay_delete(node_udp_tree, n); ++ splay_delete(node_tree, n); } -node_t *lookup_node(char *name) -{ +node_t *lookup_node(char *name) { node_t n = {0}; cp(); @@@ -166,12 -174,12 +166,12 @@@ void update_node_udp(node_t *n, const s if(sa) { n->address = *sa; n->hostname = sockaddr2hostname(&n->address); - splay_delete(node_udp_tree, n); - avl_insert(node_udp_tree, n); - ifdebug(PROTOCOL) logger(LOG_DEBUG, "UDP address of %s set to %s", n->name, n->hostname); + splay_insert(node_udp_tree, n); + logger(LOG_DEBUG, "UDP address of %s set to %s", n->name, n->hostname); } else { memset(&n->address, 0, sizeof n->address); - logger(LOG_DEBUG, "UDP address of %s cleared", n->name); + n->hostname = 0; + ifdebug(PROTOCOL) logger(LOG_DEBUG, "UDP address of %s cleared", n->name); } } @@@ -181,15 -190,16 +181,15 @@@ int dump_nodes(struct evbuffer *out) cp(); - logger(LOG_DEBUG, _("Nodes:")); - for(node = node_tree->head; node; node = node->next) { n = node->data; - logger(LOG_DEBUG, _(" %s at %s cipher %d digest %d maclength %d compression %d options %lx status %04x nexthop %s via %s pmtu %d (min %d max %d)"), - n->name, n->hostname, n->outcipher ? n->outcipher->nid : 0, - n->outdigest ? n->outdigest->type : 0, n->outmaclength, n->outcompression, + if(evbuffer_add_printf(out, _(" %s at %s cipher %d digest %d maclength %d compression %d options %lx status %04x nexthop %s via %s distance %d pmtu %d (min %d max %d)\n"), + n->name, n->hostname, cipher_get_nid(&n->outcipher), + digest_get_nid(&n->outdigest), digest_length(&n->outdigest), n->outcompression, - n->options, *(uint32_t *)&n->status, n->nexthop ? n->nexthop->name : "-", + n->options, bitfield_to_int(&n->status, sizeof n->status), n->nexthop ? n->nexthop->name : "-", - n->via ? n->via->name : "-", n->mtu, n->minmtu, n->maxmtu); + n->via ? n->via->name : "-", n->distance, n->mtu, n->minmtu, n->maxmtu) == -1) + return errno; } - logger(LOG_DEBUG, _("End of nodes.")); + return 0; } diff --cc src/process.c index 29cd486d,544c2242..546570aa --- a/src/process.c +++ b/src/process.c @@@ -258,10 -360,10 +258,9 @@@ bool detach(void) return true; } -bool execute_script(const char *name, char **envp) -{ +bool execute_script(const char *name, char **envp) { #ifdef HAVE_SYSTEM int status, len; - struct stat s; char *scriptname, *p; int i; diff --cc src/protocol_edge.c index 35776116,4066a30d..92d31dbd --- a/src/protocol_edge.c +++ b/src/protocol_edge.c @@@ -172,10 -174,11 +172,10 @@@ bool add_edge_h(connection_t *c, char * return true; } -bool send_del_edge(connection_t *c, const edge_t *e) -{ +bool send_del_edge(connection_t *c, const edge_t *e) { cp(); - return send_request(c, "%d %lx %s %s", DEL_EDGE, random(), + return send_request(c, "%d %x %s %s", DEL_EDGE, rand(), e->from->name, e->to->name); } diff --cc src/protocol_key.c index 2a0f2301,7ae98036..60e9d736 --- a/src/protocol_key.c +++ b/src/protocol_key.c @@@ -46,10 -49,11 +46,10 @@@ bool send_key_changed() if(!mykeyused) return true; - return send_request(broadcast, "%d %lx %s", KEY_CHANGED, random(), myself->name); + return send_request(broadcast, "%d %x %s", KEY_CHANGED, rand(), myself->name); } -bool key_changed_h(connection_t *c) -{ +bool key_changed_h(connection_t *c, char *request) { char name[MAX_STRING_SIZE]; node_t *n; diff --cc src/protocol_misc.c index 02e38598,18ff13c8..b8d2f67d --- a/src/protocol_misc.c +++ b/src/protocol_misc.c @@@ -154,7 -158,7 +154,7 @@@ bool send_tcppacket(connection_t *c, vp /* If there already is a lot of data in the outbuf buffer, discard this packet. We use a very simple Random Early Drop algorithm. */ - if(2.0 * c->buffer->output->off / (double)maxoutbufsize - 1 > drand48()) - if(2.0 * c->outbuflen / (float)maxoutbufsize - 1 > (float)rand()/(float)RAND_MAX) ++ if(2.0 * c->buffer->output->off / (float)maxoutbufsize - 1 > (float)rand()/(float)RAND_MAX) return true; if(!send_request(c, "%d %hd", PACKET, packet->len)) diff --cc src/protocol_subnet.c index e5927213,b50cf6a3..9c5b04c8 --- a/src/protocol_subnet.c +++ b/src/protocol_subnet.c @@@ -42,10 -42,10 +42,10 @@@ bool send_add_subnet(connection_t *c, c if(!net2str(netstr, sizeof netstr, subnet)) return false; - return send_request(c, "%d %lx %s %s", ADD_SUBNET, random(), subnet->owner->name, netstr); + return send_request(c, "%d %x %s %s", ADD_SUBNET, rand(), subnet->owner->name, netstr); } -bool add_subnet_h(connection_t *c) +bool add_subnet_h(connection_t *c, char *request) { char subnetstr[MAX_STRING_SIZE]; char name[MAX_STRING_SIZE]; @@@ -161,10 -161,10 +161,10 @@@ bool send_del_subnet(connection_t *c, c if(!net2str(netstr, sizeof netstr, s)) return false; - return send_request(c, "%d %lx %s %s", DEL_SUBNET, random(), s->owner->name, netstr); + return send_request(c, "%d %x %s %s", DEL_SUBNET, rand(), s->owner->name, netstr); } -bool del_subnet_h(connection_t *c) +bool del_subnet_h(connection_t *c, char *request) { char subnetstr[MAX_STRING_SIZE]; char name[MAX_STRING_SIZE]; diff --cc src/route.c index 8acabb1b,9b689039..da37473c --- a/src/route.c +++ b/src/route.c @@@ -97,44 -94,14 +97,51 @@@ static bool checklength(node_t *source } else return true; } + + static void swap_mac_addresses(vpn_packet_t *packet) { + mac_t tmp; + memcpy(&tmp, &packet->data[0], sizeof tmp); + memcpy(&packet->data[0], &packet->data[6], sizeof tmp); + memcpy(&packet->data[6], &tmp, sizeof tmp); + } +static void age_subnets(int fd, short events, void *data) +{ + subnet_t *s; + connection_t *c; + splay_node_t *node, *next, *node2; + bool left = false; + time_t now = time(NULL); + + cp(); + + for(node = myself->subnet_tree->head; node; node = next) { + next = node->next; + s = node->data; + if(s->expires && s->expires < now) { + ifdebug(TRAFFIC) { + char netstr[MAXNETSTR]; + if(net2str(netstr, sizeof netstr, s)) + logger(LOG_INFO, _("Subnet %s expired"), netstr); + } + + for(node2 = connection_tree->head; node2; node2 = node2->next) { + c = node2->data; + if(c->status.active) + send_del_subnet(c, s); + } + + subnet_del(myself, s); + } else { + if(s->expires) + left = true; + } + } + + if(left) + event_add(&age_subnets_event, &(struct timeval){10, 0}); +} + static void learn_mac(mac_t *address) { subnet_t *subnet; diff --cc src/subnet.c index 75fe31f8,140b6145..057550ab --- a/src/subnet.c +++ b/src/subnet.c @@@ -474,16 -474,19 +474,19 @@@ subnet_t *lookup_subnet_ipv6(const ipv6 } void subnet_update(node_t *owner, subnet_t *subnet, bool up) { - avl_node_t *node; + splay_node_t *node; int i; - char *envp[8]; - char netstr[MAXNETSTR + 7] = "SUBNET="; + char *envp[9] = {0}; + char netstr[MAXNETSTR]; char *name, *address, *port; + char empty[] = ""; + + // Prepare environment variables to be passed to the script - asprintf(&envp[0], "NETNAME=%s", netname ? : ""); - asprintf(&envp[1], "DEVICE=%s", device ? : ""); - asprintf(&envp[2], "INTERFACE=%s", iface ? : ""); - asprintf(&envp[3], "NODE=%s", owner->name); + xasprintf(&envp[0], "NETNAME=%s", netname ? : ""); + xasprintf(&envp[1], "DEVICE=%s", device ? : ""); + xasprintf(&envp[2], "INTERFACE=%s", iface ? : ""); + xasprintf(&envp[3], "NODE=%s", owner->name); if(owner != myself) { sockaddr2str(&owner->address, &address, &port); @@@ -506,20 -520,27 +520,27 @@@ execute_script(name, envp); } } else { - if(net2str(netstr + 7, sizeof netstr - 7, subnet)) + if(net2str(netstr + 7, sizeof netstr - 7, subnet)) { + // Strip the weight from the subnet, and put it in its own environment variable + char *weight = strchr(netstr + 7, '#'); + if(weight) + *weight++ = 0; + else + weight = empty; + + // Prepare the SUBNET and WEIGHT variables + xasprintf(&envp[4], "SUBNET=%s", netstr); + xasprintf(&envp[5], "WEIGHT=%s", weight); + execute_script(name, envp); + } } - for(i = 0; i < (owner != myself ? 6 : 4); i++) + for(i = 0; envp[i] && i < 9; i++) free(envp[i]); - - if(owner != myself) { - free(address); - free(port); - } } -void dump_subnets(void) +int dump_subnets(struct evbuffer *out) { char netstr[MAXNETSTR]; subnet_t *subnet; diff --cc src/tincctl.c index 814800e8,00000000..92796b6b mode 100644,000000..100644 --- a/src/tincctl.c +++ b/src/tincctl.c @@@ -1,591 -1,0 +1,591 @@@ +/* + tincctl.c -- Controlling a running tincd + Copyright (C) 2007 Guus Sliepen + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + $Id$ +*/ + +#include "system.h" + +#include +#include + +#include "xalloc.h" +#include "protocol.h" +#include "control_common.h" +#include "rsagen.h" + +/* The name this program was run with. */ +char *program_name = NULL; + +/* If nonzero, display usage information and exit. */ +bool show_help = false; + +/* If nonzero, print the version on standard output and exit. */ +bool show_version = false; + +/* If nonzero, it will attempt to kill a running tincd and exit. */ +int kill_tincd = 0; + +/* If nonzero, generate public/private keypair for this host/net. */ +int generate_keys = 0; + +static char *identname = NULL; /* program name for syslog */ +static char *controlsocketname = NULL; /* pid file location */ +char *netname = NULL; +char *confbase = NULL; + +static struct option const long_options[] = { + {"config", required_argument, NULL, 'c'}, + {"net", required_argument, NULL, 'n'}, + {"help", no_argument, NULL, 1}, + {"version", no_argument, NULL, 2}, + {"controlsocket", required_argument, NULL, 5}, + {NULL, 0, NULL, 0} +}; + +static void usage(bool status) { + if(status) + fprintf(stderr, _("Try `%s --help\' for more information.\n"), + program_name); + else { + printf(_("Usage: %s [options] command\n\n"), program_name); + printf(_("Valid options are:\n" + " -c, --config=DIR Read configuration options from DIR.\n" + " -n, --net=NETNAME Connect to net NETNAME.\n" + " --controlsocket=FILENAME Open control socket at FILENAME.\n" + " --help Display this help and exit.\n" + " --version Output version information and exit.\n" + "\n" + "Valid commands are:\n" + " start Start tincd.\n" + " stop Stop tincd.\n" + " restart Restart tincd.\n" + " reload Reload configuration of running tincd.\n" + " pid Show PID of currently running tincd.\n" + " generate-keys [bits] Generate a new public/private keypair.\n" + " dump Dump a list of one of the following things:\n" + " nodes - all known nodes in the VPN\n" + " edges - all known connections in the VPN\n" + " subnets - all known subnets in the VPN\n" + " connections - all meta connections with ourself\n" + " graph - graph of the VPN in dotty format\n" + " purge Purge unreachable nodes\n" + " debug N Set debug level\n" + " retry Retry all outgoing connections\n" + " reload Partial reload of configuration\n" + "\n")); + printf(_("Report bugs to tinc@tinc-vpn.org.\n")); + } +} + +static bool parse_options(int argc, char **argv) { + int r; + int option_index = 0; + + while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) { + switch (r) { + case 0: /* long option */ + break; + + case 'c': /* config file */ + confbase = xstrdup(optarg); + break; + + case 'n': /* net name given */ + netname = xstrdup(optarg); + break; + + case 1: /* show help */ + show_help = true; + break; + + case 2: /* show version */ + show_version = true; + break; + + case 5: /* open control socket here */ + controlsocketname = xstrdup(optarg); + break; + + case '?': + usage(true); + return false; + + default: + break; + } + } + + return true; +} + +FILE *ask_and_open(const char *filename, const char *what, const char *mode) { + FILE *r; + char *directory; + char buf[PATH_MAX]; + char buf2[PATH_MAX]; + size_t len; + + /* Check stdin and stdout */ + if(isatty(0) && isatty(1)) { + /* Ask for a file and/or directory name. */ + fprintf(stdout, _("Please enter a file to save %s to [%s]: "), + what, filename); + fflush(stdout); + + if(fgets(buf, sizeof buf, stdin) < 0) { + fprintf(stderr, _("Error while reading stdin: %s\n"), + strerror(errno)); + return NULL; + } + + len = strlen(buf); + if(len) + buf[--len] = 0; + + if(len) + filename = buf; + } + +#ifdef HAVE_MINGW + if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) { +#else + if(filename[0] != '/') { +#endif + /* The directory is a relative path or a filename. */ + directory = get_current_dir_name(); + snprintf(buf2, sizeof buf2, "%s/%s", directory, filename); + filename = buf2; + } + + umask(0077); /* Disallow everything for group and other */ + + /* Open it first to keep the inode busy */ + + r = fopen(filename, mode); + + if(!r) { + fprintf(stderr, _("Error opening file `%s': %s\n"), filename, strerror(errno)); + return NULL; + } + + return r; +} + +/* + Generate a public/private RSA keypair, and ask for a file to store + them in. +*/ +static bool keygen(int bits) { + rsa_t key; + FILE *f; + char *name = NULL; + char *filename; + + fprintf(stderr, _("Generating %d bits keys:\n"), bits); + + if(!rsa_generate(&key, bits, 0x10001)) { + fprintf(stderr, _("Error during key generation!\n")); + return false; + } else + fprintf(stderr, _("Done.\n")); + + asprintf(&filename, "%s/rsa_key.priv", confbase); + f = ask_and_open(filename, _("private RSA key"), "a"); + + if(!f) + return false; + +#ifdef HAVE_FCHMOD + /* Make it unreadable for others. */ + fchmod(fileno(f), 0600); +#endif + + if(ftell(f)) + fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n")); + + rsa_write_pem_private_key(&key, f); + + fclose(f); + free(filename); + + if(name) + asprintf(&filename, "%s/hosts/%s", confbase, name); + else + asprintf(&filename, "%s/rsa_key.pub", confbase); + + f = ask_and_open(filename, _("public RSA key"), "a"); + + if(!f) + return false; + + if(ftell(f)) + fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n")); + + rsa_write_pem_public_key(&key, f); + + fclose(f); + free(filename); + + return true; +} + +/* + Set all files and paths according to netname +*/ +static void make_names(void) { +#ifdef HAVE_MINGW + HKEY key; + char installdir[1024] = ""; + long len = sizeof installdir; +#endif + + if(netname) + asprintf(&identname, "tinc.%s", netname); + else + identname = xstrdup("tinc"); + +#ifdef HAVE_MINGW + if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) { + if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) { + if(!logfilename) + asprintf(&logfilename, "%s/log/%s.log", identname); + if(!confbase) { + if(netname) + asprintf(&confbase, "%s/%s", installdir, netname); + else + asprintf(&confbase, "%s", installdir); + } + } + RegCloseKey(key); + if(*installdir) + return; + } +#endif + + if(!controlsocketname) + asprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname); + + if(netname) { + if(!confbase) + asprintf(&confbase, CONFDIR "/tinc/%s", netname); + else + fprintf(stderr, _("Both netname and configuration directory given, using the latter...\n")); + } else { + if(!confbase) + asprintf(&confbase, CONFDIR "/tinc"); + } +} + +static int fullread(int fd, void *data, size_t datalen) { + int rv, len = 0; + + while(len < datalen) { + rv = read(fd, data + len, datalen - len); + if(rv == -1 && errno == EINTR) + continue; + else if(rv == -1) + return rv; + else if(rv == 0) { + errno = ENODATA; + return -1; + } + len += rv; + } + return 0; +} + +/* + Send a request (raw) +*/ +static int send_ctl_request(int fd, enum request_type type, + void const *outdata, size_t outdatalen, + int *res_errno_p, void **indata_p, + size_t *indatalen_p) { + tinc_ctl_request_t req; + int rv; + struct iovec vector[2] = { + {&req, sizeof req}, + {(void*) outdata, outdatalen} + }; + void *indata; + + if(res_errno_p == NULL) + return -1; + + memset(&req, 0, sizeof req); + req.length = sizeof req + outdatalen; + req.type = type; + req.res_errno = 0; + + while((rv = writev(fd, vector, 2)) == -1 && errno == EINTR) ; + if(rv != req.length) + return -1; + + if(fullread(fd, &req, sizeof req) == -1) + return -1; + + if(req.length < sizeof req) { + errno = EINVAL; + return -1; + } + + if(req.length > sizeof req) { + if(indata_p == NULL) { + errno = EINVAL; + return -1; + } + + indata = xmalloc(req.length - sizeof req); + + if(fullread(fd, indata, req.length - sizeof req) == -1) { + free(indata); + return -1; + } + + *indata_p = indata; + if(indatalen_p != NULL) + *indatalen_p = req.length - sizeof req; + } + + *res_errno_p = req.res_errno; + + return 0; +} + +/* + Send a request (with printfs) +*/ +static int send_ctl_request_cooked(int fd, enum request_type type, + void const *outdata, size_t outdatalen) +{ + int res_errno = -1; + char *buf = NULL; + size_t buflen = 0; + + if(send_ctl_request(fd, type, outdata, outdatalen, &res_errno, + (void**) &buf, &buflen)) { + fprintf(stderr, _("Error sending request: %s\n"), strerror(errno)); + return -1; + } + + if(buf != NULL) { + printf("%*s", (int)buflen, buf); + free(buf); + } + + if(res_errno != 0) { + fprintf(stderr, _("Server reported error: %s\n"), strerror(res_errno)); + return -1; + } + + return 0; +} + +int main(int argc, char *argv[], char *envp[]) { + struct sockaddr_un addr; + tinc_ctl_greeting_t greeting; + int fd; + int result; + + program_name = argv[0]; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + if(!parse_options(argc, argv)) + return 1; + + make_names(); + + if(show_version) { + printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE, + VERSION, __DATE__, __TIME__, PROT_CURRENT); + printf(_("Copyright (C) 1998-2007 Ivo Timmermans, Guus Sliepen and others.\n" + "See the AUTHORS file for a complete list.\n\n" + "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n" + "and you are welcome to redistribute it under certain conditions;\n" + "see the file COPYING for details.\n")); + + return 0; + } + + if(show_help) { + usage(false); + return 0; + } + + if(optind >= argc) { + fprintf(stderr, _("Not enough arguments.\n")); + usage(true); + return 1; + } + + // First handle commands that don't involve connecting to a running tinc daemon. + + if(!strcasecmp(argv[optind], "generate-keys")) { - return !keygen(optind > argc ? atoi(argv[optind + 1]) : 1024); ++ return !keygen(optind > argc ? atoi(argv[optind + 1]) : 2048); + } + + if(!strcasecmp(argv[optind], "start")) { + argv[optind] = NULL; + execve(SBINDIR "/tincd", argv, envp); + fprintf(stderr, _("Could not start tincd: %s"), strerror(errno)); + return 1; + } + + /* + * Now handle commands that do involve connecting to a running tinc daemon. + * Authenticate the server by ensuring the parent directory can be + * traversed only by root. Note this is not totally race-free unless all + * ancestors are writable only by trusted users, which we don't verify. + */ + + struct stat statbuf; + char *lastslash = strrchr(controlsocketname, '/'); + if(lastslash != NULL) { + /* control socket is not in cwd; stat its parent */ + *lastslash = 0; + result = stat(controlsocketname, &statbuf); + *lastslash = '/'; + } else + result = stat(".", &statbuf); + + if(result < 0) { + fprintf(stderr, _("Unable to check control socket directory permissions: %s\n"), strerror(errno)); + return 1; + } + + if(statbuf.st_uid != 0 || (statbuf.st_mode & S_IXOTH) != 0 || (statbuf.st_gid != 0 && (statbuf.st_mode & S_IXGRP)) != 0) { + fprintf(stderr, _("Insecure permissions on control socket directory\n")); + return 1; + } + + if(strlen(controlsocketname) >= sizeof addr.sun_path) { + fprintf(stderr, _("Control socket filename too long!\n")); + return 1; + } + + fd = socket(PF_UNIX, SOCK_STREAM, 0); + if(fd < 0) { + fprintf(stderr, _("Cannot create UNIX socket: %s\n"), strerror(errno)); + return 1; + } + + memset(&addr, 0, sizeof addr); + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1); + + if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) { + fprintf(stderr, _("Cannot connect to %s: %s\n"), controlsocketname, strerror(errno)); + return 1; + } + + if(fullread(fd, &greeting, sizeof greeting) == -1) { + fprintf(stderr, _("Cannot read greeting from control socket: %s\n"), + strerror(errno)); + return 1; + } + + if(greeting.version != TINC_CTL_VERSION_CURRENT) { + fprintf(stderr, _("Version mismatch: server %d, client %d\n"), + greeting.version, TINC_CTL_VERSION_CURRENT); + return 1; + } + + if(!strcasecmp(argv[optind], "pid")) { + printf("%d\n", greeting.pid); + return 0; + } + + if(!strcasecmp(argv[optind], "stop")) { + return send_ctl_request_cooked(fd, REQ_STOP, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind], "reload")) { + return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind], "restart")) { + return send_ctl_request_cooked(fd, REQ_RESTART, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind], "dump")) { + if(argc < optind + 2) { + fprintf(stderr, _("Not enough arguments.\n")); + usage(true); + return 1; + } + + if(!strcasecmp(argv[optind+1], "nodes")) { + return send_ctl_request_cooked(fd, REQ_DUMP_NODES, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind+1], "edges")) { + return send_ctl_request_cooked(fd, REQ_DUMP_EDGES, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind+1], "subnets")) { + return send_ctl_request_cooked(fd, REQ_DUMP_SUBNETS, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind+1], "connections")) { + return send_ctl_request_cooked(fd, REQ_DUMP_CONNECTIONS, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind+1], "graph")) { + return send_ctl_request_cooked(fd, REQ_DUMP_GRAPH, NULL, 0) != -1; + } + + fprintf(stderr, _("Unknown dump type '%s'.\n"), argv[optind+1]); + usage(true); + return 1; + } + + if(!strcasecmp(argv[optind], "purge")) { + return send_ctl_request_cooked(fd, REQ_PURGE, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind], "debug")) { + int debuglevel; + + if(argc != optind + 2) { + fprintf(stderr, "Invalid arguments.\n"); + return 1; + } + debuglevel = atoi(argv[optind+1]); + return send_ctl_request_cooked(fd, REQ_SET_DEBUG, &debuglevel, + sizeof debuglevel) != -1; + } + + if(!strcasecmp(argv[optind], "retry")) { + return send_ctl_request_cooked(fd, REQ_RETRY, NULL, 0) != -1; + } + + if(!strcasecmp(argv[optind], "reload")) { + return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1; + } + + fprintf(stderr, _("Unknown command `%s'.\n"), argv[optind]); + usage(true); + + close(fd); + + return 0; +} diff --cc src/tincd.c index 76053a00,602f18b1..48f5faf8 --- a/src/tincd.c +++ b/src/tincd.c @@@ -240,11 -412,11 +241,11 @@@ static void make_names(void } #endif - if(!pidfilename) - xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname); + if(!controlsocketname) - asprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname); ++ xasprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname); if(!logfilename) - asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname); + xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname); if(netname) { if(!confbase)