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