Add comments for added function in utils.h
[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
24 #include <cstdlib>
25 #include <cstring>
26 #include <algorithm>
27 #include <unordered_map>
28 #include <vector>
29 #include <iterator>
30 #include <sstream>
31 #include <map>
32
33 #include "log.h"
34 #include "utils.h"
35 #include "path_manager.h"
36
37 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
38 {
39         return static_cast<int>(a.length()) - length >= aOffset &&
40                 static_cast<int>(b.length()) - length >= bOffset &&
41                 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
42                         [](unsigned char a, unsigned char b)
43                         { return std::tolower(a) == std::tolower(b); });
44 }
45
46 bool isManagedAssembly(const std::string& fileName)
47 {
48         return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
49                         iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
50                         !isNativeImage(fileName);
51 }
52
53 bool isNativeImage(const std::string& fileName)
54 {
55         return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
56 }
57
58 std::string readSelfPath()
59 {
60         char buff[PATH_MAX];
61         ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
62         if (len != -1) {
63                 buff[len] = '\0';
64                 return std::string(buff);
65         }
66
67         return "";
68 }
69
70 std::string concatPath(const std::string& path1, const std::string& path2)
71 {
72         std::string path(path1);
73         if (path.back() == PATH_SEPARATOR) {
74                 path.append(path2);
75         } else {
76                 path += PATH_SEPARATOR;
77                 path.append(path2);
78         }
79
80         return path;
81 }
82
83 void splitPath(const std::string& path, std::vector<std::string>& out)
84 {
85         std::istringstream ss(path);
86         std::string token;
87
88         while (std::getline(ss, token, ':')) {
89                 out.push_back(token);
90         }
91 }
92
93 std::string absolutePath(const std::string& path)
94 {
95         std::string absPath;
96         char realPath[PATH_MAX];
97         if (realpath(path.c_str(), realPath) != nullptr && realPath[0] != '\0')
98                 absPath.assign(realPath);
99
100         return absPath;
101 }
102
103 std::string baseName(const std::string& path)
104 {
105         auto pos = path.find_last_of(PATH_SEPARATOR);
106         if (pos != std::string::npos)
107                 return path.substr(0, pos);
108         else
109                 return std::string(".");
110         return path;
111 }
112
113 bool isFileExist(const std::string& path)
114 {
115         struct stat sb;
116         return stat(path.c_str(), &sb) == 0;
117 }
118
119 std::string stripNiDLL(const std::string& path)
120 {
121         std::string niPath(path);
122         if (path.size() < 5) return niPath;
123         if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
124                 niPath = path.substr(0, path.size()-4);
125         else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
126                 niPath = path.substr(0, path.size()-4);
127
128         if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
129                 return niPath.substr(0, niPath.size()-3);
130
131         return niPath;
132 }
133
134 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
135 {
136         std::map<std::string, std::string> assemblyList;
137         std::map<std::string, std::string> tmpList;
138
139         auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
140                 if (isManagedAssembly(path) || isNativeImage(path)) {
141                         std::string dllName = stripNiDLL(name);
142                         std::pair<std::map<std::string, std::string>::iterator, bool> ret;
143                         ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
144                         if (ret.second == false) {
145                                 if (isNativeImage(path))
146                                         tmpList[dllName] = path;
147                         }
148                 }
149         };
150
151         for (auto directory : directories) {
152                 scanFilesInDir(directory.c_str(), reader, 1);
153                 // merge scaned dll list to tpa list.
154                 // if the dll is already exist in the list, that is skipped.
155                 assemblyList.insert(tmpList.begin(), tmpList.end());
156         }
157
158         std::map<std::string, std::string>::iterator it;
159         for (it = assemblyList.begin(); it != assemblyList.end(); it++)
160                 tpaList += it->second + ':';
161
162         if (tpaList.back() == ':')
163                 tpaList.pop_back();
164 }
165
166 void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
167 {
168         DIR *dir;
169         struct dirent* entry;
170         bool isDir;
171
172         if (strstr(directory.c_str(), "TAC.Release") != NULL)
173                 return; // skip nitool --regen-all-app (--r2r)
174
175         dir = opendir(directory.c_str());
176
177         if (dir == nullptr)
178                 return;
179
180         std::vector<std::string> innerDirectories;
181
182         while ((entry = readdir(dir)) != nullptr) {
183                 isDir = false;
184                 std::string path = concatPath(directory, entry->d_name);
185                 switch (entry->d_type) {
186                         case DT_REG: break;
187                         case DT_DIR:
188                                 isDir = true;
189                                 break;
190                         case DT_LNK:
191                         case DT_UNKNOWN:
192                                 struct stat sb;
193                                 if (stat(path.c_str(), &sb) == -1)
194                                         continue;
195
196                                 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
197                                         break;
198                         default:
199                                 continue;
200                 }
201                 if (!isDir)
202                         reader(path, entry->d_name);
203                 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
204                         innerDirectories.push_back(path);
205         }
206
207         if (depth != 0)
208                 for (auto& d : innerDirectories)
209                         scanFilesInDir(d.c_str(), reader, depth - 1);
210
211         closedir(dir);
212 }
213
214 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
215         int fd = open(path.c_str(), O_RDONLY);
216         if (fd < 0) {
217                 _ERR("Can't open directory: %s", path.c_str());
218                 return false;
219         }
220         int ret = fchown(fd, uid, gid);
221         close(fd);
222         if (ret != 0) {
223                 _ERR("Failed to change owner of: %s", path.c_str());
224                 return false;
225         }
226         return true;
227 }
228
229 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
230         bs::error_code error;
231         bf::permissions(path, permissions, error);
232         if (error) {
233                 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
234                 return false;
235         }
236         return true;
237 }
238
239 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
240         if (!setOwnership(path, uid, gid)) {
241                 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
242                 return false;
243         }
244         if (!setDirPermissions(path, permissions)) {
245                 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
246                 return false;
247         }
248         return true;
249 }
250
251 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
252         if (!bf::exists(path)) {
253                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
254                 return false;
255         }
256         bf::perms permissions = bf::status(path).permissions();
257         struct stat stats;
258         if (stat(path.c_str(), &stats) != 0) {
259                 return false;
260         }
261         if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
262                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
263                 return false;
264         }
265         return true;
266 }
267
268 bool createDir(const bf::path& path) {
269         if (bf::exists(path)) {
270                 return true;
271         }
272         bs::error_code error;
273         bf::create_directories(path, error);
274         if (error) {
275                 _ERR("Failed to create directory: %s", error.message().c_str());
276                 return false;
277         }
278         return true;
279 }
280
281 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
282         try {
283                 // Check whether the function call is valid
284                 if (!bf::exists(path1) || !bf::is_directory(path1)) {
285                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
286                         return false;
287                 }
288                 if (!bf::exists(path2)) {
289                         // Create the destination directory
290                         if (!createDir(path2)) {
291                                 _ERR("Unable to create destination directory %s", path2.c_str());
292                                 return false;
293                         }
294                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
295                                 copyOwnershipAndPermissions(path1, path2);
296                         }
297                 } else {
298                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
299                                 _ERR("Destination directory %s already exists", path2.c_str());
300                                 return false;
301                         }
302                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
303                                 copyOwnershipAndPermissions(path1, path2);
304                         }
305                 }
306         } catch (const bf::filesystem_error& error) {
307                 _ERR("Failed to copy directory: %s", error.what());
308                 return false;
309         }
310
311         // Iterate through the source directory
312         for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
313                 try {
314                         bf::path current(file->path());
315                         bf::path target = path2 / current.filename();
316                         if (bf::is_symlink(symlink_status(current))) {
317                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
318                                         continue;
319                                 }
320                                 bs::error_code error;
321                                 bf::copy_symlink(current, target, error);
322                                 if (error) {
323                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
324                                         return false;
325                                 }
326                         } else if (bf::is_directory(current)) {
327                                 // Found directory: Recursion
328                                 if (!copyDir(current, target, flags)) {
329                                         return false;
330                                 }
331                         } else {
332                                 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
333                                         continue;
334                                 }
335                                 bf::path destination = target;
336                                 if (flags & FS_COMMIT_COPY_FILE) {
337                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
338                                 }
339                                 if (flags & FS_MERGE_OVERWRITE) {
340                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
341                                 } else {
342                                         bf::copy_file(current, destination);
343                                 }
344                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
345                                         copyOwnershipAndPermissions(current, destination);
346                                 }
347                                 if (flags & FS_COMMIT_COPY_FILE) {
348                                         if (flags & FS_MERGE_OVERWRITE) {
349                                                 bf::remove(target);
350                                         }
351                                         bf::rename(destination, target);
352                                 }
353                         }
354                 } catch (const bf::filesystem_error& error) {
355                         _ERR("Failed to copy directory: %s", error.what());
356                         return false;
357                 }
358         }
359         return true;
360 }
361
362 bool copyFile(const bf::path& path1, const bf::path& path2) {
363         bs::error_code error;
364         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
365         if (error) {
366                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
367                 return false;
368         }
369         return true;
370 }
371
372 bool moveFile(const bf::path& path1, const bf::path& path2) {
373         if (bf::exists(path2)) {
374                 return false;
375         }
376         bs::error_code error;
377         bf::rename(path1, path2, error);
378         if (error) {
379                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
380                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
381                 if (error) {
382                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
383                         return false;
384                 }
385                 bf::remove_all(path1, error);
386                 if (error) {
387                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
388                         return false;
389                 }
390         }
391         return true;
392 }
393
394 bool removeFile(const bf::path& path) {
395         if (!bf::exists(path)) {
396                 return true;
397         }
398         bs::error_code error;
399         bf::remove(path, error);
400         if (error) {
401                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
402                 return false;
403         }
404         return true;
405 }
406
407 bool removeAll(const bf::path& path) {
408         if (!exists(path)) {
409                 return true;
410         }
411         bs::error_code error;
412         bf::remove_all(path, error);
413         if (error) {
414                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
415                 return false;
416         }
417         return true;
418 }