9f34fb4e922d0e663952cc3f190adbffbe8a5f1e
[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_installer_info.h>
24 #include <sys/smack.h>
25 #include <sys/prctl.h>
26
27 #include <openssl/evp.h>
28 #include <openssl/crypto.h>
29
30 #include <mntent.h>
31
32 #include <cstdlib>
33 #include <cstring>
34 #include <algorithm>
35 #include <unordered_map>
36 #include <vector>
37 #include <iterator>
38 #include <fstream>
39 #include <sstream>
40 #include <map>
41 #include <iomanip>
42
43 #include "log.h"
44 #include "utils.h"
45 #include "path_manager.h"
46
47 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
48 {
49         return static_cast<int>(a.length()) - length >= aOffset &&
50                 static_cast<int>(b.length()) - length >= bOffset &&
51                 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
52                         [](unsigned char a, unsigned char b)
53                         { return std::tolower(a) == std::tolower(b); });
54 }
55
56 bool isManagedAssembly(const std::string& fileName)
57 {
58         return iCompare(fileName, fileName.size()-4, ".dll", 0, 4) && !isNativeImage(fileName);
59 }
60
61 bool isNativeImage(const std::string& fileName)
62 {
63         return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
64 }
65
66 std::string concatPath(const std::string& path1, const std::string& path2)
67 {
68         std::string path(path1);
69         if (path.back() == PATH_SEPARATOR) {
70                 path.append(path2);
71         } else {
72                 path += PATH_SEPARATOR;
73                 path.append(path2);
74         }
75
76         return path;
77 }
78
79 void splitPath(const std::string& path, std::vector<std::string>& out)
80 {
81         std::istringstream ss(path);
82         std::string token;
83
84         while (std::getline(ss, token, ':')) {
85                 out.push_back(token);
86         }
87 }
88
89 std::string getAbsolutePath(const std::string& path)
90 {
91         std::string absPath;
92         char *realPath = realpath(path.c_str(), NULL);
93         if (realPath) {
94                 absPath.assign(realPath);
95                 free(realPath);
96         }
97
98         return absPath;
99 }
100
101 std::string getRootPath(const std::string& pkgId)
102 {
103         int ret = 0;
104         char *path = 0;
105         std::string rootPath;
106
107         pkgmgrinfo_pkginfo_h pkg_handle;
108         ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
109         if (ret != 0) {
110                 return rootPath;
111         }
112
113         ret = pkgmgrinfo_pkginfo_get_root_path(pkg_handle, &path);
114         if (ret != PMINFO_R_OK) {
115                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
116                 return rootPath;
117         }
118         rootPath = path;
119         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
120
121         return rootPath;
122 }
123
124 std::string getExecName(const std::string& pkgId)
125 {
126         char *exec = NULL;
127         char *appId = 0;
128         std::string execName;
129
130         pkgmgrinfo_pkginfo_h pkg_handle;
131         int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
132         if (ret != 0) {
133                 return execName;
134         }
135
136         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
137         if (ret != PMINFO_R_OK) {
138                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
139                 return execName;
140         }
141
142         pkgmgrinfo_appinfo_h app_handle;
143         ret = pkgmgrGetAppInfo(appId, &app_handle);
144         if (ret != 0) {
145                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
146                 return execName;
147         }
148
149         ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
150         if (ret != PMINFO_R_OK) {
151                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
152                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
153                 return execName;
154         }
155         execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
156
157         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
158         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
159
160         return execName;
161 }
162
163 std::string getAppType(const std::string& pkgId)
164 {
165         char *appId = 0;
166         char *type = 0;
167         std::string appType;
168
169         pkgmgrinfo_pkginfo_h pkg_handle;
170         int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
171         if (ret != 0) {
172                 return appType;
173         }
174
175         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
176         if (ret != PMINFO_R_OK) {
177                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
178                 return appType;
179         }
180
181         pkgmgrinfo_appinfo_h app_handle;
182         ret = pkgmgrGetAppInfo(appId, &app_handle);
183         if (ret != 0) {
184                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
185                 return appType;
186         }
187
188         ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
189         if (ret != PMINFO_R_OK) {
190                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
191                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
192                 return appType;
193         }
194         appType = type;
195
196         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
197         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
198
199         return appType;
200 }
201
202 std::string getMetadataValue(const std::string& pkgId, const std::string& key)
203 {
204         char *value = NULL;
205         char *appId = 0;
206         std::string metadataValue;
207
208         pkgmgrinfo_pkginfo_h pkg_handle;
209         int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
210         if (ret != 0) {
211                 return metadataValue;
212         }
213
214         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
215         if (ret != PMINFO_R_OK) {
216                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
217                 return metadataValue;
218         }
219
220         pkgmgrinfo_appinfo_h app_handle;
221         ret = pkgmgrGetAppInfo(appId, &app_handle);
222         if (ret != 0) {
223                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
224                 return metadataValue;
225         }
226
227         ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
228         if (ret != PMINFO_R_OK) {
229                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
230                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
231                 return metadataValue;
232         }
233         metadataValue = std::string(value);
234
235         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
236         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
237
238         return metadataValue;
239 }
240
241 bool isReadOnlyArea(const std::string& path)
242 {
243         FILE *f = NULL;
244         struct mntent *m = NULL;
245
246         // "/opt/usr" is mounted to "RW" only
247         if (path.find("/opt/usr") != std::string::npos) {
248                 return false;
249         }
250
251         // check whether "/" is mounted to RO or not
252         f = setmntent("/proc/mounts", "r");
253         if (!f) {
254                 // return true for fail case to generate NI files under RW area.
255                 return true;
256         }
257
258         while((m = getmntent(f))) {
259                 if (m->mnt_dir != NULL && strcmp(m->mnt_dir, "/") == 0 &&
260                         m->mnt_opts != NULL && strstr(m->mnt_opts, "ro,") != NULL) {
261                         endmntent(f);
262                         return true;
263                 }
264         }
265         endmntent(f);
266         return false;
267
268 }
269
270 std::string getBaseName(const std::string& path)
271 {
272         auto pos = path.find_last_of(PATH_SEPARATOR);
273         if (pos != std::string::npos)
274                 return path.substr(0, pos);
275         else
276                 return std::string(".");
277         return path;
278 }
279
280 std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
281 {
282         std::string result = str;
283         std::string::size_type pos = 0;
284         std::string::size_type offset = 0;
285
286         while ((pos = result.find(pattern, offset)) != std::string::npos) {
287                 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
288                 offset = pos + replace.size();
289         }
290
291         return result;
292 }
293
294 std::string changeExtension(const std::string& path, const std::string& from, const std::string& to)
295 {
296         return path.substr(0, path.rfind(from)) + to;
297 }
298
299 bool isFile(const std::string& path)
300 {
301         struct stat sb;
302         return lstat(path.c_str(), &sb) == 0;
303 }
304
305 bool isSymlinkFile(const std::string& path)
306 {
307         struct stat sb;
308         if (lstat(path.c_str(), &sb) != 0) {
309                 return false;
310         }
311         return (sb.st_mode & S_IFMT) == S_IFLNK;
312 }
313
314 bool isDirectory(const std::string& path)
315 {
316         struct stat sb;
317         if (stat(path.c_str(), &sb) != 0) {
318                 return false;
319         }
320         return (sb.st_mode & S_IFMT) == S_IFDIR;
321 }
322
323 std::string getAssemblyNameFromPath(const std::string& path)
324 {
325         std::string ret(getFileName(path));
326
327         if (ret.find_last_of(".") == std::string::npos)
328                 return ret;
329         ret.erase(ret.find_last_of("."));
330
331         if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
332                 ret.erase(ret.size() - 3);
333
334         return ret;
335 }
336
337 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
338 {
339         std::vector<std::string> assems;
340         std::unordered_map<std::string, std::string> assemPaths;
341
342         auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
343                 if (isManagedAssembly(filename) || isNativeImage(filename)) {
344                         std::string assem = getAssemblyNameFromPath(filename);
345
346                         if (assemPaths.count(assem) == 0) {
347                                 assems.push_back(assem);
348                                 assemPaths[assem] = path;
349                         } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
350                                 // Update only if a native image is found in the same directory.
351                                 // For example, if we have two directories = { X, Y } where X contains A.dll and
352                                 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
353                                 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
354                                         assemPaths[assem] = path;
355                         }
356                 }
357         };
358         for (auto& directory : directories)
359                 scanFilesInDirectory(directory, reader, 0);
360
361         if (!list.empty() && list.back() != ':')
362                 list.push_back(':');
363
364         for (auto& assem : assems)
365                 list += assemPaths[assem] + ":";
366
367         if (list.back() == ':')
368                 list.pop_back();
369 }
370
371 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
372 {
373         DIR *dir;
374         struct dirent* entry;
375         bool isDir;
376
377         dir = opendir(directory.c_str());
378
379         if (dir == nullptr)
380                 return;
381
382         std::vector<std::string> innerDirectories;
383
384         while ((entry = readdir(dir)) != nullptr) {
385                 isDir = false;
386                 std::string path = concatPath(directory, entry->d_name);
387                 switch (entry->d_type) {
388                         case DT_REG: break;
389                         case DT_DIR:
390                                 isDir = true;
391                                 break;
392                         // symlink is added to the list even if there is no original file.
393                         // It used to remove broken symlinks related to TAC
394                         case DT_LNK:
395                                 break;
396                         case DT_UNKNOWN:
397                                 continue;
398                         default:
399                                 continue;
400                 }
401                 if (!isDir)
402                         reader(path, entry->d_name);
403                 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
404                         innerDirectories.push_back(path);
405         }
406
407         if (depth > 0)
408                 for (auto& d : innerDirectories)
409                         scanFilesInDirectory(d, reader, depth - 1);
410
411         closedir(dir);
412 }
413
414 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
415 {
416         char* label = NULL;
417         struct stat info;
418
419         if (isSymlink) {
420                 // change smack label for symbolic link.
421                 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
422                         if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
423                                 _SERR("Fail to set smack label");
424                         }
425                         free(label);
426                 }
427
428                 // change owner and groupsfor symbolic link.
429                 // change mode is skipped for symlink because permission of symlink file is meaningless.
430                 if (!lstat(fromPath.c_str(), &info)) {
431                         if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
432                                 _SERR("Failed to change owner and group name");
433                 }
434         } else {
435                 // change smack label
436                 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
437                         if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
438                                 _SERR("Fail to set smack label");
439                         }
440                         free(label);
441                 }
442
443                 // change owner, groups and mode for generated ni file.
444                 if (!stat(fromPath.c_str(), &info)) {
445                         if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
446                                 _SERR("Failed to change owner and group name");
447                         if (chmod(toPath.c_str(), info.st_mode) == -1)
448                                 _SERR("Failed to change mode");
449                 }
450         }
451 }
452
453 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
454 {
455         int fd = open(path.c_str(), O_RDONLY);
456         if (fd < 0) {
457                 _ERR("Can't open directory: %s", path.c_str());
458                 return false;
459         }
460         int ret = fchown(fd, uid, gid);
461         close(fd);
462         if (ret != 0) {
463                 _ERR("Failed to change owner of: %s", path.c_str());
464                 return false;
465         }
466         return true;
467 }
468
469 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
470 {
471         bs::error_code error;
472         bf::permissions(path, permissions, error);
473         if (error) {
474                 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
475                 return false;
476         }
477         return true;
478 }
479
480 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
481 {
482         if (!setOwnership(path, uid, gid)) {
483                 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
484                 return false;
485         }
486         if (!setDirPermissions(path, permissions)) {
487                 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
488                 return false;
489         }
490         return true;
491 }
492
493 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
494 {
495         if (!exist(path)) {
496                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
497                 return false;
498         }
499         bs::error_code error;
500         bf::perms permissions = bf::status(path, error).permissions();
501         if (error) {
502                 _ERR("Failed to copy ownership and permissions : %s", error.message().c_str());
503                 return false;
504         }
505         struct stat stats;
506         if (stat(path.c_str(), &stats) != 0) {
507                 return false;
508         }
509         if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
510                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
511                 return false;
512         }
513         return true;
514 }
515
516 bool exist(const bf::path& path)
517 {
518         bs::error_code error;
519         int ret = bf::exists(path, error);
520         if (error) {
521                 if ((error.value() != bs::errc::success) && (error.value() != bs::errc::no_such_file_or_directory)) {
522                         _ERR("Failed to check %s exists : %s", path.c_str(), error.message().c_str());
523                 }
524         }
525         return ret;
526 }
527
528 bool createDir(const bf::path& path)
529 {
530         if (exist(path)) {
531                 return true;
532         }
533         bs::error_code error;
534         bf::create_directories(path, error);
535         if (error) {
536                 _ERR("Failed to create directory: %s", error.message().c_str());
537                 return false;
538         }
539         return true;
540 }
541
542 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
543 {
544         try {
545                 // Check whether the function call is valid
546                 if (!exist(path1) || !bf::is_directory(path1)) {
547                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
548                         return false;
549                 }
550                 if (!exist(path2)) {
551                         // Create the destination directory
552                         if (!createDir(path2)) {
553                                 _ERR("Unable to create destination directory %s", path2.c_str());
554                                 return false;
555                         }
556                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
557                                 copyOwnershipAndPermissions(path1, path2);
558                         }
559                 } else {
560                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
561                                 _ERR("Destination directory %s already exists", path2.c_str());
562                                 return false;
563                         }
564                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
565                                 copyOwnershipAndPermissions(path1, path2);
566                         }
567                 }
568         } catch (const bf::filesystem_error& error) {
569                 _ERR("Failed to copy directory: %s", error.what());
570                 return false;
571         }
572
573         // Iterate through the source directory
574         try {
575                 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
576                         bf::path current(file->path());
577                         bf::path target = path2 / current.filename();
578                         if (bf::is_symlink(bf::symlink_status(current))) {
579                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && exist(target)) {
580                                         continue;
581                                 }
582                                 bs::error_code error;
583                                 bf::copy_symlink(current, target, error);
584                                 if (error) {
585                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
586                                         return false;
587                                 }
588                         } else if (bf::is_directory(current)) {
589                                 // Found directory: Recursion
590                                 if (!copyDir(current, target, flags)) {
591                                         return false;
592                                 }
593                         } else {
594                                 if ((flags & FS_MERGE_SKIP) && exist(target)) {
595                                         continue;
596                                 }
597                                 bf::path destination = target;
598                                 if (flags & FS_COMMIT_COPY_FILE) {
599                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
600                                 }
601                                 if (flags & FS_MERGE_OVERWRITE) {
602                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
603                                 } else {
604                                         bf::copy_file(current, destination);
605                                 }
606                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
607                                         copyOwnershipAndPermissions(current, destination);
608                                 }
609                                 if (flags & FS_COMMIT_COPY_FILE) {
610                                         if (flags & FS_MERGE_OVERWRITE) {
611                                                 bf::remove(target);
612                                         }
613                                         bf::rename(destination, target);
614                                 }
615                         }
616                 }
617         } catch (const bf::filesystem_error& error) {
618                 _ERR("Failed to copy directory: %s", error.what());
619                 return false;
620         }
621
622         return true;
623 }
624
625 bool copyFile(const bf::path& path1, const bf::path& path2)
626 {
627         bs::error_code error;
628         if (!exist(path1)) {
629                 return false;
630         }
631         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
632         if (error) {
633                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
634                 return false;
635         }
636         return true;
637 }
638
639 bool moveFile(const bf::path& path1, const bf::path& path2)
640 {
641         if (!exist(path1) || exist(path2)) {
642                 return false;
643         }
644         bs::error_code error;
645         bf::rename(path1, path2, error);
646         if (error) {
647                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
648                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
649                 if (error) {
650                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
651                         return false;
652                 }
653                 bf::remove_all(path1, error);
654                 if (error) {
655                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
656                         return false;
657                 }
658         }
659         return true;
660 }
661
662 bool removeFile(const bf::path& path)
663 {
664         if (!exist(path)) {
665                 return true;
666         }
667         bs::error_code error;
668         bf::remove(path, error);
669         if (error) {
670                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
671                 return false;
672         }
673         return true;
674 }
675
676 bool removeAll(const bf::path& path)
677 {
678         if (!exist(path)) {
679                 return true;
680         }
681         bs::error_code error;
682         bf::remove_all(path, error);
683         if (error) {
684                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
685                 return false;
686         }
687         return true;
688 }
689
690 void setCmdName(const std::string& name)
691 {
692         #define PRC_NAME_LENGTH         16
693
694         char processName[PRC_NAME_LENGTH] = {0, };
695
696         if (name.empty())
697                 return;
698
699         memset(processName, '\0', PRC_NAME_LENGTH);
700         snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
701         prctl(PR_SET_NAME, processName);
702 }
703
704 std::string getFileName(const std::string& path)
705 {
706         std::string ret(path);
707         size_t index = ret.find_last_of(PATH_SEPARATOR);
708         return index == std::string::npos ? ret : ret.substr(index + 1);
709 }
710
711 std::string SHA256(const std::string& path)
712 {
713         int bytesRead = 0;
714         const int bufSize = 32768;
715
716         unsigned int digest_len = 0;
717         unsigned char* digest = NULL;
718
719         std::stringstream ss;
720         EVP_MD_CTX *mdctx = NULL;
721         std::string output = "";
722
723         FILE *file = fopen(path.c_str(), "rb");
724         if (!file) {
725                 return output;
726         }
727
728         char *buffer = (char*)malloc(bufSize);
729         if (!buffer) {
730                 goto cleanup4;
731         }
732
733         mdctx = EVP_MD_CTX_new();
734         if (mdctx == NULL) {
735                 _ERR("Message Digest Context creation NULL");
736                 goto cleanup3;
737         }
738
739         digest = (unsigned char*)OPENSSL_malloc(EVP_MD_size(EVP_sha256()));
740         if (!digest) {
741                 _ERR("Memory Allocation for SHA256 failed");
742                 goto cleanup2;
743         }
744
745         if (!EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL)) {
746                 _ERR("Message Digest init failed");
747                 goto cleanup1;
748         }
749
750         while ((bytesRead = fread(buffer, 1, bufSize, file))) {
751                 if (!EVP_DigestUpdate(mdctx, buffer, bytesRead)) {
752                         _ERR("Message Digest update failed");
753                         goto cleanup1;
754                 }
755         }
756
757         if (!EVP_DigestFinal_ex(mdctx, digest, &digest_len)) {
758                 _ERR("Message Digest Finalization falied");
759                 goto cleanup1;
760         }
761
762         for (unsigned int i = 0; i < digest_len; i++) {
763                 ss << std::hex << std::setw(2) << std::setfill('0') << (int)digest[i];
764         }
765         output = ss.str();
766
767 cleanup1:
768         EVP_MD_CTX_free(mdctx);
769 cleanup2:
770         OPENSSL_free(digest);
771 cleanup3:
772         free(buffer);
773 cleanup4:
774         fclose(file);
775
776         return output;
777 }
778
779 int pkgmgrGetPkgInfo(const std::string& pkgId, pkgmgrinfo_pkginfo_h* handle)
780 {
781         uid_t uid = 0;
782         int ret = 0;
783
784         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
785                 _ERR("Failed to get UID");
786                 return -1;
787         }
788
789         ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, handle);
790         if (ret != PMINFO_R_OK) {
791                 _ERR("Failed to get pkginfo (%d)", ret);
792                 return -1;
793         }
794
795         return 0;
796 }
797
798 int pkgmgrGetAppInfo(const std::string& appId, pkgmgrinfo_appinfo_h* handle)
799 {
800         uid_t uid = 0;
801         int ret = 0;
802
803         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
804                 _ERR("Failed to get UID");
805                 return -1;
806         }
807
808         ret = pkgmgrinfo_appinfo_get_usr_appinfo(appId.c_str(), uid, handle);
809         if (ret != PMINFO_R_OK) {
810                 _ERR("Failed to get appinfo (%d)", ret);
811                 return -1;
812         }
813
814         return 0;
815 }
816
817 int pkgmgrMDFilterForeach(pkgmgrinfo_appinfo_metadata_filter_h handle,
818                                                         pkgmgrinfo_app_list_cb app_cb,
819                                                         void *user_data)
820 {
821         uid_t uid = 0;
822         int ret = 0;
823
824         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
825                 _ERR("Failed to get UID");
826                 return -1;
827         }
828
829
830         ret = pkgmgrinfo_appinfo_usr_metadata_filter_foreach(handle, app_cb, user_data, uid);
831         if (ret != PMINFO_R_OK) {
832                 _ERR("Failed to execute the metadata filter query (%d)", ret);
833                 return -1;
834         }
835
836         return 0;
837 }
838
839 void printHWClockLog(const char* format, ...)
840 {
841         char buf[1024] = {0,};
842         va_list ap;
843
844         va_start(ap, format);
845         vsnprintf(buf, sizeof(buf), format, ap);
846         va_end(ap);
847
848         prctl(PR_TASK_PERF_USER_TRACE, buf, strlen(buf));
849 }
850
851 const char* getNCDBStartupHook()
852 {
853         return "/home/owner/share/tmp/sdk_tools/netcoredbg/ncdbhook.dll";
854 }
855
856 bool isNCDBStartupHookProvided()
857 {
858         char *env = nullptr;
859         env = getenv("DOTNET_STARTUP_HOOKS");
860         if (env == nullptr)
861                 return false;
862
863         // Note, `DOTNET_STARTUP_HOOKS` env could provide list of dlls with ':' delimiter,
864         // for example: "/path1/name1.dll:/path2/name2.dll"
865         while (*env != '\0')
866         {
867                 const char *ncdbCur = getNCDBStartupHook();
868                 while (*ncdbCur != '\0' && *env != '\0' && *env != ':')
869                 {
870                         if (*ncdbCur != *env)
871                                 break;
872
873                         ncdbCur++;
874                         env++;
875
876                         if (*ncdbCur == '\0' && (*env == '\0' || *env == ':'))
877                                 return true;
878                 }
879                 while (*env != '\0' && *env != ':')
880                 {
881                         env++;
882                 }
883                 if (*env == ':')
884                         env++;
885         }
886
887         return false;
888 }