]> git.ipfire.org Git - oddments/fireinfo.git/commitdiff
_fireinfo: Refactor some code
authorMichael Tremer <michael.tremer@ipfire.org>
Thu, 6 May 2021 15:36:47 +0000 (15:36 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Thu, 6 May 2021 15:36:47 +0000 (15:36 +0000)
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

index 58ee7e22abede8dedd64747873dca107ec8cd066..75ccb2cbf3b7bab3f29a0301ff076dc7bb80a041 100644 (file)
@@ -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;
 }