Modify the bf::exists function to check error.value (#275)
[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 (!exist(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 exist(const bf::path& path)
476 {
477         bs::error_code error;
478         int ret = bf::exists(path, error);
479         if (error) {
480                 if ((error.value() != bs::errc::success) && (error.value() != bs::errc::no_such_file_or_directory)) {
481                         _ERR("Failed to check %s exists : %s", path.c_str(), error.message().c_str());
482                 }
483         }
484         return ret;
485 }
486
487 bool createDir(const bf::path& path)
488 {
489         if (exist(path)) {
490                 return true;
491         }
492         bs::error_code error;
493         bf::create_directories(path, error);
494         if (error) {
495                 _ERR("Failed to create directory: %s", error.message().c_str());
496                 return false;
497         }
498         return true;
499 }
500
501 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
502 {
503         try {
504                 // Check whether the function call is valid
505                 if (!exist(path1) || !bf::is_directory(path1)) {
506                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
507                         return false;
508                 }
509                 if (!exist(path2)) {
510                         // Create the destination directory
511                         if (!createDir(path2)) {
512                                 _ERR("Unable to create destination directory %s", path2.c_str());
513                                 return false;
514                         }
515                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
516                                 copyOwnershipAndPermissions(path1, path2);
517                         }
518                 } else {
519                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
520                                 _ERR("Destination directory %s already exists", path2.c_str());
521                                 return false;
522                         }
523                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
524                                 copyOwnershipAndPermissions(path1, path2);
525                         }
526                 }
527         } catch (const bf::filesystem_error& error) {
528                 _ERR("Failed to copy directory: %s", error.what());
529                 return false;
530         }
531
532         // Iterate through the source directory
533         for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
534                 try {
535                         bf::path current(file->path());
536                         bf::path target = path2 / current.filename();
537                         if (bf::is_symlink(symlink_status(current))) {
538                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && exist(target)) {
539                                         continue;
540                                 }
541                                 bs::error_code error;
542                                 bf::copy_symlink(current, target, error);
543                                 if (error) {
544                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
545                                         return false;
546                                 }
547                         } else if (bf::is_directory(current)) {
548                                 // Found directory: Recursion
549                                 if (!copyDir(current, target, flags)) {
550                                         return false;
551                                 }
552                         } else {
553                                 if ((flags & FS_MERGE_SKIP) && exist(target)) {
554                                         continue;
555                                 }
556                                 bf::path destination = target;
557                                 if (flags & FS_COMMIT_COPY_FILE) {
558                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
559                                 }
560                                 if (flags & FS_MERGE_OVERWRITE) {
561                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
562                                 } else {
563                                         bf::copy_file(current, destination);
564                                 }
565                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
566                                         copyOwnershipAndPermissions(current, destination);
567                                 }
568                                 if (flags & FS_COMMIT_COPY_FILE) {
569                                         if (flags & FS_MERGE_OVERWRITE) {
570                                                 bf::remove(target);
571                                         }
572                                         bf::rename(destination, target);
573                                 }
574                         }
575                 } catch (const bf::filesystem_error& error) {
576                         _ERR("Failed to copy directory: %s", error.what());
577                         return false;
578                 }
579         }
580         return true;
581 }
582
583 bool copyFile(const bf::path& path1, const bf::path& path2)
584 {
585         bs::error_code error;
586         if (!exist(path1)) {
587                 return false;
588         }
589         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
590         if (error) {
591                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
592                 return false;
593         }
594         return true;
595 }
596
597 bool moveFile(const bf::path& path1, const bf::path& path2)
598 {
599         if (!exist(path1) || exist(path2)) {
600                 return false;
601         }
602         bs::error_code error;
603         bf::rename(path1, path2, error);
604         if (error) {
605                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
606                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
607                 if (error) {
608                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
609                         return false;
610                 }
611                 bf::remove_all(path1, error);
612                 if (error) {
613                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
614                         return false;
615                 }
616         }
617         return true;
618 }
619
620 bool removeFile(const bf::path& path)
621 {
622         if (!exist(path)) {
623                 return true;
624         }
625         bs::error_code error;
626         bf::remove(path, error);
627         if (error) {
628                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
629                 return false;
630         }
631         return true;
632 }
633
634 bool removeAll(const bf::path& path)
635 {
636         if (!exist(path)) {
637                 return true;
638         }
639         bs::error_code error;
640         bf::remove_all(path, error);
641         if (error) {
642                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
643                 return false;
644         }
645         return true;
646 }
647
648 void setCmdName(const std::string& name)
649 {
650         #define PRC_NAME_LENGTH         16
651
652         char processName[PRC_NAME_LENGTH] = {0, };
653
654         if (name.empty())
655                 return;
656
657         memset(processName, '\0', PRC_NAME_LENGTH);
658         snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
659         prctl(PR_SET_NAME, processName);
660 }
661
662 std::string getFileName(const std::string& path)
663 {
664         std::string ret(path);
665         size_t index = ret.find_last_of(PATH_SEPARATOR);
666         return index == std::string::npos ? ret : ret.substr(index + 1);
667 }
668
669 std::string SHA256(const std::string& path)
670 {
671         std::string output = "";
672         FILE *file = fopen(path.c_str(), "rb");
673         if (!file) {
674                 return output;
675         }
676
677         unsigned char hash[SHA256_DIGEST_LENGTH];
678         SHA256_CTX sha256;
679         SHA256_Init(&sha256);
680         int bytesRead = 0;
681         const int bufSize = 32768;
682         char *buffer = (char*)malloc(bufSize);
683         if (!buffer) {
684                 fclose(file);
685                 return output;
686         }
687
688         while ((bytesRead = fread(buffer, 1, bufSize, file))) {
689                 SHA256_Update(&sha256, buffer, bytesRead);
690         }
691         SHA256_Final(hash, &sha256);
692
693         std::stringstream ss;
694         for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
695                 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
696         }
697         output = ss.str();
698
699         fclose(file);
700         free(buffer);
701
702         return output;
703 }