Code cleanup (#251)
[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 #include <sys/prctl.h>
27
28 #include <cstdlib>
29 #include <cstring>
30 #include <algorithm>
31 #include <unordered_map>
32 #include <vector>
33 #include <iterator>
34 #include <fstream>
35 #include <sstream>
36 #include <map>
37
38 #include "log.h"
39 #include "utils.h"
40 #include "path_manager.h"
41
42 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
43 {
44         return static_cast<int>(a.length()) - length >= aOffset &&
45                 static_cast<int>(b.length()) - length >= bOffset &&
46                 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
47                         [](unsigned char a, unsigned char b)
48                         { return std::tolower(a) == std::tolower(b); });
49 }
50
51 bool isManagedAssembly(const std::string& fileName)
52 {
53         return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
54                         iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
55                         !isNativeImage(fileName);
56 }
57
58 bool isNativeImage(const std::string& fileName)
59 {
60         return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
61 }
62
63 std::string concatPath(const std::string& path1, const std::string& path2)
64 {
65         std::string path(path1);
66         if (path.back() == PATH_SEPARATOR) {
67                 path.append(path2);
68         } else {
69                 path += PATH_SEPARATOR;
70                 path.append(path2);
71         }
72
73         return path;
74 }
75
76 void splitPath(const std::string& path, std::vector<std::string>& out)
77 {
78         std::istringstream ss(path);
79         std::string token;
80
81         while (std::getline(ss, token, ':')) {
82                 out.push_back(token);
83         }
84 }
85
86 std::string getAbsolutePath(const std::string& path)
87 {
88         std::string absPath;
89         char *realPath = realpath(path.c_str(), NULL);
90         if (realPath) {
91                 absPath.assign(realPath);
92                 free(realPath);
93         }
94
95         return absPath;
96 }
97
98 std::string getRootPath(const std::string& pkgId)
99 {
100         int ret = 0;
101         char *path = 0;
102         uid_t uid = 0;
103         std::string rootPath;
104
105         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
106                 _ERR("Failed to get UID");
107                 return rootPath;
108         }
109
110         pkgmgrinfo_pkginfo_h handle;
111         if (uid == 0) {
112                 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
113                 if (ret != PMINFO_R_OK) {
114                         return rootPath;
115                 }
116         } else {
117                 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
118                 if (ret != PMINFO_R_OK) {
119                         return rootPath;
120                 }
121         }
122
123         ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
124         if (ret != PMINFO_R_OK) {
125                 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
126                 return rootPath;
127         }
128         rootPath = path;
129         pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
130
131         return rootPath;
132 }
133
134 std::string getExecName(const std::string& pkgId)
135 {
136         char *exec = NULL;
137         char *appId = 0;
138         std::string execName;
139
140         pkgmgrinfo_pkginfo_h pkg_handle;
141         int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
142         if (ret != PMINFO_R_OK) {
143                 return execName;
144         }
145         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
146         if (ret != PMINFO_R_OK) {
147                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
148                 return execName;
149         }
150
151         pkgmgrinfo_appinfo_h app_handle;
152         ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
153         if (ret != PMINFO_R_OK) {
154                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
155                 return execName;
156         }
157         ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
158         if (ret != PMINFO_R_OK) {
159                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
160                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
161                 return execName;
162         }
163         execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
164
165         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
166         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
167
168         return execName;
169 }
170
171 std::string getAppType(const std::string& pkgId)
172 {
173         char *appId = 0;
174         char *type = 0;
175         std::string appType;
176
177         pkgmgrinfo_pkginfo_h pkg_handle;
178         int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
179         if (ret != PMINFO_R_OK) {
180                 return appType;
181         }
182         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
183         if (ret != PMINFO_R_OK) {
184                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
185                 return appType;
186         }
187
188         pkgmgrinfo_appinfo_h app_handle;
189         ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
190         if (ret != PMINFO_R_OK) {
191                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
192                 return appType;
193         }
194         ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
195         if (ret != PMINFO_R_OK) {
196                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
197                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
198                 return appType;
199         }
200         appType = type;
201
202         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
203         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
204
205         return appType;
206 }
207
208 std::string getMetadataValue(const std::string& pkgId, const std::string& key)
209 {
210         char *value = NULL;
211         char *appId = 0;
212         std::string metadataValue;
213
214         pkgmgrinfo_pkginfo_h pkg_handle;
215         int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &pkg_handle);
216         if (ret != PMINFO_R_OK) {
217                 return metadataValue;
218         }
219         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
220         if (ret != PMINFO_R_OK) {
221                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
222                 return metadataValue;
223         }
224
225         pkgmgrinfo_appinfo_h app_handle;
226         ret = pkgmgrinfo_appinfo_get_appinfo(appId, &app_handle);
227         if (ret != PMINFO_R_OK) {
228                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
229                 return metadataValue;
230         }
231         ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
232         if (ret != PMINFO_R_OK) {
233                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
234                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
235                 return metadataValue;
236         }
237         metadataValue = std::string(value);
238
239         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
240         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
241
242         return metadataValue;
243 }
244
245 std::string getBaseName(const std::string& path)
246 {
247         auto pos = path.find_last_of(PATH_SEPARATOR);
248         if (pos != std::string::npos)
249                 return path.substr(0, pos);
250         else
251                 return std::string(".");
252         return path;
253 }
254
255 std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
256 {
257         std::string result = str;
258         std::string::size_type pos = 0;
259         std::string::size_type offset = 0;
260
261         while ((pos = result.find(pattern, offset)) != std::string::npos) {
262                 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
263                 offset = pos + replace.size();
264         }
265
266         return result;
267 }
268
269 bool isFile(const std::string& path)
270 {
271         struct stat sb;
272         return stat(path.c_str(), &sb) == 0;
273 }
274
275 bool isDirectory(const std::string& path)
276 {
277         struct stat sb;
278         if (stat(path.c_str(), &sb) != 0) {
279                 return false;
280         }
281         if (sb.st_mode & S_IFDIR) {
282                 return true;
283         } else {
284                 return false;
285         }
286 }
287
288 std::string getAssemblyNameFromPath(const std::string& path)
289 {
290         std::string ret(getFileName(path));
291
292         if (ret.find_last_of(".") == std::string::npos)
293                 return ret;
294         ret.erase(ret.find_last_of("."));
295
296         if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
297                 ret.erase(ret.size() - 3);
298
299         return ret;
300 }
301
302 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
303 {
304         std::vector<std::string> assems;
305         std::unordered_map<std::string, std::string> assemPaths;
306
307         auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
308                 if (isManagedAssembly(filename) || isNativeImage(filename)) {
309                         std::string assem = getAssemblyNameFromPath(filename);
310
311                         if (assemPaths.count(assem) == 0) {
312                                 assems.push_back(assem);
313                                 assemPaths[assem] = path;
314                         } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
315                                 // Update only if a native image is found in the same directory.
316                                 // For example, if we have two directories = { X, Y } where X contains A.dll and
317                                 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
318                                 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
319                                         assemPaths[assem] = path;
320                         }
321                 }
322         };
323         for (auto& directory : directories)
324                 scanFilesInDirectory(directory, reader, 0);
325
326         if (!list.empty() && list.back() != ':')
327                 list.push_back(':');
328
329         for (auto& assem : assems)
330                 list += assemPaths[assem] + ":";
331
332         if (list.back() == ':')
333                 list.pop_back();
334 }
335
336 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
337 {
338         DIR *dir;
339         struct dirent* entry;
340         bool isDir;
341
342         if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
343                 return;
344
345         dir = opendir(directory.c_str());
346
347         if (dir == nullptr)
348                 return;
349
350         std::vector<std::string> innerDirectories;
351
352         while ((entry = readdir(dir)) != nullptr) {
353                 isDir = false;
354                 std::string path = concatPath(directory, entry->d_name);
355                 switch (entry->d_type) {
356                         case DT_REG: break;
357                         case DT_DIR:
358                                 isDir = true;
359                                 break;
360                         case DT_LNK:
361                         case DT_UNKNOWN:
362                                 struct stat sb;
363                                 if (stat(path.c_str(), &sb) == -1)
364                                         continue;
365
366                                 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
367                                         break;
368                         default:
369                                 continue;
370                 }
371                 if (!isDir)
372                         reader(path, entry->d_name);
373                 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
374                         innerDirectories.push_back(path);
375         }
376
377         if (depth > 0)
378                 for (auto& d : innerDirectories)
379                         scanFilesInDirectory(d, reader, depth - 1);
380
381         closedir(dir);
382 }
383
384 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
385 {
386         char* label = NULL;
387         struct stat info;
388
389         if (isSymlink) {
390                 // change smack label for symbolic link.
391                 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
392                         if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
393                                 fprintf(stderr, "Fail to set smack label\n");
394                         }
395                         free(label);
396                 }
397
398                 // change owner and groups for symbolic link.
399                 if (!stat(fromPath.c_str(), &info)) {
400                         if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
401                                 fprintf(stderr, "Failed to change owner and group name\n");
402                 }
403         } else {
404                 // change smack label
405                 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
406                         if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
407                                 fprintf(stderr, "Fail to set smack label\n");
408                         }
409                         free(label);
410                 }
411
412                 // change owner and groups for generated ni file.
413                 if (!stat(fromPath.c_str(), &info)) {
414                         if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
415                                 fprintf(stderr, "Failed to change owner and group name\n");
416                 }
417         }
418 }
419
420 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
421 {
422         int fd = open(path.c_str(), O_RDONLY);
423         if (fd < 0) {
424                 _ERR("Can't open directory: %s", path.c_str());
425                 return false;
426         }
427         int ret = fchown(fd, uid, gid);
428         close(fd);
429         if (ret != 0) {
430                 _ERR("Failed to change owner of: %s", path.c_str());
431                 return false;
432         }
433         return true;
434 }
435
436 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
437 {
438         bs::error_code error;
439         bf::permissions(path, permissions, error);
440         if (error) {
441                 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
442                 return false;
443         }
444         return true;
445 }
446
447 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
448 {
449         if (!setOwnership(path, uid, gid)) {
450                 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
451                 return false;
452         }
453         if (!setDirPermissions(path, permissions)) {
454                 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
455                 return false;
456         }
457         return true;
458 }
459
460 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
461 {
462         if (!bf::exists(path)) {
463                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
464                 return false;
465         }
466         bf::perms permissions = bf::status(path).permissions();
467         struct stat stats;
468         if (stat(path.c_str(), &stats) != 0) {
469                 return false;
470         }
471         if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
472                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
473                 return false;
474         }
475         return true;
476 }
477
478 bool createDir(const bf::path& path)
479 {
480         if (bf::exists(path)) {
481                 return true;
482         }
483         bs::error_code error;
484         bf::create_directories(path, error);
485         if (error) {
486                 _ERR("Failed to create directory: %s", error.message().c_str());
487                 return false;
488         }
489         return true;
490 }
491
492 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
493 {
494         try {
495                 // Check whether the function call is valid
496                 if (!bf::exists(path1) || !bf::is_directory(path1)) {
497                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
498                         return false;
499                 }
500                 if (!bf::exists(path2)) {
501                         // Create the destination directory
502                         if (!createDir(path2)) {
503                                 _ERR("Unable to create destination directory %s", path2.c_str());
504                                 return false;
505                         }
506                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
507                                 copyOwnershipAndPermissions(path1, path2);
508                         }
509                 } else {
510                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
511                                 _ERR("Destination directory %s already exists", path2.c_str());
512                                 return false;
513                         }
514                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
515                                 copyOwnershipAndPermissions(path1, path2);
516                         }
517                 }
518         } catch (const bf::filesystem_error& error) {
519                 _ERR("Failed to copy directory: %s", error.what());
520                 return false;
521         }
522
523         // Iterate through the source directory
524         for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
525                 try {
526                         bf::path current(file->path());
527                         bf::path target = path2 / current.filename();
528                         if (bf::is_symlink(symlink_status(current))) {
529                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
530                                         continue;
531                                 }
532                                 bs::error_code error;
533                                 bf::copy_symlink(current, target, error);
534                                 if (error) {
535                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
536                                         return false;
537                                 }
538                         } else if (bf::is_directory(current)) {
539                                 // Found directory: Recursion
540                                 if (!copyDir(current, target, flags)) {
541                                         return false;
542                                 }
543                         } else {
544                                 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
545                                         continue;
546                                 }
547                                 bf::path destination = target;
548                                 if (flags & FS_COMMIT_COPY_FILE) {
549                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
550                                 }
551                                 if (flags & FS_MERGE_OVERWRITE) {
552                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
553                                 } else {
554                                         bf::copy_file(current, destination);
555                                 }
556                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
557                                         copyOwnershipAndPermissions(current, destination);
558                                 }
559                                 if (flags & FS_COMMIT_COPY_FILE) {
560                                         if (flags & FS_MERGE_OVERWRITE) {
561                                                 bf::remove(target);
562                                         }
563                                         bf::rename(destination, target);
564                                 }
565                         }
566                 } catch (const bf::filesystem_error& error) {
567                         _ERR("Failed to copy directory: %s", error.what());
568                         return false;
569                 }
570         }
571         return true;
572 }
573
574 bool copyFile(const bf::path& path1, const bf::path& path2)
575 {
576         bs::error_code error;
577         if (!bf::exists(path1)) {
578                 return false;
579         }
580         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
581         if (error) {
582                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
583                 return false;
584         }
585         return true;
586 }
587
588 bool moveFile(const bf::path& path1, const bf::path& path2)
589 {
590         if (!bf::exists(path1) || bf::exists(path2)) {
591                 return false;
592         }
593         bs::error_code error;
594         bf::rename(path1, path2, error);
595         if (error) {
596                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
597                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
598                 if (error) {
599                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
600                         return false;
601                 }
602                 bf::remove_all(path1, error);
603                 if (error) {
604                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
605                         return false;
606                 }
607         }
608         return true;
609 }
610
611 bool removeFile(const bf::path& path)
612 {
613         if (!bf::exists(path)) {
614                 return true;
615         }
616         bs::error_code error;
617         bf::remove(path, error);
618         if (error) {
619                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
620                 return false;
621         }
622         return true;
623 }
624
625 bool removeAll(const bf::path& path)
626 {
627         if (!exists(path)) {
628                 return true;
629         }
630         bs::error_code error;
631         bf::remove_all(path, error);
632         if (error) {
633                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
634                 return false;
635         }
636         return true;
637 }
638
639 void setCmdName(const std::string& name)
640 {
641         #define PRC_NAME_LENGTH         16
642
643         char processName[PRC_NAME_LENGTH] = {0, };
644
645         if (name.empty())
646                 return;
647
648         memset(processName, '\0', PRC_NAME_LENGTH);
649         snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
650         prctl(PR_SET_NAME, processName);
651 }
652
653 std::string getFileName(const std::string& path)
654 {
655         std::string ret(path);
656         size_t index = ret.find_last_of(PATH_SEPARATOR);
657         return index == std::string::npos ? ret : ret.substr(index + 1);
658 }