Modification of lchown for ni file in .tac_symlink (#258)
[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* __DOTNET_DIR = __STR(DOTNET_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(__DOTNET_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)) {
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(__DOTNET_DIR, nuget));
129                         sqlite3_free(sql);
130                 }
131         }
132         parserData.clear();
133         return 0;
134 }
135
136 tac_error_e restoreTACDB()
137 {
138         if (!removeFile(TAC_APP_LIST_RESTORE_DB)) {
139                 fprintf(stderr, "Failed to remove of %s\n", TAC_APP_LIST_RESTORE_DB);
140                 return TAC_ERROR_UNKNOWN;
141         }
142
143         std::string dbRestoreJournal = TAC_APP_LIST_RESTORE_DB + std::string("-journal");
144         if (!removeFile(dbRestoreJournal)) {
145                 fprintf(stderr, "Failed to remove of %s\n", dbRestoreJournal.c_str());
146                 return TAC_ERROR_UNKNOWN;
147         }
148
149         tac_db = dbCreate(TAC_APP_LIST_RESTORE_DB, CREATE_TAC_DB_TABLE);
150         if (!tac_db) {
151                 fprintf(stderr, "Sqlite create error\n");
152                 return TAC_ERROR_UNKNOWN;
153         }
154
155         pkgmgrinfo_appinfo_metadata_filter_h handle;
156         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
157         if (ret != PMINFO_R_OK) {
158                 return TAC_ERROR_UNKNOWN;
159         }
160
161         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
162         if (ret != PMINFO_R_OK) {
163                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
164                 return TAC_ERROR_UNKNOWN;
165         }
166
167         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, restoreDBCb, NULL);
168         if (ret != PMINFO_R_OK) {
169                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
170                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
171                 return TAC_ERROR_UNKNOWN;
172         }
173         fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
174
175         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
176
177         if (tac_db) {
178                 dbClose(tac_db);
179                 tac_db = NULL;
180         }
181
182         const uid_t g_uid = 301; // app_fw
183         const gid_t g_gid = 301; // app_fw
184
185         if (!copyFile(TAC_APP_LIST_RESTORE_DB, TAC_APP_LIST_DB)) {
186                 fprintf(stderr, "Failed to copy of %s\n", TAC_APP_LIST_DB);
187                 return TAC_ERROR_UNKNOWN;
188         }
189         if (!removeFile(TAC_APP_LIST_RESTORE_DB)) {
190                 fprintf(stderr, "Failed to remove of %s\n", TAC_APP_LIST_RESTORE_DB);
191                 return TAC_ERROR_UNKNOWN;
192         }
193         if (chown(TAC_APP_LIST_DB, g_uid, g_gid) == -1) {
194                 fprintf(stderr, "Failed to change owner and group name\n");
195         }
196
197         std::string dbJournal = TAC_APP_LIST_DB + std::string("-journal");
198         if (!copyFile(dbRestoreJournal, dbJournal)) {
199                 fprintf(stderr, "Failed to copy of %s\n", dbJournal.c_str());
200                 return TAC_ERROR_UNKNOWN;
201         }
202         if (!removeFile(dbRestoreJournal)) {
203                 fprintf(stderr, "Failed to remove of %s\n", dbRestoreJournal.c_str());
204                 return TAC_ERROR_UNKNOWN;
205         }
206         if (chown(dbJournal.c_str(), g_uid, g_gid) == -1) {
207                 fprintf(stderr, "Failed to change owner and group name\n");
208         }
209
210         cleanupDirectory();
211
212         return TAC_ERROR_NONE;
213 }
214
215 tac_error_e disableTACPackage(const std::string& pkgId)
216 {
217         std::string rootPath = getRootPath(pkgId);
218         if (rootPath.empty()) {
219                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
220                 return TAC_ERROR_INVALID_PACKAGE;
221         }
222
223         std::string binDir = concatPath(rootPath, "bin");
224         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
225         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
226         if (bf::exists(tacDir)) {
227                 try {
228                         for (auto& symlinkAssembly : bf::recursive_directory_iterator(tacDir)) {
229                                 std::string symPath = symlinkAssembly.path().string();
230                                 std::string fileName = symlinkAssembly.path().filename().string();
231                                 if (bf::is_symlink(symPath)) {
232                                         std::string originPath = bf::read_symlink(symPath).string();
233                                         if (!isNativeImage(symPath)) {
234                                                 std::string dllPath = concatPath(binDir, fileName);
235                                                 if (!copyFile(originPath, dllPath)) {
236                                                         fprintf(stderr, "Failed to copy of %s\n", dllPath.c_str());
237                                                         return TAC_ERROR_UNKNOWN;
238                                                 }
239                                                 copySmackAndOwnership(binDir.c_str(), concatPath(binDir, fileName).c_str());
240                                         } else {
241                                                 std::string niPath = concatPath(binNIDir, fileName);
242                                                 if (!copyFile(originPath, niPath)) {
243                                                         fprintf(stderr, "Failed to copy of %s\n", niPath.c_str());
244                                                         return TAC_ERROR_UNKNOWN;
245                                                 }
246                                                 copySmackAndOwnership(binDir.c_str(), niPath.c_str());
247                                         }
248                                 }
249                         }
250                         if (!removeAll(tacDir)) {
251                                 fprintf(stderr, "Failed to remove of %s\n", tacDir.c_str());
252                                 return TAC_ERROR_UNKNOWN;
253                         }
254                 } catch (const bf::filesystem_error& error) {
255                         fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
256                         return TAC_ERROR_UNKNOWN;
257                 }
258         }
259         return TAC_ERROR_NONE;
260 }
261
262 tac_error_e enableTACPackage(const std::string& pkgId)
263 {
264         std::string rootPath = getRootPath(pkgId);
265         if (rootPath.empty()) {
266                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
267                 return TAC_ERROR_INVALID_PACKAGE;
268         }
269
270         std::string execName = getExecName(pkgId);
271         if (execName.empty()) {
272                 fprintf(stderr, "Failed to get exec name from [%s]\n", pkgId.c_str());
273                 return TAC_ERROR_INVALID_PACKAGE;
274         }
275
276         std::string metaValue = getMetadataValue(pkgId, TAC_METADATA_KEY);
277         if (metaValue.empty()) {
278                 fprintf(stderr, "Failed to get metadata from [%s]\n", pkgId.c_str());
279                 return TAC_ERROR_INVALID_PACKAGE;
280         }
281
282         if (!strcmp(metaValue.c_str(), "true")) {
283                 std::string binDir = concatPath(rootPath, "bin");
284                 std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
285                 std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
286                 if (!bf::exists(tacDir)) {
287                         if (!createDir(tacDir)) {
288                                 fprintf(stderr, "Cannot create directory: %s\n", tacDir.c_str());
289                                 return TAC_ERROR_UNKNOWN;
290                         }
291                         copySmackAndOwnership(binDir.c_str(), tacDir.c_str());
292
293                         std::vector<std::string> enableNuget;
294                         for (auto& npAssembly : depsJsonParser(rootPath, execName)) {
295                                 std::string nugetPackage = npAssembly.substr(0, npAssembly.rfind(':'));
296                                 std::string assemblyName = npAssembly.substr(npAssembly.rfind(':') + 1);
297                                 std::string nugetPath = concatPath(__DOTNET_DIR, nugetPackage);
298                                 if (bf::exists(nugetPath)) {
299                                         std::string originPath = concatPath(nugetPath, assemblyName);
300                                         if (bf::exists(originPath)) {
301                                                 enableNuget.push_back(originPath);
302                                         }
303                                 }
304                         }
305
306                         for (auto& originPath : enableNuget) {
307                                 if (bf::exists(originPath)) {
308                                         std::string fileName = originPath.substr(originPath.rfind('/') + 1);
309                                         std::string NIFileName = fileName.substr(0, fileName.rfind(".dll")) + ".ni.dll";
310                                         if (bf::exists(binNIDir)) {
311                                                 std::string originNIPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
312                                                 if (bf::exists(originNIPath)) {
313                                                         bf::create_symlink(originNIPath, concatPath(tacDir, NIFileName));
314                                                         fprintf(stdout, "%s symbolic link file generated successfully.\n", concatPath(tacDir, NIFileName).c_str());
315                                                         copySmackAndOwnership(tacDir.c_str(), concatPath(tacDir, NIFileName).c_str(), true);
316
317                                                         if (!removeFile(concatPath(binNIDir, NIFileName))) {
318                                                                 fprintf(stderr, "Failed to remove of %s\n", concatPath(binNIDir, NIFileName).c_str());
319                                                                 return TAC_ERROR_UNKNOWN;
320                                                         }
321                                                 }
322                                         }
323                                         bf::create_symlink(originPath, concatPath(tacDir, fileName));
324                                         fprintf(stdout, "%s symbolic link file generated successfully.\n", concatPath(tacDir, fileName).c_str());
325                                         copySmackAndOwnership(tacDir.c_str(), concatPath(tacDir, fileName).c_str(), true);
326
327                                         if (!removeFile(concatPath(binDir, fileName))) {
328                                                 fprintf(stderr, "Failed to remove of %s\n", concatPath(binDir, fileName).c_str());
329                                                 return TAC_ERROR_UNKNOWN;
330                                         }
331                                 }
332                         }
333                         if (enableNuget.empty()) {
334                                 if (!removeAll(tacDir)) {
335                                         fprintf(stderr, "Failed to remove of %s\n", tacDir.c_str());
336                                 }
337                         }
338                         enableNuget.clear();
339                 }
340         } else {
341                 fprintf(stderr, "The metadata key is missing or the metadata value is false of [%s]\n", pkgId.c_str());
342         }
343         return TAC_ERROR_NONE;
344 }
345
346 //Parser the .deps.json file to get nuget information.
347 std::vector<std::string> depsJsonParser(const std::string& rootPath, const std::string& execName)
348 {
349         std::vector<std::string> parserData;
350         std::string depsJsonName = execName.substr(0, execName.rfind(".dll")) + ".deps.json";
351         std::string depsJsonPath = concatPath(rootPath, depsJsonName);
352         try {
353                 if (bf::exists(depsJsonPath)) {
354                         std::ifstream ifs(depsJsonPath);
355                         Json::CharReaderBuilder reader;
356                         Json::Value root;
357                         std::string error;
358                         if (ifs.is_open()) {
359                                 if (!Json::parseFromStream(reader, ifs, &root, &error)) {
360                                         _ERR("Failed to parse of deps.json");
361                                         ifs.close();
362                                         return parserData;
363                                 }
364                                 const Json::Value runtimeTargetName = root["runtimeTarget"]["name"];
365                                 const Json::Value nugetPackages = root["targets"][runtimeTargetName.asString().c_str()];
366                                 std::vector<std::string> appDependencies;
367                                 for (auto& nuget : nugetPackages.getMemberNames()) {
368                                         if (strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) != NULL ||
369                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) != NULL) {
370                                                 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
371                                                 if (assemblies != Json::nullValue) {
372                                                         const Json::Value dependencies = nugetPackages[nuget.c_str()]["dependencies"];
373                                                         for (auto& dependency : dependencies.getMemberNames()) {
374                                                                 appDependencies.push_back(dependency);
375                                                         }
376                                                 }
377                                         }
378                                 }
379                                 for (auto& nuget : nugetPackages.getMemberNames()) {
380                                         //Skip the nuget package related to Tizen
381                                         if (strstr(nuget.c_str(), TIZEN_DOTNET_NUGET) == NULL &&
382                                                 strstr(nuget.c_str(), TIZEN_DOTNET_SDK_NUGET) == NULL &&
383                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) == NULL &&
384                                                 strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) == NULL) {
385                                                 const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
386                                                 if (assemblies != Json::nullValue) {
387                                                         const Json::Value dependencies = nugetPackages[nuget.c_str()]["dependencies"];
388                                                         bool hasDependency = false;
389                                                         for (auto& dependency : dependencies.getMemberNames()) {
390                                                                 //Skip the nugget package that is dependent on another nuget package
391                                                                 if (strstr(dependency.c_str(), TIZEN_DOTNET_NUGET) == NULL &&
392                                                                         strstr(dependency.c_str(), NET_STANDARD_LIBRARY_NUGET) == NULL) {
393                                                                         hasDependency = true;
394                                                                         for (auto& ad : appDependencies) {
395                                                                                 if (!strcmp(ad.c_str(), dependency.c_str())) {
396                                                                                         hasDependency = true;
397                                                                                         break;
398                                                                                 } else {
399                                                                                         hasDependency = false;
400                                                                                 }
401                                                                         }
402                                                                         if (hasDependency) break;
403                                                                 }
404                                                         }
405                                                         if (!hasDependency) {
406                                                                 // handle assembly even though that is included in the TPA.
407                                                                 for (auto& assembly : assemblies.getMemberNames()) {
408                                                                         std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
409                                                                         parserData.push_back(nuget + ":" + assemblyName);
410                                                                         _INFO("Nuget : [%s] / Assembly : [%s]", nuget.c_str(), assemblyName.c_str());
411                                                                 }
412                                                         }
413                                                 }
414                                         }
415                                 }
416                                 appDependencies.clear();
417                                 ifs.close();
418                         }
419                 }
420         } catch (const Json::LogicError& error) {
421                 _ERR("Failed to parse Json: %s", error.what());
422         }
423         return parserData;
424 }