From 9d7f8a3ce41157c1331cf298daf46f76577c338b Mon Sep 17 00:00:00 2001
From: Marios Makassikis <mmakassikis@freebox.fr>
Date: Mon, 7 Nov 2022 10:13:38 +0100
Subject: [PATCH 14/17] ksmbd-tools: mountd: check gethostname() return value

gethostname() can fail, and depending on the libc version the string is
not always null terminated, which will cause errors afterwards.

Signed-off-by: Marios Makassikis <mmakassikis@freebox.fr>
---
 mountd/rpc_lsarpc.c | 4 +++-
 mountd/rpc_samr.c   | 8 ++++++--
 mountd/smbacl.c     | 4 +++-
 3 files changed, 12 insertions(+), 4 deletions(-)

diff --git a/mountd/rpc_lsarpc.c b/mountd/rpc_lsarpc.c
index 8220e32c503e..2bcbf7feaa63 100644
--- a/mountd/rpc_lsarpc.c
+++ b/mountd/rpc_lsarpc.c
@@ -708,7 +708,9 @@ int rpc_lsarpc_init(void)
 	 * ksmbd supports the standalone server and
 	 * uses the hostname as the domain name.
 	 */
-	gethostname(domain_string, NAME_MAX);
+	if (gethostname(domain_string, NAME_MAX))
+		return -ENOMEM;
+
 	domain_name = g_ascii_strup(domain_string, strlen(domain_string));
 	ph_table = g_hash_table_new(g_str_hash, g_str_equal);
 	if (!ph_table)
diff --git a/mountd/rpc_samr.c b/mountd/rpc_samr.c
index d5a15d5bb769..446808b028e4 100644
--- a/mountd/rpc_samr.c
+++ b/mountd/rpc_samr.c
@@ -422,7 +422,9 @@ static int samr_query_user_info_return(struct ksmbd_rpc_pipe *pipe)
 	if (!ch)
 		return KSMBD_RPC_EBAD_FID;
 
-	gethostname(hostname, NAME_MAX);
+	if (gethostname(hostname, NAME_MAX))
+		return KSMBD_RPC_ENOMEM;
+
 	home_dir_len = 2 + strlen(hostname) + 1 + strlen(ch->user->name);
 
 	home_dir = g_try_malloc0(home_dir_len);
@@ -1035,7 +1037,9 @@ int rpc_samr_init(void)
 	 * ksmbd supports the standalone server and
 	 * uses the hostname as the domain name.
 	 */
-	gethostname(hostname, NAME_MAX);
+	if (gethostname(hostname, NAME_MAX))
+		return -ENOMEM;
+
 	domain_name = g_ascii_strup(hostname, strlen(hostname));
 	rpc_samr_add_domain_entry(domain_name);
 	rpc_samr_add_domain_entry("Builtin");
diff --git a/mountd/smbacl.c b/mountd/smbacl.c
index 2793f7625191..936094f0c444 100644
--- a/mountd/smbacl.c
+++ b/mountd/smbacl.c
@@ -168,7 +168,9 @@ int set_domain_name(struct smb_sid *sid, char *domain, int *type)
 	if (!smb_compare_sids(sid, &sid_domain) &&
 	    !memcmp(&sid->sub_auth[1], global_conf.gen_subauth,
 		    sizeof(__u32) * 3)) {
-		gethostname(domain_string, NAME_MAX);
+		if (gethostname(domain_string, NAME_MAX))
+			return -ENOMEM;
+
 		domain_name = g_ascii_strup(domain_string,
 				strlen(domain_string));
 		if (!domain_name)
-- 
2.25.1

