tizen 2.4 release
[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/abstract_waitable_input_adapter.h>
29 #include <dpl/wrt-dao-ro/global_config.h>
30 #include <task_commons.h>
31 #include <sys/stat.h>
32 #include <storage.h>
33 #include <boost/filesystem.hpp>
34 #include <dpl/log/secure_log.h>
35 #if USE(DRM)
36 #include <drm-tizen-apps.h>
37 #endif
38
39 using namespace WrtDB;
40 namespace bf = boost::filesystem;
41
42 namespace {
43 const size_t SPACE_SIZE = 1024 * 1024;
44 const char *const WEB_APP_CONFIG_XML= "config.xml";
45 const char *const HYBRID_CONFIG_XML = "res/wgt/config.xml";
46
47 struct PathAndFilePair
48 {
49     std::string path;
50     std::string file;
51
52     PathAndFilePair(const std::string &p,
53                     const std::string &f) :
54         path(p),
55         file(f)
56     {}
57 };
58
59 PathAndFilePair SplitFileAndPath(const std::string &filePath)
60 {
61     std::string::size_type position = filePath.rfind('/');
62
63     // Is this only a file without a path ?
64     if (position == std::string::npos) {
65         return PathAndFilePair(std::string(), filePath);
66     }
67
68     // This is full file-path pair
69     return PathAndFilePair(filePath.substr(0,
70                                            position),
71                            filePath.substr(position + 1));
72 }
73 }
74
75 namespace Jobs {
76 namespace WidgetInstall {
77
78 bool WidgetUnzip::isAvailablePath(const bf::path &actualPath, const bf::path &destination)
79 {
80     if (actualPath == destination || m_availablePathSet.find(actualPath) != m_availablePathSet.end()) {
81         return true;
82     }
83
84     bf::path absolutePath = absolute(actualPath);
85     bf::path::iterator it = absolutePath.begin();
86     bf::path resultPath = *it++;
87
88     while (it != absolutePath.end()) {
89         if (exists(resultPath / *it)) {
90             resultPath /= *it;
91         } else {
92             if (*it == "..") {
93                 resultPath = resultPath.parent_path();
94             } else if (*it == ".") {
95                 resultPath /= *it;
96             }
97         }
98         it++;
99     }
100
101     resultPath = canonical(resultPath);
102
103     if (resultPath.string().find(canonical(destination).string()) == 0) {
104         m_availablePathSet.insert(resultPath);
105         _D("Actual path to extract: [%s]", resultPath.string().c_str());
106         return true;
107     } else {
108         return false;
109     }
110 }
111
112 WidgetUnzip::WidgetUnzip(const std::string &source)
113 {
114     Try {
115 #if USE(DRM)
116         m_requestFile = getDecryptedPackage(source);
117 #else
118         m_requestFile = source;
119 #endif
120         m_zip.reset(new DPL::ZipInput(m_requestFile));
121     }
122     Catch(DPL::ZipInput::Exception::OpenFailed)
123     {
124         ReThrowMsg(Exceptions::OpenZipFailed, source);
125     }
126 #if USE(DRM)
127     Catch(Exceptions::DrmDecryptFailed)
128     {
129         ReThrowMsg(Exceptions::ExtractFileFailed, source);
130     }
131 #endif
132 }
133
134 void WidgetUnzip::ExtractFile(DPL::ZipInput::File *input,
135                             const std::string &destFileName)
136 {
137     Try
138     {
139         DPL::AbstractWaitableInputAdapter inputAdapter(input);
140         DPL::FileOutput output(destFileName);
141
142         DPL::Copy(&inputAdapter, &output);
143     }
144     Catch(DPL::FileOutput::Exception::OpenFailed)
145     {
146         ReThrowMsg(Exceptions::ExtractFileFailed, destFileName);
147     }
148     Catch(DPL::CopyFailed)
149     {
150         ReThrowMsg(Exceptions::ExtractFileFailed, destFileName);
151     }
152 }
153
154 void WidgetUnzip::unzipProgress(const std::string &destination)
155 {
156     // Show file info
157     _D("Unzipping: '%s', Comment: '%s', Compressed size: %lld, Uncompressed size: %lld",
158             m_zipIterator->name.c_str(), m_zipIterator->comment.c_str(), m_zipIterator->compressedSize, m_zipIterator->uncompressedSize);
159
160     // Normalize file paths
161     // FIXME: Implement checking for invalid characters
162
163     // Extract file or path
164     std::string fileName = m_zipIterator->name;
165
166     if (fileName[fileName.size() - 1] == '/') {
167         // This is path
168         std::string newPath = destination + "/" +
169             fileName.substr(0, fileName.size() - 1);
170         _D("Path to extract: %s", newPath.c_str());
171
172         bf::path actualPath(newPath.c_str());
173
174         if (isAvailablePath(actualPath, bf::path(destination.c_str()))) {
175             // Create path in case of it is empty
176             createTempPath(newPath);
177         } else {
178             _E("Fail unzip progress. Actual path is different from installation path");
179             ThrowMsg(Exceptions::ExtractFileFailed, "Fail unzip progress. Actual path is different from installation path");
180         }
181     } else {
182         // This is regular file
183         std::string fileExtractPath = destination + "/" + fileName;
184         _D("File to extract: %s", fileExtractPath.c_str());
185
186         // Split into pat & file pair
187         PathAndFilePair pathAndFile = SplitFileAndPath(fileExtractPath);
188
189         _D("Path and file: %s : %s", pathAndFile.path.c_str(), pathAndFile.file.c_str());
190
191         bf::path actualPath(pathAndFile.path.c_str());
192
193         if (isAvailablePath(actualPath, bf::path(destination.c_str()))) {
194             // First, ensure that path exists
195             createTempPath(pathAndFile.path);
196         } else {
197             _E("Fail unzip progress. Actual path is different from installation path");
198             ThrowMsg(Exceptions::ExtractFileFailed, "Fail unzip progress. Actual path is different from installation path");
199         }
200
201         Try
202         {
203             // Open file
204             std::unique_ptr<DPL::ZipInput::File> file(
205                 m_zip->OpenFile(fileName));
206
207             // Extract single file
208             ExtractFile(file.get(), fileExtractPath);
209         }
210         Catch(DPL::ZipInput::Exception::OpenFileFailed)
211         {
212             ThrowMsg(Exceptions::ExtractFileFailed, fileName);
213         }
214     }
215
216     // Check whether there are more files to extract
217     if (++m_zipIterator == m_zip->end()) {
218         _D("Unzip progress finished successfuly");
219     } else {
220         unzipProgress(destination);
221     }
222 }
223
224 #if USE(DRM)
225 bool WidgetUnzip::isDRMPackage(const std::string &source)
226 {
227     _D("Enter : isDRMPackage()");
228     int ret = drm_tizen_is_drm_file(source.c_str(), source.length());
229
230     if (ret != 1) {
231         _D("%s isn't DRM file. retcode from drm[%d]", source.c_str(), ret);
232         return false;
233     }
234
235     _D("%s is DRM file", source.c_str());
236     return true;
237 }
238
239 bool WidgetUnzip::decryptDRMPackage(const std::string &source, const std::string
240         &decryptedSource)
241 {
242     _D("Enter : decryptDRMPackage()");
243     int ret = drm_tizen_decrypt_package(source.c_str(), source.length(),
244             decryptedSource.c_str(), decryptedSource.length());
245
246     if (1 != ret) {
247         _W("drm decrypt package failed. source[%s], retcode[%d]", source.c_str(), ret);
248         return false;
249     }
250
251     return true;
252 }
253
254 std::string WidgetUnzip::getDecryptedPackage(const std::string &source)
255 {
256     _D("Check DRM...");
257     if (isDRMPackage(source)) {
258         std::string decryptedFile;
259         size_t found = source.find_last_of(".wgt");
260         if (found == std::string::npos) {
261             decryptedFile += source + "_tmp.wgt";
262         } else {
263             decryptedFile += source.substr(0, source.find_last_not_of(".wgt") +
264                     1) + "_tmp.wgt";
265         }
266
267         _D("decrypted file name : %s", decryptedFile.c_str());
268         if (!decryptDRMPackage(source, decryptedFile)) {
269             _E("Failed decrypt drm file");
270             ThrowMsg(Exceptions::DrmDecryptFailed, source);
271         }
272         return decryptedFile;
273     }
274     return source;
275 }
276 #endif
277
278 void WidgetUnzip::unzipWgtFile(const std::string &destination)
279 {
280     _D("Prepare to unzip...");
281     Try
282     {
283         _D("wgtFile : %s", m_requestFile.c_str());
284         _D("Widget package comment: %s", m_zip->GetGlobalComment().c_str());
285
286         // Widget package must not be empty
287         if (m_zip->empty()) {
288             ThrowMsg(Exceptions::ZipEmpty, m_requestFile);
289         }
290
291         // Set iterator to first file
292         m_zipIterator = m_zip->begin();
293
294         unzipProgress(destination);
295
296         // Unzip finished, close internal structures
297         m_zip.reset();
298
299         // Done
300         _D("Unzip finished");
301     }
302     Catch(DPL::ZipInput::Exception::OpenFailed)
303     {
304         ReThrowMsg(Exceptions::OpenZipFailed, m_requestFile);
305     }
306     Catch(DPL::ZipInput::Exception::SeekFileFailed)
307     {
308         ThrowMsg(Exceptions::ExtractFileFailed, m_requestFile);
309     }
310 #if USE(DRM)
311     Catch(Exceptions::DrmDecryptFailed)
312     {
313         ReThrowMsg(Exceptions::ExtractFileFailed, m_requestFile);
314     }
315 #endif
316 }
317
318 bool WidgetUnzip::checkAvailableSpace(const std::string &/*destination*/)
319 {
320     _D("checkAvailableSpace ... ");
321
322     double unCompressedSize = m_zip->GetTotalUncompressedSize();
323     _D("unCompressedSize : %f", unCompressedSize);
324
325     struct statvfs vfs;
326     if (0 > storage_get_internal_memory_size(&vfs)) {
327         _E("There is no space for installation");
328         return false;
329     }
330
331     double freeSize = (double)vfs.f_bsize * vfs.f_bavail;
332     _D("Space Size : %f", freeSize);
333
334     if (unCompressedSize + SPACE_SIZE >= freeSize) {
335         _E("There is no space for installation");
336         return false;
337     }
338     return true;
339 }
340
341 void WidgetUnzip::unzipConfiguration(const std::string &destination,
342         WrtDB::PackagingType* type)
343 {
344     _D("unzipConfiguration");
345
346     Try {
347         _D("wgtFile : %s", m_requestFile.c_str());
348
349         std::unique_ptr<DPL::ZipInput::File> configFile;
350
351         Try {
352             configFile.reset(m_zip->OpenFile(HYBRID_CONFIG_XML));
353             *type = PKG_TYPE_HYBRID_WEB_APP;
354         } Catch(DPL::ZipInput::Exception::OpenFileFailed) {
355             configFile.reset(m_zip->OpenFile(WEB_APP_CONFIG_XML));
356             *type = PKG_TYPE_NOMAL_WEB_APP;
357         }
358
359         std::string extractPath = destination + "/" + WEB_APP_CONFIG_XML;
360         ExtractFile(configFile.get(), extractPath);
361     }
362     Catch(DPL::ZipInput::Exception::OpenFailed)
363     {
364         ReThrowMsg(Exceptions::OpenZipFailed, m_requestFile);
365     }
366     Catch(DPL::ZipInput::Exception::OpenFileFailed)
367     {
368         ThrowMsg(Exceptions::ExtractFileFailed, "config.xml");
369     }
370 #if USE(DRM)
371     Catch(Exceptions::DrmDecryptFailed)
372     {
373         ReThrowMsg(Exceptions::ExtractFileFailed, m_requestFile);
374     }
375 #endif
376 }
377
378 } //namespace WidgetInstall
379 } //namespace Jobs