Code cleanup (#251)
[platform/core/dotnet/launcher.git] / NativeLauncher / util / utils.cc
index ce01795..5b047ae 100644 (file)
  * limitations under the License.
  */
 
-#include <stdio.h>
 #include <dirent.h>
+#include <fcntl.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <limits.h>
 #include <strings.h>
-#include <pthread.h>
+#include <pkgmgr-info.h>
+#include <pkgmgr_installer_info.h>
+#include <sys/smack.h>
+#include <sys/prctl.h>
 
 #include <cstdlib>
 #include <cstring>
 #include <unordered_map>
 #include <vector>
 #include <iterator>
+#include <fstream>
 #include <sstream>
+#include <map>
 
-#include "utils.h"
 #include "log.h"
+#include "utils.h"
+#include "path_manager.h"
 
-static pthread_t loggingThread;
-
-bool iCompare(const std::string& a, const std::string& b)
-{
-       return a.length() == b.length() &&
-               std::equal(b.begin(), b.end(), a.begin(),
-                       [](unsigned char a, unsigned char b)
-                       { return std::tolower(a) == std::tolower(b); });
-}
-
-bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
+static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
 {
        return static_cast<int>(a.length()) - length >= aOffset &&
                static_cast<int>(b.length()) - length >= bOffset &&
@@ -54,8 +50,9 @@ bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffs
 
 bool isManagedAssembly(const std::string& fileName)
 {
-       return iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
-               iCompare(fileName, fileName.size()-4, ".exe", 0, 4);
+       return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
+                       iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
+                       !isNativeImage(fileName);
 }
 
 bool isNativeImage(const std::string& fileName)
@@ -63,18 +60,6 @@ bool isNativeImage(const std::string& fileName)
        return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
 }
 
-std::string readSelfPath()
-{
-       char buff[PATH_MAX];
-       ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
-       if (len != -1) {
-               buff[len] = '\0';
-               return std::string(buff);
-       }
-
-       return "";
-}
-
 std::string concatPath(const std::string& path1, const std::string& path2)
 {
        std::string path(path1);
@@ -88,178 +73,276 @@ std::string concatPath(const std::string& path1, const std::string& path2)
        return path;
 }
 
-void appendPath(std::string& path1, const std::string& path2)
+void splitPath(const std::string& path, std::vector<std::string>& out)
 {
-       if (path1.back() == PATH_SEPARATOR) {
-               path1.append(path2);
-       } else {
-               path1 += PATH_SEPARATOR;
-               path1.append(path2);
+       std::istringstream ss(path);
+       std::string token;
+
+       while (std::getline(ss, token, ':')) {
+               out.push_back(token);
        }
 }
 
-std::string absolutePath(const std::string& path)
+std::string getAbsolutePath(const std::string& path)
 {
        std::string absPath;
-       char realPath[PATH_MAX];
-       if (realpath(path.c_str(), realPath) != nullptr && realPath[0] != '\0')
+       char *realPath = realpath(path.c_str(), NULL);
+       if (realPath) {
                absPath.assign(realPath);
+               free(realPath);
+       }
 
        return absPath;
 }
 
-std::string baseName(const std::string& path)
+std::string getRootPath(const std::string& pkgId)
 {
-       auto pos = path.find_last_of(PATH_SEPARATOR);
-       if (pos != std::string::npos)
-               return path.substr(0, pos);
-       else
-               return std::string(".");
-       return path;
-}
+       int ret = 0;
+       char *path = 0;
+       uid_t uid = 0;
+       std::string rootPath;
+
+       if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
+               _ERR("Failed to get UID");
+               return rootPath;
+       }
 
-bool endWithIgnoreCase(const std::string& str1, const std::string& str2, std::string& fileName)
-{
-       std::string::size_type len1 = str1.length();
-       std::string::size_type len2 = str2.length();
-       if (len2 > len1)
-               return false;
+       pkgmgrinfo_pkginfo_h handle;
+       if (uid == 0) {
+               ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
+               if (ret != PMINFO_R_OK) {
+                       return rootPath;
+               }
+       } else {
+               ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
+               if (ret != PMINFO_R_OK) {
+                       return rootPath;
+               }
+       }
 
-       int i = 0;
-       bool result = std::all_of(str1.cend() - len2, str1.end(),
-                               [&i, &str2] (char x) {
-                                       return std::tolower(x) == std::tolower(str2[i++]);
-                               });
-       if (result)
-               fileName = str1.substr(0, len1 - len2);
+       ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
+               return rootPath;
+       }
+       rootPath = path;
+       pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
 
-       return result;
+       return rootPath;
 }
 
-bool fileNotExist(const std::string& path)
+std::string getExecName(const std::string& pkgId)
 {
-       struct stat sb;
-       return stat(path.c_str(), &sb) != 0;
+       char *exec = NULL;
+       char *appId = 0;
+       std::string execName;
+
+       pkgmgrinfo_pkginfo_h pkg_handle;
+       int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
+       if (ret != PMINFO_R_OK) {
+               return execName;
+       }
+       ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return execName;
+       }
+
+       pkgmgrinfo_appinfo_h app_handle;
+       ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return execName;
+       }
+       ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return execName;
+       }
+       execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
+
+       pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
+       pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+
+       return execName;
 }
 
-#ifdef NOT_USE_FUNCTION
-static bool extCheckAndGetFileNameIfExist(const std::string& dir, const std::string& ext, struct dirent* entry, std::string& fileName)
+std::string getAppType(const std::string& pkgId)
 {
-       std::string fName(entry->d_name);
-       if (fName.length() < ext.length() ||
-                       fHame.compare(fName.length() - ext.length(), ext.length(), ext) != 0) {
-               return false;
+       char *appId = 0;
+       char *type = 0;
+       std::string appType;
+
+       pkgmgrinfo_pkginfo_h pkg_handle;
+       int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
+       if (ret != PMINFO_R_OK) {
+               return appType;
+       }
+       ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return appType;
        }
 
-       std::string fullName = concatPath(dir, entry->d_name);
-       switch (entry->d_type) {
-               case DT_REG: break;
-               case DT_LNK:
-               case DT_UNKNOWN:
-                       if (fileNotExist(fullName))
-                               return false;
-               default:
-                       return false;
+       pkgmgrinfo_appinfo_h app_handle;
+       ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return appType;
        }
+       ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return appType;
+       }
+       appType = type;
 
-       fileName = fullName;
+       pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
+       pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
 
-       return true;
+       return appType;
 }
-#endif
 
-std::string stripNiDLL(const std::string& path)
+std::string getMetadataValue(const std::string& pkgId, const std::string& key)
 {
-       std::string niPath(path);
-       if (path.size() < 5) return niPath;
-       if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
-               niPath = path.substr(0, path.size()-4);
-       else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
-               niPath = path.substr(0, path.size()-4);
+       char *value = NULL;
+       char *appId = 0;
+       std::string metadataValue;
+
+       pkgmgrinfo_pkginfo_h pkg_handle;
+       int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
+       if (ret != PMINFO_R_OK) {
+               return metadataValue;
+       }
+       ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return metadataValue;
+       }
 
-       if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
-               return niPath.substr(0, niPath.size()-3);
+       pkgmgrinfo_appinfo_h app_handle;
+       ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return metadataValue;
+       }
+       ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
+               pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+               return metadataValue;
+       }
+       metadataValue = std::string(value);
 
-       return niPath;
+       pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
+       pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
+
+       return metadataValue;
+}
+
+std::string getBaseName(const std::string& path)
+{
+       auto pos = path.find_last_of(PATH_SEPARATOR);
+       if (pos != std::string::npos)
+               return path.substr(0, pos);
+       else
+               return std::string(".");
+       return path;
 }
 
-std::string joinStrings(const std::vector<std::string>& strings, const char* const delimeter)
+std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
 {
-       switch (strings.size()) {
-               case 0:
-                       return "";
-               case 1:
-                       return strings[0];
-               default:
-                       std::ostringstream os;
-                       std::copy(strings.begin(), strings.end()-1, std::ostream_iterator<std::string>(os, delimeter));
-                       os << *strings.rbegin();
-                       return os.str();
+       std::string result = str;
+       std::string::size_type pos = 0;
+       std::string::size_type offset = 0;
+
+       while ((pos = result.find(pattern, offset)) != std::string::npos) {
+               result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
+               offset = pos + replace.size();
        }
+
+       return result;
 }
 
-struct AssemblyFile {
-       std::string noExt;
-       std::string ext;
-};
+bool isFile(const std::string& path)
+{
+       struct stat sb;
+       return stat(path.c_str(), &sb) == 0;
+}
 
-bool operator == (const AssemblyFile& lhs, const AssemblyFile& rhs)
+bool isDirectory(const std::string& path)
 {
-       return lhs.noExt == rhs.noExt && lhs.ext == rhs.ext;
+       struct stat sb;
+       if (stat(path.c_str(), &sb) != 0) {
+               return false;
+       }
+       if (sb.st_mode & S_IFDIR) {
+               return true;
+       } else {
+               return false;
+       }
 }
 
-namespace std {
-       template<>
-       struct hash<AssemblyFile> {
-               std::size_t operator () (const AssemblyFile& f) const {
-                       const std::size_t h1 = std::hash<std::string>{}(f.noExt);
-                       const std::size_t h2 = std::hash<std::string>{}(f.ext);
+std::string getAssemblyNameFromPath(const std::string& path)
+{
+       std::string ret(getFileName(path));
 
-                       return h1 ^ (h2 << 1);
-               }
-       };
+       if (ret.find_last_of(".") == std::string::npos)
+               return ret;
+       ret.erase(ret.find_last_of("."));
+
+       if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
+               ret.erase(ret.size() - 3);
+
+       return ret;
 }
 
-void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
+void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
 {
-       std::map<std::string, std::string> assemblyList;
-       std::map<std::string, std::string> tmpList;
-
-       auto reader = [&assemblyList, &tmpList] (const char* path, const char* name) {
-               std::string pathStr(path);
-               if (isManagedAssembly(pathStr)) {
-                       std::string dllName = stripNiDLL(name);
-                       std::pair<std::map<std::string, std::string>::iterator, bool> ret;
-                       ret = tmpList.insert(std::pair<std::string, std::string>(dllName, pathStr));
-                       if (ret.second == false) {
-                               if (isNativeImage(pathStr))
-                                       tmpList[dllName] = pathStr;
+       std::vector<std::string> assems;
+       std::unordered_map<std::string, std::string> assemPaths;
+
+       auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
+               if (isManagedAssembly(filename) || isNativeImage(filename)) {
+                       std::string assem = getAssemblyNameFromPath(filename);
+
+                       if (assemPaths.count(assem) == 0) {
+                               assems.push_back(assem);
+                               assemPaths[assem] = path;
+                       } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
+                               // Update only if a native image is found in the same directory.
+                               // For example, if we have two directories = { X, Y } where X contains A.dll and
+                               // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
+                               if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
+                                       assemPaths[assem] = path;
                        }
                }
        };
+       for (auto& directory : directories)
+               scanFilesInDirectory(directory, reader, 0);
 
-       for (auto directory : directories) {
-               scanFilesInDir(directory.c_str(), reader, 1);
-               // merge scaned dll list to tpa list.
-               // if the dll is already exist in the list, that is skipped.
-               assemblyList.insert(tmpList.begin(), tmpList.end());
-       }
+       if (!list.empty() && list.back() != ':')
+               list.push_back(':');
 
-       std::map<std::string, std::string>::iterator it;
-       for (it = assemblyList.begin(); it != assemblyList.end(); it++)
-               tpaList += it->second + ':';
+       for (auto& assem : assems)
+               list += assemPaths[assem] + ":";
 
-       if (tpaList.back() == ':')
-               tpaList.pop_back();
+       if (list.back() == ':')
+               list.pop_back();
 }
 
-void scanFilesInDir(const char* directory, FileReader reader, unsigned int depth)
+void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
 {
        DIR *dir;
        struct dirent* entry;
        bool isDir;
 
-       dir = opendir(directory);
+       if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
+               return;
+
+       dir = opendir(directory.c_str());
 
        if (dir == nullptr)
                return;
@@ -286,79 +369,290 @@ void scanFilesInDir(const char* directory, FileReader reader, unsigned int depth
                                continue;
                }
                if (!isDir)
-                       reader(path.c_str(), entry->d_name);
-               else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
+                       reader(path, entry->d_name);
+               else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
                        innerDirectories.push_back(path);
        }
 
-       if (depth != 0)
+       if (depth > 0)
                for (auto& d : innerDirectories)
-                       scanFilesInDir(d.c_str(), reader, depth-1);
+                       scanFilesInDirectory(d, reader, depth - 1);
 
        closedir(dir);
 }
 
-static void *stdlog(void*)
+void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
 {
-       int pfd[2];
-    ssize_t readSize;
-    char buf[1024];
+       char* label = NULL;
+       struct stat info;
+
+       if (isSymlink) {
+               // change smack label for symbolic link.
+               if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
+                       if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
+                               fprintf(stderr, "Fail to set smack label\n");
+                       }
+                       free(label);
+               }
 
-    if (setvbuf(stdout, NULL, _IOLBF, 0) < 0) {
-               _DBG("fail to make stdout line-buffered");
-               return 0;
-    }
+               // change owner and groups for symbolic link.
+               if (!stat(fromPath.c_str(), &info)) {
+                       if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
+                               fprintf(stderr, "Failed to change owner and group name\n");
+               }
+       } else {
+               // change smack label
+               if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
+                       if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
+                               fprintf(stderr, "Fail to set smack label\n");
+                       }
+                       free(label);
+               }
 
-    if (setvbuf(stderr, NULL, _IONBF, 0) < 0) {
-               _DBG("make stderr unbuffered");
-               return 0;
+               // change owner and groups for generated ni file.
+               if (!stat(fromPath.c_str(), &info)) {
+                       if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
+                               fprintf(stderr, "Failed to change owner and group name\n");
+               }
        }
+}
 
-    /* create the pipe and redirect stdout and stderr */
-    if (pipe(pfd) < 0) {
-               _DBG("fail to create pipe for logging");
-               return 0;
-    }
+static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
+{
+       int fd = open(path.c_str(), O_RDONLY);
+       if (fd < 0) {
+               _ERR("Can't open directory: %s", path.c_str());
+               return false;
+       }
+       int ret = fchown(fd, uid, gid);
+       close(fd);
+       if (ret != 0) {
+               _ERR("Failed to change owner of: %s", path.c_str());
+               return false;
+       }
+       return true;
+}
 
-    if (dup2(pfd[1], fileno(stdout)) == -1) {
-               _DBG("fail to duplicate fd to stdout");
-               return 0;
-    }
+static bool setDirPermissions(const bf::path& path, bf::perms permissions)
+{
+       bs::error_code error;
+       bf::permissions(path, permissions, error);
+       if (error) {
+               _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
+               return false;
+       }
+       return true;
+}
 
-    if (dup2(pfd[1], fileno(stderr)) == -1) {
-               _DBG("fail to duplicate fd to stderr");
-               return 0;
+static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
+{
+       if (!setOwnership(path, uid, gid)) {
+               _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
+               return false;
        }
+       if (!setDirPermissions(path, permissions)) {
+               _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
+               return false;
+       }
+       return true;
+}
 
-       close(pfd[1]);
+static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
+{
+       if (!bf::exists(path)) {
+               _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
+               return false;
+       }
+       bf::perms permissions = bf::status(path).permissions();
+       struct stat stats;
+       if (stat(path.c_str(), &stats) != 0) {
+               return false;
+       }
+       if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
+               _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
+               return false;
+       }
+       return true;
+}
 
-    while ((readSize = read(pfd[0], buf, sizeof buf - 1)) > 0) {
-        if (buf[readSize - 1] == '\n') {
-            --readSize;
-        }
+bool createDir(const bf::path& path)
+{
+       if (bf::exists(path)) {
+               return true;
+       }
+       bs::error_code error;
+       bf::create_directories(path, error);
+       if (error) {
+               _ERR("Failed to create directory: %s", error.message().c_str());
+               return false;
+       }
+       return true;
+}
 
-        buf[readSize] = 0;
+bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
+{
+       try {
+               // Check whether the function call is valid
+               if (!bf::exists(path1) || !bf::is_directory(path1)) {
+                       _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
+                       return false;
+               }
+               if (!bf::exists(path2)) {
+                       // Create the destination directory
+                       if (!createDir(path2)) {
+                               _ERR("Unable to create destination directory %s", path2.c_str());
+                               return false;
+                       }
+                       if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
+                               copyOwnershipAndPermissions(path1, path2);
+                       }
+               } else {
+                       if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
+                               _ERR("Destination directory %s already exists", path2.c_str());
+                               return false;
+                       }
+                       if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
+                               copyOwnershipAndPermissions(path1, path2);
+                       }
+               }
+       } catch (const bf::filesystem_error& error) {
+               _ERR("Failed to copy directory: %s", error.what());
+               return false;
+       }
 
-        _ERRX("%s", buf);
-    }
+       // Iterate through the source directory
+       for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
+               try {
+                       bf::path current(file->path());
+                       bf::path target = path2 / current.filename();
+                       if (bf::is_symlink(symlink_status(current))) {
+                               if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
+                                       continue;
+                               }
+                               bs::error_code error;
+                               bf::copy_symlink(current, target, error);
+                               if (error) {
+                                       _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
+                                       return false;
+                               }
+                       } else if (bf::is_directory(current)) {
+                               // Found directory: Recursion
+                               if (!copyDir(current, target, flags)) {
+                                       return false;
+                               }
+                       } else {
+                               if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
+                                       continue;
+                               }
+                               bf::path destination = target;
+                               if (flags & FS_COMMIT_COPY_FILE) {
+                                       destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
+                               }
+                               if (flags & FS_MERGE_OVERWRITE) {
+                                       bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
+                               } else {
+                                       bf::copy_file(current, destination);
+                               }
+                               if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
+                                       copyOwnershipAndPermissions(current, destination);
+                               }
+                               if (flags & FS_COMMIT_COPY_FILE) {
+                                       if (flags & FS_MERGE_OVERWRITE) {
+                                               bf::remove(target);
+                                       }
+                                       bf::rename(destination, target);
+                               }
+                       }
+               } catch (const bf::filesystem_error& error) {
+                       _ERR("Failed to copy directory: %s", error.what());
+                       return false;
+               }
+       }
+       return true;
+}
 
-       close(pfd[0]);
+bool copyFile(const bf::path& path1, const bf::path& path2)
+{
+       bs::error_code error;
+       if (!bf::exists(path1)) {
+               return false;
+       }
+       bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
+       if (error) {
+               _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
+               return false;
+       }
+       return true;
+}
 
-    return 0;
+bool moveFile(const bf::path& path1, const bf::path& path2)
+{
+       if (!bf::exists(path1) || bf::exists(path2)) {
+               return false;
+       }
+       bs::error_code error;
+       bf::rename(path1, path2, error);
+       if (error) {
+               _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
+               bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
+               if (error) {
+                       _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
+                       return false;
+               }
+               bf::remove_all(path1, error);
+               if (error) {
+                       _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
+                       return false;
+               }
+       }
+       return true;
 }
 
-int runLoggingThread() {
-    /* spawn the logging thread */
-    if (pthread_create(&loggingThread, 0, stdlog, 0) != 0) {
-               _DBG("fail to create pthread");
-        return -1;
-    }
+bool removeFile(const bf::path& path)
+{
+       if (!bf::exists(path)) {
+               return true;
+       }
+       bs::error_code error;
+       bf::remove(path, error);
+       if (error) {
+               _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
+               return false;
+       }
+       return true;
+}
 
-    if (pthread_detach(loggingThread) != 0) {
-               _DBG("fail to detach pthread");
-               return -1;
+bool removeAll(const bf::path& path)
+{
+       if (!exists(path)) {
+               return true;
        }
+       bs::error_code error;
+       bf::remove_all(path, error);
+       if (error) {
+               _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
+               return false;
+       }
+       return true;
+}
+
+void setCmdName(const std::string& name)
+{
+       #define PRC_NAME_LENGTH         16
 
-    return 0;
+       char processName[PRC_NAME_LENGTH] = {0, };
+
+       if (name.empty())
+               return;
+
+       memset(processName, '\0', PRC_NAME_LENGTH);
+       snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
+       prctl(PR_SET_NAME, processName);
 }
 
+std::string getFileName(const std::string& path)
+{
+       std::string ret(path);
+       size_t index = ret.find_last_of(PATH_SEPARATOR);
+       return index == std::string::npos ? ret : ret.substr(index + 1);
+}