From f75e71bc693847af71f61fb72cd788e3e47f9bd3 Mon Sep 17 00:00:00 2001
From: Guus Sliepen <guus@tinc-vpn.org>
Date: Sat, 3 Apr 2010 09:46:45 +0100
Subject: [PATCH] Convert Port to numeric form before sending it to other
 nodes.

If one uses a symbolic name for the Port option, tinc will send that name
literally to other nodes.  However, it is not guaranteed that all nodes have
the same contents in /etc/services, or have such a file at all.
---
 src/net_setup.c     | 10 ++++++++++
 src/netutl.c        |  6 ++++--
 src/protocol_auth.c |  5 ++---
 3 files changed, 16 insertions(+), 5 deletions(-)

diff --git a/src/net_setup.c b/src/net_setup.c
index 70291bff..813c58ba 100644
--- a/src/net_setup.c
+++ b/src/net_setup.c
@@ -309,6 +309,16 @@ bool setup_myself(void) {
 			&& !get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
 		myport = xstrdup("655");
 
+	if(!atoi(myport)) {
+		struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
+		sockaddr_t sa;
+		if(!ai || !ai->ai_addr)
+			return false;
+		free(myport);
+		memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
+		sockaddr2str(&sa, NULL, &myport);
+	}
+
 	/* Read in all the subnets specified in the host configuration file */
 
 	cfg = lookup_config(myself->connection->config_tree, "Subnet");
diff --git a/src/netutl.c b/src/netutl.c
index b8ecdd1e..6acdffae 100644
--- a/src/netutl.c
+++ b/src/netutl.c
@@ -102,8 +102,10 @@ void sockaddr2str(const sockaddr_t *sa, char **addrstr, char **portstr) {
 	if(scopeid)
 		*scopeid = '\0';		/* Descope. */
 
-	*addrstr = xstrdup(address);
-	*portstr = xstrdup(port);
+	if(addrstr)
+		*addrstr = xstrdup(address);
+	if(portstr)
+		*portstr = xstrdup(port);
 }
 
 char *sockaddr2hostname(const sockaddr_t *sa) {
diff --git a/src/protocol_auth.c b/src/protocol_auth.c
index 06735dcf..98d5b61d 100644
--- a/src/protocol_auth.c
+++ b/src/protocol_auth.c
@@ -497,7 +497,7 @@ static void send_everything(connection_t *c) {
 
 bool ack_h(connection_t *c) {
 	char hisport[MAX_STRING_SIZE];
-	char *hisaddress, *dummy;
+	char *hisaddress;
 	int weight, mtu;
 	uint32_t options;
 	node_t *n;
@@ -566,10 +566,9 @@ bool ack_h(connection_t *c) {
 	c->edge = new_edge();
 	c->edge->from = myself;
 	c->edge->to = n;
-	sockaddr2str(&c->address, &hisaddress, &dummy);
+	sockaddr2str(&c->address, &hisaddress, NULL);
 	c->edge->address = str2sockaddr(hisaddress, hisport);
 	free(hisaddress);
-	free(dummy);
 	c->edge->weight = (weight + c->estimated_weight) / 2;
 	c->edge->connection = c;
 	c->edge->options = c->options;
-- 
2.39.5