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