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