Refactoring path manager
[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 lstat(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         dir = opendir(directory.c_str());
343
344         if (dir == nullptr)
345                 return;
346
347         std::vector<std::string> innerDirectories;
348
349         while ((entry = readdir(dir)) != nullptr) {
350                 isDir = false;
351                 std::string path = concatPath(directory, entry->d_name);
352                 switch (entry->d_type) {
353                         case DT_REG: break;
354                         case DT_DIR:
355                                 isDir = true;
356                                 break;
357                         // symlink is added to the list even if there is no original file.
358                         // It used to remove broken symlinks related to TAC
359                         case DT_LNK:
360                                 break;
361                         case DT_UNKNOWN:
362                                 continue;
363                         default:
364                                 continue;
365                 }
366                 if (!isDir)
367                         reader(path, entry->d_name);
368                 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
369                         innerDirectories.push_back(path);
370         }
371
372         if (depth > 0)
373                 for (auto& d : innerDirectories)
374                         scanFilesInDirectory(d, reader, depth - 1);
375
376         closedir(dir);
377 }
378
379 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
380 {
381         char* label = NULL;
382         struct stat info;
383
384         if (isSymlink) {
385                 // change smack label for symbolic link.
386                 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
387                         if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
388                                 fprintf(stderr, "Fail to set smack label\n");
389                         }
390                         free(label);
391                 }
392
393                 // change owner and groups for symbolic link.
394                 if (!stat(fromPath.c_str(), &info)) {
395                         if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
396                                 fprintf(stderr, "Failed to change owner and group name\n");
397                 }
398         } else {
399                 // change smack label
400                 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
401                         if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
402                                 fprintf(stderr, "Fail to set smack label\n");
403                         }
404                         free(label);
405                 }
406
407                 // change owner and groups for generated ni file.
408                 if (!stat(fromPath.c_str(), &info)) {
409                         if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
410                                 fprintf(stderr, "Failed to change owner and group name\n");
411                 }
412         }
413 }
414
415 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
416 {
417         int fd = open(path.c_str(), O_RDONLY);
418         if (fd < 0) {
419                 _ERR("Can't open directory: %s", path.c_str());
420                 return false;
421         }
422         int ret = fchown(fd, uid, gid);
423         close(fd);
424         if (ret != 0) {
425                 _ERR("Failed to change owner of: %s", path.c_str());
426                 return false;
427         }
428         return true;
429 }
430
431 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
432 {
433         bs::error_code error;
434         bf::permissions(path, permissions, error);
435         if (error) {
436                 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
437                 return false;
438         }
439         return true;
440 }
441
442 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
443 {
444         if (!setOwnership(path, uid, gid)) {
445                 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
446                 return false;
447         }
448         if (!setDirPermissions(path, permissions)) {
449                 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
450                 return false;
451         }
452         return true;
453 }
454
455 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
456 {
457         if (!bf::exists(path)) {
458                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
459                 return false;
460         }
461         bf::perms permissions = bf::status(path).permissions();
462         struct stat stats;
463         if (stat(path.c_str(), &stats) != 0) {
464                 return false;
465         }
466         if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
467                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
468                 return false;
469         }
470         return true;
471 }
472
473 bool createDir(const bf::path& path)
474 {
475         if (bf::exists(path)) {
476                 return true;
477         }
478         bs::error_code error;
479         bf::create_directories(path, error);
480         if (error) {
481                 _ERR("Failed to create directory: %s", error.message().c_str());
482                 return false;
483         }
484         return true;
485 }
486
487 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
488 {
489         try {
490                 // Check whether the function call is valid
491                 if (!bf::exists(path1) || !bf::is_directory(path1)) {
492                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
493                         return false;
494                 }
495                 if (!bf::exists(path2)) {
496                         // Create the destination directory
497                         if (!createDir(path2)) {
498                                 _ERR("Unable to create destination directory %s", path2.c_str());
499                                 return false;
500                         }
501                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
502                                 copyOwnershipAndPermissions(path1, path2);
503                         }
504                 } else {
505                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
506                                 _ERR("Destination directory %s already exists", path2.c_str());
507                                 return false;
508                         }
509                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
510                                 copyOwnershipAndPermissions(path1, path2);
511                         }
512                 }
513         } catch (const bf::filesystem_error& error) {
514                 _ERR("Failed to copy directory: %s", error.what());
515                 return false;
516         }
517
518         // Iterate through the source directory
519         for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
520                 try {
521                         bf::path current(file->path());
522                         bf::path target = path2 / current.filename();
523                         if (bf::is_symlink(symlink_status(current))) {
524                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
525                                         continue;
526                                 }
527                                 bs::error_code error;
528                                 bf::copy_symlink(current, target, error);
529                                 if (error) {
530                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
531                                         return false;
532                                 }
533                         } else if (bf::is_directory(current)) {
534                                 // Found directory: Recursion
535                                 if (!copyDir(current, target, flags)) {
536                                         return false;
537                                 }
538                         } else {
539                                 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
540                                         continue;
541                                 }
542                                 bf::path destination = target;
543                                 if (flags & FS_COMMIT_COPY_FILE) {
544                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
545                                 }
546                                 if (flags & FS_MERGE_OVERWRITE) {
547                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
548                                 } else {
549                                         bf::copy_file(current, destination);
550                                 }
551                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
552                                         copyOwnershipAndPermissions(current, destination);
553                                 }
554                                 if (flags & FS_COMMIT_COPY_FILE) {
555                                         if (flags & FS_MERGE_OVERWRITE) {
556                                                 bf::remove(target);
557                                         }
558                                         bf::rename(destination, target);
559                                 }
560                         }
561                 } catch (const bf::filesystem_error& error) {
562                         _ERR("Failed to copy directory: %s", error.what());
563                         return false;
564                 }
565         }
566         return true;
567 }
568
569 bool copyFile(const bf::path& path1, const bf::path& path2)
570 {
571         bs::error_code error;
572         if (!bf::exists(path1)) {
573                 return false;
574         }
575         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
576         if (error) {
577                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
578                 return false;
579         }
580         return true;
581 }
582
583 bool moveFile(const bf::path& path1, const bf::path& path2)
584 {
585         if (!bf::exists(path1) || bf::exists(path2)) {
586                 return false;
587         }
588         bs::error_code error;
589         bf::rename(path1, path2, error);
590         if (error) {
591                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
592                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
593                 if (error) {
594                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
595                         return false;
596                 }
597                 bf::remove_all(path1, error);
598                 if (error) {
599                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
600                         return false;
601                 }
602         }
603         return true;
604 }
605
606 bool removeFile(const bf::path& path)
607 {
608         if (!bf::exists(path)) {
609                 return true;
610         }
611         bs::error_code error;
612         bf::remove(path, error);
613         if (error) {
614                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
615                 return false;
616         }
617         return true;
618 }
619
620 bool removeAll(const bf::path& path)
621 {
622         if (!exists(path)) {
623                 return true;
624         }
625         bs::error_code error;
626         bf::remove_all(path, error);
627         if (error) {
628                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
629                 return false;
630         }
631         return true;
632 }
633
634 void setCmdName(const std::string& name)
635 {
636         #define PRC_NAME_LENGTH         16
637
638         char processName[PRC_NAME_LENGTH] = {0, };
639
640         if (name.empty())
641                 return;
642
643         memset(processName, '\0', PRC_NAME_LENGTH);
644         snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
645         prctl(PR_SET_NAME, processName);
646 }
647
648 std::string getFileName(const std::string& path)
649 {
650         std::string ret(path);
651         size_t index = ret.find_last_of(PATH_SEPARATOR);
652         return index == std::string::npos ? ret : ret.substr(index + 1);
653 }