Add send signal if there is not enough memory during web app installation
[framework/web/wrt-installer.git] / src / jobs / widget_install / widget_unzip.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    widget_unzip.cpp
18  * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @version 1.0
20  * @brief   Implementation file for installer widget unzip
21  */
22 #include <widget_install/widget_unzip.h>
23 #include <widget_install/widget_install_errors.h>
24 #include <widget_install/widget_install_context.h>
25 #include <widget_install/job_widget_install.h>
26 #include <dpl/copy.h>
27 #include <dpl/file_output.h>
28 #include "dpl/utils/path.h"
29 #include <dpl/abstract_waitable_input_adapter.h>
30 #include <dpl/wrt-dao-ro/global_config.h>
31 #include <sys/stat.h>
32 #include <sys/statvfs.h>
33 #include <dlfcn.h>
34 #include <installer_log.h>
35
36 using namespace WrtDB;
37
38 namespace {
39 const char *const DRM_LIB_PATH = "/usr/lib/libdrm-service-core-tizen.so";
40 const size_t SPACE_SIZE = 1024 * 1024;
41
42 struct PathAndFilePair
43 {
44     std::string path;
45     std::string file;
46
47     PathAndFilePair(const std::string &p,
48                     const std::string &f) :
49         path(p),
50         file(f)
51     {}
52 };
53
54 PathAndFilePair SplitFileAndPath(const std::string &filePath)
55 {
56     std::string::size_type position = filePath.rfind('/');
57
58     // Is this only a file without a path ?
59     if (position == std::string::npos) {
60         return PathAndFilePair(std::string(), filePath);
61     }
62
63     // This is full file-path pair
64     return PathAndFilePair(filePath.substr(0,
65                                            position),
66                            filePath.substr(position + 1));
67 }
68 }
69
70 namespace Jobs {
71 namespace WidgetInstall {
72 void WidgetUnzip::ExtractFile(DPL::ZipInput::File *input,
73                             const std::string &destFileName)
74 {
75     Try
76     {
77         DPL::AbstractWaitableInputAdapter inputAdapter(input);
78         DPL::FileOutput output(destFileName);
79
80         DPL::Copy(&inputAdapter, &output);
81     }
82     Catch(DPL::FileOutput::Exception::OpenFailed)
83     {
84         ReThrowMsg(Exceptions::ExtractFileFailed, destFileName);
85     }
86     Catch(DPL::CopyFailed)
87     {
88         ReThrowMsg(Exceptions::ExtractFileFailed, destFileName);
89     }
90 }
91
92 void WidgetUnzip::unzipProgress(const std::string &destination)
93 {
94     // Show file info
95     _D("Unzipping: '%s', Comment: '%s', Compressed size: %lld, Uncompressed size: %lld",
96             m_zipIterator->name.c_str(), m_zipIterator->comment.c_str(), m_zipIterator->compressedSize, m_zipIterator->uncompressedSize);
97
98     // Normalize file paths
99     // FIXME: Implement checking for invalid characters
100
101     // Extract file or path
102     std::string fileName = m_zipIterator->name;
103
104     if (fileName[fileName.size() - 1] == '/') {
105         // This is path
106         std::string newPath = destination + "/" +
107             fileName.substr(0, fileName.size() - 1);
108         _D("Path to extract: %s", newPath.c_str());
109
110         // Create path in case of it is empty
111         Try
112         {
113             DPL::Utils::MakeDir(DPL::Utils::Path(newPath));
114         }
115         Catch(DPL::Utils::Path::BaseException)
116         {
117             ThrowMsg(Exceptions::FileOperationFailed, "Failed to create temporary directory");
118         }
119     } else {
120         // This is regular file
121         std::string fileExtractPath = destination + "/" + fileName;
122
123         _D("File to extract: %s", fileExtractPath.c_str());
124
125         // Split into pat & file pair
126         PathAndFilePair pathAndFile = SplitFileAndPath(fileExtractPath);
127
128         _D("Path and file: %s : %s", pathAndFile.path.c_str(), pathAndFile.file.c_str());
129
130         // First, ensure that path exists
131         Try
132         {
133             DPL::Utils::MakeDir(DPL::Utils::Path(pathAndFile.path));
134         }
135         Catch(DPL::Utils::Path::BaseException)
136         {
137             ThrowMsg(Exceptions::FileOperationFailed, "Failed to create temporary directory");
138         }
139
140         Try
141         {
142             // Open file
143             std::unique_ptr<DPL::ZipInput::File> file(
144                 m_zip->OpenFile(fileName));
145
146             // Extract single file
147             ExtractFile(file.get(), fileExtractPath);
148         }
149         Catch(DPL::ZipInput::Exception::OpenFileFailed)
150         {
151             ThrowMsg(Exceptions::ExtractFileFailed, fileName);
152         }
153     }
154
155     // Check whether there are more files to extract
156     if (++m_zipIterator == m_zip->end()) {
157         _D("Unzip progress finished successfuly");
158     } else {
159         unzipProgress(destination);
160     }
161 }
162
163 bool WidgetUnzip::isDRMPackage(const std::string &source)
164 {
165     _D("Enter : isDRMPackage()");
166     int ret = 0;
167     void* pHandle = NULL;
168     char* pErrorMsg = NULL;
169     int (*drm_oem_sapps_is_drm_file)(const char* pDcfPath, int dcfPathLen);
170
171     pHandle = dlopen(DRM_LIB_PATH, RTLD_LAZY | RTLD_GLOBAL);
172     if (!pHandle) {
173         _E("dlopen failed : %s [%s]", source.c_str(), dlerror());
174         return false;
175     }
176
177     // clear existing error
178     dlerror();
179
180     drm_oem_sapps_is_drm_file = reinterpret_cast <int (*)(const char*, int)>
181         (dlsym(pHandle, "drm_oem_sapps_is_drm_file"));
182
183     if ((pErrorMsg = dlerror()) != NULL) {
184         _E("dlsym failed : %s [%s]", source.c_str(), pErrorMsg);
185         dlclose(pHandle);
186         return false;
187     }
188
189     if (drm_oem_sapps_is_drm_file == NULL) {
190         _E("drm_oem_sapps_is_drm_file is NULL : %s", source.c_str());
191         dlclose(pHandle);
192         return false;
193     }
194
195     ret = drm_oem_sapps_is_drm_file(source.c_str(), source.length());
196     dlclose(pHandle);
197     if (1 == ret) {
198         _D("%s is DRM file", source.c_str());
199         return true;
200     }
201     _D("%s isn't DRM file", source.c_str());
202     return false;
203 }
204
205 bool WidgetUnzip::decryptDRMPackage(const std::string &source, const std::string
206         &decryptedSource)
207 {
208     _D("Enter : decryptDRMPackage()");
209     int ret = 0;
210     void* pHandle = NULL;
211     char* pErrorMsg = NULL;
212     int (*drm_oem_sapps_decrypt_package)(const char* pDcfPath, int dcfPathLen,
213             const char* pDecryptedFile, int decryptedFileLen);
214
215     pHandle = dlopen(DRM_LIB_PATH, RTLD_LAZY | RTLD_GLOBAL);
216     if (!pHandle) {
217         _E("dlopen failed : %s [%s]", source.c_str(), dlerror());
218         return false;
219     }
220
221     // clear existing error
222     dlerror();
223
224     drm_oem_sapps_decrypt_package = reinterpret_cast <int (*)(const char*, int,
225             const char*, int)>
226         (dlsym(pHandle, "drm_oem_sapps_decrypt_package"));
227
228     if ((pErrorMsg = dlerror()) != NULL) {
229         _E("dlsym failed : %s [%s]", source.c_str(), pErrorMsg);
230         dlclose(pHandle);
231         return false;
232     }
233
234     if (drm_oem_sapps_decrypt_package == NULL) {
235         _E("drm_oem_sapps_decrypt_package is NULL : %s", source.c_str());
236         dlclose(pHandle);
237         return false;
238     }
239
240     ret = drm_oem_sapps_decrypt_package(source.c_str(), source.length(),
241             decryptedSource.c_str(), decryptedSource.length());
242     dlclose(pHandle);
243     if (1 == ret) {
244         _D("%s is decrypted : %s", source.c_str(), decryptedSource.c_str());
245         return true;
246     }
247     return false;
248 }
249
250 std::string WidgetUnzip::getDecryptedPackage(const std::string &source)
251 {
252     _D("Check DRM...");
253     if (isDRMPackage(source)) {
254         std::string decryptedFile;
255         size_t found = source.find_last_of(".wgt");
256         if (found == std::string::npos) {
257             decryptedFile += source + "_tmp.wgt";
258         } else {
259             decryptedFile += source.substr(0, source.find_last_not_of(".wgt") +
260                     1) + "_tmp.wgt";
261         }
262
263         _D("decrypted file name : %s", decryptedFile.c_str());
264         if (!decryptDRMPackage(source, decryptedFile)) {
265             _E("Failed decrypt drm file");
266             ThrowMsg(Exceptions::DrmDecryptFailed, source);
267         }
268         return decryptedFile;
269     }
270     return source;
271 }
272
273 void WidgetUnzip::unzipWgtFile(const std::string &source, const std::string &destination)
274 {
275     _D("Prepare to unzip...");
276     std::string wgtFile;
277     Try
278     {
279         wgtFile = getDecryptedPackage(source);
280         _D("wgtFile : %s", wgtFile.c_str());
281
282         m_zip.reset(new DPL::ZipInput(wgtFile));
283         _D("Widget package comment: %s", m_zip->GetGlobalComment().c_str());
284
285
286         // Widget package must not be empty
287         if (m_zip->empty()) {
288             ThrowMsg(Exceptions::ZipEmpty, wgtFile);
289         }
290
291         checkAvailableSpace(destination);
292
293         // Set iterator to first file
294         m_zipIterator = m_zip->begin();
295
296         unzipProgress(destination);
297
298         // Unzip finished, close internal structures
299         m_zip.reset();
300
301         // Done
302         _D("Unzip finished");
303     }
304     Catch(DPL::ZipInput::Exception::OpenFailed)
305     {
306         ReThrowMsg(Exceptions::OpenZipFailed, wgtFile);
307     }
308     Catch(DPL::ZipInput::Exception::SeekFileFailed)
309     {
310         ThrowMsg(Exceptions::ExtractFileFailed, wgtFile);
311     }
312     Catch(Exceptions::DrmDecryptFailed)
313     {
314         ReThrowMsg(Exceptions::ExtractFileFailed, wgtFile);
315     }
316 }
317
318 void WidgetUnzip::checkAvailableSpace(const std::string &destination)
319 {
320     _D("checkAvailableSpace ... ");
321
322     double unCompressedSize = m_zip->GetTotalUncompressedSize();
323     _D("unCompressedSize : %ld", unCompressedSize);
324
325     struct statvfs vfs;
326     if (-1 == statvfs(destination.c_str(), &vfs)) {
327         ThrowMsg(Exceptions::OutOfStorageFailed, "There is no space for installation");
328     }
329
330     double freeSize = (double)vfs.f_bsize * vfs.f_bavail;
331     _D("Space Size : %ld", freeSize);
332
333     if (unCompressedSize + SPACE_SIZE >= freeSize) {
334         ThrowMsg(Exceptions::OutOfStorageFailed, "There is no space for installation");
335     }
336 }
337
338 } //namespace WidgetInstall
339 } //namespace Jobs