]> git.ipfire.org Git - pakfire.git/commitdiff
_pakfire: Fix memory leaks in generating key lists
authorMichael Tremer <michael.tremer@ipfire.org>
Fri, 9 Jul 2021 10:19:58 +0000 (10:19 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Fri, 9 Jul 2021 10:19:58 +0000 (10:19 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/_pakfire/pakfire.c

index 9cdf190f493c88c68fabedc3331cd7e913a5bac8..a8b9f944d8af72c352597cba4d193b63a112ee9b 100644 (file)
@@ -407,23 +407,28 @@ static PyObject* Pakfire_update(PakfireObject* self, PyObject* args, PyObject* k
        Py_RETURN_NONE;
 }
 
-static PyObject* _import_keylist(PakfireObject* pakfire, struct pakfire_key** keys) {
+static PyObject* Pakfire_keys_to_list(struct pakfire_key** keys) {
        PyObject* list = PyList_New(0);
 
-       while (keys && *keys) {
-               struct pakfire_key* key = *keys++;
+       // Empty input?
+       if (!keys)
+               return list;
 
-               PyObject* object = new_key(&KeyType, key);
-               PyList_Append(list, object);
+       // Push all keys onto the list
+       for (struct pakfire_key** key = keys; *key; key++) {
+               PyObject* object = new_key(&KeyType, *key);
+               if (!object)
+                       goto ERROR;
 
-               // Drop reference to the Python object
+               PyList_Append(list, object);
                Py_DECREF(object);
-
-               // Drop reference to the key object
-               pakfire_key_unref(key);
        }
 
        return list;
+
+ERROR:
+       Py_DECREF(list);
+       return NULL;
 }
 
 static PyObject* Pakfire_get_keys(PakfireObject* self) {
@@ -435,8 +440,15 @@ static PyObject* Pakfire_get_keys(PakfireObject* self) {
                return NULL;
        }
 
-#warning THIS LEAKS MEMORY
-       return _import_keylist(self, keys);
+       // Convert keys to list
+       PyObject* list = Pakfire_keys_to_list(keys);
+
+       // Free keys
+       for (struct pakfire_key** key = keys; *key; key++)
+               pakfire_key_unref(*key);
+       free(keys);
+
+       return list;
 }
 
 static PyObject* Pakfire_get_key(PakfireObject* self, PyObject* args) {
@@ -498,8 +510,15 @@ static PyObject* Pakfire_import_key(PakfireObject* self, PyObject* args) {
                return NULL;
        }
 
-#warning THIS LEAKS MEMORY
-       return _import_keylist(self, keys);
+       // Convert keys to list
+       PyObject* list = Pakfire_keys_to_list(keys);
+
+       // Free keys
+       for (struct pakfire_key** key = keys; *key; key++)
+               pakfire_key_unref(*key);
+       free(keys);
+
+       return list;
 }
 
 static PyObject* Pakfire_fetch_key(PakfireObject* self, PyObject* args, PyObject* kwds) {