Blob Blame Raw
From 85b835f8258a57e3b23de47a255dddd822d5bfb3 Mon Sep 17 00:00:00 2001
From: Sumit Bose <sbose@redhat.com>
Date: Fri, 15 Mar 2019 17:33:44 +0100
Subject: [PATCH] library: use getaddrinfo with AI_CANONNAME to find a FQDN

Currently adcli creates service principals only with a short name if the
hostname of the client is a short name. This would fail is
Kerberos/GSSAPI clients will use the fully-qualified domain name (FQDN)
to access the host.

With this patch adcli tries to expand the short name by calling
getaddrinfo with the AI_CANONNAME hint.

Related to https://gitlab.freedesktop.org/realmd/adcli/issues/1
---
 doc/adcli.xml    |  6 +++++-
 library/adconn.c | 30 +++++++++++++++++++++++++++++-
 2 files changed, 34 insertions(+), 2 deletions(-)

diff --git a/doc/adcli.xml b/doc/adcli.xml
index 97dec08..4722c3a 100644
--- a/doc/adcli.xml
+++ b/doc/adcli.xml
@@ -228,7 +228,11 @@ Password for Administrator:
 			<term><option>-H, --host-fqdn=<parameter>host</parameter></option></term>
 			<listitem><para>Override the local machine's fully qualified
 			domain name. If not specified, the local machine's hostname
-			will be retrieved via <function>gethostname()</function>.</para></listitem>
+			will be retrieved via <function>gethostname()</function>.
+			If <function>gethostname()</function> only returns a short name
+			<function>getaddrinfo()</function> with the AI_CANONNAME hint
+			is called to expand the name to a fully qualified domain
+			name.</para></listitem>
 		</varlistentry>
 		<varlistentry>
 			<term><option>-K, --host-keytab=<parameter>/path/to/keytab</parameter></option></term>
diff --git a/library/adconn.c b/library/adconn.c
index e2250e3..f6c23d3 100644
--- a/library/adconn.c
+++ b/library/adconn.c
@@ -86,11 +86,36 @@ struct _adcli_conn_ctx {
 	krb5_keytab keytab;
 };
 
+static char *try_to_get_fqdn (const char *host_name)
+{
+	int ret;
+	char *fqdn = NULL;
+	struct addrinfo *res;
+	struct addrinfo hints;
+
+	memset (&hints, 0, sizeof (struct addrinfo));
+	hints.ai_socktype = SOCK_DGRAM;
+	hints.ai_flags = AI_CANONNAME;
+
+	ret = getaddrinfo (host_name, NULL, &hints, &res);
+	if (ret != 0) {
+		_adcli_err ("Failed to find FQDN: %s", gai_strerror (ret));
+		return NULL;
+	}
+
+	fqdn = strdup (res->ai_canonname);
+
+	freeaddrinfo (res);
+
+	return fqdn;
+}
+
 static adcli_result
 ensure_host_fqdn (adcli_result res,
                   adcli_conn *conn)
 {
 	char hostname[HOST_NAME_MAX + 1];
+	char *fqdn = NULL;
 	int ret;
 
 	if (res != ADCLI_SUCCESS)
@@ -107,7 +132,10 @@ ensure_host_fqdn (adcli_result res,
 		return ADCLI_ERR_UNEXPECTED;
 	}
 
-	conn->host_fqdn = strdup (hostname);
+	if (strchr (hostname, '.') == NULL) {
+		fqdn = try_to_get_fqdn (hostname);
+	}
+	conn->host_fqdn = fqdn != NULL ? fqdn : strdup (hostname);
 	return_unexpected_if_fail (conn->host_fqdn != NULL);
 	return ADCLI_SUCCESS;
 }
-- 
2.20.1