log manager code cleanup
[platform/core/dotnet/launcher.git] / NativeLauncher / util / utils.cc
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <dirent.h>
18 #include <fcntl.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <limits.h>
22 #include <strings.h>
23 #include <pkgmgr-info.h>
24 #include <pkgmgr_installer_info.h>
25 #include <sys/smack.h>
26
27 #include <cstdlib>
28 #include <cstring>
29 #include <algorithm>
30 #include <unordered_map>
31 #include <vector>
32 #include <iterator>
33 #include <fstream>
34 #include <sstream>
35 #include <map>
36
37 #include "log.h"
38 #include "utils.h"
39 #include "path_manager.h"
40
41 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
42 {
43         return static_cast<int>(a.length()) - length >= aOffset &&
44                 static_cast<int>(b.length()) - length >= bOffset &&
45                 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
46                         [](unsigned char a, unsigned char b)
47                         { return std::tolower(a) == std::tolower(b); });
48 }
49
50 bool isManagedAssembly(const std::string& fileName)
51 {
52         return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
53                         iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
54                         !isNativeImage(fileName);
55 }
56
57 bool isNativeImage(const std::string& fileName)
58 {
59         return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
60 }
61
62 bool cmdOptionExists(char** begin, char** end, const std::string& option)
63 {
64         return std::find(begin, end, option) != end;
65 }
66
67 std::string readSelfPath()
68 {
69         char buff[PATH_MAX];
70         ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
71         if (len != -1) {
72                 buff[len] = '\0';
73                 return std::string(buff);
74         }
75
76         return "";
77 }
78
79 std::string concatPath(const std::string& path1, const std::string& path2)
80 {
81         std::string path(path1);
82         if (path.back() == PATH_SEPARATOR) {
83                 path.append(path2);
84         } else {
85                 path += PATH_SEPARATOR;
86                 path.append(path2);
87         }
88
89         return path;
90 }
91
92 void splitPath(const std::string& path, std::vector<std::string>& out)
93 {
94         std::istringstream ss(path);
95         std::string token;
96
97         while (std::getline(ss, token, ':')) {
98                 out.push_back(token);
99         }
100 }
101
102 std::string absolutePath(const std::string& path)
103 {
104         std::string absPath;
105         char *realPath = realpath(path.c_str(), NULL);
106         if (realPath) {
107                 absPath.assign(realPath);
108                 free(realPath);
109         }
110
111         return absPath;
112 }
113
114 int getRootPath(std::string pkgId, std::string& rootPath)
115 {
116         int ret = 0;
117         char *path = 0;
118         uid_t uid = 0;
119
120         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
121                 _ERR("Failed to get UID");
122                 return -1;
123         }
124
125         pkgmgrinfo_pkginfo_h handle;
126         if (uid == 0) {
127                 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
128                 if (ret != PMINFO_R_OK) {
129                         return -1;
130                 }
131         } else {
132                 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
133                 if (ret != PMINFO_R_OK) {
134                         return -1;
135                 }
136         }
137
138         ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
139         if (ret != PMINFO_R_OK) {
140                 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
141                 return -1;
142         }
143         rootPath = path;
144         pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
145         return 0;
146 }
147
148 int getExecName(std::string pkgId, std::string& execName)
149 {
150         char *exec = NULL;
151         char *appId = 0;
152
153         pkgmgrinfo_pkginfo_h pkg_handle;
154         int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
155         if (ret != PMINFO_R_OK) {
156                 return -1;
157         }
158         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
159         if (ret != PMINFO_R_OK) {
160                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
161                 return -1;
162         }
163
164         pkgmgrinfo_appinfo_h app_handle;
165         ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
166         if (ret != PMINFO_R_OK) {
167                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
168                 return -1;
169         }
170         ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
171         if (ret != PMINFO_R_OK) {
172                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
173                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
174                 return -1;
175         }
176         execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
177
178         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
179         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
180         return 0;
181 }
182
183 int getMetadataValue(std::string pkgId, std::string metadataKey, std::string& metadataValue)
184 {
185         char *value = NULL;
186         char *appId = 0;
187
188         pkgmgrinfo_pkginfo_h pkg_handle;
189         int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
190         if (ret != PMINFO_R_OK) {
191                 return -1;
192         }
193         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
194         if (ret != PMINFO_R_OK) {
195                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
196                 return -1;
197         }
198
199         pkgmgrinfo_appinfo_h app_handle;
200         ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
201         if (ret != PMINFO_R_OK) {
202                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
203                 return -1;
204         }
205         ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, metadataKey.c_str(), &value);
206         if (ret != PMINFO_R_OK) {
207                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
208                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
209                 //Does not return error because the metadata key may not exist.
210                 return 0;
211         }
212         metadataValue = std::string(value);
213
214         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
215         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
216         return 0;
217 }
218
219 std::string baseName(const std::string& path)
220 {
221         auto pos = path.find_last_of(PATH_SEPARATOR);
222         if (pos != std::string::npos)
223                 return path.substr(0, pos);
224         else
225                 return std::string(".");
226         return path;
227 }
228
229 std::string replaceAll(const std::string &str, const std::string &pattern, const std::string &replace)
230 {
231         std::string result = str;
232         std::string::size_type pos = 0;
233         std::string::size_type offset = 0;
234
235         while ((pos = result.find(pattern, offset)) != std::string::npos) {
236                 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
237                 offset = pos + replace.size();
238         }
239
240         return result;
241 }
242
243 bool isFileExist(const std::string& path)
244 {
245         struct stat sb;
246         return stat(path.c_str(), &sb) == 0;
247 }
248
249 uintptr_t getFileSize(const std::string& path)
250 {
251         struct stat sb;
252
253         if (stat(path.c_str(), &sb) == 0) {
254                 return sb.st_size;
255         }
256
257         return 0;
258 }
259
260 std::string stripNiDLL(const std::string& path)
261 {
262         std::string niPath(path);
263         if (path.size() < 5) return niPath;
264         if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
265                 niPath = path.substr(0, path.size()-4);
266         else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
267                 niPath = path.substr(0, path.size()-4);
268
269         if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
270                 return niPath.substr(0, niPath.size()-3);
271
272         return niPath;
273 }
274
275 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
276 {
277         std::map<std::string, std::string> assemblyList;
278         std::map<std::string, std::string> tmpList;
279
280         auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
281                 if (isManagedAssembly(path) || isNativeImage(path)) {
282                         std::string dllName = stripNiDLL(name);
283                         std::pair<std::map<std::string, std::string>::iterator, bool> ret;
284                         ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
285                         if (ret.second == false) {
286                                 if (isNativeImage(path))
287                                         tmpList[dllName] = path;
288                         }
289                 }
290         };
291
292         for (auto directory : directories) {
293                 scanFilesInDir(directory.c_str(), reader, 1);
294                 // merge scaned dll list to tpa list.
295                 // if the dll is already exist in the list, that is skipped.
296                 assemblyList.insert(tmpList.begin(), tmpList.end());
297         }
298
299         std::map<std::string, std::string>::iterator it;
300         for (it = assemblyList.begin(); it != assemblyList.end(); it++)
301                 tpaList += it->second + ':';
302
303         if (tpaList.back() == ':')
304                 tpaList.pop_back();
305 }
306
307 void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
308 {
309         DIR *dir;
310         struct dirent* entry;
311         bool isDir;
312
313         if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
314                 return;
315
316         dir = opendir(directory.c_str());
317
318         if (dir == nullptr)
319                 return;
320
321         std::vector<std::string> innerDirectories;
322
323         while ((entry = readdir(dir)) != nullptr) {
324                 isDir = false;
325                 std::string path = concatPath(directory, entry->d_name);
326                 switch (entry->d_type) {
327                         case DT_REG: break;
328                         case DT_DIR:
329                                 isDir = true;
330                                 break;
331                         case DT_LNK:
332                         case DT_UNKNOWN:
333                                 struct stat sb;
334                                 if (stat(path.c_str(), &sb) == -1)
335                                         continue;
336
337                                 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
338                                         break;
339                         default:
340                                 continue;
341                 }
342                 if (!isDir)
343                         reader(path, entry->d_name);
344                 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
345                         innerDirectories.push_back(path);
346         }
347
348         if (depth != 0)
349                 for (auto& d : innerDirectories)
350                         scanFilesInDir(d.c_str(), reader, depth - 1);
351
352         closedir(dir);
353 }
354
355 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
356 {
357         char* label = NULL;
358         struct stat info;
359
360         if (isSymlink) {
361                 // change smack label for symbolic link.
362                 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
363                         if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
364                                 fprintf(stderr, "Fail to set smack label\n");
365                         }
366                         free(label);
367                 }
368
369                 // change owner and groups for symbolic link.
370                 if (!stat(fromPath.c_str(), &info)) {
371                         if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
372                                 fprintf(stderr, "Failed to change owner and group name\n");
373                 }
374         } else {
375                 // change smack label
376                 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
377                         if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
378                                 fprintf(stderr, "Fail to set smack label\n");
379                         }
380                         free(label);
381                 }
382
383                 // change owner and groups for generated ni file.
384                 if (!stat(fromPath.c_str(), &info)) {
385                         if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
386                                 fprintf(stderr, "Failed to change owner and group name\n");
387                 }
388         }
389 }
390
391 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
392         int fd = open(path.c_str(), O_RDONLY);
393         if (fd < 0) {
394                 _ERR("Can't open directory: %s", path.c_str());
395                 return false;
396         }
397         int ret = fchown(fd, uid, gid);
398         close(fd);
399         if (ret != 0) {
400                 _ERR("Failed to change owner of: %s", path.c_str());
401                 return false;
402         }
403         return true;
404 }
405
406 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
407         bs::error_code error;
408         bf::permissions(path, permissions, error);
409         if (error) {
410                 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
411                 return false;
412         }
413         return true;
414 }
415
416 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
417         if (!setOwnership(path, uid, gid)) {
418                 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
419                 return false;
420         }
421         if (!setDirPermissions(path, permissions)) {
422                 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
423                 return false;
424         }
425         return true;
426 }
427
428 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
429         if (!bf::exists(path)) {
430                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
431                 return false;
432         }
433         bf::perms permissions = bf::status(path).permissions();
434         struct stat stats;
435         if (stat(path.c_str(), &stats) != 0) {
436                 return false;
437         }
438         if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
439                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
440                 return false;
441         }
442         return true;
443 }
444
445 bool createDir(const bf::path& path) {
446         if (bf::exists(path)) {
447                 return true;
448         }
449         bs::error_code error;
450         bf::create_directories(path, error);
451         if (error) {
452                 _ERR("Failed to create directory: %s", error.message().c_str());
453                 return false;
454         }
455         return true;
456 }
457
458 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
459         try {
460                 // Check whether the function call is valid
461                 if (!bf::exists(path1) || !bf::is_directory(path1)) {
462                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
463                         return false;
464                 }
465                 if (!bf::exists(path2)) {
466                         // Create the destination directory
467                         if (!createDir(path2)) {
468                                 _ERR("Unable to create destination directory %s", path2.c_str());
469                                 return false;
470                         }
471                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
472                                 copyOwnershipAndPermissions(path1, path2);
473                         }
474                 } else {
475                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
476                                 _ERR("Destination directory %s already exists", path2.c_str());
477                                 return false;
478                         }
479                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
480                                 copyOwnershipAndPermissions(path1, path2);
481                         }
482                 }
483         } catch (const bf::filesystem_error& error) {
484                 _ERR("Failed to copy directory: %s", error.what());
485                 return false;
486         }
487
488         // Iterate through the source directory
489         for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
490                 try {
491                         bf::path current(file->path());
492                         bf::path target = path2 / current.filename();
493                         if (bf::is_symlink(symlink_status(current))) {
494                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
495                                         continue;
496                                 }
497                                 bs::error_code error;
498                                 bf::copy_symlink(current, target, error);
499                                 if (error) {
500                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
501                                         return false;
502                                 }
503                         } else if (bf::is_directory(current)) {
504                                 // Found directory: Recursion
505                                 if (!copyDir(current, target, flags)) {
506                                         return false;
507                                 }
508                         } else {
509                                 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
510                                         continue;
511                                 }
512                                 bf::path destination = target;
513                                 if (flags & FS_COMMIT_COPY_FILE) {
514                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
515                                 }
516                                 if (flags & FS_MERGE_OVERWRITE) {
517                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
518                                 } else {
519                                         bf::copy_file(current, destination);
520                                 }
521                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
522                                         copyOwnershipAndPermissions(current, destination);
523                                 }
524                                 if (flags & FS_COMMIT_COPY_FILE) {
525                                         if (flags & FS_MERGE_OVERWRITE) {
526                                                 bf::remove(target);
527                                         }
528                                         bf::rename(destination, target);
529                                 }
530                         }
531                 } catch (const bf::filesystem_error& error) {
532                         _ERR("Failed to copy directory: %s", error.what());
533                         return false;
534                 }
535         }
536         return true;
537 }
538
539 bool copyFile(const bf::path& path1, const bf::path& path2) {
540         bs::error_code error;
541         if (!bf::exists(path1)) {
542                 return false;
543         }
544         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
545         if (error) {
546                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
547                 return false;
548         }
549         return true;
550 }
551
552 bool moveFile(const bf::path& path1, const bf::path& path2) {
553         if (!bf::exists(path1) || bf::exists(path2)) {
554                 return false;
555         }
556         bs::error_code error;
557         bf::rename(path1, path2, error);
558         if (error) {
559                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
560                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
561                 if (error) {
562                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
563                         return false;
564                 }
565                 bf::remove_all(path1, error);
566                 if (error) {
567                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
568                         return false;
569                 }
570         }
571         return true;
572 }
573
574 bool removeFile(const bf::path& path) {
575         if (!bf::exists(path)) {
576                 return true;
577         }
578         bs::error_code error;
579         bf::remove(path, error);
580         if (error) {
581                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
582                 return false;
583         }
584         return true;
585 }
586
587 bool removeAll(const bf::path& path) {
588         if (!exists(path)) {
589                 return true;
590         }
591         bs::error_code error;
592         bf::remove_all(path, error);
593         if (error) {
594                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
595                 return false;
596         }
597         return true;
598 }