Fixed decrypt DRM web app.
[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/log/log.h>
27 #include <dpl/copy.h>
28 #include <dpl/file_output.h>
29 #include <dpl/abstract_waitable_input_adapter.h>
30 #include <dpl/wrt-dao-ro/global_config.h>
31 #include <task_commons.h>
32 #include <sys/stat.h>
33 #include <dlfcn.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     LogInfo("Unzipping: '" << m_zipIterator->name <<
94             "', Comment: '" << m_zipIterator->comment <<
95             "', Compressed size: " << m_zipIterator->compressedSize <<
96             ", Uncompressed size: " << 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         LogPedantic("Path to extract: " << newPath);
109
110         // Create path in case of it is empty
111         createTempPath(newPath);
112     } else {
113         // This is regular file
114         std::string fileExtractPath = destination + "/" + fileName;
115
116         LogPedantic("File to extract: " << fileExtractPath);
117
118         // Split into pat & file pair
119         PathAndFilePair pathAndFile = SplitFileAndPath(fileExtractPath);
120
121         LogPedantic("Path and file: " <<
122                     pathAndFile.path <<
123                     " : " << pathAndFile.file);
124
125         // First, ensure that path exists
126         createTempPath(pathAndFile.path);
127
128         Try
129         {
130             // Open file
131             std::unique_ptr<DPL::ZipInput::File> file(
132                 m_zip->OpenFile(fileName));
133
134             // Extract single file
135             ExtractFile(file.get(), fileExtractPath);
136         }
137         Catch(DPL::ZipInput::Exception::OpenFileFailed)
138         {
139             ThrowMsg(Exceptions::ExtractFileFailed, fileName);
140         }
141     }
142
143     // Check whether there are more files to extract
144     if (++m_zipIterator == m_zip->end()) {
145         LogInfo("Unzip progress finished successfuly");
146     } else {
147         unzipProgress(destination);
148     }
149 }
150
151 bool WidgetUnzip::isDRMPackage(const std::string &source)
152 {
153     LogDebug("Enter : isDRMPackage()");
154     int ret = 0;
155     void* pHandle = NULL;
156     char* pErrorMsg = NULL;
157     int (*drm_oem_sapps_is_drm_file)(const char* pDcfPath, int dcfPathLen);
158
159     pHandle = dlopen(DRM_LIB_PATH, RTLD_LAZY | RTLD_GLOBAL);
160     if (!pHandle) {
161         LogError("dlopen failed : " << source << " [" << dlerror() << "]");
162         return false;
163     }
164
165     drm_oem_sapps_is_drm_file = reinterpret_cast <int (*)(const char*, int)>
166         (dlsym(pHandle, "drm_oem_sapps_is_drm_file"));
167     pErrorMsg = dlerror();
168     if ((pErrorMsg != NULL) || (drm_oem_sapps_is_drm_file == NULL)) {
169         LogError("dlopen failed : " << source << " [" << dlerror() << "]");
170         dlclose(pHandle);
171         return false;
172     }
173
174     ret = drm_oem_sapps_is_drm_file(source.c_str(), source.length());
175     dlclose(pHandle);
176     if (1 == ret) {
177         LogInfo(source << " is DRM file");
178         return true;
179     }
180     LogInfo(source << " isn't DRM file");
181     return false;
182 }
183
184 bool WidgetUnzip::decryptDRMPackage(const std::string &source, const std::string
185         &decryptedSource)
186 {
187     LogDebug("Enter : decryptDRMPackage()");
188     int ret = 0;
189     void* pHandle = NULL;
190     char* pErrorMsg = NULL;
191     int (*drm_oem_sapps_decrypt_package)(const char* pDcfPath, int dcfPathLen,
192             const char* pDecryptedFile, int decryptedFileLen);
193
194     pHandle = dlopen(DRM_LIB_PATH, RTLD_LAZY | RTLD_GLOBAL);
195     if (!pHandle) {
196         LogError("dlopen failed : " << source << " [" << dlerror() << "]");
197         return false;
198     }
199
200     drm_oem_sapps_decrypt_package = reinterpret_cast <int (*)(const char*, int,
201             const char*, int)>
202         (dlsym(pHandle, "drm_oem_sapps_decrypt_package"));
203     pErrorMsg = dlerror();
204     if ((pErrorMsg != NULL) || (drm_oem_sapps_decrypt_package == NULL)) {
205         LogError("dlopen failed : " << source << " [" << dlerror() << "]");
206         dlclose(pHandle);
207         return false;
208     }
209
210     ret = drm_oem_sapps_decrypt_package(source.c_str(), source.length(),
211             decryptedSource.c_str(), decryptedSource.length());
212     dlclose(pHandle);
213     if (1 == ret) {
214         LogInfo(source << " is decrypted : " << decryptedSource);
215         return true;
216     }
217     return false;
218 }
219
220 std::string WidgetUnzip::getDecryptedPackage(const std::string &source)
221 {
222     LogInfo("Check DRM...");
223     if (isDRMPackage(source)) {
224         std::string decryptedFile;
225         size_t found = source.find_last_of(".wgt");
226         if (found == std::string::npos) {
227             decryptedFile += source + "_tmp.wgt";
228         } else {
229             decryptedFile += source.substr(0, source.find_last_not_of(".wgt") +
230                     1) + "_tmp.wgt";
231         }
232
233         LogDebug("decrypted file name : " << decryptedFile);
234         if (!decryptDRMPackage(source, decryptedFile)) {
235             LogError("Failed decrypt drm file");
236             ThrowMsg(Exceptions::DrmDecryptFailed, source);
237         }
238         return decryptedFile;
239     }
240     return source;
241 }
242
243 void WidgetUnzip::unzipWgtFile(const std::string &source, const std::string &destination)
244 {
245     LogInfo("Prepare to unzip...");
246     std::string wgtFile;
247     Try
248     {
249         wgtFile = getDecryptedPackage(source);
250         LogDebug("wgtFile : " << wgtFile);
251
252         m_zip.reset(new DPL::ZipInput(wgtFile));
253         LogInfo("Widget package comment: " << m_zip->GetGlobalComment());
254
255         // Widget package must not be empty
256         if (m_zip->empty()) {
257             ThrowMsg(Exceptions::ZipEmpty, wgtFile);
258         }
259
260         // Set iterator to first file
261         m_zipIterator = m_zip->begin();
262
263         unzipProgress(destination);
264
265         // Unzip finished, close internal structures
266         m_zip.reset();
267
268         // Done
269         LogInfo("Unzip finished");
270     }
271     Catch(DPL::ZipInput::Exception::OpenFailed)
272     {
273         ReThrowMsg(Exceptions::OpenZipFailed, wgtFile);
274     }
275     Catch(DPL::ZipInput::Exception::SeekFileFailed)
276     {
277         ThrowMsg(Exceptions::ExtractFileFailed, wgtFile);
278     }
279     Catch(Exceptions::DrmDecryptFailed)
280     {
281         ReThrowMsg(Exceptions::ExtractFileFailed, wgtFile);
282     }
283 }
284
285 } //namespace WidgetInstall
286 } //namespace Jobs