Change temporary storage path
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_file_manipulation.cpp
1 /*
2  * Copyright (c) 2011 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  * @file    task_db_update.cpp
18  * @author  Lukasz Wrzosek(l.wrzosek@samsung.com)
19  * @version 1.0
20  * @brief   Implementation file for installer task database updating
21  */
22 #include <unistd.h>
23 #include <sys/stat.h>
24 #include <dirent.h>
25 #include <widget_install/task_file_manipulation.h>
26 #include <widget_install/job_widget_install.h>
27 #include <widget_install/widget_install_errors.h>
28 #include <widget_install/widget_install_context.h>
29 #include <widget_install/directory_api.h>
30 #include <dpl/utils/wrt_utility.h>
31 #include <dpl/foreach.h>
32 #include <dpl/log/log.h>
33 #include <dpl/assert.h>
34 #include <dpl/errno_string.h>
35 #include <dpl/utils/folder_size.h>
36 #include <dpl/wrt-dao-ro/global_config.h>
37 #include <string>
38 #include <fstream>
39 #include <widget_install_to_external.h>
40
41 #define WEBAPP_DEFAULT_UID  5000
42 #define WEBAPP_DEFAULT_GID  5000
43
44 namespace {
45 const mode_t PRIVATE_STORAGE_MODE = 0700;
46 const mode_t SHARE_MODE = 0705;
47 }
48
49 using namespace WrtDB;
50
51 namespace {
52 const char* GLIST_RES_DIR = "res";
53
54 bool _FolderCopy(std::string source, std::string dest)
55 {
56     DIR* dir = opendir(source.c_str());
57     if (NULL == dir) {
58         return false;
59     }
60
61     struct dirent dEntry;
62     struct dirent *dEntryResult;
63     int return_code;
64
65     do {
66         struct stat statInfo;
67         return_code = readdir_r(dir, &dEntry, &dEntryResult);
68         if (dEntryResult != NULL && return_code == 0) {
69             std::string fileName = dEntry.d_name;
70             std::string fullName = source + "/" + fileName;
71
72             if (stat(fullName.c_str(), &statInfo) != 0) {
73                 closedir(dir);
74                 return false;
75             }
76
77             if (S_ISDIR(statInfo.st_mode)) {
78                 if (("." == fileName) || (".." == fileName)) {
79                     continue;
80                 }
81                 std::string destFolder = dest + "/" + fileName;
82                 WrtUtilMakeDir(destFolder);
83
84                 if (!_FolderCopy(fullName, destFolder)) {
85                     closedir(dir);
86                     return false;
87                 }
88             }
89
90             std::string destFile = dest + "/" + fileName;
91             std::ifstream infile(fullName);
92             std::ofstream outfile(destFile);
93             outfile << infile.rdbuf();
94             outfile.close();
95             infile.close();
96         }
97     } while (dEntryResult != NULL && return_code == 0);
98     closedir(dir);
99     return true;
100 }
101
102 void changeOwnerForDirectory(std::string storagePath) {
103     if (euidaccess(storagePath.c_str(), F_OK) != 0) {
104         if (!WrtUtilMakeDir(storagePath, PRIVATE_STORAGE_MODE)) {
105             LogError("Failed to create directory for private storage");
106             ThrowMsg(Jobs::WidgetInstall::Exceptions::FileOperationFailed,
107                      "Failed to create directory for private storage");
108         }
109         // '5000' is default uid, gid for applications.
110         // So installed applications should be launched as process of uid
111         // '5000'.
112         // the process can access private directory 'data' of itself.
113         if (chown(storagePath.c_str(),
114                   WEBAPP_DEFAULT_UID,
115                   WEBAPP_DEFAULT_GID) != 0)
116         {
117             ThrowMsg(Jobs::WidgetInstall::Exceptions::FileOperationFailed,
118                      "Chown to invaild user");
119         }
120     } else if (euidaccess(storagePath.c_str(), W_OK | R_OK | X_OK) == 0) {
121         LogInfo("Private storage already exists.");
122         // Even if private directory already is created, private dircetory
123         // should change owner.
124         if (chown(storagePath.c_str(),
125                   WEBAPP_DEFAULT_UID,
126                   WEBAPP_DEFAULT_GID) != 0)
127         {
128             ThrowMsg(Jobs::WidgetInstall::Exceptions::FileOperationFailed,
129                      "Chown to invaild user");
130         }
131         if (chmod(storagePath.c_str(), PRIVATE_STORAGE_MODE) != 0) {
132             ThrowMsg(Jobs::WidgetInstall::Exceptions::FileOperationFailed,
133                      "chmod to 0700");
134         }
135     } else {
136         ThrowMsg(Jobs::WidgetInstall::Exceptions::FileOperationFailed,
137                  "No access to private storage.");
138     }
139 }
140 }
141
142 namespace Jobs {
143 namespace WidgetInstall {
144 TaskFileManipulation::TaskFileManipulation(InstallerContext& context) :
145     DPL::TaskDecl<TaskFileManipulation>(this),
146     m_context(context),
147     m_extHandle(NULL)
148 {
149     if (INSTALL_LOCATION_TYPE_EXTERNAL !=
150             m_context.locationType)
151     {
152         AddStep(&TaskFileManipulation::StepCreateDirs);
153         if (m_context.widgetConfig.packagingType !=
154             WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
155         {
156             AddStep(&TaskFileManipulation::StepRenamePath);
157             AddAbortStep(&TaskFileManipulation::StepAbortRenamePath);
158         }
159         AddStep(&TaskFileManipulation::StepCreatePrivateStorageDir);
160         AddStep(&TaskFileManipulation::StepCreateSharedFolder);
161         AddStep(&TaskFileManipulation::StepLinkForPreload);
162
163     } else {
164         AddStep(&TaskFileManipulation::StepPrepareExternalDir);
165         AddStep(&TaskFileManipulation::StepInstallToExternal);
166         AddStep(&TaskFileManipulation::StepCreatePrivateStorageDir);
167         AddStep(&TaskFileManipulation::StepCreateSharedFolder);
168
169         AddAbortStep(&TaskFileManipulation::StepAbortCreateExternalDir);
170     }
171 }
172
173 void TaskFileManipulation::StepCreateDirs()
174 {
175     std::string widgetPath;
176
177     widgetPath = m_context.locations->getPackageInstallationDir();
178
179     std::string widgetBinPath = m_context.locations->getBinaryDir();
180     std::string widgetSrcPath = m_context.locations->getSourceDir();
181
182     WrtUtilMakeDir(widgetPath);
183
184     // If package type is widget with osp service, we don't need to make bin
185     // and src directory
186     if (m_context.widgetConfig.packagingType == PKG_TYPE_HYBRID_WEB_APP) {
187         LogDebug("Doesn't need to create resource directory");
188     } else {
189         LogDebug("Create resource directory");
190         WrtUtilMakeDir(widgetBinPath);
191         WrtUtilMakeDir(widgetSrcPath);
192         if (m_context.mode.installTime == InstallMode::InstallTime::PRELOAD) {
193             std::string userWidgetDir = m_context.locations->getUserDataRootDir();
194             WrtUtilMakeDir(userWidgetDir);
195         }
196     }
197
198     m_context.job->UpdateProgress(
199         InstallerContext::INSTALL_DIR_CREATE,
200         "Widget Directory Created");
201 }
202
203 void TaskFileManipulation::StepCreatePrivateStorageDir()
204 {
205     std::string storagePath = m_context.locations->getPrivateStorageDir();
206     LogDebug("Create private storage directory : " <<
207             m_context.locations->getPrivateStorageDir());
208
209     if (m_context.isUpdateMode) { //update
210         std::string backData = m_context.locations->getBackupPrivateDir();
211         LogDebug("copy private storage " << backData << " to " << storagePath);
212         WrtUtilMakeDir(storagePath);
213         if (!DirectoryApi::DirectoryCopy(backData, storagePath)) {
214             LogError("Failed to rename " << backData << " to " << storagePath);
215             ThrowMsg(Exceptions::BackupFailed,
216                     "Error occurs copy private strage files");
217         }
218     }
219     changeOwnerForDirectory(storagePath);
220
221     std::string tempStoragePath = m_context.locations->getPrivateTempStorageDir();
222     LogDebug("Create temp private storage directory : " << tempStoragePath);
223     changeOwnerForDirectory(tempStoragePath);
224 }
225
226 void TaskFileManipulation::StepRenamePath()
227 {
228     std::string instDir;
229
230     if (m_context.widgetConfig.packagingType == PKG_TYPE_HYBRID_WEB_APP) {
231         instDir = m_context.locations->getPackageInstallationDir();
232     } else {
233         instDir = m_context.locations->getSourceDir();
234     }
235
236     LogDebug("Copy file from temp directory to " << instDir);
237     if (!WrtUtilRemove(instDir)) {
238         ThrowMsg(Exceptions::RemovingFolderFailure,
239                  "Error occurs during removing existing folder");
240     }
241
242     if (!(rename(m_context.locations->getTemporaryPackageDir().c_str(),
243                  instDir.c_str()) == 0))
244     {
245         ThrowMsg(Exceptions::FileOperationFailed,
246                  "Error occurs during renaming widget folder");
247     }
248     m_context.job->UpdateProgress(
249         InstallerContext::INSTALL_RENAME_PATH,
250         "Widget Rename path Finished");
251 }
252
253 void TaskFileManipulation::StepLinkForPreload()
254 {
255     if (m_context.mode.rootPath == InstallMode::RootPath::RO) {
256         std::string srcDir = m_context.locations->getUserDataRootDir() +
257             WrtDB::GlobalConfig::GetWidgetSrcPath();
258
259         if (0 != access(srcDir.c_str(), F_OK)) {
260             LogDebug("Make symbolic name for preaload app" <<
261                     m_context.locations->getSourceDir() << " to " << srcDir);
262             std::string resDir = m_context.locations->getUserDataRootDir() +
263                 "/res";
264
265             WrtUtilMakeDir(resDir);
266             if (symlink(m_context.locations->getSourceDir().c_str(), srcDir.c_str()) != 0)
267             {
268                 int error = errno;
269                 if (error)
270                     LogPedantic("Failed to make a symbolic name for a file "
271                             << "[" <<  DPL::GetErrnoString(error) << "]");
272                 ThrowMsg(Exceptions::FileOperationFailed,
273                         "Symbolic link creating is not done.");
274             }
275         }
276
277         /* link for data directory */
278         std::string storagePath = m_context.locations->getPrivateStorageDir();
279         std::string dataDir = m_context.locations->getPackageInstallationDir() +
280             "/" + WrtDB::GlobalConfig::GetWidgetPrivateStoragePath();
281         if (0 != access(dataDir.c_str(), F_OK)) {
282             LogDebug("Make symbolic name for preaload app " <<
283                     storagePath << " to " << dataDir);
284
285             if (symlink(storagePath.c_str(), dataDir.c_str()) != 0)
286             {
287                 int error = errno;
288                 if (error)
289                     LogPedantic("Failed to make a symbolic name for a file "
290                             << "[" <<  DPL::GetErrnoString(error) << "]");
291                 ThrowMsg(Exceptions::FileOperationFailed,
292                         "Symbolic link creating is not done.");
293             }
294             changeOwnerForDirectory(dataDir);
295         }
296
297         if (m_context.widgetConfig.packagingType != PKG_TYPE_HYBRID_WEB_APP) {
298             std::string widgetBinPath = m_context.locations->getBinaryDir();
299             std::string userBinPath = m_context.locations->getUserBinaryDir();
300             LogDebug("Make symbolic link for preload app " << widgetBinPath <<
301                     " to " << userBinPath);
302             if (symlink(widgetBinPath.c_str(), userBinPath.c_str()) != 0)
303             {
304                 int error = errno;
305                 if (error)
306                     LogPedantic("Failed to make a symbolic name for a file "
307                             << "[" <<  DPL::GetErrnoString(error) << "]");
308                 ThrowMsg(Exceptions::FileOperationFailed,
309                         "Symbolic link creating is not done.");
310             }
311
312         }
313     }
314 }
315
316 void TaskFileManipulation::StepAbortRenamePath()
317 {
318     LogDebug("[Rename Widget Path] Aborting.... (Rename path)");
319     std::string widgetPath;
320     if (m_context.widgetConfig.packagingType != PKG_TYPE_HYBRID_WEB_APP) {
321         widgetPath = m_context.locations->getPackageInstallationDir();
322         if (!WrtUtilRemove(widgetPath)) {
323             ThrowMsg(Exceptions::RemovingFolderFailure,
324                      "Error occurs during removing existing folder");
325         }
326         // Remove user data directory if preload web app.
327         std::string userData = m_context.locations->getUserDataRootDir();
328         if (0 == access(userData.c_str(), F_OK)) {
329             if (!WrtUtilRemove(userData)) {
330                 ThrowMsg(Exceptions::RemovingFolderFailure,
331                          "Error occurs during removing user data directory");
332             }
333         }
334
335     }
336     LogDebug("Rename widget path sucessful!");
337 }
338
339 void TaskFileManipulation::StepPrepareExternalDir()
340 {
341     LogDebug("Step prepare to install in exernal directory");
342     Try {
343         std::string pkgid =
344             DPL::ToUTF8String(m_context.widgetConfig.tzPkgid);
345
346         WidgetInstallToExtSingleton::Instance().initialize(pkgid);
347
348         size_t totalSize =
349             Utils::getFolderSize(m_context.locations->getTemporaryPackageDir());
350
351         int folderSize = (int)(totalSize / (1024 * 1024)) + 1;
352
353         GList *list = NULL;
354         app2ext_dir_details* dirDetail = NULL;
355
356         dirDetail = (app2ext_dir_details*) calloc(1,
357                 sizeof(
358                     app2ext_dir_details));
359         if (NULL == dirDetail) {
360             ThrowMsg(Exceptions::ErrorExternalInstallingFailure,
361                     "error in app2ext");
362         }
363         dirDetail->name = strdup(GLIST_RES_DIR);
364         dirDetail->type = APP2EXT_DIR_RO;
365         list = g_list_append(list, dirDetail);
366
367         if (m_context.isUpdateMode) {
368             WidgetInstallToExtSingleton::Instance().preUpgrade(list,
369                                                                folderSize);
370         } else {
371             WidgetInstallToExtSingleton::Instance().preInstallation(list,
372                                                                     folderSize);
373         }
374         free(dirDetail);
375         g_list_free(list);
376
377         /* make bin directory */
378         std::string widgetBinPath = m_context.locations->getBinaryDir();
379         WrtUtilMakeDir(widgetBinPath);
380     }
381     Catch(WidgetInstallToExt::Exception::ErrorInstallToExt)
382     {
383         ReThrowMsg(Exceptions::ErrorExternalInstallingFailure,
384                    "Error during \
385                 create external folder ");
386     }
387 }
388
389 void TaskFileManipulation::StepInstallToExternal()
390 {
391     LogDebug("StepInstallExternal");
392     if (!WrtUtilMakeDir(m_context.locations->getSourceDir())) {
393         ThrowMsg(Exceptions::ErrorExternalInstallingFailure,
394                  "To make src \
395                 directory failed");
396     }
397
398     LogDebug("Resource move to external storage " <<
399              m_context.locations->getSourceDir());
400     if (!_FolderCopy(m_context.locations->getTemporaryPackageDir(),
401                      m_context.locations->getSourceDir()))
402     {
403         ThrowMsg(Exceptions::ErrorExternalInstallingFailure,
404                  "Error occurs during renaming widget folder");
405     }
406 }
407
408 void TaskFileManipulation::StepAbortCreateExternalDir()
409 {
410     LogError("Abort StepAbortCreateExternalDir");
411     if (m_context.isUpdateMode) {
412         WidgetInstallToExtSingleton::Instance().postUpgrade(false);
413     } else {
414         WidgetInstallToExtSingleton::Instance().postInstallation(false);
415     }
416     WidgetInstallToExtSingleton::Instance().deinitialize();
417 }
418
419 void TaskFileManipulation::StepCreateSharedFolder()
420 {
421     LogDebug("StepCreateSharedFolder");
422     std::string sharedPath = m_context.locations->getSharedRootDir();
423     LogDebug("Create shared directory : " <<
424             m_context.locations->getSharedRootDir());
425
426     WrtUtilMakeDir(sharedPath);
427
428     if (m_context.isUpdateMode) { //update
429         std::string backData = m_context.locations->getBackupSharedDir();
430         LogDebug("copy shared storage " << backData << " to " << sharedPath);
431         if (!DirectoryApi::DirectoryCopy(backData, sharedPath)) {
432             LogError("Failed to rename " << backData << " to " << sharedPath);
433             ThrowMsg(Exceptions::BackupFailed,
434                     "Error occurs copy shared strage files");
435         }
436     } else {
437         WrtUtilMakeDir(m_context.locations->getSharedResourceDir());
438         WrtUtilMakeDir(m_context.locations->getSharedDataDir());
439         WrtUtilMakeDir(m_context.locations->getSharedTrustedDir());
440     }
441 }
442 } //namespace WidgetInstall
443 } //namespace Jobs