Refactoring to extract duplicate logic as a separate method
[platform/core/dotnet/launcher.git] / NativeLauncher / tool / tac_common.cc
1 /*
2  * Copyright (c) 2019 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 <fstream>
18 #include <json/json.h>
19 #include <pkgmgr-info.h>
20 #include <pkgmgr_installer_info.h>
21
22 #include "log.h"
23 #include "utils.h"
24 #include "tac_common.h"
25 #include "db_manager.h"
26 #include "r2r_checker.h"
27
28 #ifdef  LOG_TAG
29 #undef  LOG_TAG
30 #endif
31 #define LOG_TAG "DOTNET_INSTALLER_PLUGIN"
32
33 #define __XSTR(x) #x
34 #define __STR(x) __XSTR(x)
35 static const char* __DOTNET_DIR = __STR(DOTNET_DIR);
36 static const char* __READ_ONLY_APP_UPDATE_DIR = __STR(READ_ONLY_APP_UPDATE_DIR);
37 #undef __STR
38 #undef __XSTR
39
40 static sqlite3 *tac_db = NULL;
41 static sqlite3 *tlc_db = NULL;
42 static std::vector<std::string> restore_nuget;
43 static std::vector<std::string> restore_library;
44
45 static void cleanupDirectory()
46 {
47         std::vector<std::string> removeNuget;
48         try {
49                 for (auto& nuget : bf::recursive_directory_iterator(__DOTNET_DIR)) {
50                         std::string nugetPath = nuget.path().string();
51                         if (!bf::is_directory(nugetPath) ||
52                                 nugetPath.find(TLC_LIBRARIES_DIR) != std::string::npos ||
53                                 nugetPath.find(__READ_ONLY_APP_UPDATE_DIR) != std::string::npos) {
54                                 continue;
55                         }
56
57                         bool isExist = false;
58                         for (auto& restore : restore_nuget) {
59                                 if (nugetPath == restore || nugetPath == getBaseName(restore)) {
60                                         isExist = true;
61                                         break;
62                                 }
63                         }
64                         if (!isExist) {
65                                 removeNuget.push_back(nugetPath);
66                         }
67                 }
68
69                 for (auto& rm : removeNuget) {
70                         if (!removeAll(rm)) {
71                                 _SERR("Failed to remove of %s", rm.c_str());
72                         }
73                 }
74                 removeNuget.clear();
75         } catch (const bf::filesystem_error& error) {
76                 _SERR("Failed to recursive directory: %s", error.what());
77                 return;
78         }
79 }
80
81 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
82 static int tac_restoreDBCb(pkgmgrinfo_appinfo_h handle, void *userData)
83 {
84         char *pkgId = NULL;
85         char *root = NULL;
86         char *exec = NULL;
87
88         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
89         if (ret != PMINFO_R_OK) {
90                 _SERR("Failed to get pkgid");
91                 return -1;
92         }
93
94         ret = pkgmgrinfo_appinfo_get_root_path(handle, &root);
95         if (ret != PMINFO_R_OK) {
96                 _SERR("Failed to get root path");
97                 return -1;
98         }
99         std::string rootPath = std::string(root);
100
101         ret = pkgmgrinfo_appinfo_get_exec(handle, &exec);
102         if (ret != PMINFO_R_OK) {
103                 _SERR("Failed to get exec name");
104                 return -1;
105         }
106         std::string execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
107
108         enableTACPackage(std::string(pkgId));
109
110         std::vector<std::string> parserData;
111         std::string binDir = concatPath(rootPath, "bin");
112         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
113         for (auto& npAssembly : depsJsonParser(rootPath, execName)) {
114                 std::string nugetPackage = npAssembly.substr(0, npAssembly.rfind(':'));
115                 std::string assemblyName = npAssembly.substr(npAssembly.rfind(':') + 1);
116                 if (exist(tacDir) && exist(concatPath(tacDir, assemblyName))) {
117                         parserData.push_back(nugetPackage);
118                 }
119         }
120         std::sort(parserData.begin(), parserData.end());
121         parserData.erase(unique(parserData.begin(), parserData.end()), parserData.end());
122
123         for (auto& nuget : parserData) {
124                 if (tac_db) {
125                         std::string name = nuget.substr(0, nuget.find('/'));
126                         std::string version = nuget.substr(nuget.rfind('/') + 1);
127                         char *sql = sqlite3_mprintf(
128                                 "INSERT INTO TAC (PKGID, NUGET, NAME, VERSION) " \
129                                 "VALUES (%Q, %Q, %Q, %Q);",     pkgId, nuget.c_str(), name.c_str(), version.c_str());
130                         insertDB(tac_db, sql);
131                         restore_nuget.push_back(concatPath(__DOTNET_DIR, nuget));
132                         sqlite3_free(sql);
133                 }
134         }
135         parserData.clear();
136
137         return 0;
138 }
139
140 tac_error_e tac_restoreDB()
141 {
142         if (!removeFile(TAC_APP_LIST_RESTORE_DB)) {
143                 _SERR("Failed to remove of %s", TAC_APP_LIST_RESTORE_DB);
144                 return TAC_ERROR_UNKNOWN;
145         }
146
147         std::string dbRestoreJournal = TAC_APP_LIST_RESTORE_DB + std::string("-journal");
148         if (!removeFile(dbRestoreJournal)) {
149                 _SERR("Failed to remove of %s", dbRestoreJournal.c_str());
150                 return TAC_ERROR_UNKNOWN;
151         }
152
153         tac_db = createDB(TAC_APP_LIST_RESTORE_DB, CREATE_TAC_DB_TABLE);
154         if (!tac_db) {
155                 _SERR("Sqlite create error");
156                 return TAC_ERROR_UNKNOWN;
157         }
158         sqlite3_exec(tac_db, "BEGIN;", NULL, NULL, NULL);
159
160         pkgmgrinfo_appinfo_metadata_filter_h handle;
161         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
162         if (ret != PMINFO_R_OK) {
163                 return TAC_ERROR_UNKNOWN;
164         }
165
166         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE_TRUE);
167         if (ret != PMINFO_R_OK) {
168                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
169                 return TAC_ERROR_UNKNOWN;
170         }
171
172         ret = pkgmgrAppMDFilterForeach(handle, tac_restoreDBCb, NULL);
173         if (ret != 0) {
174                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
175                 return TAC_ERROR_UNKNOWN;
176         }
177
178         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
179
180         if (tac_db) {
181                 closeDB(tac_db);
182                 tac_db = NULL;
183         }
184
185         if (!copyFile(TAC_APP_LIST_RESTORE_DB, TAC_APP_LIST_DB)) {
186                 _SERR("Failed to copy of %s", TAC_APP_LIST_DB);
187                 return TAC_ERROR_UNKNOWN;
188         }
189         if (!removeFile(TAC_APP_LIST_RESTORE_DB)) {
190                 _SERR("Failed to remove of %s", TAC_APP_LIST_RESTORE_DB);
191                 return TAC_ERROR_UNKNOWN;
192         }
193
194         std::string dbJournal = TAC_APP_LIST_DB + std::string("-journal");
195         if (!copyFile(dbRestoreJournal, dbJournal)) {
196                 _SERR("Failed to copy of %s", dbJournal.c_str());
197                 return TAC_ERROR_UNKNOWN;
198         }
199         if (!removeFile(dbRestoreJournal)) {
200                 _SERR("Failed to remove of %s", dbRestoreJournal.c_str());
201                 return TAC_ERROR_UNKNOWN;
202         }
203
204         cleanupDirectory();
205
206         return TAC_ERROR_NONE;
207 }
208
209 static tac_error_e createSymlinkFile(const std::string& tacDir, const std::string& binDir, const std::string& from, const std::string& to)
210 {
211         bs::error_code error;
212         std::string symlinkFile = concatPath(tacDir, to);
213         bf::create_symlink(from, symlinkFile, error);
214         if (error) {
215                 _SERR("Failed to create symlink %s file", symlinkFile.c_str());
216                 return TAC_ERROR_UNKNOWN;
217         }
218         _SOUT("%s symbolic link file generated successfully.", symlinkFile.c_str());
219         copySmackAndOwnership(tacDir.c_str(), symlinkFile.c_str(), true);
220
221         if (!removeFile(concatPath(binDir, to))) {
222                 _SERR("Failed to remove of %s", concatPath(binDir, to).c_str());
223                 return TAC_ERROR_UNKNOWN;
224         }
225         return TAC_ERROR_NONE;
226 }
227
228 tac_error_e disableTACPackage(const std::string& pkgId)
229 {
230         std::string rootPath = getRootPath(pkgId);
231         if (rootPath.empty()) {
232                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
233                 return TAC_ERROR_INVALID_PACKAGE;
234         }
235
236         std::string binDir = concatPath(rootPath, "bin");
237         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
238         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
239         if (exist(tacDir)) {
240                 try {
241                         for (auto& symlinkAssembly : bf::recursive_directory_iterator(tacDir)) {
242                                 std::string symPath = symlinkAssembly.path().string();
243                                 std::string fileName = symlinkAssembly.path().filename().string();
244                                 if (isSymlinkFile(symPath)) {
245                                         std::string originPath = bf::read_symlink(symPath).string();
246                                         if (!isR2RImage(symPath)) {
247                                                 std::string dllPath = concatPath(binDir, fileName);
248                                                 if (!copyFile(originPath, dllPath)) {
249                                                         _SERR("Failed to copy of %s", dllPath.c_str());
250                                                         return TAC_ERROR_UNKNOWN;
251                                                 }
252                                                 copySmackAndOwnership(binDir.c_str(), concatPath(binDir, fileName).c_str());
253                                         } else {
254                                                 std::string niPath = concatPath(binNIDir, fileName);
255                                                 if (!copyFile(originPath, niPath)) {
256                                                         _SERR("Failed to copy of %s", niPath.c_str());
257                                                         return TAC_ERROR_UNKNOWN;
258                                                 }
259                                                 copySmackAndOwnership(binDir.c_str(), niPath.c_str());
260                                         }
261                                 }
262                         }
263                         if (!removeAll(tacDir)) {
264                                 _SERR("Failed to remove of %s", tacDir.c_str());
265                                 return TAC_ERROR_UNKNOWN;
266                         }
267                 } catch (const bf::filesystem_error& error) {
268                         _SERR("Failed to recursive directory: %s", error.what());
269                         return TAC_ERROR_UNKNOWN;
270                 }
271         }
272         return TAC_ERROR_NONE;
273 }
274
275 tac_error_e enableTACPackage(const std::string& pkgId)
276 {
277         std::string rootPath = getRootPath(pkgId);
278         if (rootPath.empty()) {
279                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
280                 return TAC_ERROR_INVALID_PACKAGE;
281         }
282
283         std::string binDir = concatPath(rootPath, "bin");
284         if (exist(concatPath(binDir, PRE_COMPILED_PACKAGE_FILE))) {
285                 _INFO("The %s is a Pre-Compiled package. So, skip the TAC", pkgId.c_str());
286                 return TAC_ERROR_NONE;
287         }
288
289         std::string execName = getExecName(pkgId);
290         if (execName.empty()) {
291                 _SERR("Failed to get exec name from [%s]", pkgId.c_str());
292                 return TAC_ERROR_INVALID_PACKAGE;
293         }
294
295         std::string metaValue = getMetadataValue(pkgId, TAC_METADATA_KEY);
296         if (metaValue.empty()) {
297                 _SERR("Failed to get metadata from [%s]", pkgId.c_str());
298                 return TAC_ERROR_INVALID_PACKAGE;
299         }
300
301         if (strcmp(metaValue.c_str(), METADATA_VALUE_TRUE)) {
302                 _INFO("The metadata key is missing or the metadata value is false of [%s]", pkgId.c_str());
303                 return TAC_ERROR_NONE;
304         }
305
306         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
307         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
308         if (exist(tacDir)) {
309                 return TAC_ERROR_NONE;
310         }
311
312         if (!createDir(tacDir)) {
313                 _SERR("Cannot create directory: %s", tacDir.c_str());
314                 return TAC_ERROR_UNKNOWN;
315         }
316         copySmackAndOwnership(binDir.c_str(), tacDir.c_str());
317
318         std::vector<std::string> enableNuget;
319         for (auto& npAssembly : depsJsonParser(rootPath, execName)) {
320                 std::string nugetPackage = npAssembly.substr(0, npAssembly.rfind(':'));
321                 std::string assemblyName = npAssembly.substr(npAssembly.rfind(':') + 1);
322                 std::string nugetPath = concatPath(__DOTNET_DIR, nugetPackage);
323                 if (exist(nugetPath)) {
324                         std::string originPath = concatPath(nugetPath, assemblyName);
325                         if (exist(originPath)) {
326                                 enableNuget.push_back(originPath);
327                         }
328                 }
329         }
330
331         if (enableNuget.empty()) {
332                 if (!removeAll(tacDir)) {
333                         _SERR("Failed to remove of %s", tacDir.c_str());
334                 }
335                 return TAC_ERROR_NONE;
336         }
337
338         for (auto& originPath : enableNuget) {
339                 if (exist(originPath)) {
340                         std::string fileName = originPath.substr(originPath.rfind('/') + 1);
341                         if (exist(binNIDir)) {
342                                 std::string originNIPath = changeExtension(originPath, "dll", "ni.dll");
343                                 if (exist(originNIPath)) {
344                                         if (createSymlinkFile(tacDir, binNIDir, originNIPath, changeExtension(fileName, "dll", "ni.dll")) != TAC_ERROR_NONE) {
345                                                 return TAC_ERROR_UNKNOWN;
346                                         }
347                                 }
348                         }
349                         if (createSymlinkFile(tacDir, binDir, originPath, fileName) != TAC_ERROR_NONE) {
350                                 return TAC_ERROR_UNKNOWN;
351                         }
352                 }
353         }
354         enableNuget.clear();
355
356         return TAC_ERROR_NONE;
357 }
358
359 //Parser the .deps.json file to get nuget information.
360 std::vector<std::string> depsJsonParser(const std::string& rootPath, const std::string& execName)
361 {
362         std::vector<std::string> parserData;
363         std::string depsJsonName = changeExtension(execName, "dll", "deps.json");
364         std::string depsJsonPath = concatPath(rootPath, depsJsonName);
365         try {
366                 if (exist(depsJsonPath)) {
367                         std::ifstream ifs(depsJsonPath);
368                         Json::CharReaderBuilder reader;
369                         Json::Value root;
370                         std::string error;
371                         if (ifs.is_open()) {
372                                 if (!Json::parseFromStream(reader, ifs, &root, &error)) {
373                                         _ERR("Failed to parse of deps.json");
374                                         ifs.close();
375                                         return parserData;
376                                 }
377                                 const Json::Value runtimeTargetName = root["runtimeTarget"]["name"];
378                                 const Json::Value nugetPackages = root["targets"][runtimeTargetName.asString().c_str()];
379                                 for (auto& nuget : nugetPackages.getMemberNames()) {
380                                         //Skip the nuget package related to Tizen
381                                         if (strstr(nuget.c_str(), TIZEN_DOTNET_NUGET) == NULL &&
382                                                 strstr(nuget.c_str(), TIZEN_DOTNET_SDK_NUGET) == NULL &&
383                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) == NULL &&
384                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) == NULL) {
385                                                 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
386                                                 if (assemblies != Json::nullValue) {
387                                                         // handle assembly even though that is included in the TPA.
388                                                         for (auto& assembly : assemblies.getMemberNames()) {
389                                                                 std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
390                                                                 parserData.push_back(nuget + ":" + assemblyName);
391                                                                 _INFO("Nuget : [%s] / Assembly : [%s]", nuget.c_str(), assemblyName.c_str());
392                                                         }
393                                                 }
394                                         }
395                                 }
396                                 ifs.close();
397                         }
398                 }
399         } catch (const Json::Exception& error) {
400                 _ERR("Failed to parse Json: %s", error.what());
401         }
402         return parserData;
403 }
404
405 std::vector<std::string> getLibrariesInfo(const std::string& rootPath)
406 {
407         std::vector<std::string> LibrariesInfo;
408         std::string binDir = concatPath(rootPath, "bin");
409         if (!exist(binDir))
410                 return LibrariesInfo;
411
412         auto convert = [&LibrariesInfo](const std::string& filepath, const std::string& filename) {
413                 if (filename.find(".so", filename.size() - 3) != std::string::npos || filepath.rfind(".so.") != std::string::npos) {
414                         std::string buffer = SHA256(filepath);
415                         LibrariesInfo.push_back(filepath + ":" + buffer);
416                         _INFO("Library : [%s] / SHA256 : [%s]", filename.c_str(), buffer.c_str());
417                 }
418         };
419         scanFilesInDirectory(binDir, convert, -1);
420
421         return LibrariesInfo;
422 }
423
424 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
425 static int tlc_restoreDBCb(pkgmgrinfo_appinfo_h handle, void *userData)
426 {
427         char *pkgId = NULL;
428         char *root = NULL;
429         std::string rootPath;
430
431         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
432         if (ret != PMINFO_R_OK) {
433                 _SERR("Failed to get pkgid");
434                 return -1;
435         }
436
437         ret = pkgmgrinfo_appinfo_get_root_path(handle, &root);
438         if (ret != PMINFO_R_OK) {
439                 _SERR("Failed to get root path");
440                 return -1;
441         }
442         rootPath = std::string(root);
443
444         for (auto& librarySha : getLibrariesInfo(rootPath)) {
445                 std::string library = librarySha.substr(0, librarySha.find(':'));
446                 if (exist(library)) {
447                         std::string fileSha = library.substr(library.rfind('/') + 1) + ".." + librarySha.substr(librarySha.find(':') + 1);
448                         char *sql = sqlite3_mprintf("INSERT INTO TLC (PKGID, LIBRARY) VALUES (%Q, %Q);", pkgId, fileSha.c_str());
449                         insertDB(tlc_db, sql);
450                         restore_library.push_back(fileSha);
451                         sqlite3_free(sql);
452                 }
453         }
454         return 0;
455 }
456
457 tac_error_e tlc_restoreDB()
458 {
459         if (!removeFile(TLC_APP_LIST_RESTORE_DB)) {
460                 _SERR("Failed to remove of %s", TLC_APP_LIST_RESTORE_DB);
461                 return TAC_ERROR_UNKNOWN;
462         }
463
464         std::string dbRestoreJournal = TLC_APP_LIST_RESTORE_DB + std::string("-journal");
465         if (!removeFile(dbRestoreJournal)) {
466                 _SERR("Failed to remove of %s", dbRestoreJournal.c_str());
467                 return TAC_ERROR_UNKNOWN;
468         }
469
470         tlc_db = createDB(TLC_APP_LIST_RESTORE_DB, CREATE_TLC_DB_TABLE);
471         if (!tlc_db) {
472                 _SERR("Sqlite create error");
473                 return TAC_ERROR_UNKNOWN;
474         }
475         sqlite3_exec(tlc_db, "BEGIN;", NULL, NULL, NULL);
476
477         pkgmgrinfo_appinfo_metadata_filter_h handle;
478         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
479         if (ret != PMINFO_R_OK) {
480                 return TAC_ERROR_UNKNOWN;
481         }
482
483         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE_TRUE);
484         if (ret != PMINFO_R_OK) {
485                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
486                 return TAC_ERROR_UNKNOWN;
487         }
488
489         ret = pkgmgrAppMDFilterForeach(handle, tlc_restoreDBCb, NULL);
490         if (ret != 0) {
491                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
492                 return TAC_ERROR_UNKNOWN;
493         }
494
495         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
496
497         if (tlc_db) {
498                 closeDB(tlc_db);
499                 tlc_db = NULL;
500         }
501
502         if (!copyFile(TLC_APP_LIST_RESTORE_DB, TLC_APP_LIST_DB)) {
503                 _SERR("Failed to copy of %s", TLC_APP_LIST_DB);
504                 return TAC_ERROR_UNKNOWN;
505         }
506         if (!removeFile(TLC_APP_LIST_RESTORE_DB)) {
507                 _SERR("Failed to remove of %s", TLC_APP_LIST_RESTORE_DB);
508                 return TAC_ERROR_UNKNOWN;
509         }
510
511         std::string dbJournal = TLC_APP_LIST_DB + std::string("-journal");
512         if (!copyFile(dbRestoreJournal, dbJournal)) {
513                 _SERR("Failed to copy of %s", dbJournal.c_str());
514                 return TAC_ERROR_UNKNOWN;
515         }
516         if (!removeFile(dbRestoreJournal)) {
517                 _SERR("Failed to remove of %s", dbRestoreJournal.c_str());
518                 return TAC_ERROR_UNKNOWN;
519         }
520
521         auto convert = [](const std::string& path, const std::string& filename) {
522                 bool isExist = false;
523                 for (auto& library : restore_library) {
524                         if (!strcmp(filename.c_str(), library.c_str())) {
525                                 isExist = true;
526                                 break;
527                         }
528                 }
529                 if (!isExist) {
530                         if (!removeFile(path)) {
531                                 _ERR("Failed to remove of %s", path.c_str());
532                         }
533                 }
534         };
535
536         scanFilesInDirectory(TLC_LIBRARIES_DIR, convert, 0);
537
538         return TAC_ERROR_NONE;
539 }