Fixed resource symbolic link for prealod app.
[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 SHARED_STORAGE_MODE = 0755;
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, mode_t mode) {
103     if (euidaccess(storagePath.c_str(), F_OK) != 0) {
104         if (!WrtUtilMakeDir(storagePath, mode)) {
105             LogError("Failed to create directory : " << storagePath);
106             ThrowMsg(Jobs::WidgetInstall::Exceptions::FileOperationFailed,
107                      "Failed to create directory : " << storagePath);
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(storagePath << " 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(), 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.mode.extension != InstallMode::ExtensionType::DIR)
154         {
155             AddStep(&TaskFileManipulation::StepRenamePath);
156             AddAbortStep(&TaskFileManipulation::StepAbortRenamePath);
157         }
158         AddStep(&TaskFileManipulation::StepCreatePrivateStorageDir);
159         AddStep(&TaskFileManipulation::StepCreateSharedFolder);
160         AddStep(&TaskFileManipulation::StepLinkForPreload);
161
162     } else {
163         AddStep(&TaskFileManipulation::StepPrepareExternalDir);
164         AddStep(&TaskFileManipulation::StepInstallToExternal);
165         AddStep(&TaskFileManipulation::StepCreatePrivateStorageDir);
166         AddStep(&TaskFileManipulation::StepCreateSharedFolder);
167
168         AddAbortStep(&TaskFileManipulation::StepAbortCreateExternalDir);
169     }
170 }
171
172 void TaskFileManipulation::StepCreateDirs()
173 {
174     std::string widgetPath;
175
176     widgetPath = m_context.locations->getPackageInstallationDir();
177
178     std::string widgetBinPath = m_context.locations->getBinaryDir();
179     std::string widgetSrcPath = m_context.locations->getSourceDir();
180
181     WrtUtilMakeDir(widgetPath);
182
183     // If package type is widget with osp service, we don't need to make bin
184     // and src directory
185     if (m_context.widgetConfig.packagingType == PKG_TYPE_HYBRID_WEB_APP) {
186         LogDebug("Doesn't need to create resource directory");
187     } else {
188         LogDebug("Create resource directory");
189         WrtUtilMakeDir(widgetBinPath);
190         WrtUtilMakeDir(widgetSrcPath);
191         if (m_context.mode.installTime == InstallMode::InstallTime::PRELOAD) {
192             std::string userWidgetDir = m_context.locations->getUserDataRootDir();
193             WrtUtilMakeDir(userWidgetDir);
194         }
195     }
196
197     m_context.job->UpdateProgress(
198         InstallerContext::INSTALL_DIR_CREATE,
199         "Widget Directory Created");
200 }
201
202 void TaskFileManipulation::StepCreatePrivateStorageDir()
203 {
204     std::string storagePath = m_context.locations->getPrivateStorageDir();
205     LogDebug("Create private storage directory : " <<
206             m_context.locations->getPrivateStorageDir());
207
208     if (m_context.isUpdateMode) { //update
209         std::string backData = m_context.locations->getBackupPrivateDir();
210         LogDebug("copy private storage " << backData << " to " << storagePath);
211         WrtUtilMakeDir(storagePath);
212         if (!DirectoryApi::DirectoryCopy(backData, storagePath)) {
213             LogError("Failed to rename " << backData << " to " << storagePath);
214             ThrowMsg(Exceptions::BackupFailed,
215                     "Error occurs copy private strage files");
216         }
217     }
218     changeOwnerForDirectory(storagePath, PRIVATE_STORAGE_MODE);
219
220     std::string tempStoragePath = m_context.locations->getPrivateTempStorageDir();
221     LogDebug("Create temp private storage directory : " << tempStoragePath);
222     changeOwnerForDirectory(tempStoragePath, PRIVATE_STORAGE_MODE);
223 }
224
225 void TaskFileManipulation::StepRenamePath()
226 {
227     std::string instDir;
228
229     if (m_context.widgetConfig.packagingType == PKG_TYPE_HYBRID_WEB_APP) {
230         instDir = m_context.locations->getPackageInstallationDir();
231     } else {
232         instDir = m_context.locations->getSourceDir();
233     }
234
235     LogDebug("Copy file from temp directory to " << instDir);
236     if (!WrtUtilRemove(instDir)) {
237         ThrowMsg(Exceptions::RemovingFolderFailure,
238                  "Error occurs during removing existing folder");
239     }
240
241     if (!(rename(m_context.locations->getTemporaryPackageDir().c_str(),
242                  instDir.c_str()) == 0))
243     {
244         ThrowMsg(Exceptions::FileOperationFailed,
245                  "Error occurs during renaming widget folder");
246     }
247     m_context.job->UpdateProgress(
248         InstallerContext::INSTALL_RENAME_PATH,
249         "Widget Rename path Finished");
250 }
251
252 void TaskFileManipulation::StepLinkForPreload()
253 {
254     if (m_context.mode.rootPath == InstallMode::RootPath::RO) {
255         std::string optRes = m_context.locations->getUserDataRootDir() +
256             WrtDB::GlobalConfig::GetWidgetResPath();
257         std::string usrRes = m_context.locations->getPackageInstallationDir() +
258             WrtDB::GlobalConfig::GetWidgetResPath();
259
260         if (0 != access(optRes.c_str(), F_OK)) {
261             LogDebug("Make symbolic name for preaload app" <<
262                     usrRes << " to " << optRes);
263
264             if (symlink(usrRes.c_str(), optRes.c_str()) != 0)
265             {
266                 int error = errno;
267                 if (error)
268                     LogPedantic("Failed to make a symbolic name for a file "
269                             << "[" <<  DPL::GetErrnoString(error) << "]");
270                 ThrowMsg(Exceptions::FileOperationFailed,
271                         "Symbolic link creating is not done.");
272             }
273         }
274
275         /* link for data directory */
276         std::string storagePath = m_context.locations->getPrivateStorageDir();
277         std::string dataDir = m_context.locations->getPackageInstallationDir() +
278             "/" + WrtDB::GlobalConfig::GetWidgetPrivateStoragePath();
279         if (0 != access(dataDir.c_str(), F_OK)) {
280             LogDebug("Make symbolic name for preaload app " <<
281                     storagePath << " to " << dataDir);
282
283             if (symlink(storagePath.c_str(), dataDir.c_str()) != 0)
284             {
285                 int error = errno;
286                 if (error)
287                     LogPedantic("Failed to make a symbolic name for a file "
288                             << "[" <<  DPL::GetErrnoString(error) << "]");
289                 ThrowMsg(Exceptions::FileOperationFailed,
290                         "Symbolic link creating is not done.");
291             }
292             changeOwnerForDirectory(dataDir, PRIVATE_STORAGE_MODE);
293         }
294
295         if (m_context.widgetConfig.packagingType != PKG_TYPE_HYBRID_WEB_APP) {
296             std::string widgetBinPath = m_context.locations->getBinaryDir();
297             std::string userBinPath = m_context.locations->getUserBinaryDir();
298             LogDebug("Make symbolic link for preload app " << widgetBinPath <<
299                     " to " << userBinPath);
300             if (symlink(widgetBinPath.c_str(), userBinPath.c_str()) != 0)
301             {
302                 int error = errno;
303                 if (error)
304                     LogPedantic("Failed to make a symbolic name for a file "
305                             << "[" <<  DPL::GetErrnoString(error) << "]");
306                 ThrowMsg(Exceptions::FileOperationFailed,
307                         "Symbolic link creating is not done.");
308             }
309
310         }
311     }
312 }
313
314 void TaskFileManipulation::StepAbortRenamePath()
315 {
316     LogDebug("[Rename Widget Path] Aborting.... (Rename path)");
317     std::string widgetPath;
318     widgetPath = m_context.locations->getPackageInstallationDir();
319     if (!WrtUtilRemove(widgetPath)) {
320         LogError("Error occurs during removing existing folder");
321     }
322     // Remove user data directory if preload web app.
323     std::string userData = m_context.locations->getUserDataRootDir();
324     if (0 == access(userData.c_str(), F_OK)) {
325         if (!WrtUtilRemove(userData)) {
326             LogError("Error occurs during removing user data directory");
327         }
328     }
329
330     LogDebug("Rename widget path sucessful!");
331 }
332
333 void TaskFileManipulation::StepPrepareExternalDir()
334 {
335     LogDebug("Step prepare to install in exernal directory");
336     Try {
337         std::string pkgid =
338             DPL::ToUTF8String(m_context.widgetConfig.tzPkgid);
339
340         WidgetInstallToExtSingleton::Instance().initialize(pkgid);
341
342         size_t totalSize =
343             Utils::getFolderSize(m_context.locations->getTemporaryPackageDir());
344
345         int folderSize = (int)(totalSize / (1024 * 1024)) + 1;
346
347         GList *list = NULL;
348         app2ext_dir_details* dirDetail = NULL;
349
350         dirDetail = (app2ext_dir_details*) calloc(1,
351                 sizeof(
352                     app2ext_dir_details));
353         if (NULL == dirDetail) {
354             ThrowMsg(Exceptions::ErrorExternalInstallingFailure,
355                     "error in app2ext");
356         }
357         dirDetail->name = strdup(GLIST_RES_DIR);
358         dirDetail->type = APP2EXT_DIR_RO;
359         list = g_list_append(list, dirDetail);
360
361         if (m_context.isUpdateMode) {
362             WidgetInstallToExtSingleton::Instance().preUpgrade(list,
363                                                                folderSize);
364         } else {
365             WidgetInstallToExtSingleton::Instance().preInstallation(list,
366                                                                     folderSize);
367         }
368         free(dirDetail);
369         g_list_free(list);
370
371         /* make bin directory */
372         std::string widgetBinPath = m_context.locations->getBinaryDir();
373         WrtUtilMakeDir(widgetBinPath);
374     }
375     Catch(WidgetInstallToExt::Exception::ErrorInstallToExt)
376     {
377         ReThrowMsg(Exceptions::ErrorExternalInstallingFailure,
378                    "Error during \
379                 create external folder ");
380     }
381 }
382
383 void TaskFileManipulation::StepInstallToExternal()
384 {
385     LogDebug("StepInstallExternal");
386     if (!WrtUtilMakeDir(m_context.locations->getSourceDir())) {
387         ThrowMsg(Exceptions::ErrorExternalInstallingFailure,
388                  "To make src \
389                 directory failed");
390     }
391
392     LogDebug("Resource move to external storage " <<
393              m_context.locations->getSourceDir());
394     if (!_FolderCopy(m_context.locations->getTemporaryPackageDir(),
395                      m_context.locations->getSourceDir()))
396     {
397         ThrowMsg(Exceptions::ErrorExternalInstallingFailure,
398                  "Error occurs during renaming widget folder");
399     }
400 }
401
402 void TaskFileManipulation::StepAbortCreateExternalDir()
403 {
404     LogError("Abort StepAbortCreateExternalDir");
405     if (m_context.isUpdateMode) {
406         WidgetInstallToExtSingleton::Instance().postUpgrade(false);
407     } else {
408         WidgetInstallToExtSingleton::Instance().postInstallation(false);
409     }
410     WidgetInstallToExtSingleton::Instance().deinitialize();
411 }
412
413 void TaskFileManipulation::StepCreateSharedFolder()
414 {
415     LogDebug("StepCreateSharedFolder");
416     std::string sharedPath = m_context.locations->getSharedRootDir();
417     LogDebug("Create shared directory : " <<
418             m_context.locations->getSharedRootDir());
419
420     WrtUtilMakeDir(sharedPath);
421
422     if (m_context.isUpdateMode) { //update
423         std::string backData = m_context.locations->getBackupSharedDir();
424         LogDebug("copy shared storage " << backData << " to " << sharedPath);
425         if (!DirectoryApi::DirectoryCopy(backData, sharedPath)) {
426             LogError("Failed to rename " << backData << " to " << sharedPath);
427             ThrowMsg(Exceptions::BackupFailed,
428                     "Error occurs copy shared strage files");
429         }
430     } else {
431         WrtUtilMakeDir(m_context.locations->getSharedResourceDir());
432         changeOwnerForDirectory(m_context.locations->getSharedDataDir(),
433                 SHARED_STORAGE_MODE);
434         changeOwnerForDirectory(m_context.locations->getSharedTrustedDir(),
435                 SHARED_STORAGE_MODE);
436     }
437 }
438 } //namespace WidgetInstall
439 } //namespace Jobs