From f24d89b76811f7b2bbfea787bb403358f960f097 Mon Sep 17 00:00:00 2001
From: Peiyang Wang <wangpeiyang1@huawei.com>
Date: Wed, 21 Aug 2024 10:30:09 +0800
Subject: [PATCH 15/27] hikptool: nic: adding NUL at the end of the buffer
 length that is actually read.

When pread is called, the return value may be smaller than the length that
want to read, the position of adding NUL is too much and memory might be
exposed. To avoid that case, to add NUL at the end of the buffer length
that is actually read.

Signed-off-by: Peiyang Wang <wangpeiyang1@huawei.com>
---
 net/hikp_net_lib.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/net/hikp_net_lib.c b/net/hikp_net_lib.c
index 23adbdc..fbf03bd 100644
--- a/net/hikp_net_lib.c
+++ b/net/hikp_net_lib.c
@@ -47,13 +47,14 @@ static int hikp_read_net_pci_info(const char *file_path, char *content, size_t l
 
 	ret = pread(fd, content, len - 1, 0);
 	if (ret < 0) {
-		close(fd);
-		return -EIO;
+		ret = -errno;
+	} else {
+		content[ret] = '\0'; // The invoker ensures that the bounds are not crossed.
+		ret = 0;
 	}
-	content[len - 1] = '\0'; // The invoker ensures that the bounds are not crossed.
-	close(fd);
 
-	return 0;
+	close(fd);
+	return ret;
 }
 
 int hikp_net_creat_sock(void)
-- 
2.45.0.windows.1

