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