Remove installed directory and manifest file when installation failed after ace check
[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                 return false;
67             }
68
69             if (S_ISDIR(statInfo.st_mode)) {
70                 if(("." == fileName) || (".." == fileName)) {
71                     continue;
72                 }
73                 std::string destFolder = dest + "/" + fileName;
74                 WrtUtilMakeDir(destFolder);
75
76                 if (!_FolderCopy(fullName, destFolder)) {
77                     return false;
78                 }
79             }
80
81             std::string destFile = dest + "/" + fileName;
82             std::ifstream infile(fullName);
83             std::ofstream outfile(destFile);
84             outfile << infile.rdbuf();
85             outfile.close();
86             infile.close();
87         }
88     } while(dEntry);
89     return true;
90 }
91 }
92
93 namespace Jobs {
94 namespace WidgetInstall {
95 TaskFileManipulation::TaskFileManipulation(InstallerContext& context) :
96     DPL::TaskDecl<TaskFileManipulation>(this),
97     m_context(context)
98 {
99     if (INSTALL_LOCATION_TYPE_EXTERNAL !=
100             m_context.locationType) {
101         AddStep(&TaskFileManipulation::StepCreateDirs);
102         AddStep(&TaskFileManipulation::StepCreatePrivateStorageDir);
103         AddStep(&TaskFileManipulation::StepCreateShareDir);
104         if (m_context.widgetConfig.packagingType !=
105                 WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
106         {
107             AddStep(&TaskFileManipulation::StepRenamePath);
108             AddAbortStep(&TaskFileManipulation::StepAbortRenamePath);
109         }
110     } else {
111         AddStep(&TaskFileManipulation::StepPrepareExternalDir);
112         AddStep(&TaskFileManipulation::StepInstallToExternal);
113         AddStep(&TaskFileManipulation::StepCreatePrivateStorageDir);
114         AddStep(&TaskFileManipulation::StepCreateShareDir);
115
116         AddAbortStep(&TaskFileManipulation::StepAbortCreateExternalDir);
117     }
118 }
119
120 void TaskFileManipulation::StepCreateDirs()
121 {
122     std::string widgetPath;
123     DPL::OptionalString pkgname = m_context.widgetConfig.pkgname;
124     if (pkgname.IsNull()) {
125         ThrowMsg(Exceptions::InternalError, "No Package name exists.");
126     }
127
128     widgetPath = m_context.locations->getPackageInstallationDir();
129
130     std::string widgetBinPath = m_context.locations->getBinaryDir();
131     std::string widgetSrcPath = m_context.locations->getSourceDir();
132
133     WrtUtilMakeDir(widgetPath);
134
135     // If package type is widget with osp service, we don't need to make bin
136     // and src directory
137     if (m_context.widgetConfig.packagingType == PKG_TYPE_HYBRID_WEB_APP) {
138         LogDebug("Doesn't need to create resource directory");
139     } else {
140         LogDebug("Create resource directory");
141         WrtUtilMakeDir(widgetBinPath);
142         WrtUtilMakeDir(widgetSrcPath);
143     }
144
145     m_context.job->UpdateProgress(
146         InstallerContext::INSTALL_DIR_CREATE,
147         "Widget Directory Created");
148 }
149
150 void TaskFileManipulation::StepCreatePrivateStorageDir()
151 {
152     std::string storagePath = m_context.locations->getPrivateStorageDir();
153
154     if (euidaccess(storagePath.c_str(), F_OK) != 0) {
155         if(!WrtUtilMakeDir(storagePath, PRIVATE_STORAGE_MODE)){
156             LogError("Failed to create directory for private storage");
157             ThrowMsg(Exceptions::InternalError,
158                     "Failed to create directory for private storage");
159         }
160         // '5000' is default uid, gid for applications.
161         // So installed applications should be launched as process of uid '5000'.
162         // the process can access private directory 'data' of itself.
163         if(chown(storagePath.c_str(),
164                  WEBAPP_DEFAULT_UID,
165                  WEBAPP_DEFAULT_GID) != 0)
166         {
167             ThrowMsg(Exceptions::InternalError,
168                  "Chown to invaild user");
169         }
170     } else if (euidaccess(storagePath.c_str(), W_OK | R_OK | X_OK) == 0) {
171         LogInfo("Private storage already exists.");
172         // Even if private directory already is created, private dircetory
173         // should change owner.
174         if(chown(storagePath.c_str(),
175                  WEBAPP_DEFAULT_UID,
176                  WEBAPP_DEFAULT_GID) != 0)
177         {
178             ThrowMsg(Exceptions::InternalError,
179                  "Chown to invaild user");
180         }
181         if(chmod(storagePath.c_str(), PRIVATE_STORAGE_MODE) != 0) {
182             ThrowMsg(Exceptions::InternalError,
183                  "chmod to 0700");
184         }
185
186     } else {
187         ThrowMsg(Exceptions::InternalError,
188                  "No access to private storage.");
189     }
190 }
191
192 void TaskFileManipulation::StepCreateShareDir()
193 {
194     std::string sharePath = m_context.locations->getShareDir();
195
196     if (euidaccess(sharePath.c_str(), F_OK) != 0) {
197         if(!WrtUtilMakeDir(sharePath, SHARE_MODE)){
198             LogError("Failed to create directory for share");
199             ThrowMsg(Exceptions::InternalError,
200                     "Failed to create directory for share");
201         }
202         // '5000' is default uid, gid for applications.
203         // So installed applications should be launched as process of uid '5000'.
204         // the process can access private directory 'data' of itself.
205         if(chown(sharePath.c_str(),
206                  WEBAPP_DEFAULT_UID,
207                  WEBAPP_DEFAULT_GID) != 0)
208         {
209             ThrowMsg(Exceptions::InternalError,
210                  "Chown to invaild user");
211         }
212     } else if (euidaccess(sharePath.c_str(), W_OK | R_OK | X_OK) == 0) {
213         LogInfo("Share directory already exists.");
214         // Even if share directory already is created, share dircetory
215         // should change owner.
216         if(chown(sharePath.c_str(),
217                  WEBAPP_DEFAULT_UID,
218                  WEBAPP_DEFAULT_GID) != 0)
219         {
220             ThrowMsg(Exceptions::InternalError,
221                  "Chown to invaild user");
222         }
223         if(chmod(sharePath.c_str(), SHARE_MODE) != 0) {
224             ThrowMsg(Exceptions::InternalError,
225                  "chmod to 0700");
226         }
227
228     } else {
229         ThrowMsg(Exceptions::InternalError,
230                  "No access to private storage.");
231     }
232
233 }
234
235 void TaskFileManipulation::StepRenamePath()
236 {
237     std::string instDir;
238     DPL::OptionalString pkgname = m_context.widgetConfig.pkgname;
239     if (pkgname.IsNull()) {
240         ThrowMsg(Exceptions::InternalError, "No Package name exists.");
241     }
242
243     if (m_context.widgetConfig.packagingType == PKG_TYPE_HYBRID_WEB_APP) {
244         instDir = m_context.locations->getPackageInstallationDir();
245     } else {
246         instDir = m_context.locations->getSourceDir();
247     }
248
249     LogDebug("Copy file from temp directory to " << instDir);
250     if (!WrtUtilRemove(instDir)) {
251         ThrowMsg(Exceptions::RemovingFolderFailure,
252                 "Error occurs during removing existing folder");
253     }
254
255     if (!(rename(m_context.locations->getTemporaryPackageDir().c_str(), instDir.c_str()) == 0)) {
256         ThrowMsg(Exceptions::UnknownError,
257                 "Error occurs during renaming widget folder");
258     }
259     m_context.job->UpdateProgress(
260         InstallerContext::INSTALL_RENAME_PATH,
261         "Widget Rename path Finished");
262 }
263
264 void TaskFileManipulation::StepAbortRenamePath()
265 {
266     LogDebug("[Rename Widget Path] Aborting.... (Rename path)");
267     std::string widgetPath;
268     if (m_context.widgetConfig.packagingType != PKG_TYPE_HYBRID_WEB_APP) {
269         widgetPath = m_context.locations->getPackageInstallationDir();
270         if (!WrtUtilRemove(widgetPath)) {
271             ThrowMsg(Exceptions::RemovingFolderFailure,
272                     "Error occurs during removing existing folder");
273         }
274     }
275     LogDebug("Rename widget path sucessful!");
276 }
277
278 void TaskFileManipulation::StepPrepareExternalDir()
279 {
280     LogDebug("Step prepare to install in exernal directory");
281     Try {
282         std::string pkgname =
283             DPL::ToUTF8String(*m_context.widgetConfig.pkgname);
284
285         WidgetInstallToExtSingleton::Instance().initialize(pkgname);
286
287         size_t totalSize =
288             Utils::getFolderSize(m_context.locations->getTemporaryPackageDir());
289
290         int folderSize = (int)(totalSize / (1024 * 1024)) + 1;
291
292         GList *list = NULL;
293         app2ext_dir_details* dirDetail = NULL;
294
295         std::string dirNames[2] = {GLIST_RES_DIR, GLIST_BIN_DIR};
296
297         for (int i = 0; i < 2; i++) {
298             dirDetail = (app2ext_dir_details*) calloc(1,
299                     sizeof(app2ext_dir_details));
300             if (NULL == dirDetail) {
301                 ThrowMsg(Exceptions::ErrorExternalInstallingFailure, "error in app2ext");
302             }
303             dirDetail->name = strdup(dirNames[i].c_str());
304             dirDetail->type = APP2EXT_DIR_RO;
305             list = g_list_append(list, dirDetail);
306         }
307
308         if (false == m_context.existingWidgetInfo.isExist) {
309             WidgetInstallToExtSingleton::Instance().preInstallation(list,
310                     folderSize);
311         } else {
312             WidgetInstallToExtSingleton::Instance().preUpgrade(list,
313                     folderSize);
314         }
315         free(dirDetail);
316         g_list_free(list);
317     }
318     Catch (WidgetInstallToExt::Exception::ErrorInstallToExt)
319     {
320         ReThrowMsg(Exceptions::ErrorExternalInstallingFailure, "Error during \
321                 create external folder ");
322     }
323 }
324
325 void TaskFileManipulation::StepInstallToExternal()
326 {
327     LogDebug("StepInstallExternal");
328     if (!WrtUtilMakeDir(m_context.locations->getSourceDir())) {
329         ThrowMsg(Exceptions::ErrorExternalInstallingFailure, "To make src \
330                 directory failed");
331     }
332
333     LogDebug("Resource move to external storage " <<
334             m_context.locations->getSourceDir());
335     if (!_FolderCopy(m_context.locations->getTemporaryPackageDir(),
336                 m_context.locations->getSourceDir()))
337     {
338         ThrowMsg(Exceptions::UnknownError,
339                 "Error occurs during renaming widget folder");
340     }
341 }
342
343 void TaskFileManipulation::StepAbortCreateExternalDir()
344 {
345     LogError("Abort StepAbortCreateExternalDir");
346     if (false == m_context.existingWidgetInfo.isExist) {
347         WidgetInstallToExtSingleton::Instance().postInstallation(false);
348     } else {
349         WidgetInstallToExtSingleton::Instance().postUpgrade(false);
350     }
351     WidgetInstallToExtSingleton::Instance().deinitialize();
352 }
353 } //namespace WidgetInstall
354 } //namespace Jobs