Source code formating unification
[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 <sys/stat.h>
23 #include <dirent.h>
24 #include <widget_install/task_file_manipulation.h>
25 #include <widget_install/job_widget_install.h>
26 #include <widget_install/widget_install_errors.h>
27 #include <widget_install/widget_install_context.h>
28 #include <dpl/utils/wrt_utility.h>
29 #include <dpl/foreach.h>
30 #include <dpl/log/log.h>
31 #include <dpl/assert.h>
32 #include <dpl/utils/folder_size.h>
33 #include <string>
34 #include <fstream>
35 #include <widget_install_to_external.h>
36
37 #define WEBAPP_DEFAULT_UID  5000
38 #define WEBAPP_DEFAULT_GID  5000
39
40 namespace {
41 const mode_t PRIVATE_STORAGE_MODE = 0700;
42 const mode_t SHARE_MODE = 0705;
43 }
44
45 using namespace WrtDB;
46
47 namespace {
48 const char* GLIST_RES_DIR = "res";
49 const char* GLIST_BIN_DIR = "bin";
50
51 bool _FolderCopy(std::string source, std::string dest)
52 {
53     DIR* dir = opendir(source.c_str());
54     if (NULL == dir) {
55         return false;
56     }
57
58     struct dirent* dEntry = NULL;
59     do {
60         struct stat statInfo;
61         if (dEntry = readdir(dir)) {
62             std::string fileName = dEntry->d_name;
63             std::string fullName = source + "/" + fileName;
64
65             if (stat(fullName.c_str(), &statInfo) != 0) {
66                 closedir(dir);
67                 return false;
68             }
69
70             if (S_ISDIR(statInfo.st_mode)) {
71                 if (("." == fileName) || (".." == fileName)) {
72                     continue;
73                 }
74                 std::string destFolder = dest + "/" + fileName;
75                 WrtUtilMakeDir(destFolder);
76
77                 if (!_FolderCopy(fullName, destFolder)) {
78                     closedir(dir);
79                     return false;
80                 }
81             }
82
83             std::string destFile = dest + "/" + fileName;
84             std::ifstream infile(fullName);
85             std::ofstream outfile(destFile);
86             outfile << infile.rdbuf();
87             outfile.close();
88             infile.close();
89         }
90     } while (dEntry);
91     closedir(dir);
92     return true;
93 }
94 }
95
96 namespace Jobs {
97 namespace WidgetInstall {
98 TaskFileManipulation::TaskFileManipulation(InstallerContext& context) :
99     DPL::TaskDecl<TaskFileManipulation>(this),
100     m_context(context)
101 {
102     if (INSTALL_LOCATION_TYPE_EXTERNAL !=
103         m_context.locationType)
104     {
105         AddStep(&TaskFileManipulation::StepCreateDirs);
106         AddStep(&TaskFileManipulation::StepCreatePrivateStorageDir);
107         if (m_context.widgetConfig.packagingType !=
108             WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
109         {
110             AddStep(&TaskFileManipulation::StepRenamePath);
111             AddAbortStep(&TaskFileManipulation::StepAbortRenamePath);
112         }
113     } else {
114         AddStep(&TaskFileManipulation::StepPrepareExternalDir);
115         AddStep(&TaskFileManipulation::StepInstallToExternal);
116         AddStep(&TaskFileManipulation::StepCreatePrivateStorageDir);
117
118         AddAbortStep(&TaskFileManipulation::StepAbortCreateExternalDir);
119     }
120 }
121
122 void TaskFileManipulation::StepCreateDirs()
123 {
124     std::string widgetPath;
125
126     widgetPath = m_context.locations->getPackageInstallationDir();
127
128     std::string widgetBinPath = m_context.locations->getBinaryDir();
129     std::string widgetSrcPath = m_context.locations->getSourceDir();
130
131     WrtUtilMakeDir(widgetPath);
132
133     // If package type is widget with osp service, we don't need to make bin
134     // and src directory
135     if (m_context.widgetConfig.packagingType == PKG_TYPE_HYBRID_WEB_APP) {
136         LogDebug("Doesn't need to create resource directory");
137     } else {
138         LogDebug("Create resource directory");
139         WrtUtilMakeDir(widgetBinPath);
140         WrtUtilMakeDir(widgetSrcPath);
141     }
142
143     m_context.job->UpdateProgress(
144         InstallerContext::INSTALL_DIR_CREATE,
145         "Widget Directory Created");
146 }
147
148 void TaskFileManipulation::StepCreatePrivateStorageDir()
149 {
150     std::string storagePath = m_context.locations->getPrivateStorageDir();
151
152     if (euidaccess(storagePath.c_str(), F_OK) != 0) {
153         if (!WrtUtilMakeDir(storagePath, PRIVATE_STORAGE_MODE)) {
154             LogError("Failed to create directory for private storage");
155             ThrowMsg(Exceptions::InternalError,
156                      "Failed to create directory for private storage");
157         }
158         // '5000' is default uid, gid for applications.
159         // So installed applications should be launched as process of uid
160         // '5000'.
161         // the process can access private directory 'data' of itself.
162         if (chown(storagePath.c_str(),
163                   WEBAPP_DEFAULT_UID,
164                   WEBAPP_DEFAULT_GID) != 0)
165         {
166             ThrowMsg(Exceptions::InternalError,
167                      "Chown to invaild user");
168         }
169     } else if (euidaccess(storagePath.c_str(), W_OK | R_OK | X_OK) == 0) {
170         LogInfo("Private storage already exists.");
171         // Even if private directory already is created, private dircetory
172         // should change owner.
173         if (chown(storagePath.c_str(),
174                   WEBAPP_DEFAULT_UID,
175                   WEBAPP_DEFAULT_GID) != 0)
176         {
177             ThrowMsg(Exceptions::InternalError,
178                      "Chown to invaild user");
179         }
180         if (chmod(storagePath.c_str(), PRIVATE_STORAGE_MODE) != 0) {
181             ThrowMsg(Exceptions::InternalError,
182                      "chmod to 0700");
183         }
184     } else {
185         ThrowMsg(Exceptions::InternalError,
186                  "No access to private storage.");
187     }
188 }
189
190 void TaskFileManipulation::StepRenamePath()
191 {
192     std::string instDir;
193
194     if (m_context.widgetConfig.packagingType == PKG_TYPE_HYBRID_WEB_APP) {
195         instDir = m_context.locations->getPackageInstallationDir();
196     } else {
197         instDir = m_context.locations->getSourceDir();
198     }
199
200     LogDebug("Copy file from temp directory to " << instDir);
201     if (!WrtUtilRemove(instDir)) {
202         ThrowMsg(Exceptions::RemovingFolderFailure,
203                  "Error occurs during removing existing folder");
204     }
205
206     if (!(rename(m_context.locations->getTemporaryPackageDir().c_str(),
207                  instDir.c_str()) == 0))
208     {
209         ThrowMsg(Exceptions::UnknownError,
210                  "Error occurs during renaming widget folder");
211     }
212     m_context.job->UpdateProgress(
213         InstallerContext::INSTALL_RENAME_PATH,
214         "Widget Rename path Finished");
215 }
216
217 void TaskFileManipulation::StepAbortRenamePath()
218 {
219     LogDebug("[Rename Widget Path] Aborting.... (Rename path)");
220     std::string widgetPath;
221     if (m_context.widgetConfig.packagingType != PKG_TYPE_HYBRID_WEB_APP) {
222         widgetPath = m_context.locations->getPackageInstallationDir();
223         if (!WrtUtilRemove(widgetPath)) {
224             ThrowMsg(Exceptions::RemovingFolderFailure,
225                      "Error occurs during removing existing folder");
226         }
227     }
228     LogDebug("Rename widget path sucessful!");
229 }
230
231 void TaskFileManipulation::StepPrepareExternalDir()
232 {
233     LogDebug("Step prepare to install in exernal directory");
234     Try {
235         std::string appid =
236             DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
237
238         WidgetInstallToExtSingleton::Instance().initialize(appid);
239
240         size_t totalSize =
241             Utils::getFolderSize(m_context.locations->getTemporaryPackageDir());
242
243         int folderSize = (int)(totalSize / (1024 * 1024)) + 1;
244
245         GList *list = NULL;
246         app2ext_dir_details* dirDetail = NULL;
247
248         std::string dirNames[2] = { GLIST_RES_DIR, GLIST_BIN_DIR };
249
250         for (int i = 0; i < 2; i++) {
251             dirDetail = (app2ext_dir_details*) calloc(1,
252                                                       sizeof(
253                                                           app2ext_dir_details));
254             if (NULL == dirDetail) {
255                 ThrowMsg(Exceptions::ErrorExternalInstallingFailure,
256                          "error in app2ext");
257             }
258             dirDetail->name = strdup(dirNames[i].c_str());
259             dirDetail->type = APP2EXT_DIR_RO;
260             list = g_list_append(list, dirDetail);
261         }
262
263         if (false == m_context.existingWidgetInfo.isExist) {
264             WidgetInstallToExtSingleton::Instance().preInstallation(list,
265                                                                     folderSize);
266         } else {
267             WidgetInstallToExtSingleton::Instance().preUpgrade(list,
268                                                                folderSize);
269         }
270         free(dirDetail);
271         g_list_free(list);
272     }
273     Catch(WidgetInstallToExt::Exception::ErrorInstallToExt)
274     {
275         ReThrowMsg(Exceptions::ErrorExternalInstallingFailure,
276                    "Error during \
277                 create external folder ");
278     }
279 }
280
281 void TaskFileManipulation::StepInstallToExternal()
282 {
283     LogDebug("StepInstallExternal");
284     if (!WrtUtilMakeDir(m_context.locations->getSourceDir())) {
285         ThrowMsg(Exceptions::ErrorExternalInstallingFailure,
286                  "To make src \
287                 directory failed");
288     }
289
290     LogDebug("Resource move to external storage " <<
291              m_context.locations->getSourceDir());
292     if (!_FolderCopy(m_context.locations->getTemporaryPackageDir(),
293                      m_context.locations->getSourceDir()))
294     {
295         ThrowMsg(Exceptions::UnknownError,
296                  "Error occurs during renaming widget folder");
297     }
298 }
299
300 void TaskFileManipulation::StepAbortCreateExternalDir()
301 {
302     LogError("Abort StepAbortCreateExternalDir");
303     if (false == m_context.existingWidgetInfo.isExist) {
304         WidgetInstallToExtSingleton::Instance().postInstallation(false);
305     } else {
306         WidgetInstallToExtSingleton::Instance().postUpgrade(false);
307     }
308     WidgetInstallToExtSingleton::Instance().deinitialize();
309 }
310 } //namespace WidgetInstall
311 } //namespace Jobs