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