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