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