seperate executable to apply User execute label to dotnet-loader
[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 uintptr_t getFileSize(const std::string& path)
251 {
252         struct stat sb;
253
254         if (stat(path.c_str(), &sb) == 0) {
255                 return sb.st_size;
256         }
257
258         return 0;
259 }
260
261 std::string stripNiDLL(const std::string& path)
262 {
263         std::string niPath(path);
264         if (path.size() < 5) return niPath;
265         if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
266                 niPath = path.substr(0, path.size()-4);
267         else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
268                 niPath = path.substr(0, path.size()-4);
269
270         if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
271                 return niPath.substr(0, niPath.size()-3);
272
273         return niPath;
274 }
275
276 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
277 {
278         std::map<std::string, std::string> assemblyList;
279         std::map<std::string, std::string> tmpList;
280
281         auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
282                 if (isManagedAssembly(path) || isNativeImage(path)) {
283                         std::string dllName = stripNiDLL(name);
284                         std::pair<std::map<std::string, std::string>::iterator, bool> ret;
285                         ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
286                         if (ret.second == false) {
287                                 if (isNativeImage(path))
288                                         tmpList[dllName] = path;
289                         }
290                 }
291         };
292
293         for (auto directory : directories) {
294                 scanFilesInDir(directory.c_str(), reader, 1);
295                 // merge scaned dll list to tpa list.
296                 // if the dll is already exist in the list, that is skipped.
297                 assemblyList.insert(tmpList.begin(), tmpList.end());
298         }
299
300         std::map<std::string, std::string>::iterator it;
301         for (it = assemblyList.begin(); it != assemblyList.end(); it++)
302                 tpaList += it->second + ':';
303
304         if (tpaList.back() == ':')
305                 tpaList.pop_back();
306 }
307
308 void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
309 {
310         DIR *dir;
311         struct dirent* entry;
312         bool isDir;
313
314         if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
315                 return;
316
317         dir = opendir(directory.c_str());
318
319         if (dir == nullptr)
320                 return;
321
322         std::vector<std::string> innerDirectories;
323
324         while ((entry = readdir(dir)) != nullptr) {
325                 isDir = false;
326                 std::string path = concatPath(directory, entry->d_name);
327                 switch (entry->d_type) {
328                         case DT_REG: break;
329                         case DT_DIR:
330                                 isDir = true;
331                                 break;
332                         case DT_LNK:
333                         case DT_UNKNOWN:
334                                 struct stat sb;
335                                 if (stat(path.c_str(), &sb) == -1)
336                                         continue;
337
338                                 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
339                                         break;
340                         default:
341                                 continue;
342                 }
343                 if (!isDir)
344                         reader(path, entry->d_name);
345                 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
346                         innerDirectories.push_back(path);
347         }
348
349         if (depth != 0)
350                 for (auto& d : innerDirectories)
351                         scanFilesInDir(d.c_str(), reader, depth - 1);
352
353         closedir(dir);
354 }
355
356 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
357 {
358         char* label = NULL;
359         struct stat info;
360
361         if (isSymlink) {
362                 // change smack label for symbolic link.
363                 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
364                         if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
365                                 fprintf(stderr, "Fail to set smack label\n");
366                         }
367                         free(label);
368                 }
369
370                 // change owner and groups for symbolic link.
371                 if (!stat(fromPath.c_str(), &info)) {
372                         if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
373                                 fprintf(stderr, "Failed to change owner and group name\n");
374                 }
375         } else {
376                 // change smack label
377                 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
378                         if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
379                                 fprintf(stderr, "Fail to set smack label\n");
380                         }
381                         free(label);
382                 }
383
384                 // change owner and groups for generated ni file.
385                 if (!stat(fromPath.c_str(), &info)) {
386                         if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
387                                 fprintf(stderr, "Failed to change owner and group name\n");
388                 }
389         }
390 }
391
392 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
393         int fd = open(path.c_str(), O_RDONLY);
394         if (fd < 0) {
395                 _ERR("Can't open directory: %s", path.c_str());
396                 return false;
397         }
398         int ret = fchown(fd, uid, gid);
399         close(fd);
400         if (ret != 0) {
401                 _ERR("Failed to change owner of: %s", path.c_str());
402                 return false;
403         }
404         return true;
405 }
406
407 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
408         bs::error_code error;
409         bf::permissions(path, permissions, error);
410         if (error) {
411                 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
412                 return false;
413         }
414         return true;
415 }
416
417 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
418         if (!setOwnership(path, uid, gid)) {
419                 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
420                 return false;
421         }
422         if (!setDirPermissions(path, permissions)) {
423                 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
424                 return false;
425         }
426         return true;
427 }
428
429 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
430         if (!bf::exists(path)) {
431                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
432                 return false;
433         }
434         bf::perms permissions = bf::status(path).permissions();
435         struct stat stats;
436         if (stat(path.c_str(), &stats) != 0) {
437                 return false;
438         }
439         if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
440                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
441                 return false;
442         }
443         return true;
444 }
445
446 bool createDir(const bf::path& path) {
447         if (bf::exists(path)) {
448                 return true;
449         }
450         bs::error_code error;
451         bf::create_directories(path, error);
452         if (error) {
453                 _ERR("Failed to create directory: %s", error.message().c_str());
454                 return false;
455         }
456         return true;
457 }
458
459 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
460         try {
461                 // Check whether the function call is valid
462                 if (!bf::exists(path1) || !bf::is_directory(path1)) {
463                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
464                         return false;
465                 }
466                 if (!bf::exists(path2)) {
467                         // Create the destination directory
468                         if (!createDir(path2)) {
469                                 _ERR("Unable to create destination directory %s", path2.c_str());
470                                 return false;
471                         }
472                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
473                                 copyOwnershipAndPermissions(path1, path2);
474                         }
475                 } else {
476                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
477                                 _ERR("Destination directory %s already exists", path2.c_str());
478                                 return false;
479                         }
480                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
481                                 copyOwnershipAndPermissions(path1, path2);
482                         }
483                 }
484         } catch (const bf::filesystem_error& error) {
485                 _ERR("Failed to copy directory: %s", error.what());
486                 return false;
487         }
488
489         // Iterate through the source directory
490         for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
491                 try {
492                         bf::path current(file->path());
493                         bf::path target = path2 / current.filename();
494                         if (bf::is_symlink(symlink_status(current))) {
495                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
496                                         continue;
497                                 }
498                                 bs::error_code error;
499                                 bf::copy_symlink(current, target, error);
500                                 if (error) {
501                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
502                                         return false;
503                                 }
504                         } else if (bf::is_directory(current)) {
505                                 // Found directory: Recursion
506                                 if (!copyDir(current, target, flags)) {
507                                         return false;
508                                 }
509                         } else {
510                                 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
511                                         continue;
512                                 }
513                                 bf::path destination = target;
514                                 if (flags & FS_COMMIT_COPY_FILE) {
515                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
516                                 }
517                                 if (flags & FS_MERGE_OVERWRITE) {
518                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
519                                 } else {
520                                         bf::copy_file(current, destination);
521                                 }
522                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
523                                         copyOwnershipAndPermissions(current, destination);
524                                 }
525                                 if (flags & FS_COMMIT_COPY_FILE) {
526                                         if (flags & FS_MERGE_OVERWRITE) {
527                                                 bf::remove(target);
528                                         }
529                                         bf::rename(destination, target);
530                                 }
531                         }
532                 } catch (const bf::filesystem_error& error) {
533                         _ERR("Failed to copy directory: %s", error.what());
534                         return false;
535                 }
536         }
537         return true;
538 }
539
540 bool copyFile(const bf::path& path1, const bf::path& path2) {
541         bs::error_code error;
542         if (!bf::exists(path1)) {
543                 return false;
544         }
545         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
546         if (error) {
547                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
548                 return false;
549         }
550         return true;
551 }
552
553 bool moveFile(const bf::path& path1, const bf::path& path2) {
554         if (!bf::exists(path1) || bf::exists(path2)) {
555                 return false;
556         }
557         bs::error_code error;
558         bf::rename(path1, path2, error);
559         if (error) {
560                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
561                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
562                 if (error) {
563                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
564                         return false;
565                 }
566                 bf::remove_all(path1, error);
567                 if (error) {
568                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
569                         return false;
570                 }
571         }
572         return true;
573 }
574
575 bool removeFile(const bf::path& path) {
576         if (!bf::exists(path)) {
577                 return true;
578         }
579         bs::error_code error;
580         bf::remove(path, error);
581         if (error) {
582                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
583                 return false;
584         }
585         return true;
586 }
587
588 bool removeAll(const bf::path& path) {
589         if (!exists(path)) {
590                 return true;
591         }
592         bs::error_code error;
593         bf::remove_all(path, error);
594         if (error) {
595                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
596                 return false;
597         }
598         return true;
599 }
600
601 void setCmdName(const char* name)
602 {
603         #define PRC_NAME_LENGTH         16
604
605         char processName[PRC_NAME_LENGTH] = {0, };
606
607         if (name == NULL || *name == '\0') {
608                 return;
609         }
610
611         memset(processName, '\0', PRC_NAME_LENGTH);
612         snprintf(processName, PRC_NAME_LENGTH, "%s", name);
613         prctl(PR_SET_NAME, processName);                
614 }
615
616 char* getFileNameFromPath(char* path)
617 {
618         char* fileName = strrchr(path, PATH_SEPARATOR);
619         if (fileName != NULL && *fileName != '\0') {
620                 return ++fileName;
621         }
622
623         return NULL;
624 }
625