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