From 4ef2d36615eccb3d2b7965693afe91fb4de67445 Mon Sep 17 00:00:00 2001 From: Jule Anger Date: Tue, 22 Mar 2022 16:06:37 +0100 Subject: [PATCH] audit_logging: add method to replace the object for a given key with a new object Signed-off-by: Jule Anger Reviewed-by: Ralph Boehme --- lib/audit_logging/audit_logging.c | 46 +++++++++++++++++++++++++++++++++++++++ lib/audit_logging/audit_logging.h | 4 ++++ 2 files changed, 50 insertions(+) diff --git a/lib/audit_logging/audit_logging.c b/lib/audit_logging/audit_logging.c index 87378e1bb95..43acf9512c9 100644 --- a/lib/audit_logging/audit_logging.c +++ b/lib/audit_logging/audit_logging.c @@ -906,6 +906,52 @@ int json_add_guid(struct json_object *object, } /* + * @brief Replaces the object for a given key with a given json object. + * + * If key already exists, the value will be replaced. Otherwise the given + * value will be added under the given key. + * + * @param object the JSON object to be updated. + * @param key the key which will be updated. + * @param new_obj the new value object to be inserted. + * + * @return 0 the operation was successful + * -1 the operation failed (e.j. if one of the paramters is invalid) + */ +int json_update_object(struct json_object *object, + const char *key, + struct json_object *new_obj) +{ + int ret = 0; + + if (json_is_invalid(object)) { + DBG_ERR("Unable to update key [%s], " + "target object is invalid\n", + key); + return JSON_ERROR; + } + if (json_is_invalid(new_obj)) { + DBG_ERR("Unable to update key [%s], " + "new object is invalid\n", + key); + return JSON_ERROR; + } + + if (key == NULL) { + DBG_ERR("Unable to add null String as key\n"); + return JSON_ERROR; + } + + ret = json_object_set(object->root, key, new_obj->root); + if (ret != 0) { + DBG_ERR("Unable to update object\n"); + return ret; + } + + return ret; +} + +/* * @brief Convert a JSON object into a string * * Convert the json object into a string suitable for printing on a log line, diff --git a/lib/audit_logging/audit_logging.h b/lib/audit_logging/audit_logging.h index 86e9134a86a..49576ece68d 100644 --- a/lib/audit_logging/audit_logging.h +++ b/lib/audit_logging/audit_logging.h @@ -87,6 +87,10 @@ _WARN_UNUSED_RESULT_ int json_add_guid(struct json_object *object, const char *name, const struct GUID *guid); +_WARN_UNUSED_RESULT_ int json_update_object(struct json_object *object, + const char *key, + struct json_object *new_obj); + _WARN_UNUSED_RESULT_ struct json_object json_get_array( struct json_object *object, const char *name); _WARN_UNUSED_RESULT_ struct json_object json_get_object( -- 2.11.4.GIT