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