Added logic to recover when db file is corrupted.
[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 "path_manager.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* __TAC_DIR = __STR(TAC_DIR);
36 #undef __STR
37 #undef __XSTR
38
39 static sqlite3 *tac_db = NULL;
40 std::vector<std::string> restore_nuget;
41
42 static void cleanupDirectory()
43 {
44         std::vector<std::string> removeNuget;
45         try {
46                 for (auto& nuget : bf::recursive_directory_iterator(__TAC_DIR)) {
47                         bool isExist = false;
48                         std::string nugetPath = nuget.path().string();
49                         for (auto& restore : restore_nuget) {
50                                 if (!bf::is_directory(nugetPath)) {
51                                         isExist = true;
52                                 }
53                                 if (!strcmp(nugetPath.c_str(), restore.c_str()) ||
54                                         !strcmp(nugetPath.c_str(), restore.substr(0, restore.rfind('/')).c_str())) {
55                                         isExist = true;
56                                         break;
57                                 }
58                         }
59                         if (!isExist) {
60                                 removeNuget.push_back(nugetPath);
61                         }
62                 }
63
64                 for (auto& rm : removeNuget) {
65                         if (!removeAll(rm)) {
66                                 fprintf(stderr, "Failed to remove of %s\n", rm.c_str());
67                         }
68                 }
69                 removeNuget.clear();
70         } catch (const bf::filesystem_error& error) {
71                 fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
72                 return;
73         }
74 }
75
76 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
77 static int restoreDBCb(pkgmgrinfo_appinfo_h handle, void *userData)
78 {
79         char *pkgId = NULL;
80         char *root = NULL;
81         char *exec = NULL;
82         std::string rootPath;
83         std::string execName;
84
85         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
86         if (ret != PMINFO_R_OK) {
87                 fprintf(stderr, "Failed to get pkgid\n");
88                 return -1;
89         }
90
91         ret = pkgmgrinfo_appinfo_get_root_path(handle, &root);
92         if (ret != PMINFO_R_OK) {
93                 fprintf(stderr, "Failed to get root path\n");
94                 return -1;
95         }
96         rootPath = root;
97
98         ret = pkgmgrinfo_appinfo_get_exec(handle, &exec);
99         if (ret != PMINFO_R_OK) {
100                 fprintf(stderr, "Failed to get exec name\n");
101                 return -1;
102         }
103         execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
104
105         std::vector<std::string> parserData;
106         for (auto& npAssembly : depsJsonParser(rootPath, execName, getTPA())) {
107                 std::string nugetPackage = npAssembly.substr(0, npAssembly.rfind(':'));
108                 parserData.push_back(nugetPackage);
109         }
110         std::sort(parserData.begin(), parserData.end());
111         parserData.erase(unique(parserData.begin(), parserData.end()), parserData.end());
112
113         for (auto& nuget : parserData) {
114                 if (tac_db) {
115                         std::string name = nuget.substr(0, nuget.find('/'));
116                         std::string version = nuget.substr(nuget.rfind('/') + 1);
117                         std::string sql = "INSERT INTO TAC (PKGID, NUGET, NAME, VERSION) " \
118                                                 "VALUES ('" + std::string(pkgId) + "', '" + nuget + "', '" + name + "', '" + version + "');";
119                         dbInsert(tac_db, TAC_APP_LIST_RESTORE_DB, sql);
120                         restore_nuget.push_back(concatPath(__TAC_DIR, nuget));
121                 }
122         }
123         parserData.clear();
124         return 0;
125 }
126
127 tac_error_e restoreTACDB()
128 {
129         if (!removeFile(TAC_APP_LIST_RESTORE_DB)) {
130                 fprintf(stderr, "Failed to remove of %s\n", TAC_APP_LIST_RESTORE_DB);
131                 return TAC_ERROR_UNKNOWN;
132         }
133
134         std::string dbRestoreJournal = TAC_APP_LIST_RESTORE_DB + std::string("-journal");
135         if (!removeFile(dbRestoreJournal)) {
136                 fprintf(stderr, "Failed to remove of %s\n", dbRestoreJournal.c_str());
137                 return TAC_ERROR_UNKNOWN;
138         }
139
140         if (initializePathManager(std::string(), std::string(), std::string())) {
141                 fprintf(stderr, "Fail to initialize PathManger\n");
142                 return TAC_ERROR_UNKNOWN;
143         }
144
145         tac_db = dbCreate(TAC_APP_LIST_RESTORE_DB);
146         if (!tac_db) {
147                 fprintf(stderr, "Sqlite create error\n");
148                 return TAC_ERROR_UNKNOWN;
149         }
150
151         pkgmgrinfo_appinfo_metadata_filter_h handle;
152         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
153         if (ret != PMINFO_R_OK) {
154                 return TAC_ERROR_UNKNOWN;
155         }
156
157         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
158         if (ret != PMINFO_R_OK) {
159                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
160                 return TAC_ERROR_UNKNOWN;
161         }
162
163         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, restoreDBCb, NULL);
164         if (ret != PMINFO_R_OK) {
165                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
166                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
167                 return TAC_ERROR_UNKNOWN;
168         }
169         fprintf(stderr, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
170
171         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
172
173         if (tac_db) {
174                 dbClose(tac_db);
175                 tac_db = NULL;
176         }
177
178         if (!copyFile(TAC_APP_LIST_RESTORE_DB, TAC_APP_LIST_DB)) {
179                 fprintf(stderr, "Failed to copy of %s\n", TAC_APP_LIST_DB);
180                 return TAC_ERROR_UNKNOWN;
181         }
182         if (!removeFile(TAC_APP_LIST_RESTORE_DB)) {
183                 fprintf(stderr, "Failed to remove of %s\n", TAC_APP_LIST_RESTORE_DB);
184                 return TAC_ERROR_UNKNOWN;
185         }
186
187         std::string dbJournal = TAC_APP_LIST_DB + std::string("-journal");
188         if (!copyFile(dbRestoreJournal, dbJournal)) {
189                 fprintf(stderr, "Failed to copy of %s\n", dbJournal.c_str());
190                 return TAC_ERROR_UNKNOWN;
191         }
192         if (!removeFile(dbRestoreJournal)) {
193                 fprintf(stderr, "Failed to remove of %s\n", dbRestoreJournal.c_str());
194                 return TAC_ERROR_UNKNOWN;
195         }
196
197         cleanupDirectory();
198         return TAC_ERROR_NONE;
199 }
200
201 tac_error_e resetTACPackage(const std::string& pkgId)
202 {
203         std::string pkgRoot;
204         if (getRootPath(pkgId, pkgRoot) < 0) {
205                 return TAC_ERROR_INVALID_PACKAGE;
206         }
207
208         std::vector<std::string> tacNativeImage;
209         std::string binDir = concatPath(pkgRoot, "bin");
210         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
211         if (bf::exists(tacDir)) {
212                 try {
213                         for (auto& symlinkAssembly : bf::recursive_directory_iterator(tacDir)) {
214                                 std::string symPath = symlinkAssembly.path().string();
215                                 if (bf::is_symlink(symPath)) {
216                                         if (isNativeImage(symPath)) {
217                                                 tacNativeImage.push_back(symPath);
218                                         }
219                                 }
220                         }
221                         for (auto& path : tacNativeImage) {
222                                 if (!removeFile(path)) {
223                                         fprintf(stderr, "Failed to remove of %s\n", path.c_str());
224                                         return TAC_ERROR_UNKNOWN;
225                                 }
226                         }
227                         tacNativeImage.clear();
228                 } catch (const bf::filesystem_error& error) {
229                         fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
230                         return TAC_ERROR_UNKNOWN;
231                 }
232         }
233         return TAC_ERROR_NONE;
234 }
235
236 tac_error_e disableTACPackage(const std::string& pkgId)
237 {
238         std::string pkgRoot;
239         if (getRootPath(pkgId, pkgRoot) < 0) {
240                 return TAC_ERROR_INVALID_PACKAGE;
241         }
242
243         std::string binDir = concatPath(pkgRoot, "bin");
244         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
245         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
246         if (bf::exists(tacDir)) {
247                 try {
248                         for (auto& symlinkAssembly : bf::recursive_directory_iterator(tacDir)) {
249                                 std::string symPath = symlinkAssembly.path().string();
250                                 std::string fileName = symlinkAssembly.path().filename().string();
251                                 if (bf::is_symlink(symPath)) {
252                                         std::string originPath = bf::read_symlink(symPath).string();
253                                         if (!isNativeImage(symPath)) {
254                                                 std::string dllPath = concatPath(binDir, fileName);
255                                                 if (!copyFile(originPath, dllPath)) {
256                                                         fprintf(stderr, "Failed to copy of %s\n", dllPath.c_str());
257                                                         return TAC_ERROR_UNKNOWN;
258                                                 }
259                                                 updateAssemblyInfo(binDir.c_str(), concatPath(binDir, fileName).c_str());
260                                         } else {
261                                                 std::string niPath = concatPath(binNIDir, fileName);
262                                                 if (!copyFile(originPath, niPath)) {
263                                                         fprintf(stderr, "Failed to copy of %s\n", niPath.c_str());
264                                                         return TAC_ERROR_UNKNOWN;
265                                                 }
266                                                 updateAssemblyInfo(binDir.c_str(), niPath.c_str());
267                                         }
268                                 }
269                         }
270                         if (!removeAll(tacDir)) {
271                                 fprintf(stderr, "Failed to remove of %s\n", tacDir.c_str());
272                                 return TAC_ERROR_UNKNOWN;
273                         }
274                 } catch (const bf::filesystem_error& error) {
275                         fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
276                         return TAC_ERROR_UNKNOWN;
277                 }
278         }
279         return TAC_ERROR_NONE;
280 }
281
282 tac_error_e enableTACPackage(const std::string& pkgId)
283 {
284         std::string rootPath;
285         if (getRootPath(pkgId, rootPath) < 0) {
286                 return TAC_ERROR_INVALID_PACKAGE;
287         }
288
289         std::string execName;
290         if (getExecName(pkgId, execName) < 0) {
291                 return TAC_ERROR_INVALID_PACKAGE;
292         }
293
294         std::string metaValue;
295         if (getMetadataValue(pkgId, TAC_METADATA_KEY, metaValue) < 0) {
296                 return TAC_ERROR_INVALID_PACKAGE;
297         }
298
299         if (initializePathManager(std::string(), std::string(), std::string())) {
300                 fprintf(stderr, "Fail to initialize PathManger\n");
301                 return TAC_ERROR_UNKNOWN;
302         }
303
304         if (!strcmp(metaValue.c_str(), "true")) {
305                 std::string binDir = concatPath(rootPath, "bin");
306                 std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
307                 std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
308                 if (!bf::exists(tacDir)) {
309                         if (!createDir(tacDir)) {
310                                 fprintf(stderr, "Cannot create directory: %s\n", tacDir.c_str());
311                                 return TAC_ERROR_UNKNOWN;
312                         }
313                         updateAssemblyInfo(binDir.c_str(), tacDir.c_str());
314
315                         std::vector<std::string> enableNuget;
316                         for (auto& npAssembly : depsJsonParser(rootPath, execName, getTPA())) {
317                                 std::string nugetPackage = npAssembly.substr(0, npAssembly.rfind(':'));
318                                 std::string assemblyName = npAssembly.substr(npAssembly.rfind(':') + 1);
319                                 std::string nugetPath = concatPath(__TAC_DIR, nugetPackage);
320                                 if (bf::exists(nugetPath)) {
321                                         std::string originPath = concatPath(nugetPath, assemblyName);
322                                         if (bf::exists(originPath)) {
323                                                 enableNuget.push_back(originPath);
324                                         }
325                                 }
326                         }
327
328                         for (auto& originPath : enableNuget) {
329                                 if (bf::exists(originPath)) {
330                                         std::string fileName = originPath.substr(originPath.rfind('/') + 1);
331                                         std::string NIFileName = fileName.substr(0, fileName.rfind(".dll")) + ".ni.dll";
332                                         if (bf::exists(binNIDir)) {
333                                                 std::string originNIPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
334                                                 if (bf::exists(originNIPath)) {
335                                                         bf::create_symlink(originNIPath, concatPath(tacDir, NIFileName));
336                                                         fprintf(stderr, "%s symbolic link file generated successfully.\n", concatPath(tacDir, NIFileName).c_str());
337                                                         updateAssemblyInfo(tacDir.c_str(), concatPath(tacDir, NIFileName).c_str(), true);
338
339                                                         if (!removeFile(concatPath(binNIDir, NIFileName))) {
340                                                                 fprintf(stderr, "Failed to remove of %s\n", concatPath(binNIDir, NIFileName).c_str());
341                                                                 return TAC_ERROR_UNKNOWN;
342                                                         }
343                                                 }
344                                         }
345                                         bf::create_symlink(originPath, concatPath(tacDir, fileName));
346                                         fprintf(stderr, "%s symbolic link file generated successfully.\n", concatPath(tacDir, fileName).c_str());
347                                         updateAssemblyInfo(tacDir.c_str(), concatPath(tacDir, fileName).c_str(), true);
348
349                                         if (!removeFile(concatPath(binDir, fileName))) {
350                                                 fprintf(stderr, "Failed to remove of %s\n", concatPath(binDir, fileName).c_str());
351                                                 return TAC_ERROR_UNKNOWN;
352                                         }
353                                 }
354                         }
355                         if (enableNuget.empty()) {
356                                 if (!removeAll(tacDir)) {
357                                         fprintf(stderr, "Failed to remove of %s\n", tacDir.c_str());
358                                 }
359                         }
360                         enableNuget.clear();
361                 }
362         } else {
363                 fprintf(stderr, "The metadata key is missing or the metadata value is false of [%s]\n", pkgId.c_str());
364         }
365         return TAC_ERROR_NONE;
366 }
367
368 //Parser the .deps.json file to get nuget information.
369 std::vector<std::string> depsJsonParser(std::string rootPath, std::string execName, std::string tpaList)
370 {
371         std::vector<std::string> tpaAssemblies;
372         splitPath(tpaList, tpaAssemblies);
373
374         std::vector<std::string> parserData;
375         std::string depsJsonName = execName.substr(0, execName.rfind(".dll")) + ".deps.json";
376         std::string depsJsonPath = concatPath(rootPath, depsJsonName);
377         try {
378                 if (bf::exists(depsJsonPath)) {
379                         std::ifstream ifs(depsJsonPath);
380                         Json::CharReaderBuilder reader;
381                         Json::Value root;
382                         std::string error;
383                         if (ifs.is_open()) {
384                                 if (!Json::parseFromStream(reader, ifs, &root, &error)) {
385                                         _ERR("Failed to parse of deps.json");
386                                         ifs.close();
387                                         tpaAssemblies.clear();
388                                         return parserData;
389                                 }
390                                 const Json::Value runtimeTargetName = root["runtimeTarget"]["name"];
391                                 const Json::Value nugetPackages = root["targets"][runtimeTargetName.asString().c_str()];
392                                 std::vector<std::string> appDependencies;
393                                 for (auto& nuget : nugetPackages.getMemberNames()) {
394                                         if (strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) != NULL ||
395                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) != NULL) {
396                                                 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
397                                                 if (assemblies != Json::nullValue) {
398                                                         const Json::Value dependencies = nugetPackages[nuget.c_str()]["dependencies"];
399                                                         for (auto& dependency : dependencies.getMemberNames()) {
400                                                                 appDependencies.push_back(dependency);
401                                                         }
402                                                 }
403                                         }
404                                 }
405                                 for (auto& nuget : nugetPackages.getMemberNames()) {
406                                         //Skip the nuget package related to Tizen
407                                         if (strstr(nuget.c_str(), TIZEN_DOTNET_NUGET) == NULL &&
408                                                 strstr(nuget.c_str(), TIZEN_DOTNET_SDK_NUGET) == NULL &&
409                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) == NULL &&
410                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) == NULL) {
411                                                 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
412                                                 if (assemblies != Json::nullValue) {
413                                                         const Json::Value dependencies = nugetPackages[nuget.c_str()]["dependencies"];
414                                                         bool hasDependency = false;
415                                                         for (auto& dependency : dependencies.getMemberNames()) {
416                                                                 //Skip the nugget package that is dependent on another nuget package
417                                                                 if (strstr(dependency.c_str(), TIZEN_DOTNET_NUGET) == NULL &&
418                                                                         strstr(dependency.c_str(), NET_STANDARD_LIBRARY_NUGET) == NULL) {
419                                                                         hasDependency = true;
420                                                                         for (auto& ad : appDependencies) {
421                                                                                 if (!strcmp(ad.c_str(), dependency.c_str())) {
422                                                                                         hasDependency = true;
423                                                                                         break;
424                                                                                 } else {
425                                                                                         hasDependency = false;
426                                                                                 }
427                                                                         }
428                                                                         if (hasDependency) break;
429                                                                 }
430                                                         }
431                                                         if (!hasDependency) {
432                                                                 bool isExistTpaAssembly = false;
433                                                                 for (auto& assembly : assemblies.getMemberNames()) {
434                                                                         std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
435                                                                         //Skip the assembly present in the TPA list
436                                                                         for (auto& tpa : tpaAssemblies) {
437                                                                                 if (!strcmp(replaceAll(tpa, ".ni.dll", ".dll").c_str(), assembly.c_str())) {
438                                                                                         isExistTpaAssembly = true;
439                                                                                         break;
440                                                                                 }
441                                                                         }
442                                                                         if (isExistTpaAssembly) break;
443                                                                 }
444                                                                 if (!isExistTpaAssembly) {
445                                                                         for (auto& assembly : assemblies.getMemberNames()) {
446                                                                                 std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
447                                                                                 parserData.push_back(nuget + ":" + assemblyName);
448                                                                                 _INFO("Nuget : [%s] / Assembly : [%s]", nuget.c_str(), assemblyName.c_str());
449                                                                         }
450                                                                 }
451                                                         }
452                                                 }
453                                         }
454                                 }
455                                 appDependencies.clear();
456                                 ifs.close();
457                         }
458                 }
459         } catch (const Json::LogicError& error) {
460                 _ERR("Failed to parse Json: %s", error.what());
461         }
462         tpaAssemblies.clear();
463         return parserData;
464 }