[03/10] _fireinfo: Refactor some code

Message ID 20210507111654.2397-4-michael.tremer@ipfire.org
State Accepted
Headers
Series [01/10] configure: Link against Python 3 |

Commit Message

Michael Tremer May 7, 2021, 11:16 a.m. UTC
  No functional changes. This only makes the code more similar to what I
am writing in other projects and makes it tidier.

Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
---
 src/_fireinfo/fireinfo.c | 35 ++++++++++++++++++-----------------
 1 file changed, 18 insertions(+), 17 deletions(-)
  

Patch

diff --git a/src/_fireinfo/fireinfo.c b/src/_fireinfo/fireinfo.c
index 58ee7e2..75ccb2c 100644
--- a/src/_fireinfo/fireinfo.c
+++ b/src/_fireinfo/fireinfo.c
@@ -58,23 +58,22 @@  const char *hypervisor_vendors[] = {
 
 #define NEWLINE "\n\r"
 
-char *truncate_nl(char *s) {
+static void truncate_nl(char *s) {
 	assert(s);
 
-	s[strcspn(s, NEWLINE)] = 0;
-	return s;
+	s[strcspn(s, NEWLINE)] = '\0';
 }
 
-int read_one_line_file(const char *filename, char **line) {
-	assert(filename);
-	assert(line);
+static int read_one_line_file(const char *filename, char **line) {
+	char t[2048];
+
+	if (!filename || !line)
+		return -EINVAL;
 
-	FILE *f = NULL;
-	f = fopen(filename, "re");
+	FILE* f = fopen(filename, "re");
 	if (!f)
 		return -errno;
 
-	char t[2048];
 	if (!fgets(t, sizeof(t), f)) {
 		if (ferror(f))
 			return errno ? -errno : -EIO;
@@ -85,6 +84,7 @@  int read_one_line_file(const char *filename, char **line) {
 	char *c = strdup(t);
 	if (!c)
 		return -ENOMEM;
+
 	truncate_nl(c);
 
 	*line = c;
@@ -171,7 +171,6 @@  int detect_hypervisor(int *hypervisor) {
 	return 0;
 }
 
-
 static PyObject *
 do_detect_hypervisor() {
 	/*
@@ -197,27 +196,29 @@  do_get_harddisk_serial(PyObject *o, PyObject *args) {
 		Python wrapper around read_harddisk_serial.
 	*/
 	static struct hd_driveid hd;
-	int fd;
 	const char *device = NULL;
+	char serial[21];
 
 	if (!PyArg_ParseTuple(args, "s", &device))
 		return NULL;
 
-	if ((fd = open(device, O_RDONLY | O_NONBLOCK)) < 0) {
+	int fd = open(device, O_RDONLY | O_NONBLOCK);
+	if (fd < 0) {
 		PyErr_Format(PyExc_OSError, "Could not open block device: %s", device);
 		return NULL;
 	}
 
 	if (!ioctl(fd, HDIO_GET_IDENTITY, &hd)) {
-		char serial[21];
-		memset(serial, 0, sizeof(serial));
-
-		strncpy(serial, (const char *)hd.serial_no, sizeof(serial) - 1);
+		snprintf(serial, sizeof(serial) - 1, "%s", (const char *)hd.serial_no);
 
-		if (serial[0])
+		if (*serial) {
+			close(fd);
 			return PyUnicode_FromString(serial);
+		}
 	}
 
+	close(fd);
+
 	Py_RETURN_NONE;
 }