Refactor errno logging 95/279395/3
authorKonrad Lipinski <k.lipinski2@samsung.com>
Tue, 2 Aug 2022 13:33:07 +0000 (15:33 +0200)
committerKonrad Lipinski <k.lipinski2@samsung.com>
Wed, 10 Aug 2022 09:58:01 +0000 (11:58 +0200)
* Macros to factor out common patterns.
* Minor error detection optimization at sites that happened to be nearby.

Change-Id: Ibd14776e5d52fa59c00098317bc8031fb351eb0b

18 files changed:
src/client/client-label-monitor.cpp
src/client/client-security-manager.cpp
src/common/connection.cpp
src/common/cynara.cpp
src/common/file-lock.cpp
src/common/filesystem.cpp
src/common/mount-monitor.cpp
src/common/mount-namespace.cpp
src/common/permissible-set.cpp
src/common/service_impl_utils.cpp
src/common/smack-labels.cpp
src/common/utils.cpp
src/dpl/core/include/dpl/errno_string.h
src/server/cleanup/security-manager-cleanup.cpp
src/server/main/server-main.cpp
src/server/main/socket-manager.cpp
test/test_file-lock.cpp
test/test_service_impl_utils.cpp

index 9095eb33519b18143f254432dfb6adfcd3c749f3..6b40e05211ed97b29756d8d3f647b33322b88a05 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016-2020 Samsung Electronics Co., Ltd. All rights reserved.
+ * Copyright (c) 2016-2022 Samsung Electronics Co., Ltd. All rights reserved
  *
  * This file is licensed under the terms of MIT License or the Apache License
  * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
@@ -95,7 +95,7 @@ static lib_retcode inotify_add_watch_full(int fd, const char* pathname, uint32_t
 {
     int inotify_fd = inotify_add_watch(fd, pathname, mask);
     if (inotify_fd == -1) {
-        LogError("Inotify watch failed on file " << pathname << ": " << GetErrnoString(errno));
+        LogErrno("Inotify watch on file " << pathname);
         return SECURITY_MANAGER_ERROR_WATCH_ADD_TO_FILE_FAILED;
     }
     *wd = inotify_fd;
@@ -131,7 +131,7 @@ int security_manager_app_labels_monitor_init(app_labels_monitor **monitor)
 
         ret = inotify_init();
         if (ret == -1) {
-            LogError("Inotify init failed: " << GetErrnoString(errno));
+            LogErrno("Inotify init");
             return SECURITY_MANAGER_ERROR_WATCH_ADD_TO_FILE_FAILED;
         }
         monitorPtr.get()->inotify = ret;
@@ -166,15 +166,13 @@ void security_manager_app_labels_monitor_finish(app_labels_monitor *monitor)
             if (monitorPtr->global_labels_file_watch != -1) {
                 int ret = inotify_rm_watch(monitorPtr->inotify, monitorPtr->global_labels_file_watch);
                 if (ret == -1) {
-                    LogError("Inotify watch removal failed on file " <<
-                            APPS_LABELS_FILE << ": " << GetErrnoString(errno));
+                    LogErrno("Inotify watch removal on file " << APPS_LABELS_FILE);
                 }
             }
             if (monitorPtr->user_labels_file_watch != -1) {
                 int ret = inotify_rm_watch(monitorPtr->inotify, monitorPtr->user_labels_file_watch);
                 if (ret == -1) {
-                    LogError("Inotify watch removal failed on file "
-                            << monitor->user_label_file_path << ": " << GetErrnoString(errno));
+                    LogErrno("Inotify watch removal on file " << monitor->user_label_file_path);
                 }
             }
             close(monitorPtr->inotify);
@@ -235,7 +233,7 @@ int security_manager_app_labels_monitor_process(app_labels_monitor *monitor)
         int avail;
         int ret = ioctl(monitor->inotify, FIONREAD, &avail);
         if (ret == -1) {
-            LogError("Ioctl on inotify descriptor failed: " << GetErrnoString(errno));
+            LogErrno("Ioctl on inotify descriptor");
             return SECURITY_MANAGER_ERROR_UNKNOWN;
         }
 
@@ -243,7 +241,7 @@ int security_manager_app_labels_monitor_process(app_labels_monitor *monitor)
         for (int pos = 0; pos < avail;) {
             int ret = TEMP_FAILURE_RETRY(read(monitor->inotify, bufPtr.get() + pos, avail - pos));
             if (ret == -1) {
-                LogError("Inotify read failed: " << GetErrnoString(errno));
+                LogErrno("Inotify read");
                 return SECURITY_MANAGER_ERROR_UNKNOWN;
             }
             pos += ret;
index ff9f7da1e8223f4c0cf405bbd62193ed1bbf5a4a..314e4fb2e4e8a66128efff6c379736aeb8c21bfa 100644 (file)
@@ -653,7 +653,7 @@ static inline int security_manager_sync_threads_internal(const std::string &app_
                 if (ESRCH == err) // thread already gone
                     threads_gone++;
                 else
-                    LogError("Error in tgkill()" << GetErrnoString(err));
+                    LogWithErrno(err, "tgkill()");
 
                 continue;
             }
@@ -712,8 +712,7 @@ static int security_manager_set_process_groups_internal(const std::vector<gid_t>
 
     ret = getgroups(NGROUPS_MAX + 1, grp);
     if (ret < 0) {
-        LogError("Unable to get list of current supplementary groups: " <<
-            GetErrnoString(errno));
+        LogErrno("get list of current supplementary groups");
         return SECURITY_MANAGER_ERROR_UNKNOWN;
     }
 
@@ -762,8 +761,7 @@ static int security_manager_set_process_groups_internal(const std::vector<gid_t>
     LogDebug("Final supplementary groups count: " << size);
 
     if (setgroups(size, grp) < 0) {
-        LogError("Unable to set list of current supplementary groups: " <<
-            GetErrnoString(errno));
+        LogErrno("set list of current supplementary groups");
         return SECURITY_MANAGER_ERROR_UNKNOWN;
     }
 
index 469f1a5ccd7461971e655ca59c32502397dc9e21..b1337079449d9430eaf6ee508941aeb5eda9e4a6 100644 (file)
@@ -63,8 +63,7 @@ int waitForSocket(int sock, int event, int timeout) {
     if (0 == retval) {
         LogDebug("Poll timeout");
     } else if (-1 == retval) {
-        int err = errno;
-        LogError("Error in poll: " << GetErrnoString(err));
+        LogErrno("poll");
     }
     return retval;
 }
@@ -89,16 +88,14 @@ public:
 
         m_sock = socket(AF_UNIX, SOCK_STREAM, 0);
         if (m_sock < 0) {
-            int err = errno;
-            LogError("Error creating socket: " << GetErrnoString(err));
+            LogErrno("socket");
             return SECURITY_MANAGER_ERROR_SOCKET;
         }
 
         if ((flags = fcntl(m_sock, F_GETFL, 0)) < 0 ||
             fcntl(m_sock, F_SETFL, flags | O_NONBLOCK) < 0)
         {
-            int err = errno;
-            LogError("Error in fcntl: " << GetErrnoString(err));
+            LogErrno("fcntl");
             return SECURITY_MANAGER_ERROR_SOCKET;
         }
 
@@ -126,8 +123,7 @@ public:
             retval = getsockopt(m_sock, SOL_SOCKET, SO_ERROR, &error, &len);
 
             if (-1 == retval) {
-                int err = errno;
-                LogError("Error in getsockopt: " << GetErrnoString(err));
+                LogErrno("getsockopt");
                 return SECURITY_MANAGER_ERROR_SOCKET;
             }
 
@@ -137,7 +133,7 @@ public:
             }
 
             if (error != 0) {
-                LogError("Error in connect: " << GetErrnoString(error));
+                LogWithErrno(error, "connect");
                 return SECURITY_MANAGER_ERROR_SOCKET;
             }
 
@@ -146,7 +142,7 @@ public:
 
         if (-1 == retval) {
             int err = errno;
-            LogError("Error connecting socket: " << GetErrnoString(err));
+            LogWithErrno(err, "connecting socket");
             if (err == EACCES)
                 return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
             if (err == ENOTSOCK)
@@ -187,8 +183,7 @@ int sendToServer(char const * const interface, MessageBuffer &buffer) {
         }
         const auto temp = TEMP_FAILURE_RETRY(::send(sock.Get(), buffer.Ptr(), buffer.OutputSize(), MSG_NOSIGNAL));
         if (temp < 0) {
-            int err = errno;
-            LogError("Error in write: " << GetErrnoString(err));
+            LogErrno("write");
             return SECURITY_MANAGER_ERROR_SOCKET;
         }
         if (buffer.OutputDone(temp))
@@ -206,10 +201,8 @@ int sendToServer(char const * const interface, MessageBuffer &buffer) {
         if (temp <= 0) {
             if (!temp)
                 LogError("Read return 0/Connection closed by server(?)");
-            else {
-                int err = errno;
-                LogError("Error in read: " << GetErrnoString(err));
-            }
+            else
+                LogErrno("read");
             return SECURITY_MANAGER_ERROR_SOCKET;
         }
         switch (buffer.InputDone(temp)) {
index fcb6baa5831e400106210c320e1ac1fa95f56be1..abdab35e011be43bc78b84431f2692a5c2441348 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved.
+ * Copyright (c) 2014-2022 Samsung Electronics Co., Ltd. All rights reserved
  *
  * This file is licensed under the terms of MIT License or the Apache License
  * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
@@ -887,7 +887,7 @@ int CynaraAdmin::getPrivilegeManagerMaxLevel(const std::string &label, const std
 Cynara::Cynara() : m_eventFd(eventfd(0, 0)), m_cynaraFd(m_eventFd), m_cynaraFdEvents(0), m_terminate(false)
 {
     if (m_eventFd == -1) {
-        LogError("Error while creating eventfd: " << GetErrnoString(errno));
+        LogErrno("creating eventfd");
         ThrowMsg(CynaraException::UnknownError, "Error while creating eventfd");
     }
 
@@ -919,17 +919,15 @@ Cynara::~Cynara()
 
 void Cynara::threadNotifyPut()
 {
-    int ret = eventfd_write(m_eventFd, 1);
-    if (ret == -1)
-        LogError("Unexpected error while writing to eventfd: " << GetErrnoString(errno));
+    if (eventfd_write(m_eventFd, 1))
+        LogErrno("writing to eventfd");
 }
 
 void Cynara::threadNotifyGet()
 {
     eventfd_t value;
-    int ret = eventfd_read(m_eventFd, &value);
-    if (ret == -1)
-        LogError("Unexpected error while reading from eventfd: " << GetErrnoString(errno));
+    if (eventfd_read(m_eventFd, &value))
+        LogErrno("reading from eventfd");
 }
 
 void Cynara::statusCallback(int oldFd, int newFd, cynara_async_status status)
index 021a9988e07924515e2b20fbed4b7b37afc3f4ee..620461db14e57963e5d4526649891f2d78b0a90e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved.
+ * Copyright (c) 2014-2022 Samsung Electronics Co., Ltd. All rights reserved
  *
  * This file is licensed under the terms of MIT License or the Apache License
  * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
@@ -78,14 +78,11 @@ void FileLocker::Lock()
         return;
 
     int ret;
-    while((-1 == (ret = flock(m_lockFileFd, m_blocking ? LOCK_EX : LOCK_NB | LOCK_EX))) && (errno == EINTR));
+    while ((ret = flock(m_lockFileFd, m_blocking ? LOCK_EX : LOCK_NB | LOCK_EX)) && (errno == EINTR));
     m_locked = ret == 0;
     int err = errno;
-    if (-1 == ret && err != EWOULDBLOCK) {
-        LogError("Error while locking a file " << m_lockFile);
-        ThrowMsg(FileLocker::Exception::LockFailed,
-              "Error while locking a file " << m_lockFile << ", error: " << GetErrnoString(err));
-    }
+    if (ret && err != EWOULDBLOCK)
+        LogAndThrowWithErrno(err, FileLocker::Exception::LockFailed, "locking a file " << m_lockFile);
 
     if (m_locked)
         LogDebug("We have a lock on " << m_lockFile << " file.");
@@ -97,13 +94,10 @@ void FileLocker::Unlock()
 {
     if (m_locked) {
         int ret;
-        while((-1 == (ret = flock(m_lockFileFd, LOCK_UN))) && (errno == EINTR));
-        if (-1 == ret) {
-            int err = errno;
-            LogError("Error while unlocking a file " << m_lockFile);
-            ThrowMsg(FileLocker::Exception::UnlockFailed,
-                 "Error while unlocking a file " << m_lockFile << ", error: " << GetErrnoString(err));
-        }
+        while ((ret = flock(m_lockFileFd, LOCK_UN)) && (errno == EINTR));
+        if (ret)
+            LogAndThrowErrno(FileLocker::Exception::UnlockFailed, "unlocking a file " << m_lockFile);
+
         m_locked = false;
         LogDebug("Lock released.");
     }
index 977752497072b17d16ed809684bc8a0b06bbcc43..3a4a4f5a7754b0f841840e99c2b23a41da60daf5 100644 (file)
@@ -64,32 +64,24 @@ FileNameVector getDirectoryContents(const std::string &path, const mode_t &mode,
 {
     FileNameVector result;
     dirent *ptr;
-    int err;
     auto dir = makeUnique(opendir(path.c_str()), closedir);
 
-    if (!dir) {
-        err = errno;
-        ThrowMsg(FS::Exception::FileError,
-                 "Error opening directory: " << path << " Error: " << GetErrnoString(err));
-    }
+    if (!dir)
+        ThrowErrno(FS::Exception::FileError, "opening directory: " << path);
 
     while (true) {
         errno = 0;
         ptr = readdir(dir.get());
 
         if (!ptr) {
-            if (errno) {
-                err = errno;
-                ThrowMsg(FS::Exception::FileError,
-                         "Error reading directory: " << path << " Error: " << GetErrnoString(err));
-            }
+            if (const auto err = errno)
+                ThrowWithErrno(err, FS::Exception::FileError, "reading directory: " << path);
             break;
         }
 
         struct stat finfo;
-        if (0 > fstatat(dirfd(dir.get()), ptr->d_name, &finfo, AT_SYMLINK_NOFOLLOW)) {
+        if (0 > fstatat(dirfd(dir.get()), ptr->d_name, &finfo, AT_SYMLINK_NOFOLLOW))
             ThrowMsg(FS::Exception::FileError, "Error reading: " << ptr->d_name);
-        }
 
         if (noDot && (!strcmp(ptr->d_name, ".") || !strcmp(ptr->d_name, "..")))
             continue;
@@ -142,9 +134,8 @@ int createDirectory(const std::string &path)
         createDirectory(parent);
     }
 
-    int ret = mkdir(path.c_str(), 0750);
-    if (ret != 0 && errno != EEXIST) {
-        LogError("Failed to create directory: " << path << " " << GetErrnoString(errno));
+    if (mkdir(path.c_str(), 0750) && errno != EEXIST) {
+        LogErrno("create directory: " << path);
         return SECURITY_MANAGER_ERROR_FILE_CREATE_FAILED;
     }
     return SECURITY_MANAGER_SUCCESS;
@@ -152,9 +143,8 @@ int createDirectory(const std::string &path)
 
 int removeDirectory(const std::string &path)
 {
-    int ret = rmdir(path.c_str());
-    if (ret != 0) {
-        LogWarning("Failed to remove directory: " << path << " " << GetErrnoString(errno));
+    if (rmdir(path.c_str())) {
+        WarnErrno("remove directory: " << path);
         return SECURITY_MANAGER_ERROR_FILE_DELETE_FAILED;
     }
     return SECURITY_MANAGER_SUCCESS;
@@ -181,9 +171,8 @@ bool fileExists(const std::string &path)
 
 int removeFile(const std::string &path)
 {
-    int ret = unlink(path.c_str());
-    if (ret != 0) {
-        LogWarning("Failed to remove file: " << path << " " << GetErrnoString(errno));
+    if (unlink(path.c_str())) {
+        WarnErrno("remove file: " << path);
         return SECURITY_MANAGER_ERROR_FILE_DELETE_FAILED;
     }
     return SECURITY_MANAGER_SUCCESS;
@@ -191,9 +180,8 @@ int removeFile(const std::string &path)
 
 int symLink(const std::string &src, const std::string &dst)
 {
-    int ret = symlink(src.c_str(), dst.c_str());
-    if (ret == -1) {
-        LogError("Failed to symlink path " << src << " to " << dst << " " << GetErrnoString(errno));
+    if (symlink(src.c_str(), dst.c_str())) {
+        WarnErrno("symlink path " << src << " to " << dst);
         return SECURITY_MANAGER_ERROR_FILE_CREATE_FAILED;
     }
     return SECURITY_MANAGER_SUCCESS;
index 6dae5fcce9d86540c11c5a009a8e17a78a489181..478af965d98e7cde6c44e182859ff037b1fbd333 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017-2020 Samsung Electronics Co., Ltd. All rights reserved.
+ * Copyright (c) 2017-2022 Samsung Electronics Co., Ltd. All rights reserved
  *
  * This file is licensed under the terms of MIT License or the Apache License
  * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
@@ -148,7 +148,7 @@ void MntMonitor::threadNotifyPut()
 {
     int ret = eventfd_write(m_eventFd, 1);
     if (ret == -1)
-        LogError("Unexpected error while writing to eventfd: " << GetErrnoString(errno));
+        LogErrno("writing to eventfd");
 }
 
 void MntMonitor::threadNotifyGet()
@@ -156,7 +156,7 @@ void MntMonitor::threadNotifyGet()
     eventfd_t value;
     int ret = eventfd_read(m_eventFd, &value);
     if (ret == -1)
-        LogError("Unexpected error while reading from eventfd: " << GetErrnoString(errno));
+        LogErrno("reading from eventfd");
 }
 
 void MntMonitor::run()
index 8294a581ec3e61a8835c040eacacde654d62c939..89fed4eb6ef4ce67566426ba3175c5d9ee866e7b 100644 (file)
@@ -160,9 +160,8 @@ bool isPrivacyPrivilegeMountNamespaceEnabled(void)
 
 int createMountNamespace(void)
 {
-    int ret = unshare(CLONE_NEWNS);
-    if (ret != 0) {
-        LogError("Failed to unshare mount namespace: " << GetErrnoString(errno));
+    if (unshare(CLONE_NEWNS)) {
+        LogErrno("unshare mount namespace");
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
     return SECURITY_MANAGER_SUCCESS;
@@ -172,15 +171,16 @@ int enterMountNamespace(const Path &mntPath)
 {
     int fd = open(mntPath.c_str(), O_RDONLY);
     if (fd < 0) {
-        LogError("Failed to open " << mntPath << ": " << GetErrnoString(errno));
+        LogErrno("open " << mntPath);
         return SECURITY_MANAGER_ERROR_FILE_OPEN_FAILED;
     }
 
     // 0 == allow any type of namespace
     int ret = setns(fd, 0);
+    const auto err = errno;
     close(fd);
     if (ret != 0) {
-        LogError("Failed to setns " << mntPath << ": " << GetErrnoString(errno));
+        LogWithErrno(err, "setns " << mntPath);
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
 
@@ -189,9 +189,8 @@ int enterMountNamespace(const Path &mntPath)
 
 int makeMountSlave(const Path &mountPoint)
 {
-    int ret = mount("none", mountPoint.c_str(), NULL, MS_REC|MS_SLAVE, NULL);
-    if (ret != 0) {
-        LogError("Failed to make mount point " << mountPoint << " slave: " << GetErrnoString(errno));
+    if (mount(NULL, mountPoint.c_str(), NULL, MS_REC|MS_SLAVE, NULL)) {
+        LogErrno("make mount point " << mountPoint << " slave");
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
     return SECURITY_MANAGER_SUCCESS;
@@ -199,9 +198,8 @@ int makeMountSlave(const Path &mountPoint)
 
 int makeMountPrivate(const Path &mountPoint)
 {
-    int ret = mount("none", mountPoint.c_str(), NULL, MS_PRIVATE, NULL);
-    if (ret != 0) {
-        LogError("Failed to make mount point " << mountPoint << " private: " << GetErrnoString(errno));
+    if (mount(NULL, mountPoint.c_str(), NULL, MS_PRIVATE, NULL)) {
+        LogErrno("make mount point " << mountPoint << " private");
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
     return SECURITY_MANAGER_SUCCESS;
@@ -209,9 +207,8 @@ int makeMountPrivate(const Path &mountPoint)
 
 int bindMountRW(const Path &source, const Path &target)
 {
-    int ret = mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL);
-    if (ret != 0) {
-        LogError("Failed to RW bind directory " << source << " to " << target << " " << GetErrnoString(errno));
+    if (mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL)) {
+        LogErrno("RW bind directory " << source << " to " << target);
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
     return SECURITY_MANAGER_SUCCESS;
@@ -219,15 +216,13 @@ int bindMountRW(const Path &source, const Path &target)
 
 int bindMountRO(const Path &source, const Path &target)
 {
-    int ret = mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL);
-    if (ret != 0) {
-        LogError("Failed to bind directory " << source << " to " << target << " " << GetErrnoString(errno));
+    if (mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL)) {
+        LogErrno("bind directory " << source << " to " << target);
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
 
-    ret = mount(NULL, target.c_str(), NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL);
-    if (ret != 0) {
-        LogError("Failed to RO bind directory " << source << " to " << target << " " << GetErrnoString(errno));
+    if (mount(NULL, target.c_str(), NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL)) {
+        LogErrno("RO bind directory " << source << " to " << target);
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
 
@@ -236,19 +231,18 @@ int bindMountRO(const Path &source, const Path &target)
 
 int bindMountROIfExists(const Path &source, const Path &target)
 {
-    int ret = mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL);
-    if (ret != 0) {
-        if (errno == ENOENT) {
+    if (mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL)) {
+        const auto err = errno;
+        if (err == ENOENT) {
             LogDebug("ENOENT when binding " << source << " to " << target << ", skipping");
             return SECURITY_MANAGER_SUCCESS;
         }
-        LogError("Failed to bind directory " << source << " to " << target << " " << GetErrnoString(errno));
+        LogWithErrno(err, "bind directory " << source << " to " << target);
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
 
-    ret = mount(NULL, target.c_str(), NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL);
-    if (ret != 0) {
-        LogError("Failed to RO bind directory " << source << " to " << target << " " << GetErrnoString(errno));
+    if (mount(NULL, target.c_str(), NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL)) {
+        LogErrno("RO bind directory " << source << " to " << target);
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
 
@@ -257,9 +251,8 @@ int bindMountROIfExists(const Path &source, const Path &target)
 
 int uMount(const Path &target)
 {
-    int ret = umount(target.c_str());
-    if (ret != 0) {
-        LogWarning("Failed to umount: "  << target << " " << GetErrnoString(errno));
+    if (umount(target.c_str())) {
+        WarnErrno("umount "  << target);
         return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
     }
     return SECURITY_MANAGER_SUCCESS;
@@ -268,17 +261,14 @@ int uMount(const Path &target)
 bool isPathBound(const Path &what, const Path &where)
 {
     struct stat st1, st2;
-    int ret;
 
-    ret = lstat(what.c_str(), &st1);
-    if (ret < 0) {
-        LogError("Unable to stat " << what << " " << GetErrnoString(errno));
+    if (lstat(what.c_str(), &st1)) {
+        LogErrno("stat " << what);
         return false;
     }
 
-    ret = lstat(where.c_str(), &st2);
-    if (ret < 0) {
-        LogError("Unable to stat " << where << " " << GetErrnoString(errno));
+    if (lstat(where.c_str(), &st2)) {
+        LogErrno("stat " << where);
         return false;
     }
 
index 9ab845ea9d4c895a7473e16a0eeeb565da1a1d18..f99989e57df7ffdcee65dabaf071d27da7188043 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016-2020 Samsung Electronics Co., Ltd. All rights reserved.
+ * Copyright (c) 2016-2022 Samsung Electronics Co., Ltd. All rights reserved
  *
  * This file is licensed under the terms of MIT License or the Apache License
  * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
@@ -71,16 +71,11 @@ template <typename T>
 static void openAndLockNameFile(const std::string &nameFile, T &fstream)
 {
     fstream.open(nameFile);
-    if (!fstream.is_open()) {
-        LogError("Unable to open file " << nameFile << ": " << GetErrnoString(errno));
-        ThrowMsg(PermissibleSetException::FileOpenError, "Unable to open file ");
-    }
+    if (!fstream.is_open())
+        LogAndThrowErrno(PermissibleSetException::FileOpenError, "open file " << nameFile);
 
-    int ret = TEMP_FAILURE_RETRY(flock(getFd(fstream), LOCK_EX));
-    if (ret == -1) {
-        LogError("Unable to lock file " << nameFile << ": " << GetErrnoString(errno));
-        ThrowMsg(PermissibleSetException::FileLockError, "Unable to lock file");
-    }
+    if (TEMP_FAILURE_RETRY(flock(getFd(fstream), LOCK_EX)))
+        LogAndThrowErrno(PermissibleSetException::FileLockError, "lock file " << nameFile);
 }
 
 std::string getPermissibleFileLocation(uid_t uid, int installationType)
@@ -96,15 +91,9 @@ std::string getPermissibleFileLocation(uid_t uid, int installationType)
 
 static void markPermissibleFileValid(int fd, const std::string &nameFile, bool valid)
 {
-    int ret;
-    if (valid)
-        ret = TEMP_FAILURE_RETRY(fchmod(fd, 00444));
-    else
-        ret = TEMP_FAILURE_RETRY(fchmod(fd, 00000));
-    if (ret == -1) {
-        LogError("Error at fchmod " << nameFile << ": " << GetErrnoString(errno));
-        ThrowMsg(PermissibleSetException::FileWriteError, "Error at fchmod");
-    }
+    const auto mode = valid ? 00444 : 00000;
+    if (TEMP_FAILURE_RETRY(fchmod(fd, mode)))
+        LogAndThrowErrno(PermissibleSetException::FileWriteError, "fchmod " << nameFile);
 }
 
 void updatePermissibleFile(uid_t uid, int installationType,
@@ -117,20 +106,14 @@ void updatePermissibleFile(uid_t uid, int installationType,
 
     for (auto &label : labelsForUser) {
         fstream << label << '\n';
-        if (fstream.bad()) {
-            LogError("Unable to write to file " << nameFile << ": " << GetErrnoString(errno));
-            ThrowMsg(PermissibleSetException::PermissibleSetException::FileWriteError,
-                    "Unable to write to file");
-        }
-    }
-    if (fstream.flush().fail()) {
-        LogError("Error at fflush " << nameFile << ": " << GetErrnoString(errno));
-        ThrowMsg(PermissibleSetException::FileWriteError, "Error at fflush");
-    }
-    if (fsync(getFd(fstream)) == -1) {
-        LogError("Error at fsync " << nameFile << ": " << GetErrnoString(errno));
-        ThrowMsg(PermissibleSetException::FileWriteError, "Error at fsync");
+        if (fstream.bad())
+            LogAndThrowErrno(PermissibleSetException::PermissibleSetException::FileWriteError,
+                    "write to file " << nameFile);
     }
+    if (fstream.flush().fail())
+        LogAndThrowErrno(PermissibleSetException::FileWriteError, "fflush " << nameFile);
+    if (fsync(getFd(fstream)) == -1)
+        LogAndThrowErrno(PermissibleSetException::FileWriteError, "fsync " << nameFile);
     markPermissibleFileValid(getFd(fstream), nameFile, true);
 }
 
@@ -143,10 +126,8 @@ void readLabelsFromPermissibleFile(const std::string &nameFile, std::vector<std:
     while (std::getline(fstream, line))
         appLabels.push_back(line);
 
-    if (fstream.bad()) {
-        LogError("Failure while reading file " << nameFile << ": " << GetErrnoString(errno));
-        ThrowMsg(PermissibleSetException::FileReadError, "Failure while reading file");
-    }
+    if (fstream.bad())
+        LogAndThrowErrno(PermissibleSetException::FileReadError, "reading file " << nameFile);
 }
 
 void initializeUserPermissibleFile(uid_t uid)
@@ -155,8 +136,8 @@ void initializeUserPermissibleFile(uid_t uid)
     std::string nameDir = FS::getDirectoryName(nameFile);
 
     if (mkdir(nameDir.c_str(), 0755) != 0 && errno != EEXIST)
-        ThrowMsg(PermissibleSetException::FileInitError,
-            "Unable to create directory for user permissible file:" << GetErrnoString(errno));
+        ThrowErrno(PermissibleSetException::FileInitError,
+            "create directory for user permissible file");
 
     std::ofstream fstream;
     openAndLockNameFile(nameFile, fstream);
@@ -171,12 +152,12 @@ void removeUserPermissibleFile(uid_t uid)
     std::string nameDir = FS::getDirectoryName(nameFile);
 
     if (unlink(nameFile.c_str()) != 0 && errno != ENOENT)
-        ThrowMsg(PermissibleSetException::FileRemoveError,
-            "Unable to remove user permissible file:" << GetErrnoString(errno));
+        ThrowErrno(PermissibleSetException::FileRemoveError,
+            "remove user permissible file");
 
     if (rmdir(nameFile.c_str()) != 0 && errno != ENOENT)
-        ThrowMsg(PermissibleSetException::FileRemoveError,
-            "Unable to remove directory for user permissible file:" << GetErrnoString(errno));
+        ThrowErrno(PermissibleSetException::FileRemoveError,
+            "remove directory for user permissible file");
 }
 
 } // PermissibleSet
index 97c16a6f35eb950ed199c69f8e55a07e916026ba..2a47c2aebe718fa9e5ed2132a8e23995692d84c1 100644 (file)
@@ -104,7 +104,7 @@ std::string realPath(const std::string &path)
 {
     auto real_pathPtr = makeUnique(realpath(path.c_str(), nullptr), free);
     if (!real_pathPtr) {
-        LogWarning("Error in realpath(): " << GetErrnoString(errno) << " for: " << path);
+        WarnErrno("realpath(" << path << ')');
         return std::string();
     }
 
index 634f01a7b0c67ac7a984a0be85194a7ddfe197ba..9c95961c87920c235d75672a2b5624572221a912 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved.
+ * Copyright (c) 2014-2022 Samsung Electronics Co., Ltd. All rights reserved
  *
  * This file is licensed under the terms of MIT License or the Apache License
  * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
@@ -115,10 +115,8 @@ static void dirSetSmack(const std::string &path, const Smack::Label &label,
     }
 
     /* If last call to fts_read() set errno, we need to return error. */
-    if ((errno != 0) && (ftsent == NULL)) {
-        LogError("Last errno from fts_read: " << GetErrnoString(errno));
-        ThrowMsg(SmackException::FileError, "Last errno from fts_read: " << GetErrnoString(errno));
-    }
+    if ((errno != 0) && (ftsent == NULL))
+        LogAndThrowErrno(SmackException::FileError, "last fts_read");
 }
 
 static void labelDir(const std::string &path, const Smack::Label &label,
index 0f263acd47a488555d53650f688d13e04fdd430e..282ec837370c5ea84bdbc0dd0421cc3412775cbc 100644 (file)
@@ -68,8 +68,7 @@ int try_catch(const std::function<int()>& func)
 time_t monotonicCoarseNow() {
     struct timespec now;
     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now)) {
-        int err = errno;
-        LogError("Can't access monotonic clock, error: " <<  GetErrnoString(err));
+        LogErrno("access monotonic clock");
         return 0;
     }
     return now.tv_sec;
@@ -82,19 +81,16 @@ ScopedTimeStamper::ScopedTimeStamper(const std::string & location, const Credent
                     ", caller pid = " + std::to_string(creds.pid) +
                     ", caller label = " + creds.label;
 
-    if (clock_gettime(CLOCK_MONOTONIC_RAW, &m_start) == -1) {
-        int err = errno;
-        LogError("Can't access monotonic clock, error: " <<  GetErrnoString(err));
-    }
+    if (clock_gettime(CLOCK_MONOTONIC_RAW, &m_start))
+        LogErrno("access monotonic clock");
 }
 
 ScopedTimeStamper::~ScopedTimeStamper()
 {
     struct timespec end;
-    if (clock_gettime(CLOCK_MONOTONIC_RAW, &end) == -1) {
-        int err = errno;
-        LogError("Can't access monothonic clock, error: " <<  GetErrnoString(err));
-    }
+    if (clock_gettime(CLOCK_MONOTONIC_RAW, &end))
+        LogErrno("access monothonic clock");
+
     long ndiff = (end.tv_nsec - m_start.tv_nsec ) + (end.tv_sec - m_start.tv_sec ) * 1E9;
     float sec(ndiff);
     sec *= 0.000000001;
index 0ce8ca476cc806d884271a52905709dea517c247..0d11944f8960223a8227e2738ed2c6b3b0055531 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2020 Samsung Electronics Co., Ltd. All rights reserved.
+ * Copyright (c) 2011-2022 Samsung Electronics Co., Ltd. All rights reserved
  *
  * This file is licensed under the terms of MIT License or the Apache License
  * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
 namespace SecurityManager {
 std::string GetErrnoString(int error = errno);
 } // namespace SecurityManager
+
+#define _PrepareLogErrnoMsg_(ERRNO) const auto _errnoString_ = GetErrnoString(ERRNO)
+#define _LogErrnoMsg_(...) __VA_ARGS__ << " failed: " << _errnoString_
+
+#define LogWithErrno(ERRNO, ...) do { \
+    _PrepareLogErrnoMsg_(ERRNO); \
+    LogError(_LogErrnoMsg_(__VA_ARGS__)); \
+} while (0)
+
+#define WarnWithErrno(ERRNO, ...) do { \
+    _PrepareLogErrnoMsg_(ERRNO); \
+    LogWarning(_LogErrnoMsg_(__VA_ARGS__)); \
+} while (0)
+
+#define ThrowWithErrno(ERRNO, CLASS, ...) do { \
+    _PrepareLogErrnoMsg_(ERRNO); \
+    ThrowMsg(CLASS, _LogErrnoMsg_(__VA_ARGS__)); \
+} while (0)
+
+#define LogAndThrowWithErrno(ERRNO, CLASS, ...) do { \
+    _PrepareLogErrnoMsg_(ERRNO); \
+    LogError(_LogErrnoMsg_(__VA_ARGS__)); \
+    ThrowMsg(CLASS, _LogErrnoMsg_(__VA_ARGS__)); \
+} while (0)
+
+#define LogErrno(...) LogWithErrno(errno, __VA_ARGS__)
+#define WarnErrno(...) WarnWithErrno(errno, __VA_ARGS__)
+#define ThrowErrno(...) ThrowWithErrno(errno, __VA_ARGS__)
+#define LogAndThrowErrno(...) LogAndThrowWithErrno(errno, __VA_ARGS__)
index 2812f4d16d21d5a1236041c1ed5a3022596d9602..4da06aae4be2b480fe11de751975a6c66b9a5333 100644 (file)
@@ -46,7 +46,7 @@ bool createFile(const std::string &path)
     mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
     fd = TEMP_FAILURE_RETRY(creat(path.c_str(), mode));
     if (fd == -1) {
-        std::cerr << "Creating file " << path << " failed with " << SecurityManager::GetErrnoString(errno);
+        std::cerr << "Creating file " << path << " failed with " << SecurityManager::GetErrnoString();
         return false;
     }
     close(fd);
index 4bba0672b74420269d92150875957ca5421ce070..b5ec89faaea5eedfbdc647011d86be4a29e3d3c3 100644 (file)
@@ -88,7 +88,7 @@ int security_manager(Channel channel)
     self_data.pid = getpid();
 
     if (resource_register_cpu_inheritance_destination(RESOURCE_CPU_DEST_NAME, self_data) != 0)
-        LogError("resource_register_cpi_inheritance_destination failed");
+        LogError("resource_register_cpu_inheritance_destination failed");
 
     if (!REGISTER_SOCKET_SERVICE(manager, SecurityManager::Service, std::move(channel))) {
         LogError("Unable to create socket service. Exiting.");
index 7fbdb2ccbe08f72148d015c61aad8bce3e8ddbd2..7a9f3c8504ebbd6a4d9f49befe0525c4dd5608d3 100644 (file)
@@ -95,16 +95,12 @@ SocketManager::SocketManager()
         ThrowMsg(Exception::InitFailed, "Error in pthread_sigmask: " << err);
 
     // add support for TERM signal (passed from systemd)
-    if ((m_signalFd = signalfd(-1, &set, 0)) < 0) {
-        int err = errno;
-        ThrowMsg(Exception::InitFailed, "Error in signalfd: " << GetErrnoString(err));
-    }
+    if ((m_signalFd = signalfd(-1, &set, 0)) < 0)
+        ThrowErrno(Exception::InitFailed, "signalfd");
     RegisterFdForReading(m_signalFd);
 
-    if ((m_notifyMe = eventfd(0, 0)) < 0) {
-        int err = errno;
-        ThrowMsg(Exception::InitFailed, "Error in eventfd: " << GetErrnoString(err));
-    }
+    if ((m_notifyMe = eventfd(0, 0)) < 0)
+        ThrowErrno(Exception::InitFailed, "eventfd");
     LogInfo("Eventfd desc: " << m_notifyMe);
     RegisterFdForReading(m_notifyMe);
 }
@@ -128,8 +124,7 @@ void SocketManager::ReadyForAccept() {
     int client = accept4(m_listenSock, (struct sockaddr*) &clientAddr, &clientLen, SOCK_NONBLOCK);
 //    LogInfo("Accept on sock: " << sock << " Socket opended: " << client);
     if (-1 == client) {
-        int err = errno;
-        LogError("Error in accept: " << GetErrnoString(err));
+        LogErrno("accept");
         return;
     }
 
@@ -178,7 +173,7 @@ void SocketManager::ReadyForRead(int sock) {
             case EINTR:
                 break;
             default:
-                LogError("Reading sock error: " << GetErrnoString(err));
+                LogWithErrno(err, "Reading sock");
                 goto close;
         }
     } else {
@@ -228,7 +223,7 @@ void SocketManager::ReadyForWrite(int sock) {
             // select will trigger write once again, nothing to do
             break;
         default:
-            LogError("Error during write: " << GetErrnoString(err));
+            LogWithErrno(err, "write");
             CloseSocket(sock);
             break;
         }
@@ -252,8 +247,7 @@ void SocketManager::MainLoop() {
 
         int ret = TEMP_FAILURE_RETRY(select(m_maxDesc+1, &readSet, &writeSet, nullptr, nullptr));
         if (ret < 0) {
-            int err = errno;
-            LogError("Error in select: " << GetErrnoString(err));
+            LogErrno("select");
             return;
         }
 
@@ -330,9 +324,7 @@ int SocketManager::CreateDomainSocketHelp(const ServiceDescription &desc)
     }
 
     if (-1 == (sockfd = socket(AF_UNIX, SOCK_STREAM, 0))) {
-        int err = errno;
-        LogError("Error in socket: " << GetErrnoString(err));
-        ThrowMsg(Exception::InitFailed, "Error in socket: " << GetErrnoString(err));
+        LogAndThrowErrno(Exception::InitFailed, "socket");
     }
 
     if (smack_check()) {
@@ -350,11 +342,10 @@ int SocketManager::CreateDomainSocketHelp(const ServiceDescription &desc)
     if (-1 == (flags = fcntl(sockfd, F_GETFL, 0)))
         flags = 0;
 
-    if (-1 == fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)) {
+    if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)) {
         int err = errno;
         close(sockfd);
-        LogError("Error in fcntl: " << GetErrnoString(err));
-        ThrowMsg(Exception::InitFailed, "Error in fcntl: " << GetErrnoString(err));
+        LogAndThrowWithErrno(err, Exception::InitFailed, "fcntl");
     }
 
     sockaddr_un serverAddress;
@@ -366,20 +357,18 @@ int SocketManager::CreateDomainSocketHelp(const ServiceDescription &desc)
     mode_t originalUmask;
     originalUmask = umask(0);
 
-    if (-1 == bind(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) {
+    if (bind(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) {
         int err = errno;
         close(sockfd);
-        LogError("Error in bind: " << GetErrnoString(err));
-        ThrowMsg(Exception::InitFailed, "Error in bind: " << GetErrnoString(err));
+        LogAndThrowWithErrno(err, Exception::InitFailed, "bind");
     }
 
     umask(originalUmask);
 
-    if (-1 == listen(sockfd, SOMAXCONN)) {
+    if (listen(sockfd, SOMAXCONN)) {
         int err = errno;
         close(sockfd);
-        LogError("Error in listen: " << GetErrnoString(err));
-        ThrowMsg(Exception::InitFailed, "Error in listen: " << GetErrnoString(err));
+        LogAndThrowWithErrno(err, Exception::InitFailed, "listen");
     }
 
     return sockfd;
index dfa36a4f2b16788a4b6a9a5a0cf198ee9c493f0c..13d34403d3f6649ad2582dac47b012bd02106c21 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016-2020 Samsung Electronics Co., Ltd. All rights reserved.
+ * Copyright (c) 2016-2022 Samsung Electronics Co., Ltd. All rights reserved
  *
  * This file is licensed under the terms of MIT License or the Apache License
  * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
@@ -46,18 +46,18 @@ struct FileLockFixture
         if (f != NULL)
             fclose(f);
         else
-            LogError("Failed to open file " << existingLockFile << " : " << GetErrnoString());
-        if (-1 == remove(noExistingLockFile.c_str()))
-            LogError("Failed to remove file " << noExistingLockFile << " : " << GetErrnoString());
+            LogErrno("open file " << existingLockFile);
+        if (remove(noExistingLockFile.c_str()))
+            LogErrno("remove file " << noExistingLockFile);
 
     }
 
     ~FileLockFixture()
     {
         if (remove(existingLockFile.c_str()))
-            LogWarning("Failed to remove file " << existingLockFile << " : " << GetErrnoString());
-        if (-1 == remove(noExistingLockFile.c_str()))
-            LogError("Failed to remove file " << noExistingLockFile << " : " << GetErrnoString());
+            WarnErrno("remove file " << existingLockFile);
+        if (remove(noExistingLockFile.c_str()))
+            LogErrno("remove file " << noExistingLockFile);
     }
 
     const static std::string existingLockFile;
index bacc4b3c84bb6032eb6b52d852a7264457d3f3e2..22fa93e81b169e33ae41a106e23e337fd9a81b98 100644 (file)
@@ -48,11 +48,10 @@ struct ServiceImplUtilFixture
     {
         FILE *f;
         f = fopen(existingFile.c_str(), "w");
-        int er = errno;
         if (f != NULL)
             fclose(f);
         else
-            LogError("Failed to open file " << existingFile << " : " << GetErrnoString(er));
+            LogErrno("open file " << existingFile);
         uid_t i = 0;
         while(getpwuid(++i));
         nonexistingUid = i;