[Refactoring] Code cleanup and remove duplicate methods
[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 = pkgmgrMDFilterForeach(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 tac_error_e disableTACPackage(const std::string& pkgId)
210 {
211         std::string rootPath = getRootPath(pkgId);
212         if (rootPath.empty()) {
213                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
214                 return TAC_ERROR_INVALID_PACKAGE;
215         }
216
217         std::string binDir = concatPath(rootPath, "bin");
218         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
219         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
220         if (exist(tacDir)) {
221                 try {
222                         for (auto& symlinkAssembly : bf::recursive_directory_iterator(tacDir)) {
223                                 std::string symPath = symlinkAssembly.path().string();
224                                 std::string fileName = symlinkAssembly.path().filename().string();
225                                 if (isSymlinkFile(symPath)) {
226                                         std::string originPath = bf::read_symlink(symPath).string();
227                                         if (!isR2RImage(symPath)) {
228                                                 std::string dllPath = concatPath(binDir, fileName);
229                                                 if (!copyFile(originPath, dllPath)) {
230                                                         _SERR("Failed to copy of %s", dllPath.c_str());
231                                                         return TAC_ERROR_UNKNOWN;
232                                                 }
233                                                 copySmackAndOwnership(binDir.c_str(), concatPath(binDir, fileName).c_str());
234                                         } else {
235                                                 std::string niPath = concatPath(binNIDir, fileName);
236                                                 if (!copyFile(originPath, niPath)) {
237                                                         _SERR("Failed to copy of %s", niPath.c_str());
238                                                         return TAC_ERROR_UNKNOWN;
239                                                 }
240                                                 copySmackAndOwnership(binDir.c_str(), niPath.c_str());
241                                         }
242                                 }
243                         }
244                         if (!removeAll(tacDir)) {
245                                 _SERR("Failed to remove of %s", tacDir.c_str());
246                                 return TAC_ERROR_UNKNOWN;
247                         }
248                 } catch (const bf::filesystem_error& error) {
249                         _SERR("Failed to recursive directory: %s", error.what());
250                         return TAC_ERROR_UNKNOWN;
251                 }
252         }
253         return TAC_ERROR_NONE;
254 }
255
256 tac_error_e enableTACPackage(const std::string& pkgId)
257 {
258         std::string rootPath = getRootPath(pkgId);
259         if (rootPath.empty()) {
260                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
261                 return TAC_ERROR_INVALID_PACKAGE;
262         }
263
264         std::string binDir = concatPath(rootPath, "bin");
265         if (exist(concatPath(binDir, PRE_COMPILED_PACKAGE_FILE))) {
266                 _INFO("The %s is a Pre-Compiled package. So, skip the TAC", pkgId.c_str());
267                 return TAC_ERROR_NONE;
268         }
269
270         std::string execName = getExecName(pkgId);
271         if (execName.empty()) {
272                 _SERR("Failed to get exec name from [%s]", pkgId.c_str());
273                 return TAC_ERROR_INVALID_PACKAGE;
274         }
275
276         std::string metaValue = getMetadataValue(pkgId, TAC_METADATA_KEY);
277         if (metaValue.empty()) {
278                 _SERR("Failed to get metadata from [%s]", pkgId.c_str());
279                 return TAC_ERROR_INVALID_PACKAGE;
280         }
281
282         if (!strcmp(metaValue.c_str(), METADATA_VALUE_TRUE)) {
283                 std::string binDir = concatPath(rootPath, "bin");
284                 std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
285                 std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
286                 if (!exist(tacDir)) {
287                         if (!createDir(tacDir)) {
288                                 _SERR("Cannot create directory: %s", tacDir.c_str());
289                                 return TAC_ERROR_UNKNOWN;
290                         }
291                         copySmackAndOwnership(binDir.c_str(), tacDir.c_str());
292
293                         std::vector<std::string> enableNuget;
294                         for (auto& npAssembly : depsJsonParser(rootPath, execName)) {
295                                 std::string nugetPackage = npAssembly.substr(0, npAssembly.rfind(':'));
296                                 std::string assemblyName = npAssembly.substr(npAssembly.rfind(':') + 1);
297                                 std::string nugetPath = concatPath(__DOTNET_DIR, nugetPackage);
298                                 if (exist(nugetPath)) {
299                                         std::string originPath = concatPath(nugetPath, assemblyName);
300                                         if (exist(originPath)) {
301                                                 enableNuget.push_back(originPath);
302                                         }
303                                 }
304                         }
305
306                         bs::error_code error;
307                         for (auto& originPath : enableNuget) {
308                                 if (exist(originPath)) {
309                                         std::string fileName = originPath.substr(originPath.rfind('/') + 1);
310                                         std::string NIFileName = changeExtension(fileName, "dll", "ni.dll");
311                                         if (exist(binNIDir)) {
312                                                 std::string originNIPath = changeExtension(originPath, "dll", "ni.dll");
313                                                 if (exist(originNIPath)) {
314                                                         bf::create_symlink(originNIPath, concatPath(tacDir, NIFileName), error);
315                                                         if (error) {
316                                                                 _SERR("Failed to create symlink %s file", concatPath(tacDir, NIFileName).c_str());
317                                                                 return TAC_ERROR_UNKNOWN;
318                                                         }
319                                                         _SOUT("%s symbolic link file generated successfully.", concatPath(tacDir, NIFileName).c_str());
320                                                         copySmackAndOwnership(tacDir.c_str(), concatPath(tacDir, NIFileName).c_str(), true);
321
322                                                         if (!removeFile(concatPath(binNIDir, NIFileName))) {
323                                                                 _SERR("Failed to remove of %s", concatPath(binNIDir, NIFileName).c_str());
324                                                                 return TAC_ERROR_UNKNOWN;
325                                                         }
326                                                 }
327                                         }
328                                         bf::create_symlink(originPath, concatPath(tacDir, fileName), error);
329                                         if (error) {
330                                                 _SERR("Failed to create symlink %s file", concatPath(tacDir, fileName).c_str());
331                                                 return TAC_ERROR_UNKNOWN;
332                                         }
333                                         _SOUT("%s symbolic link file generated successfully.", concatPath(tacDir, fileName).c_str());
334                                         copySmackAndOwnership(tacDir.c_str(), concatPath(tacDir, fileName).c_str(), true);
335
336                                         if (!removeFile(concatPath(binDir, fileName))) {
337                                                 _SERR("Failed to remove of %s", concatPath(binDir, fileName).c_str());
338                                                 return TAC_ERROR_UNKNOWN;
339                                         }
340                                 }
341                         }
342                         if (enableNuget.empty()) {
343                                 if (!removeAll(tacDir)) {
344                                         _SERR("Failed to remove of %s", tacDir.c_str());
345                                 }
346                         }
347                         enableNuget.clear();
348                 }
349         } else {
350                 _SERR("The metadata key is missing or the metadata value is false of [%s]", pkgId.c_str());
351         }
352         return TAC_ERROR_NONE;
353 }
354
355 //Parser the .deps.json file to get nuget information.
356 std::vector<std::string> depsJsonParser(const std::string& rootPath, const std::string& execName)
357 {
358         std::vector<std::string> parserData;
359         std::string depsJsonName = changeExtension(execName, "dll", "deps.json");
360         std::string depsJsonPath = concatPath(rootPath, depsJsonName);
361         try {
362                 if (exist(depsJsonPath)) {
363                         std::ifstream ifs(depsJsonPath);
364                         Json::CharReaderBuilder reader;
365                         Json::Value root;
366                         std::string error;
367                         if (ifs.is_open()) {
368                                 if (!Json::parseFromStream(reader, ifs, &root, &error)) {
369                                         _ERR("Failed to parse of deps.json");
370                                         ifs.close();
371                                         return parserData;
372                                 }
373                                 const Json::Value runtimeTargetName = root["runtimeTarget"]["name"];
374                                 const Json::Value nugetPackages = root["targets"][runtimeTargetName.asString().c_str()];
375                                 for (auto& nuget : nugetPackages.getMemberNames()) {
376                                         //Skip the nuget package related to Tizen
377                                         if (strstr(nuget.c_str(), TIZEN_DOTNET_NUGET) == NULL &&
378                                                 strstr(nuget.c_str(), TIZEN_DOTNET_SDK_NUGET) == NULL &&
379                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) == NULL &&
380                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) == NULL) {
381                                                 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
382                                                 if (assemblies != Json::nullValue) {
383                                                         // handle assembly even though that is included in the TPA.
384                                                         for (auto& assembly : assemblies.getMemberNames()) {
385                                                                 std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
386                                                                 parserData.push_back(nuget + ":" + assemblyName);
387                                                                 _INFO("Nuget : [%s] / Assembly : [%s]", nuget.c_str(), assemblyName.c_str());
388                                                         }
389                                                 }
390                                         }
391                                 }
392                                 ifs.close();
393                         }
394                 }
395         } catch (const Json::Exception& error) {
396                 _ERR("Failed to parse Json: %s", error.what());
397         }
398         return parserData;
399 }
400
401 std::vector<std::string> getLibrariesInfo(const std::string& rootPath)
402 {
403         std::vector<std::string> LibrariesInfo;
404         std::string binDir = concatPath(rootPath, "bin");
405         if (!exist(binDir))
406                 return LibrariesInfo;
407
408         auto convert = [&LibrariesInfo](const std::string& filepath, const std::string& filename) {
409                 if (filename.find(".so", filename.size() - 3) != std::string::npos || filepath.rfind(".so.") != std::string::npos) {
410                         std::string buffer = SHA256(filepath);
411                         LibrariesInfo.push_back(filepath + ":" + buffer);
412                         _INFO("Library : [%s] / SHA256 : [%s]", filename.c_str(), buffer.c_str());
413                 }
414         };
415         scanFilesInDirectory(binDir, convert, -1);
416
417         return LibrariesInfo;
418 }
419
420 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
421 static int tlc_restoreDBCb(pkgmgrinfo_appinfo_h handle, void *userData)
422 {
423         char *pkgId = NULL;
424         char *root = NULL;
425         std::string rootPath;
426
427         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
428         if (ret != PMINFO_R_OK) {
429                 _SERR("Failed to get pkgid");
430                 return -1;
431         }
432
433         ret = pkgmgrinfo_appinfo_get_root_path(handle, &root);
434         if (ret != PMINFO_R_OK) {
435                 _SERR("Failed to get root path");
436                 return -1;
437         }
438         rootPath = std::string(root);
439
440         for (auto& librarySha : getLibrariesInfo(rootPath)) {
441                 std::string library = librarySha.substr(0, librarySha.find(':'));
442                 if (exist(library)) {
443                         std::string fileSha = library.substr(library.rfind('/') + 1) + ".." + librarySha.substr(librarySha.find(':') + 1);
444                         char *sql = sqlite3_mprintf("INSERT INTO TLC (PKGID, LIBRARY) VALUES (%Q, %Q);", pkgId, fileSha.c_str());
445                         insertDB(tlc_db, sql);
446                         restore_library.push_back(fileSha);
447                         sqlite3_free(sql);
448                 }
449         }
450         return 0;
451 }
452
453 tac_error_e tlc_restoreDB()
454 {
455         if (!removeFile(TLC_APP_LIST_RESTORE_DB)) {
456                 _SERR("Failed to remove of %s", TLC_APP_LIST_RESTORE_DB);
457                 return TAC_ERROR_UNKNOWN;
458         }
459
460         std::string dbRestoreJournal = TLC_APP_LIST_RESTORE_DB + std::string("-journal");
461         if (!removeFile(dbRestoreJournal)) {
462                 _SERR("Failed to remove of %s", dbRestoreJournal.c_str());
463                 return TAC_ERROR_UNKNOWN;
464         }
465
466         tlc_db = createDB(TLC_APP_LIST_RESTORE_DB, CREATE_TLC_DB_TABLE);
467         if (!tlc_db) {
468                 _SERR("Sqlite create error");
469                 return TAC_ERROR_UNKNOWN;
470         }
471         sqlite3_exec(tlc_db, "BEGIN;", NULL, NULL, NULL);
472
473         pkgmgrinfo_appinfo_metadata_filter_h handle;
474         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
475         if (ret != PMINFO_R_OK) {
476                 return TAC_ERROR_UNKNOWN;
477         }
478
479         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE_TRUE);
480         if (ret != PMINFO_R_OK) {
481                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
482                 return TAC_ERROR_UNKNOWN;
483         }
484
485         ret = pkgmgrMDFilterForeach(handle, tlc_restoreDBCb, NULL);
486         if (ret != 0) {
487                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
488                 return TAC_ERROR_UNKNOWN;
489         }
490
491         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
492
493         if (tlc_db) {
494                 closeDB(tlc_db);
495                 tlc_db = NULL;
496         }
497
498         if (!copyFile(TLC_APP_LIST_RESTORE_DB, TLC_APP_LIST_DB)) {
499                 _SERR("Failed to copy of %s", TLC_APP_LIST_DB);
500                 return TAC_ERROR_UNKNOWN;
501         }
502         if (!removeFile(TLC_APP_LIST_RESTORE_DB)) {
503                 _SERR("Failed to remove of %s", TLC_APP_LIST_RESTORE_DB);
504                 return TAC_ERROR_UNKNOWN;
505         }
506
507         std::string dbJournal = TLC_APP_LIST_DB + std::string("-journal");
508         if (!copyFile(dbRestoreJournal, dbJournal)) {
509                 _SERR("Failed to copy of %s", dbJournal.c_str());
510                 return TAC_ERROR_UNKNOWN;
511         }
512         if (!removeFile(dbRestoreJournal)) {
513                 _SERR("Failed to remove of %s", dbRestoreJournal.c_str());
514                 return TAC_ERROR_UNKNOWN;
515         }
516
517         auto convert = [](const std::string& path, const std::string& filename) {
518                 bool isExist = false;
519                 for (auto& library : restore_library) {
520                         if (!strcmp(filename.c_str(), library.c_str())) {
521                                 isExist = true;
522                                 break;
523                         }
524                 }
525                 if (!isExist) {
526                         if (!removeFile(path)) {
527                                 _ERR("Failed to remove of %s", path.c_str());
528                         }
529                 }
530         };
531
532         scanFilesInDirectory(concatPath(__DOTNET_DIR, TLC_LIBRARIES_DIR), convert, 0);
533
534         return TAC_ERROR_NONE;
535 }