b0004d1d4b25a74d6986e98703484d4d42cf172d
[platform/core/appfw/app-installers.git] / test / smoke_tests / common / smoke_utils.cc
1 // Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
2 // Use of this source code is governed by an apache-2.0 license that can be
3 // found in the LICENSE file.
4
5 #include "smoke_tests/common/smoke_utils.h"
6
7 #include <gum/gum-user.h>
8 #include <gum/gum-user-service.h>
9 #include <gum/common/gum-user-types.h>
10 #include <manifest_parser/utils/version_number.h>
11 #include <sys/smack.h>
12 #include <vconf.h>
13 #include <vconf-internal-keys.h>
14
15 #include <boost/filesystem/path.hpp>
16 #include <gtest/gtest.h>
17
18 #include <common/installer/app_installer.h>
19 #include <common/utils/paths.h>
20 #include <common/pkgmgr_interface.h>
21 #include <common/utils/pkgmgr_query.h>
22 #include <common/tzip_interface.h>
23
24 #include "pkgmgr_parser_db.h"
25
26 #include <list>
27 #include <memory>
28 #include <string>
29 #include <vector>
30
31 namespace bf = boost::filesystem;
32 namespace bs = boost::system;
33 namespace ci = common_installer;
34 namespace bo = boost::program_options;
35
36 namespace {
37
38 const uid_t kDefaultUserUid = tzplatform_getuid(TZ_SYS_DEFAULT_USER);
39 const gid_t kDefaultUserGid = tzplatform_getgid(TZ_SYS_DEFAULT_USER);
40 const char kNormalUserName[] = "smokeuser";
41 const char kSystemShareGroupName[] = "system_share";
42 const char kMigrateTestDBName[] = "app2sd_migrate.db";
43 // common entries
44 const std::vector<std::string> kDBEntries = {
45   {".pkgmgr_parser.db"},
46   {".pkgmgr_parser.db-journal"},
47   {".pkgmgr_cert.db"},
48   {".pkgmgr_cert.db-journal"},
49   {".app2sd.db"},
50   {".app2sd.db-journal"},
51 };
52 // globaluser entries
53 const char kGlobalManifestDir[] = "/opt/share/packages";
54 const char kSkelDir[] = "/etc/skel/apps_rw";
55 const char kPreloadApps[] = "/usr/apps";
56 const char kPreloadManifestDir[] = "/usr/share/packages";
57 const char kPreloadIcons[] = "/usr/share/icons";
58 const char kData[] = "data";
59 const char kShared[] = ".shared";
60 const char kSharedTmp[] = ".shared_tmp";
61
62 enum RWDirectory {
63   DATA,
64   CACHE,
65   SHARED_CACHE,
66   SHARED_DATA,
67   SHARED_TRUSTED
68 };
69
70 const char* rwDirectories[] = {
71   "data",
72   "cache",
73   "shared/cache",
74   "shared/data",
75   "shared/trusted",
76 };
77
78 }  // namespace
79
80 namespace smoke_test {
81
82 const char kLegacyExtImageDir[] = "legacy_extimage_dir";
83 const std::string& kDefaultUserIdStr = std::to_string(kDefaultUserUid);
84 const uid_t kGlobalUserUid = tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
85 const uid_t kGlobalUserGid = tzplatform_getgid(TZ_SYS_GLOBALAPP_USER);
86 extern const bf::path kSdkDirectory = "/home/owner/share/tmp/sdk_tools";
87
88 ci::RequestMode ParseRequestMode(int argc,  char** argv) {
89   bo::options_description desc("Available options");
90   desc.add_options()
91       ("request-mode", bo::value<std::string>(), "set request mode")
92       ("global-request,g", "set request mode to global")
93       ("user-request,u", "set request mode to user");
94
95   bo::variables_map vm;
96   bo::store(bo::command_line_parser(argc, argv).
97       options(desc).allow_unregistered().run(), vm);
98   bo::notify(vm);
99
100   if (vm.count("global-request")) {
101     std::cout << "Request mode was set to global." << std::endl;
102     return ci::RequestMode::GLOBAL;
103   }
104   if (vm.count("user-request")) {
105     std::cout << "Request mode was set to user." << std::endl;
106     return ci::RequestMode::USER;
107   }
108   if (vm.count("request-mode")) {
109     if (vm["request-mode"].as<std::string>() == "global") {
110       std::cout << "Request mode was set to global." << std::endl;
111       return ci::RequestMode::GLOBAL;
112     }
113     if (vm["request-mode"].as<std::string>() == "user") {
114       std::cout << "Request mode was set to user." << std::endl;
115       return ci::RequestMode::USER;
116     }
117     std::cout << "Cannot set request mode to "
118               << vm["request-mode"].as<std::string>() << std::endl;
119   }
120   std::cout << "Request mode was set to global." << std::endl;
121   return ci::RequestMode::GLOBAL;
122 }
123
124 static bool AddUser(const char* user_name) {
125   GumUser* user = nullptr;
126   user = gum_user_create_sync(FALSE);
127   if (user == nullptr)
128     LOG(WARNING) << "Failed to create gum user! (user name: "
129                  << user_name << ")";
130   g_object_set(G_OBJECT(user), "username", user_name, "usertype",
131       GUM_USERTYPE_NORMAL, NULL);
132   gboolean rval = FALSE;
133   rval = gum_user_add_sync(user);
134   g_object_unref(user);
135   return rval;
136 }
137
138 static bool DeleteUser(const char* user_name, bool rem_home_dir) {
139   bool rval = FALSE;
140   GumUser* guser = gum_user_get_by_name_sync(user_name, FALSE);
141   if (guser)
142     rval = gum_user_delete_sync(guser, rem_home_dir);
143   return rval;
144 }
145
146 bool AddTestUser(User* test_user) {
147   std::cout << "Adding test user: " << kNormalUserName << std::endl;
148   AddUser(kNormalUserName);
149   if (boost::optional<uid_t> uid = ci::GetUidByUserName(kNormalUserName)) {
150     test_user->uid = *uid;
151     std::cout << "User created properly: uid=" << *uid;
152     if (boost::optional<gid_t> gid = ci::GetGidByUid(*uid)) {
153       test_user->gid = *gid;
154       std::cout << " gid=" << *gid;
155     }
156     std::cout << std::endl;
157     return true;
158   }
159   LOG(ERROR) << "Adding test user failed";
160   return false;
161 }
162
163 bool DeleteTestUser() {
164   std::cout << "Deleting test user: " << kNormalUserName << std::endl;
165   uid_t test_uid;
166   if (boost::optional<uid_t> uid = ci::GetUidByUserName(kNormalUserName))
167     test_uid = *uid;
168   else
169     return false;
170   DeleteUser(kNormalUserName, true);
171   if (!ci::GetUidByUserName(kNormalUserName)) {
172     std::cout << "User deleted properly: user_name=" << kNormalUserName
173               << " uid=" << test_uid << std::endl;
174     return true;
175   }
176   LOG(ERROR) << "Deleting test user failed";
177   return false;
178 }
179
180 bool TouchFile(const bf::path& path) {
181   FILE* f = fopen(path.c_str(), "w+");
182   if (!f)
183     return false;
184   fclose(f);
185   return true;
186 }
187
188 void AddDataFiles(const std::string& pkgid, uid_t uid) {
189   if (uid == kGlobalUserUid) {
190     ci::UserList list = ci::GetUserList();
191     for (auto l : list) {
192       auto pkg_path = GetPackageRoot(pkgid, std::get<0>(l));
193       ASSERT_TRUE(TouchFile(pkg_path / "data" / "file1.txt"));
194       ASSERT_TRUE(TouchFile(pkg_path / "data" / "file2.txt"));
195     }
196   } else {
197     auto pkg_path = GetPackageRoot(pkgid, uid);
198     ASSERT_TRUE(TouchFile(pkg_path / "data" / "file1.txt"));
199     ASSERT_TRUE(TouchFile(pkg_path / "data" / "file2.txt"));
200   }
201 }
202
203 void RemoveAllRecoveryFiles(const std::string& prefix, uid_t uid) {
204   bf::path root_path = ci::GetRootAppPath(false, uid);
205   if (!bf::exists(root_path))
206     return;
207   for (auto& dir_entry : boost::make_iterator_range(
208       bf::directory_iterator(root_path), bf::directory_iterator())) {
209     if (bf::is_regular_file(dir_entry)) {
210       if (dir_entry.path().string().find(prefix) != std::string::npos) {
211         bs::error_code error;
212         bf::remove(dir_entry.path(), error);
213         if (error)
214           LOG(ERROR) << "Failed to remove " << dir_entry.path()
215                      << ": " << error.message();
216       }
217     }
218   }
219 }
220
221 bf::path FindRecoveryFile(const std::string& prefix, uid_t uid) {
222   bf::path root_path = ci::GetRootAppPath(false, uid);
223   if (!bf::exists(root_path))
224     return {};
225
226   for (auto& dir_entry : boost::make_iterator_range(
227       bf::directory_iterator(root_path), bf::directory_iterator())) {
228     if (bf::is_regular_file(dir_entry)) {
229       if (dir_entry.path().string().find(prefix) != std::string::npos) {
230         return dir_entry.path();
231       }
232     }
233   }
234   return {};
235 }
236
237 std::unique_ptr<ci::recovery::RecoveryFile> GetRecoverFileInfo(
238     const bf::path& recovery_file_path) {
239   return ci::recovery::RecoveryFile::OpenRecoveryFile(recovery_file_path);
240 }
241
242 bf::path GetPackageRoot(const std::string& pkgid, uid_t uid) {
243   bf::path root_path = ci::GetRootAppPath(false, uid);
244   return root_path / pkgid;
245 }
246
247 bool ValidateFileContentInPackage(const std::string& pkgid,
248                                   const std::string& relative,
249                                   const std::string& expected,
250                                   const TestParameters& params) {
251   bf::path file_path = ci::GetRootAppPath(params.is_readonly,
252                                           params.test_user.uid);
253   file_path = file_path / pkgid / relative;
254   if (!bf::exists(file_path)) {
255     LOG(ERROR) << file_path << " doesn't exist";
256     return false;
257   }
258   FILE* handle = fopen(file_path.c_str(), "r");
259   if (!handle) {
260     LOG(ERROR) << file_path << " cannot be open";
261     return false;
262   }
263   std::string content;
264   std::array<char, 200> buffer;
265   while (fgets(buffer.data(), buffer.size(), handle)) {
266     content += buffer.data();
267   }
268   fclose(handle);
269   return content == expected;
270 }
271
272 static bool ValidatePackageRWFS(const std::string& pkgid, uid_t uid) {
273   bf::path root_path = ci::GetRootAppPath(false, uid);
274   bf::path package_path = root_path / pkgid;
275   bf::path data_path = package_path / rwDirectories[DATA];
276   bf::path cache_path = package_path / rwDirectories[CACHE];
277   bf::path shared_data_path = package_path / rwDirectories[SHARED_DATA];
278
279   EXTENDED_ASSERT_TRUE(bf::exists(data_path));
280   EXTENDED_ASSERT_TRUE(bf::exists(cache_path));
281
282   struct stat stats;
283   stat(data_path.c_str(), &stats);
284   // gid of RW dirs should be system_share
285   boost::optional<gid_t> system_share =
286       ci::GetGidByGroupName(kSystemShareGroupName);
287   EXTENDED_ASSERT_EQ(uid, stats.st_uid);
288   EXTENDED_ASSERT_EQ(*system_share, stats.st_gid);
289   if (bf::exists(shared_data_path)) {
290     stat(shared_data_path.c_str(), &stats);
291     EXTENDED_ASSERT_EQ(uid, stats.st_uid);
292     EXTENDED_ASSERT_EQ(*system_share, stats.st_gid);
293   }
294
295   stat(cache_path.c_str(), &stats);
296   EXTENDED_ASSERT_EQ(uid, stats.st_uid);
297   EXTENDED_ASSERT_EQ(*system_share, stats.st_gid);
298   return true;
299 }
300
301 static bool ValidatePackageFS(const std::string& pkgid, const Apps& apps,
302     const TestParameters& params) {
303   bf::path root_path = ci::GetRootAppPath(params.is_readonly,
304                                           params.test_user.uid);
305   bf::path package_path = root_path / pkgid;
306   bf::path shared_path = package_path / "shared";
307   EXTENDED_ASSERT_TRUE(bf::exists(root_path));
308   EXTENDED_ASSERT_TRUE(bf::exists(package_path));
309   EXTENDED_ASSERT_TRUE(bf::exists(shared_path));
310
311   bf::path manifest_path =
312       bf::path(getUserManifestPath(params.test_user.uid,
313           params.is_readonly)) / (pkgid + ".xml");
314   EXTENDED_ASSERT_TRUE(bf::exists(manifest_path));
315
316   for (auto& app : apps) {
317     const std::string &exec = app.second;
318     bf::path binary_path = package_path / "bin" / exec;
319     EXTENDED_ASSERT_TRUE(bf::exists(binary_path));
320   }
321
322   if (params.pkg_type == PackageType::WGT ||
323       params.pkg_type == PackageType::HYBRID) {
324     bf::path widget_root_path = package_path / "res" / "wgt";
325     bf::path config_path = widget_root_path / "config.xml";
326     EXTENDED_ASSERT_TRUE(bf::exists(widget_root_path));
327     EXTENDED_ASSERT_TRUE(bf::exists(config_path));
328
329     bf::path private_tmp_path = package_path / "tmp";
330     EXTENDED_ASSERT_TRUE(bf::exists(private_tmp_path));
331   }
332
333   // backups should not exist
334   bf::path package_backup = ci::GetBackupPathForPackagePath(package_path);
335   bf::path manifest_backup = ci::GetBackupPathForManifestFile(manifest_path);
336   EXTENDED_ASSERT_FALSE(bf::exists(package_backup));
337   EXTENDED_ASSERT_FALSE(bf::exists(manifest_backup));
338
339   for (bf::recursive_directory_iterator iter(package_path);
340       iter != bf::recursive_directory_iterator(); ++iter) {
341     if (bf::is_symlink(symlink_status(iter->path())))
342       continue;
343     bool is_rw_dir = false;
344     for (const auto rw_dir : rwDirectories) {
345       bf::path rw_dir_path = rw_dir;
346       is_rw_dir |= ci::MakeRelativePath(iter->path(), package_path)
347           == rw_dir_path;
348     }
349     if (is_rw_dir || iter->path().filename() == ".mmc") {
350       iter.no_push();
351       continue;
352     }
353     struct stat stats;
354     stat(iter->path().c_str(), &stats);
355     EXTENDED_ASSERT_EQ(params.test_user.uid, stats.st_uid);
356     EXTENDED_ASSERT_EQ(params.test_user.gid, stats.st_gid);
357   }
358   return true;
359 }
360
361 bool ValidatePackage(const std::string& pkgid, const Apps& apps,
362     const TestParameters& params) {
363   ci::PkgQueryInterface pkg_query(pkgid, params.test_user.uid, true);
364   EXTENDED_ASSERT_TRUE(pkg_query.IsPackageInstalled(
365       ci::GetRequestMode(params.test_user.uid)));
366   EXTENDED_ASSERT_TRUE(ValidatePackageFS(pkgid, apps, params));
367   if (params.test_user.uid == kGlobalUserUid) {
368     ci::UserList list = ci::GetUserList();
369     for (auto& l : list)
370       EXTENDED_ASSERT_TRUE(ValidatePackageRWFS(pkgid, std::get<0>(l)));
371   } else {
372     EXTENDED_ASSERT_TRUE(ValidatePackageRWFS(pkgid, params.test_user.uid));
373   }
374   return true;
375 }
376
377 bool ValidateDataFiles(const std::string& pkgid, uid_t uid) {
378   if (uid == kGlobalUserUid) {
379     ci::UserList list = ci::GetUserList();
380     for (auto l : list) {
381       auto pkg_path = GetPackageRoot(pkgid, std::get<0>(l));
382       EXTENDED_ASSERT_TRUE(bf::exists(pkg_path / "data" / "file1.txt"));
383       EXTENDED_ASSERT_TRUE(bf::exists(pkg_path / "data" / "file2.txt"));
384     }
385   } else {
386     auto pkg_path = GetPackageRoot(pkgid, uid);
387     EXTENDED_ASSERT_TRUE(bf::exists(pkg_path / "data" / "file1.txt"));
388     EXTENDED_ASSERT_TRUE(bf::exists(pkg_path / "data" / "file2.txt"));
389   }
390   return true;
391 }
392
393 static bool ValidateExternalPackageFS(const std::string& pkgid,
394     const Apps& apps, const TestParameters& params) {
395   EXTENDED_ASSERT_EQ(app2ext_usr_enable_external_pkg(pkgid.c_str(),
396       params.test_user.uid), 0);
397   bf::path root_path = ci::GetRootAppPath(false, params.test_user.uid);
398   if (params.pkg_type == PackageType::TPK) {
399     EXTENDED_ASSERT_TRUE(bf::exists(root_path / pkgid / ".mmc" / "bin"));
400     EXTENDED_ASSERT_TRUE(bf::exists(root_path / pkgid / ".mmc" / "lib"));
401   }
402   EXTENDED_ASSERT_TRUE(bf::exists(root_path / pkgid / ".mmc" / "res"));
403   EXTENDED_ASSERT_TRUE(ValidatePackageFS(pkgid, apps, params));
404   EXTENDED_ASSERT_EQ(app2ext_usr_disable_external_pkg(pkgid.c_str(),
405       params.test_user.uid), 0);
406   return true;
407 }
408
409 bool ValidateExternalPackage(const std::string& pkgid, const Apps& apps,
410     const TestParameters& params) {
411   ci::PkgQueryInterface pkg_query(pkgid, params.test_user.uid, true);
412   std::string storage = pkg_query.StorageForPkgId();
413   bf::path ext_mount_path = ci::GetExternalCardPath();
414   if (bf::is_empty(ext_mount_path)) {
415     LOG(INFO) << "Sdcard not exists!";
416     EXTENDED_ASSERT_EQ(storage, "installed_internal");
417   } else {
418     EXTENDED_ASSERT_EQ(storage, "installed_external");
419   }
420   EXTENDED_ASSERT_TRUE(ValidateExternalPackageFS(pkgid, apps, params));
421   return true;
422 }
423
424 bool ValidateExtendedPackage(const std::string& pkgid, const Apps& apps,
425     const TestParameters& params) {
426   ci::PkgQueryInterface pkg_query(pkgid, params.test_user.uid, true);
427   std::string storage = pkg_query.StorageForPkgId();
428   bf::path extended_path =
429       bf::path(ci::GetExtendedRootAppPath(params.test_user.uid)) / pkgid;
430   if (!bf::exists(extended_path)) {
431     LOG(INFO) << "Extended storage not exists!";
432     EXTENDED_ASSERT_EQ(storage, "installed_internal");
433   } else {
434     EXTENDED_ASSERT_EQ(storage, "installed_extended");
435   }
436   EXTENDED_ASSERT_TRUE(ValidatePackage(pkgid, apps, params));
437   return true;
438 }
439
440 static bool PackageCheckCleanup(const std::string& pkgid,
441     const TestParameters& params) {
442   bf::path root_path = ci::GetRootAppPath(params.is_readonly,
443                                           params.test_user.uid);
444   bf::path package_path = root_path / pkgid;
445   EXTENDED_ASSERT_FALSE(bf::exists(package_path));
446
447   bf::path manifest_path = bf::path(getUserManifestPath(params.test_user.uid,
448       params.is_readonly)) / (pkgid + ".xml");
449   EXTENDED_ASSERT_FALSE(bf::exists(manifest_path));
450
451   // backups should not exist
452   bf::path package_backup = ci::GetBackupPathForPackagePath(package_path);
453   bf::path manifest_backup = ci::GetBackupPathForManifestFile(manifest_path);
454   EXTENDED_ASSERT_FALSE(bf::exists(package_backup));
455   EXTENDED_ASSERT_FALSE(bf::exists(manifest_backup));
456   return true;
457 }
458
459 bool CheckPackageNonExistance(const std::string& pkgid,
460                               const TestParameters& params) {
461   ci::PkgQueryInterface pkg_query(pkgid, params.test_user.uid, true);
462   EXTENDED_ASSERT_FALSE(pkg_query.IsPackageInstalled(
463       ci::GetRequestMode(params.test_user.uid)));
464   EXTENDED_ASSERT_TRUE(PackageCheckCleanup(pkgid, params));
465   if (params.test_user.uid == kGlobalUserUid) {
466     bf::path skel_path(kSkelDir);
467     EXTENDED_ASSERT_FALSE(bf::exists(skel_path / pkgid));
468     EXTENDED_ASSERT_FALSE(bf::exists(skel_path / kShared / pkgid));
469     EXTENDED_ASSERT_FALSE(bf::exists(skel_path / kSharedTmp / pkgid));
470     ci::UserList list = ci::GetUserList();
471     for (auto& l : list) {
472       bf::path root_path = ci::GetRootAppPath(false, std::get<0>(l));
473       EXTENDED_ASSERT_FALSE(bf::exists(root_path / kShared / pkgid));
474       EXTENDED_ASSERT_FALSE(bf::exists(root_path / kSharedTmp / pkgid));
475       bf::path package_path = root_path / pkgid;
476       EXTENDED_ASSERT_FALSE(bf::exists(package_path));
477     }
478   }
479   return true;
480 }
481
482 bool CheckAvailableExternalPath() {
483   bf::path ext_mount_path = ci::GetExternalCardPath();
484   LOG(DEBUG) << "ext_mount_path :" << ext_mount_path;
485   if (ext_mount_path.empty()) {
486     LOG(ERROR) << "Sdcard not exists!";
487     return false;
488   }
489   return true;
490 }
491
492 bool CheckAvailableExtendedPath() {
493   bf::path extended_path = bf::path(tzplatform_getenv(TZ_SYS_EXTENDEDSD));
494   LOG(DEBUG) << "extended_path :" << extended_path;
495   // TODO(jeremy.jang): It should be checked by libstorage API.
496   if (!bf::exists(extended_path)) {
497     LOG(ERROR) << "Extended storage not exists!";
498     return false;
499   }
500   return true;
501 }
502
503 bool CheckPackageReadonlyNonExistance(const std::string& pkgid,
504                                       const TestParameters& params) {
505   ci::PkgQueryInterface pkg_query(pkgid, params.test_user.uid, true);
506   EXTENDED_ASSERT_FALSE(pkg_query.IsPackageInstalled(
507       ci::GetRequestMode(params.test_user.uid)));
508   EXTENDED_ASSERT_TRUE(PackageCheckCleanup(pkgid, params));
509   return true;
510 }
511
512 static bool CheckSharedDataExistanceForPath(const bf::path& apps_rw,
513     const std::string& pkgid) {
514   bf::path shared_data_path = apps_rw / pkgid / rwDirectories[SHARED_DATA];
515   bf::path shared = apps_rw / kShared / pkgid / kData;
516   bf::path shared_tmp = apps_rw / kSharedTmp / pkgid;
517   EXTENDED_ASSERT_TRUE(bf::exists(shared_data_path));
518   EXTENDED_ASSERT_TRUE(bf::exists(shared));
519   EXTENDED_ASSERT_TRUE(bf::exists(shared_tmp));
520   return true;
521 }
522
523 static bool CheckSharedDataPermissions(const bf::path& apps_rw,
524     const std::string& pkgid, uid_t uid) {
525   bf::path shared_data_path = apps_rw / pkgid / rwDirectories[SHARED_DATA];
526   bf::path shared = apps_rw / kShared / pkgid / kData;
527   bf::path shared_tmp = apps_rw / kSharedTmp / pkgid;
528   // gid of RW dirs should be system_share
529   boost::optional<gid_t> system_share =
530       ci::GetGidByGroupName(kSystemShareGroupName);
531   struct stat stats;
532   stat(shared_data_path.c_str(), &stats);
533   EXTENDED_ASSERT_EQ(uid, stats.st_uid);
534   EXTENDED_ASSERT_EQ(*system_share, stats.st_gid);
535   stat(shared.c_str(), &stats);
536   EXTENDED_ASSERT_EQ(uid, stats.st_uid);
537   EXTENDED_ASSERT_EQ(*system_share, stats.st_gid);
538   stat(shared_tmp.c_str(), &stats);
539   EXTENDED_ASSERT_EQ(uid, stats.st_uid);
540   EXTENDED_ASSERT_EQ(kDefaultUserGid, stats.st_gid);
541   return true;
542 }
543
544 bool CheckSharedDataExistance(const std::string& pkgid,
545     const TestParameters& params) {
546   if (params.test_user.uid == kGlobalUserUid) {
547     bf::path skel_path(kSkelDir);
548     EXTENDED_ASSERT_TRUE(CheckSharedDataExistanceForPath(kSkelDir, pkgid));
549     ci::UserList list = ci::GetUserList();
550     for (auto& l : list) {
551       uid_t uid = std::get<0>(l);
552       bf::path apps_rw = ci::GetRootAppPath(false, uid);
553       EXTENDED_ASSERT_TRUE(CheckSharedDataExistanceForPath(apps_rw, pkgid));
554       EXTENDED_ASSERT_TRUE(CheckSharedDataPermissions(apps_rw, pkgid, uid));
555     }
556   } else {
557     bf::path apps_rw = ci::GetRootAppPath(false, params.test_user.uid);
558     EXTENDED_ASSERT_TRUE(CheckSharedDataExistanceForPath(apps_rw, pkgid));
559     EXTENDED_ASSERT_TRUE(
560         CheckSharedDataPermissions(apps_rw, pkgid, params.test_user.uid));
561   }
562   return true;
563 }
564
565 static bool CheckSharedDataNonExistanceForPath(const bf::path& apps_rw,
566     const std::string pkgid) {
567   bf::path shared_data_path = apps_rw / pkgid / rwDirectories[SHARED_DATA];
568   bf::path shared = apps_rw / kShared / pkgid / kData;
569   bf::path shared_tmp = apps_rw / kSharedTmp / pkgid;
570   EXTENDED_ASSERT_FALSE(bf::exists(shared_data_path));
571   EXTENDED_ASSERT_FALSE(bf::exists(shared));
572   EXTENDED_ASSERT_FALSE(bf::exists(shared_tmp));
573   return true;
574 }
575
576 bool CheckSharedDataNonExistance(const std::string& pkgid,
577     const TestParameters& params) {
578   if (params.test_user.uid == kGlobalUserUid) {
579     bf::path skel_path(kSkelDir);
580     EXTENDED_ASSERT_TRUE(
581         CheckSharedDataNonExistanceForPath(skel_path, pkgid));
582
583     ci::UserList list = ci::GetUserList();
584     for (auto& l : list) {
585       uid_t uid = std::get<0>(l);
586       bf::path apps_rw = ci::GetRootAppPath(false, uid);
587       EXTENDED_ASSERT_TRUE(CheckSharedDataNonExistanceForPath(apps_rw, pkgid));
588     }
589   } else {
590     bf::path apps_rw = ci::GetRootAppPath(false, params.test_user.uid);
591     EXTENDED_ASSERT_TRUE(CheckSharedDataNonExistanceForPath(apps_rw, pkgid));
592   }
593   return true;
594 }
595
596 void BackendInterface::TestRollbackAfterEachStep(int argc, const char* argv[],
597     std::function<bool()> validator) const {
598   TestPkgmgrInstaller pkgmgr_installer;
599   std::shared_ptr<ci::AppQueryInterface> query_interface =
600       CreateQueryInterface();
601   auto pkgmgr =
602       ci::PkgMgrInterface::Create(argc, const_cast<char**>(argv),
603                                   &pkgmgr_installer,
604                                   query_interface);
605   if (!pkgmgr) {
606     LOG(ERROR) << "Failed to initialize pkgmgr interface";
607     return;
608   }
609   AppInstallerPtr backend;
610   unsigned int insert_idx = 0;
611   do {
612     backend = CreateFailExpectedInstaller(pkgmgr, insert_idx);
613     LOG(DEBUG) << "StepFail is inserted at: " << insert_idx;
614     ASSERT_EQ(ci::AppInstaller::Result::ERROR, backend->Run());
615     if (!validator())
616       break;
617     insert_idx++;
618   } while (insert_idx < backend->StepCount());
619   ASSERT_EQ(insert_idx, backend->StepCount());
620 }
621
622 void BackendInterface::CrashAfterEachStep(std::vector<std::string>* args,
623     std::function<bool(int iter)> validator, PackageType type) const {
624   std::unique_ptr<const char*[]> argv(new const char*[args->size()]);
625   for (size_t i = 0; i < args->size(); ++i) {
626     argv[i] = args->at(i).c_str();
627   }
628   TestPkgmgrInstaller pkgmgr_installer;
629   auto query_interface = CreateQueryInterface();
630   auto pkgmgr =
631       ci::PkgMgrInterface::Create(args->size(), const_cast<char**>(argv.get()),
632                                   &pkgmgr_installer,
633                                   query_interface);
634   if (!pkgmgr) {
635     LOG(ERROR) << "Failed to initialize pkgmgr interface";
636     return;
637   }
638   auto backend = CreateFailExpectedInstaller(pkgmgr, 0);
639   ASSERT_EQ(backend->Run(), ci::AppInstaller::Result::ERROR);
640   int stepCount = backend->StepCount();
641
642   args->push_back("-idx");
643   args->push_back(std::to_string(stepCount));
644   int i;
645   std::string prefix = (type == PackageType::TPK) ? "tpk" : "wgt";
646   for (i = 0; i < stepCount; i++) {
647     ci::Subprocess backend_crash(
648         "/usr/bin/" + prefix + "-installer-ut/smoke-test-helper");
649     args->back() = std::to_string(i);
650     backend_crash.Run(*args);
651     ASSERT_NE(backend_crash.Wait(), 0);
652     if (!validator(i))
653       break;
654   }
655   ASSERT_EQ(stepCount, i);
656
657   args->push_back("-type_clean");
658   for (i = stepCount - 1; i >= 2; i--) {
659     ci::Subprocess backend_crash(
660         "/usr/bin/" + prefix + "-installer-ut/smoke-test-helper");
661     auto it = args->end();
662     it -= 2;
663     *it = std::to_string(i);
664     backend_crash.Run(*args);
665     ASSERT_NE(backend_crash.Wait(), 0);
666     if (!validator(i))
667       break;
668   }
669   ASSERT_EQ(i , 1);
670 }
671
672 BackendInterface::CommandResult BackendInterface::RunInstallersWithPkgmgr(
673     ci::PkgMgrPtr pkgmgr) const {
674   std::list<AppInstallerPtr> installers;
675   for (int i = 0; i < pkgmgr->GetRequestInfoCount(); i++) {
676     AppInstallerPtr installer;
677     if (mode_ == RequestResult::FAIL && i == pkgmgr->GetRequestInfoCount() - 1)
678       installer = factory_->CreateFailExpectedInstaller(i, pkgmgr);
679     else
680       installer = factory_->CreateInstaller(i, pkgmgr);
681     if (!installer)
682       LOG(ERROR) << "Failed to create installer";
683     else
684       installers.emplace_back(std::move(installer));
685   }
686
687   // FIXME: I think we should not implement this logic here...
688   CommandResult result = CommandResult::OK;
689   std::list<AppInstallerPtr>::iterator it(installers.begin());
690   for (; it != installers.end(); ++it) {
691     result = (*it)->Process();
692     if (result != CommandResult::OK)
693       break;
694   }
695   if (it != installers.end() && result == CommandResult::ERROR) {
696     do {
697       CommandResult ret = (*it)->Undo();
698       if (ret != CommandResult::OK && ret != CommandResult::ERROR)
699         result = CommandResult::UNDO_ERROR;
700     } while (it-- != installers.begin());
701   } else {
702     --it;
703     do {
704       if ((*it)->Clean() != CommandResult::OK)
705         result = CommandResult::CLEANUP_ERROR;
706     } while (it-- != installers.begin());
707   }
708   return result;
709 }
710
711 BackendInterface::CommandResult BackendInterface::CallBackendWithRunner(
712     int argc, const char* argv[]) const {
713   TestPkgmgrInstaller pkgmgr_installer;
714   auto pkgmgr = ci::PkgMgrInterface::Create(argc, const_cast<char**>(argv),
715       &pkgmgr_installer);
716   if (!pkgmgr) {
717     LOG(ERROR) << "Failed to initialize pkgmgr interface";
718     return BackendInterface::CommandResult::UNKNOWN;
719   }
720   return RunInstallersWithPkgmgr(pkgmgr);
721 }
722
723 BackendInterface::CommandResult BackendInterface::Install(
724     const std::vector<bf::path>& paths) const {
725   std::vector<const char*> argv;
726   argv.emplace_back("");
727   argv.emplace_back("-i");
728   for (const auto& p : paths)
729     argv.emplace_back(p.string().c_str());
730   return CallBackendWithRunner(argv.size(), argv.data());
731 }
732
733 BackendInterface::CommandResult BackendInterface::Uninstall(
734     const std::vector<std::string>& pkgids) const {
735   std::vector<const char*> argv;
736   argv.emplace_back("");
737   argv.emplace_back("-d");
738   for (const auto& p : pkgids)
739     argv.emplace_back(p.c_str());
740   return CallBackendWithRunner(argv.size(), argv.data());
741 }
742
743 BackendInterface::CommandResult BackendInterface::InstallSuccess(
744     const std::vector<bf::path>& paths) const {
745   RequestResult tmp_mode = mode_;
746   RequestResult &original_mode = const_cast<RequestResult&>(mode_);
747   original_mode = RequestResult::NORMAL;
748   if (Install(paths) != BackendInterface::CommandResult::OK) {
749     LOG(ERROR) << "Failed to install application. Cannot update";
750     return BackendInterface::CommandResult::UNKNOWN;
751   }
752   original_mode = tmp_mode;
753   return BackendInterface::CommandResult::OK;
754 }
755
756 BackendInterface::CommandResult BackendInterface::RunInstallerWithPkgrmgr(
757     ci::PkgMgrPtr pkgmgr) const {
758   std::unique_ptr<ci::AppInstaller> installer;
759   switch (mode_) {
760   case RequestResult::FAIL:
761     installer = CreateFailExpectedInstaller(pkgmgr);
762     break;
763   default:
764     installer = CreateInstaller(pkgmgr);
765     break;
766   }
767   return installer->Run();
768 }
769
770 BackendInterface::CommandResult BackendInterface::CallBackend(int argc,
771     const char* argv[]) const {
772   TestPkgmgrInstaller pkgmgr_installer;
773   auto query_interface = CreateQueryInterface();
774   auto pkgmgr = ci::PkgMgrInterface::Create(argc, const_cast<char**>(argv),
775       &pkgmgr_installer, query_interface);
776   if (!pkgmgr) {
777     LOG(ERROR) << "Failed to initialize pkgmgr interface";
778     return BackendInterface::CommandResult::UNKNOWN;
779   }
780   return RunInstallerWithPkgrmgr(pkgmgr);
781 }
782
783 BackendInterface::CommandResult BackendInterface::Install(
784     const bf::path& path) const {
785   const char* argv[] = {"", "-i", path.c_str(), "-u", uid_str_.c_str()};
786   return CallBackend(SIZEOFARRAY(argv), argv);
787 }
788
789 BackendInterface::CommandResult BackendInterface::InstallPreload(
790     const bf::path& path) const {
791   const char* argv[] = {"", "-i", path.c_str(), "--preload"};
792   return CallBackend(SIZEOFARRAY(argv), argv);
793 }
794
795 BackendInterface::CommandResult BackendInterface::InstallWithStorage(
796     const bf::path& path, StorageType type) const {
797   int default_storage = 0;
798   int storage = 0;
799   switch (type) {
800     case StorageType::EXTERNAL:
801       storage = 1;
802       break;
803     case StorageType::EXTENDED:
804       storage = 2;
805       break;
806     default:
807       LOG(ERROR) << "Unknown storage type";
808       break;
809   }
810   if (vconf_get_int(VCONFKEY_SETAPPL_DEFAULT_MEM_INSTALL_APPLICATIONS_INT,
811       &default_storage) != 0) {
812     LOG(ERROR) << "Failed to get value of "
813         "VCONFKEY_SETAPPL_DEFAULT_MEM_INSTALL_APPLICATIONS_INT";
814     return BackendInterface::CommandResult::ERROR;
815   }
816   if (vconf_set_int(VCONFKEY_SETAPPL_DEFAULT_MEM_INSTALL_APPLICATIONS_INT,
817       storage) != 0) {
818     LOG(ERROR) << "Failed to set value of "
819         "VCONFKEY_SETAPPL_DEFAULT_MEM_INSTALL_APPLICATIONS_INT";
820     return BackendInterface::CommandResult::ERROR;
821   }
822
823   const char* argv[] = {"", "-i", path.c_str(), "-u", uid_str_.c_str()};
824   BackendInterface::CommandResult result = CallBackend(SIZEOFARRAY(argv), argv);
825
826   if (vconf_set_int(VCONFKEY_SETAPPL_DEFAULT_MEM_INSTALL_APPLICATIONS_INT,
827       default_storage) != 0) {
828     LOG(ERROR) << "Failed to set value of "
829         "VCONFKEY_SETAPPL_DEFAULT_MEM_INSTALL_APPLICATIONS_INT";
830     return BackendInterface::CommandResult::ERROR;
831   }
832
833   return result;
834 }
835
836 BackendInterface::CommandResult BackendInterface::MigrateLegacyExternalImage(
837     const std::string& pkgid,
838     const bf::path& path,
839     const bf::path& legacy_path) const {
840   if (InstallWithStorage(path, StorageType::EXTERNAL) !=
841       BackendInterface::CommandResult::OK) {
842     LOG(ERROR) << "Failed to install application. Cannot perform Migrate";
843     return BackendInterface::CommandResult::ERROR;
844   }
845
846   bf::path ext_mount_path = ci::GetExternalCardPath();
847   if (bf::is_empty(ext_mount_path)) {
848     LOG(ERROR) << "Sdcard not exists!";
849     return BackendInterface::CommandResult::ERROR;
850   }
851   bf::path app2sd_path = ext_mount_path / "app2sd";
852
853   char* image_name = app2ext_usr_getname_image(pkgid.c_str(),
854                      kGlobalUserUid);
855   if (!image_name) {
856     LOG(ERROR) << "Failed to get external image name";
857     return BackendInterface::CommandResult::ERROR;
858   }
859   bf::path org_image = app2sd_path / image_name;
860   free(image_name);
861
862   bs::error_code error;
863   bf::remove(org_image, error);
864   if (error) {
865     LOG(ERROR) << "Failed to remove org image";
866     return BackendInterface::CommandResult::ERROR;
867   }
868
869   bf::path db_path = tzplatform_getenv(TZ_SYS_DB);
870   bf::path app2sd_db = db_path / ".app2sd.db";
871   bf::path app2sd_db_journal = db_path / ".app2sd.db-journal";
872   bf::remove(app2sd_db, error);
873   if (error) {
874     LOG(ERROR) << "Failed to remove app2sd db";
875     return BackendInterface::CommandResult::ERROR;
876   }
877   bf::remove(app2sd_db_journal, error);
878   if (error) {
879     LOG(ERROR) << "Failed to remove app2sd journal db";
880     return BackendInterface::CommandResult::ERROR;
881   }
882
883   bf::path app2sd_migrate_db = legacy_path / kMigrateTestDBName;
884   if (!ci::CopyFile(app2sd_migrate_db, app2sd_db)) {
885     LOG(ERROR) << "Failed to copy test db";
886     return BackendInterface::CommandResult::ERROR;
887   }
888
889   bf::path legacy_src = legacy_path / pkgid;
890   bf::path legacy_dst = app2sd_path / pkgid;
891   if (!ci::CopyFile(legacy_src, legacy_dst)) {
892     LOG(ERROR) << "Failed to copy test image";
893     return BackendInterface::CommandResult::ERROR;
894   }
895   const char* argv[] = {"", "--migrate-extimg", pkgid.c_str(),
896                        "-u", uid_str_.c_str()};
897   return CallBackend(SIZEOFARRAY(argv), argv);
898 }
899
900 BackendInterface::CommandResult BackendInterface::RDSUpdate(
901     const bf::path& path,
902     const std::string& pkgid) const {
903   RequestResult tmp_mode = mode_;
904   RequestResult &original_mode = const_cast<RequestResult&>(mode_);
905   original_mode = RequestResult::NORMAL;
906   if (Install(path) != BackendInterface::CommandResult::OK) {
907     LOG(ERROR) << "Failed to install application. Cannot perform RDS";
908     return BackendInterface::CommandResult::UNKNOWN;
909   }
910   const char* argv[] = {"", "-r", pkgid.c_str(), "-u",
911                         uid_str_.c_str()};
912   original_mode = tmp_mode;
913   return CallBackend(SIZEOFARRAY(argv), argv);
914 }
915
916 BackendInterface::CommandResult BackendInterface::EnablePackage(
917     const std::string& pkgid) const {
918   const char* argv[] = {"", "-A", pkgid.c_str(), "-u", uid_str_.c_str()};
919   return CallBackend(SIZEOFARRAY(argv), argv);
920 }
921
922 BackendInterface::CommandResult BackendInterface::DisablePackage(
923     const std::string& pkgid) const {
924   const char* argv[] = {"", "-D", pkgid.c_str(), "-u", uid_str_.c_str()};
925   return CallBackend(SIZEOFARRAY(argv), argv);
926 }
927
928 BackendInterface::CommandResult BackendInterface::Recover(
929     const bf::path& recovery_file) const {
930   const char* argv[] = {"", "-b", recovery_file.c_str(), "-u",
931       uid_str_.c_str()};
932   return CallBackend(SIZEOFARRAY(argv), argv);
933 }
934
935 BackendInterface::CommandResult BackendInterface::ManifestDirectInstall(
936     const std::string& pkgid) const {
937   const char* argv[] = {"", "-y", pkgid.c_str(), "-u", uid_str_.c_str()};
938   return CallBackend(SIZEOFARRAY(argv), argv);
939 }
940
941 BackendInterface::CommandResult BackendInterface::Uninstall(
942     const std::string& pkgid) const {
943   const char* argv[] = {"", "-d", pkgid.c_str(), "-u", uid_str_.c_str()};
944   return CallBackend(SIZEOFARRAY(argv), argv);
945 }
946
947 BackendInterface::CommandResult BackendInterface::UninstallPreload(
948     const std::string& pkgid) const {
949   const char* argv[] = {"", "-d", pkgid.c_str(), "--preload",
950       "--force-remove"};
951   return CallBackend(SIZEOFARRAY(argv), argv);
952 }
953
954 BackendInterface::CommandResult BackendInterface::InstallSuccess(
955     const bf::path& path) const {
956   RequestResult tmp_mode = mode_;
957   RequestResult &original_mode = const_cast<RequestResult&>(mode_);
958   original_mode = RequestResult::NORMAL;
959   if (Install(path) != BackendInterface::CommandResult::OK) {
960     LOG(ERROR) << "Failed to install application. Cannot update";
961     return BackendInterface::CommandResult::UNKNOWN;
962   }
963   original_mode = tmp_mode;
964   return BackendInterface::CommandResult::OK;
965 }
966
967 BackendInterface::CommandResult BackendInterface::InstallPreloadSuccess(
968     const bf::path& path) const {
969   RequestResult tmp_mode = mode_;
970   RequestResult &original_mode = const_cast<RequestResult&>(mode_);
971   original_mode = RequestResult::NORMAL;
972   if (InstallPreload(path) != BackendInterface::CommandResult::OK) {
973     LOG(ERROR) << "Failed to install application. Cannot update";
974     return BackendInterface::CommandResult::UNKNOWN;
975   }
976   original_mode = tmp_mode;
977   return BackendInterface::CommandResult::OK;
978 }
979
980 BackendInterface::CommandResult BackendInterface::MountInstall(
981     const bf::path& path) const {
982   const char* argv[] = {"", "-w", path.c_str(), "-u", uid_str_.c_str()};
983   return CallBackend(SIZEOFARRAY(argv), argv);
984 }
985
986 BackendInterface::CommandResult BackendInterface::MountInstallSuccess(
987     const bf::path& path) const {
988   RequestResult tmp_mode = mode_;
989   RequestResult &original_mode = const_cast<RequestResult&>(mode_);
990   original_mode = RequestResult::NORMAL;
991   if (MountInstall(path) != BackendInterface::CommandResult::OK) {
992     LOG(ERROR) << "Failed to mount-install application. Cannot mount-update";
993     return BackendInterface::CommandResult::UNKNOWN;
994   }
995   original_mode = tmp_mode;
996   return BackendInterface::CommandResult::OK;
997 }
998
999 static boost::filesystem::path GetTrashPath(
1000     const boost::filesystem::path& path) {
1001   return path.string() + ".trash";
1002 }
1003
1004 BackendInterface::SubProcessResult BackendInterface::RunSubprocess(
1005     std::vector<std::string> args) const {
1006   args.push_back("-remove_plugin_steps");
1007   ci::Subprocess backend = CreateSubprocess();
1008   backend.RunWithArgs(args);
1009   int status = backend.Wait();
1010   if (WIFEXITED(status)) {
1011     if (WEXITSTATUS(status) == 0)
1012       return BackendInterface::SubProcessResult::SUCCESS;
1013     else
1014       return BackendInterface::SubProcessResult::FAIL;
1015   }
1016   return BackendInterface::SubProcessResult::UnKnown;
1017 }
1018
1019 BackendInterface::SubProcessResult BackendInterface::RunSubprocessAndKill(
1020     std::vector<std::string> args, useconds_t delay) const {
1021   args.push_back("-remove_plugin_steps");
1022   ci::Subprocess backend = CreateSubprocess();
1023   backend.RunWithArgs(args);
1024   usleep(delay);
1025   backend.Kill();
1026   int status = backend.Wait();
1027   if (WIFEXITED(status)) {
1028     if (WEXITSTATUS(status) == 0)
1029       return BackendInterface::SubProcessResult::SUCCESS;
1030     else
1031       return BackendInterface::SubProcessResult::FAIL;
1032   } else {
1033     if (WTERMSIG(status) == SIGKILL)
1034       return BackendInterface::SubProcessResult::KILLED;
1035     else
1036       return BackendInterface::SubProcessResult::UnKnown;
1037   }
1038 }
1039
1040 BackendInterface::SubProcessResult BackendInterface::InstallWithSubprocess(
1041     const bf::path& path) const {
1042   std::vector<std::string> args =
1043       { "-i", path.string(), "-u", uid_str_ };
1044   return RunSubprocess(args);
1045 }
1046
1047 BackendInterface::SubProcessResult BackendInterface::MountInstallWithSubprocess(
1048     const bf::path& path) const {
1049   std::vector<std::string> args =
1050       { "-w", path.string(), "-u", uid_str_ };
1051   return RunSubprocess(args);
1052 }
1053
1054 BackendInterface::SubProcessResult BackendInterface::RecoverWithSubprocess(
1055     const bf::path& path) const {
1056   std::vector<std::string> args =
1057       { "-b", path.string(), "-u", uid_str_ };
1058   return RunSubprocess(args);
1059 }
1060
1061 BackendInterface::SubProcessResult BackendInterface::UninstallWithSubprocess(
1062     const std::string& pkgid) const {
1063   std::vector<std::string> args = { "-d", pkgid, "-u", uid_str_ };
1064   return RunSubprocess(args);
1065 }
1066
1067 BackendInterface::SubProcessResult
1068 BackendInterface::InstallPreloadWithSubprocess(
1069     const boost::filesystem::path& path) const {
1070   std::vector<std::string> args = { "", "-i", path.string(), "--preload" };
1071   return RunSubprocess(args);
1072 }
1073
1074 BackendInterface::SubProcessResult
1075     BackendInterface::InstallWithSubprocessAndKill(
1076         const bf::path& path, useconds_t delay) const {
1077   std::vector<std::string> args =
1078       { "-i", path.string(), "-u", uid_str_ };
1079   return RunSubprocessAndKill(args, delay);
1080 }
1081
1082 BackendInterface::SubProcessResult
1083     BackendInterface::MountInstallWithSubprocessAndKill(
1084         const bf::path& path, useconds_t delay) const {
1085   std::vector<std::string> args =
1086       { "-w", path.string(), "-u", uid_str_ };
1087   return RunSubprocessAndKill(args, delay);
1088 }
1089
1090 BackendInterface::SubProcessResult
1091     BackendInterface::UninstallWithSubprocessAndKill(
1092         const std::string& pkgid, useconds_t delay) const {
1093   std::vector<std::string> args =
1094       { "-d", pkgid, "-u", uid_str_ };
1095   return RunSubprocessAndKill(args, delay);
1096 }
1097
1098 BackendInterface::SubProcessResult BackendInterface::InstallPkgsWithSubprocess(
1099     const std::vector<bf::path>& paths) const {
1100   std::vector<std::string> args;
1101   args.emplace_back("-i");
1102   for (const bf::path& p : paths)
1103     args.emplace_back(p.string());
1104   args.emplace_back("-u");
1105   args.emplace_back(uid_str_);
1106   return RunSubprocess(args);
1107 }
1108
1109 BackendInterface::SubProcessResult
1110     BackendInterface::MountInstallPkgsWithSubprocess(
1111     const std::vector<bf::path>& paths) const {
1112   std::vector<std::string> args;
1113   args.emplace_back("-w");
1114   for (const bf::path& p : paths)
1115     args.emplace_back(p.string());
1116   args.emplace_back("-u");
1117   args.emplace_back(uid_str_);
1118   return RunSubprocess(args);
1119 }
1120
1121 BackendInterface::SubProcessResult BackendInterface::RecoverPkgsWithSubprocess(
1122     const std::vector<bf::path>& paths) const {
1123   std::vector<std::string> args;
1124   args.emplace_back("-b");
1125   for (const bf::path& p : paths)
1126     args.emplace_back(p.string());
1127   args.emplace_back("-u");
1128   args.emplace_back(uid_str_);
1129   return RunSubprocess(args);
1130 }
1131
1132 BackendInterface::SubProcessResult
1133     BackendInterface::UninstallPkgsWithSubprocess(
1134         const std::vector<std::string>& pkgids) const {
1135   std::vector<std::string> args;
1136   args.emplace_back("-d");
1137   args.insert(args.end(), pkgids.begin(), pkgids.end());
1138   args.emplace_back("-u");
1139   args.emplace_back(uid_str_);
1140   return RunSubprocess(args);
1141 }
1142
1143 BackendInterface::SubProcessResult
1144     BackendInterface::InstallPkgsWithSubprocessAndKill(
1145         const std::vector<bf::path>& paths, useconds_t delay) const {
1146   std::vector<std::string> args;
1147   args.emplace_back("-i");
1148   for (const bf::path& p : paths)
1149     args.emplace_back(p.string());
1150   args.emplace_back("-u");
1151   args.emplace_back(uid_str_);
1152   return RunSubprocessAndKill(args, delay);
1153 }
1154
1155 BackendInterface::SubProcessResult
1156     BackendInterface::MountInstallPkgsWithSubprocessAndKill(
1157         const std::vector<bf::path>& paths, useconds_t delay) const {
1158   std::vector<std::string> args;
1159   args.emplace_back("-w");
1160   for (const bf::path& p : paths)
1161     args.emplace_back(p.string());
1162   args.emplace_back("-u");
1163   args.emplace_back(uid_str_);
1164   return RunSubprocessAndKill(args, delay);
1165 }
1166
1167 bool CopySmackAccess(const boost::filesystem::path& src,
1168                      const boost::filesystem::path& dst) {
1169   if (!bf::exists(src) && !bf::is_symlink(src)) {
1170     LOG(ERROR) << "Failed to copy smack access label";
1171     return false;
1172   }
1173   int ret;
1174   char* access_label = nullptr;
1175   ret = smack_lgetlabel(src.c_str(), &access_label, SMACK_LABEL_ACCESS);
1176   if (ret < 0) {
1177     LOG(ERROR) << "get access label from [" << src << "] fail";
1178     return false;
1179   }
1180   if (!access_label)
1181     return true;
1182   ret = smack_lsetlabel(dst.c_str(), access_label, SMACK_LABEL_ACCESS);
1183   free(access_label);
1184   if (ret < 0) {
1185     LOG(ERROR) << "set access label to [" << dst << "] fail";
1186     return false;
1187   }
1188   return true;
1189 }
1190
1191 bool CopySmackExec(const boost::filesystem::path& src,
1192                    const boost::filesystem::path& dst) {
1193   if (!bf::exists(src) && !bf::is_symlink(src)) {
1194     LOG(ERROR) << "Failed to copy smack exec label";
1195     return false;
1196   }
1197   int ret;
1198   char *exec_label = nullptr;
1199   ret = smack_lgetlabel(src.c_str(), &exec_label, SMACK_LABEL_EXEC);
1200   if (ret < 0) {
1201     LOG(ERROR) << "get exec label from [" << src << "] fail";
1202     return false;
1203   }
1204   if (!exec_label)
1205     return true;
1206   ret = smack_lsetlabel(dst.c_str(), exec_label, SMACK_LABEL_EXEC);
1207   free(exec_label);
1208   if (ret < 0) {
1209     LOG(ERROR) << "set exec label to [" << dst << "] fail";
1210     return false;
1211   }
1212   return true;
1213 }
1214
1215 bool CopySmackMmap(const boost::filesystem::path& src,
1216                    const boost::filesystem::path& dst) {
1217   if (!bf::exists(src) && !bf::is_symlink(src)) {
1218     LOG(ERROR) << "Failed to copy smack mmap label";
1219     return false;
1220   }
1221   int ret;
1222   char *mmap_label = nullptr;
1223   ret = smack_lgetlabel(src.c_str(), &mmap_label, SMACK_LABEL_MMAP);
1224   if (ret < 0) {
1225     LOG(ERROR) << "get mmap label from [" << src << "] fail";
1226     return false;
1227   }
1228   if (!mmap_label)
1229     return true;
1230   ret = smack_lsetlabel(dst.c_str(), mmap_label, SMACK_LABEL_MMAP);
1231   free(mmap_label);
1232   if (ret < 0) {
1233     LOG(ERROR) << "set mmap label to [" << dst << "] fail";
1234     return false;
1235   }
1236   return true;
1237 }
1238
1239 bool CopySmackTransmute(const boost::filesystem::path& src,
1240                         const boost::filesystem::path& dst) {
1241   if (!bf::exists(src)) {
1242     LOG(ERROR) << "Failed to copy smack tranmute label";
1243     return false;
1244   }
1245   int ret;
1246   char *transmute_label = nullptr;
1247   ret = smack_lgetlabel(src.c_str(), &transmute_label, SMACK_LABEL_TRANSMUTE);
1248   if (ret < 0) {
1249     LOG(ERROR) << "get access label from [" << src << "] fail";
1250     return false;
1251   }
1252   if (!transmute_label) {
1253     ret = smack_lsetlabel(dst.c_str(), "0", SMACK_LABEL_TRANSMUTE);
1254   } else {
1255     if (strcmp(transmute_label, "TRUE") == 0)
1256       ret = smack_lsetlabel(dst.c_str(), "1", SMACK_LABEL_TRANSMUTE);
1257     else
1258       ret = smack_lsetlabel(dst.c_str(), "0", SMACK_LABEL_TRANSMUTE);
1259     free(transmute_label);
1260     if (ret < 0) {
1261       LOG(ERROR) << "set access label to [" << dst << "] fail";
1262       return false;
1263     }
1264   }
1265
1266   return true;
1267 }
1268
1269 bool CopySmackLabels(const boost::filesystem::path& src,
1270                      const boost::filesystem::path& dst) {
1271   if (!CopySmackAccess(src, dst))
1272     return false;
1273   if (!CopySmackExec(src, dst))
1274     return false;
1275   if (!CopySmackMmap(src, dst))
1276     return false;
1277   if (!bf::is_symlink(src) && bf::is_directory(src)) {
1278     if (!CopySmackTransmute(src, dst))
1279       return false;
1280   }
1281   return true;
1282 }
1283
1284 bool CopyAndRemoveWithSmack(const bf::path& src, const bf::path& dst) {
1285   bs::error_code error;
1286   if (bf::exists(dst)) {
1287     try {
1288       bf::remove_all(dst, error);
1289     } catch (...) {
1290       std::cout << "Exception occurred during remove [" << dst.string()
1291                 << "], and skip this file"<< std::endl;
1292     }
1293     if (error) {
1294       if (!bf::is_directory(dst)) {
1295         LOG(ERROR) << "remove_all fail";
1296         return false;
1297       }
1298     }
1299   }
1300   try {
1301     if (bf::is_symlink(src)) {
1302       bf::copy_symlink(src, dst, error);
1303       if (error) {
1304         LOG(ERROR) << "Failed to copy symlink: " << src << ", "
1305                    << error.message();
1306         return false;
1307       }
1308       if (!CopySmackLabels(src, dst)) {
1309         LOG(ERROR) << "copy smack label from [" << src.string()
1310                    << "] to [" << dst.string() << "] fail";
1311         return false;
1312       }
1313     } else if (bf::is_directory(src)) {
1314       if (!bf::exists(dst)) {
1315         bf::create_directories(dst, error);
1316         if (error) {
1317           LOG(ERROR) << "create directories fail";
1318           return false;
1319         }
1320         ci::CopyOwnershipAndPermissions(src, dst);
1321         if (!CopySmackLabels(src, dst)) {
1322           LOG(ERROR) << "copy smack label from [" << src.string()
1323                      << "] to [" << dst.string() << "] fail";
1324           return false;
1325         }
1326       }
1327       bool success = true;
1328       for (bf::directory_iterator file(src);
1329           file != bf::directory_iterator();
1330           ++file) {
1331         bf::path current(file->path());
1332         bf::path target = dst / current.filename();
1333         success &= CopyAndRemoveWithSmack(current, target);
1334       }
1335       bf::remove_all(src);
1336       if (!success)
1337         return false;
1338     } else {
1339       bf::copy_file(src, dst);
1340       ci::CopyOwnershipAndPermissions(src, dst);
1341       if (!CopySmackLabels(src, dst)) {
1342         LOG(ERROR) << "copy smack label from [" << src.string()
1343                    << "] to [" << dst.string() << "] fail";
1344         return false;
1345       }
1346       bf::remove_all(src);
1347     }
1348   } catch (...) {
1349     std::cout << "Exception occurred during copy [" << src.string()
1350               << "], and skip this file"<< std::endl;
1351     return true;
1352   }
1353
1354   return true;
1355 }
1356
1357 bool BackupPathCopyAndRemove(const bf::path& path) {
1358   if (!bf::exists(path))
1359     return true;
1360
1361   bf::path backup_path = path.string() + ".bck";
1362   std::cout << "Backup path: " << path << " to " << backup_path << std::endl;
1363   if (!CopyAndRemoveWithSmack(path, backup_path)) {
1364     LOG(ERROR) << "Failed to setup test environment. Does some previous"
1365                << " test crashed? Path: "
1366                << backup_path << " should not exist.";
1367     return false;
1368   }
1369   return true;
1370 }
1371
1372 bool BackupPath(const bf::path& path) {
1373   bf::path trash_path = GetTrashPath(path);
1374   if (bf::exists(trash_path)) {
1375     LOG(ERROR) << trash_path << " exists. Please remove "
1376                << trash_path << " manually!";
1377     return false;
1378   }
1379   bf::path backup_path = path.string() + ".bck";
1380   std::cout << "Backup path: " << path << " to " << backup_path << std::endl;
1381   bs::error_code error;
1382   bf::remove_all(backup_path, error);
1383   if (error)
1384     LOG(ERROR) << "Remove failed: " << backup_path
1385                << " (" << error.message() << ")";
1386   if (bf::exists(path)) {
1387     bf::rename(path, backup_path, error);
1388     if (error) {
1389       LOG(ERROR) << "Failed to setup test environment. Does some previous"
1390                  << " test crashed? Path: "
1391                  << backup_path << " should not exist.";
1392       return false;
1393     }
1394     assert(!error);
1395     if (bf::is_directory(backup_path))
1396       bf::create_directory(path);
1397   }
1398   return true;
1399 }
1400
1401 void CreateDatabase() {
1402   pkgmgr_parser_create_and_initialize_db(kGlobalUserUid);
1403   pkgmgr_parser_create_and_initialize_db(getuid());
1404 }
1405
1406 bool RestorePathCopyAndRemove(const bf::path& path) {
1407   bf::path backup_path = path.string() + ".bck";
1408   if (!bf::exists(backup_path))
1409     return true;
1410
1411   std::cout << "Restore path: " << path << " from " << backup_path << std::endl;
1412   if (!CopyAndRemoveWithSmack(backup_path, path)) {
1413     LOG(ERROR) << "Failed to restore backup path: " << backup_path;
1414     return false;
1415   }
1416   return true;
1417 }
1418
1419 bool RestorePath(const bf::path& path) {
1420   bf::path backup_path = path.string() + ".bck";
1421   std::cout << "Restore path: " << path << " from " << backup_path << std::endl;
1422   bs::error_code error;
1423   bf::remove_all(path, error);
1424   if (error) {
1425     bf::path trash_path = GetTrashPath(path);
1426     LOG(ERROR) << "Remove failed: " << path << " (" << error.message() << ")";
1427     std::cout << "Moving " << path << " to " << trash_path << std::endl;
1428     bf::rename(path, trash_path, error);
1429     if (error)
1430       LOG(ERROR) << "Failed to move " << path << " to " << trash_path
1431                  << " (" << error.message() << ")";
1432     else
1433       LOG(ERROR) << trash_path << " should be removed manually!";
1434   }
1435   if (bf::exists(backup_path)) {
1436     bf::rename(backup_path, path, error);
1437     if (error) {
1438       LOG(ERROR) << "Failed to restore backup path: " << backup_path
1439                  << " (" << error.message() << ")";
1440       return false;
1441     }
1442   }
1443   return true;
1444 }
1445
1446 std::vector<bf::path> SetupBackupDirectories(uid_t test_uid) {
1447   std::vector<bf::path> entries;
1448   bf::path db_dir = bf::path(tzplatform_getenv(TZ_SYS_DB));
1449   if (test_uid != kGlobalUserUid)
1450     db_dir = db_dir / "user" / std::to_string(test_uid);
1451   for (auto e : kDBEntries) {
1452     bf::path path = db_dir / e;
1453     entries.emplace_back(path);
1454   }
1455
1456   if (getuid() == 0) {
1457     entries.emplace_back(kPreloadApps);
1458     entries.emplace_back(kPreloadManifestDir);
1459     entries.emplace_back(kPreloadIcons);
1460   }
1461
1462   if (test_uid == kGlobalUserUid) {
1463     entries.emplace_back(kSkelDir);
1464     entries.emplace_back(kGlobalManifestDir);
1465     ci::UserList list = ci::GetUserList();
1466     for (auto l : list) {
1467       bf::path apps = std::get<2>(l) / "apps_rw";
1468       entries.emplace_back(apps);
1469     }
1470   } else {
1471     tzplatform_set_user(test_uid);
1472     bf::path approot = tzplatform_getenv(TZ_USER_APPROOT);
1473     tzplatform_reset_user();
1474     entries.emplace_back(approot);
1475   }
1476
1477   bf::path apps_rw = ci::GetRootAppPath(false, test_uid);
1478   entries.emplace_back(apps_rw);
1479   entries.emplace_back(kSdkDirectory);
1480
1481   return entries;
1482 }
1483
1484 void UninstallAllAppsInDirectory(bf::path dir, bool is_preload,
1485     BackendInterface* backend) {
1486   if (bf::exists(dir)) {
1487     for (auto& dir_entry : boost::make_iterator_range(
1488         bf::directory_iterator(dir), bf::directory_iterator())) {
1489       if (dir_entry.path().string().find("smoke") != std::string::npos &&
1490           bf::is_directory(dir_entry)) {
1491         std::string package = dir_entry.path().filename().string();
1492         std::regex pkg_regex("smoke[a-zA-Z0-9]{5,}");
1493         if (std::regex_match(package, pkg_regex)) {
1494           BackendInterface::CommandResult result =
1495               BackendInterface::CommandResult::OK;
1496           if (is_preload)
1497             result = backend->UninstallPreload(
1498                 dir_entry.path().filename().string());
1499           else
1500             result = backend->Uninstall(
1501                 dir_entry.path().filename().string());
1502           if (result != BackendInterface::CommandResult::OK) {
1503             LOG(ERROR) << "Cannot uninstall smoke test app: "
1504                 << dir_entry.path().filename().string();
1505           }
1506         }
1507       }
1508     }
1509   }
1510 }
1511
1512 void UninstallAllSmokeApps(ci::RequestMode request_mode, uid_t test_uid,
1513     BackendInterface *backend) {
1514   std::cout << "Uninstalling all smoke apps" << std::endl;
1515   bf::path apps_rw = ci::GetRootAppPath(false, test_uid);
1516   UninstallAllAppsInDirectory(apps_rw, false, backend);
1517   if (getuid() == 0 && request_mode == ci::RequestMode::GLOBAL) {
1518     bf::path root_path = kPreloadApps;
1519     UninstallAllAppsInDirectory(root_path, true, backend);
1520   }
1521 }
1522
1523 int GetAppInstalledTime(const char* appid, uid_t uid) {
1524   int ret = 0;
1525   int installed_time = 0;
1526   pkgmgrinfo_appinfo_h handle = NULL;
1527   ret = pkgmgrinfo_appinfo_get_usr_appinfo(appid, uid, &handle);
1528   if (ret != PMINFO_R_OK)
1529     return -1;
1530   ret = pkgmgrinfo_appinfo_get_installed_time(handle, &installed_time);
1531   if (ret != PMINFO_R_OK) {
1532     pkgmgrinfo_appinfo_destroy_appinfo(handle);
1533     return -1;
1534   }
1535   pkgmgrinfo_appinfo_destroy_appinfo(handle);
1536   return installed_time;
1537 }
1538
1539 }  // namespace smoke_test