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