[Release] wrt-installer_0.1.0 for sdk branch
[framework/web/wrt-installer.git] / src / jobs / widget_install / job_widget_install.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    job_widget_install.cpp
18  * @author  Radoslaw Wicik r.wicik@samsung.com
19  * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
20  * @version 1.0
21  * @brief   Implementation file for main installer task
22  */
23 #include <memory>
24 #include <string>
25 #include <sys/time.h>
26 #include <ctime>
27 #include <cstdlib>
28 #include <limits.h>
29 #include <regex.h>
30
31 #include <dpl/noncopyable.h>
32 #include <dpl/abstract_waitable_input_adapter.h>
33 #include <dpl/abstract_waitable_output_adapter.h>
34 #include <dpl/zip_input.h>
35 #include <dpl/binary_queue.h>
36 #include <dpl/copy.h>
37 #include <dpl/assert.h>
38 #include <dpl/sstream.h>
39 #include <dpl/file_input.h>
40 #include <dpl/utils/wrt_utility.h>
41 #include <dpl/wrt-dao-ro/common_dao_types.h>
42 #include <dpl/wrt-dao-ro/widget_dao_read_only.h>
43 #include <dpl/wrt-dao-ro/global_config.h>
44 #include <dpl/wrt-dao-ro/config_parser_data.h>
45 #include <dpl/wrt-dao-rw/global_dao.h> // TODO remove
46 #include <dpl/localization/w3c_file_localization.h>
47
48 #include <libiriwrapper.h>
49 #include <pkg-manager/pkgmgr_signal.h>
50 #include <app_manager.h>
51 //#include <drm_client.h>
52 #include <drm-oem-intel.h> //temporary code
53
54 #include "root_parser.h"
55 #include "widget_parser.h"
56 #include "parser_runner.h"
57 #include <widget_install/job_widget_install.h>
58 #include <widget_install/task_certify.h>
59 #include <widget_install/task_widget_config.h>
60 #include <widget_install/task_file_manipulation.h>
61 #include <widget_install/task_ace_check.h>
62 #include <widget_install/task_smack.h>
63 #include <widget_install/task_manifest_file.h>
64 #include <widget_install/task_prepare_files.h>
65 #include <widget_install/task_recovery.h>
66 #include <widget_install/task_install_ospsvc.h>
67 #include <widget_install/task_update_files.h>
68 #include <widget_install/task_database.h>
69 #include <widget_install/task_remove_backup.h>
70 #include <widget_install/task_encrypt_resource.h>
71 #include <widget_install/task_certificates.h>
72 #include <widget_install/task_unzip.h>
73 #include <widget_install/task_commons.h>
74
75 #include <widget_install/task_plugins_copy.h>
76
77 #include <widget_install/widget_install_errors.h>
78 #include <widget_install/widget_install_context.h>
79 #include <widget_install_to_external.h>
80
81 using namespace WrtDB;
82
83 namespace // anonymous
84 {
85 const char * const CONFIG_XML = "config.xml";
86 const char * const WITH_OSP_XML = "res/wgt/config.xml";
87
88 //allowed: a-z, A-Z, 0-9
89 const char* REG_TIZENID_PATTERN = "^[a-zA-Z0-9]{10}.{1,}$";
90 const size_t PACKAGE_ID_LENGTH = 10;
91
92 static const DPL::String SETTING_VALUE_ENCRYPTION = L"encryption";
93 static const DPL::String SETTING_VALUE_ENCRYPTION_ENABLE = L"enable";
94 const DPL::String SETTING_VALUE_INSTALLTOEXT_NAME =
95     L"install-location-type";
96 const DPL::String SETTING_VALUE_INSTALLTOEXT_PREPER_EXT =
97     L"prefer-external";
98
99 class InstallerTaskFail :
100     public DPL::TaskDecl<InstallerTaskFail>
101 {
102   private:
103     bool m_deferred;
104
105     void StepFail()
106     {
107         if (m_deferred) {
108             ThrowMsg(Jobs::WidgetInstall::Exceptions::Deferred,
109                      "Widget installation or update deferred!");
110         } else {
111             ThrowMsg(Jobs::WidgetInstall::Exceptions::NotAllowed,
112                      "Widget installation or update not allowed!");
113         }
114     }
115
116   public:
117     InstallerTaskFail(bool deferred) :
118         DPL::TaskDecl<InstallerTaskFail>(this),
119         m_deferred(deferred)
120     {
121         AddStep(&InstallerTaskFail::StepFail);
122     }
123 };
124
125 const std::string XML_EXTENSION = ".xml";
126
127 bool hasExtension(const std::string& filename, const std::string& extension) {
128     LogDebug("Looking for extension " << extension << " in: "  << filename);
129     size_t fileLen = filename.length();
130     size_t extLen = extension.length();
131     if (fileLen < extLen) {
132         LogError("Filename " << filename << " is shorter than extension "
133                  << extension);
134         return false;
135     }
136     return (0 == filename.compare(fileLen-extLen, extLen, extension));
137 }
138
139 bool checkTizenPkgIdExist(const std::string& tizenPkgId) {
140     std::string installPath =
141         std::string(GlobalConfig::GetUserInstalledWidgetPath()) +
142         "/" + tizenPkgId;
143     std::string preinstallPath =
144         std::string(GlobalConfig::GetUserPreloadedWidgetPath()) +
145         "/" + tizenPkgId;
146
147     struct stat dirStat;
148     if ((stat(installPath.c_str(), &dirStat) == 0) &&
149             (stat(preinstallPath.c_str(), &dirStat) == 0)) {
150         return true;
151     }
152     return false;
153 }
154 } // namespace anonymous
155
156 namespace Jobs {
157 namespace WidgetInstall {
158 JobWidgetInstall::JobWidgetInstall(std::string const &widgetPath,
159         const WidgetInstallationStruct &installerStruct) :
160     Job(Installation),
161     JobContextBase<WidgetInstallationStruct>(installerStruct),
162     m_exceptionCaught(Exceptions::Success)
163 {
164     struct timeval tv;
165     gettimeofday(&tv, NULL);
166     srand(time(NULL) + tv.tv_usec);
167
168     m_installerContext.m_quiet = m_jobStruct.m_quiet;
169
170     ConfigureResult result = PrePareInstallation(widgetPath);
171     m_installerContext.job->SetProgressFlag(true);
172
173     if (result == ConfigureResult::Ok) {
174         LogInfo("Configure installation succeeded");
175
176         AddTask(new TaskRecovery(m_installerContext));
177
178         // Create installation tasks
179         if (m_installerContext.widgetConfig.packagingType !=
180                 WrtDB::PKG_TYPE_DIRECTORY_WEB_APP &&
181             m_installerContext.widgetConfig.packagingType !=
182                 WrtDB::PKG_TYPE_HOSTED_WEB_APP &&
183             !m_isDRM)
184         {
185             AddTask(new TaskUnzip(m_installerContext));
186         }
187
188         AddTask(new TaskWidgetConfig(m_installerContext));
189         if (m_installerContext.widgetConfig.packagingType  ==
190                 WrtDB::PKG_TYPE_HOSTED_WEB_APP)
191         {
192             AddTask(new TaskPrepareFiles(m_installerContext));
193         }
194         AddTask(new TaskCertify(m_installerContext));
195         if (m_needEncryption) {
196             AddTask(new TaskEncryptResource(m_installerContext));
197         }
198
199         AddTask(new TaskFileManipulation(m_installerContext));
200         // TODO: Update progress information for this task
201
202         //This is sort of quick solution, because ACE verdicts are based upon
203         //data from DAO (DB). So AceCheck for now has to be AFTER DbUpdate
204         //task.
205         AddTask(new TaskSmack(m_installerContext));
206
207         AddTask(new TaskManifestFile(m_installerContext));
208         AddTask(new TaskCertificates(m_installerContext));
209         if (m_installerContext.widgetConfig.packagingType ==
210                 PKG_TYPE_HYBRID_WEB_APP) {
211             AddTask(new TaskInstallOspsvc(m_installerContext));
212         }
213         AddTask(new TaskPluginsCopy(m_installerContext));
214         AddTask(new TaskDatabase(m_installerContext));
215         AddTask(new TaskAceCheck(m_installerContext));
216     } else if (result == ConfigureResult::Updated) {
217         LogInfo("Configure installation updated");
218         LogInfo("Widget Update");
219         if (m_installerContext.widgetConfig.packagingType !=
220                 WrtDB::PKG_TYPE_HOSTED_WEB_APP &&
221             m_installerContext.widgetConfig.packagingType !=
222                 WrtDB::PKG_TYPE_DIRECTORY_WEB_APP &&
223             !m_isDRM)
224         {
225             AddTask(new TaskUnzip(m_installerContext));
226         }
227
228         AddTask(new TaskWidgetConfig(m_installerContext));
229
230         if (m_installerContext.widgetConfig.packagingType ==
231                 WrtDB::PKG_TYPE_HOSTED_WEB_APP)
232         {
233             AddTask(new TaskPrepareFiles(m_installerContext));
234         }
235
236         AddTask(new TaskCertify(m_installerContext));
237         if (m_installerContext.widgetConfig.packagingType !=
238             WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
239         {
240             AddTask(new TaskUpdateFiles(m_installerContext));
241         }
242
243         /* TODO : To backup file, save md5 values */
244         AddTask(new TaskSmack(m_installerContext));
245
246         AddTask(new TaskManifestFile(m_installerContext));
247         if (m_installerContext.widgetConfig.packagingType ==
248                 PKG_TYPE_HYBRID_WEB_APP) {
249             AddTask(new TaskInstallOspsvc(m_installerContext));
250         }
251         if (m_installerContext.widgetConfig.packagingType !=
252             WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
253         {
254             AddTask(new TaskRemoveBackupFiles(m_installerContext));
255         }
256         AddTask(new TaskPluginsCopy(m_installerContext));
257         AddTask(new TaskDatabase(m_installerContext));
258         AddTask(new TaskAceCheck(m_installerContext));
259         //TODO: remove widgetHandle from this task and move before database task
260         // by now widget handle is needed in ace check
261         // Any error in acecheck while update will break widget
262
263     } else if (result == ConfigureResult::Deferred) {
264         // Installation is deferred
265         LogInfo("Configure installation deferred");
266
267         AddTask(new InstallerTaskFail(true));
268     } else if (result == ConfigureResult::Failed) {
269         // Installation is not allowed to proceed due to widget update policy
270         LogWarning("Configure installation failed!");
271
272         AddTask(new InstallerTaskFail(false));
273     } else {
274         Assert(false && "Invalid configure result!");
275     }
276 }
277
278 JobWidgetInstall::ConfigureResult JobWidgetInstall::PrePareInstallation(
279         const std::string &widgetPath)
280 {
281     ConfigureResult result;
282     m_needEncryption = false;
283
284     Try
285     {
286         std::string tempDir =
287             Jobs::WidgetInstall::createTempPath(m_jobStruct.m_preload);
288
289         m_isDRM = isDRMWidget(widgetPath);
290         if (true == m_isDRM) {
291             LogDebug("decrypt DRM widget");
292             if(DecryptDRMWidget(widgetPath, tempDir)) {
293                 LogDebug("Failed decrypt DRM widget");
294                 return ConfigureResult::Failed;
295             }
296         }
297
298         LogDebug("widgetPath:" << widgetPath);
299
300         m_installerContext.widgetConfig.packagingType =
301             checkPackageType(widgetPath, tempDir);
302         ConfigParserData configData = getWidgetDataFromXML(
303             widgetPath,
304             tempDir,
305             m_installerContext.widgetConfig.packagingType,
306             m_isDRM);
307         LogDebug("widget packaging type : " <<
308                 m_installerContext.widgetConfig.packagingType.pkgType);
309
310         setTizenId(configData);
311         setApplicationType(configData);
312         m_needEncryption = detectResourceEncryption(configData);
313         setInstallLocationType(configData);
314
315         // Configure installation
316         result = ConfigureInstallation(widgetPath, configData, tempDir);
317     }
318     Catch(Exceptions::ExtractFileFailed)
319     {
320         LogError("Failed to create temporary path for widget");
321         result = ConfigureResult::Failed;
322     }
323
324     return result;
325 }
326
327 void JobWidgetInstall::setTizenId(
328         const WrtDB::ConfigParserData &configInfo)
329 {
330     bool shouldMakeAppid = false;
331     using namespace PackageManager;
332     if(!!configInfo.tizenAppId) {
333         LogDebug("Setting tizenAppId provided in config.xml: " <<
334                 configInfo.tizenAppId);
335
336         m_installerContext.widgetConfig.tzAppid = *configInfo.tizenAppId;
337         //check package id.
338         if(!!configInfo.tizenPkgId) {
339             LogDebug("Setting tizenPkgId provided in config.xml: " <<
340                     configInfo.tizenPkgId);
341
342             m_installerContext.widgetConfig.tzPkgid = *configInfo.tizenPkgId;
343         } else {
344             std::string appid = DPL::ToUTF8String(*configInfo.tizenAppId);
345             if(appid.length() > PACKAGE_ID_LENGTH) {
346                 m_installerContext.widgetConfig.tzPkgid =
347                     DPL::FromUTF8String(appid.substr(PACKAGE_ID_LENGTH));
348             } else {
349                 m_installerContext.widgetConfig.tzPkgid =
350                     *configInfo.tizenAppId;
351             }
352             shouldMakeAppid = true;
353         }
354     } else {
355         shouldMakeAppid = true;
356         TizenPkgId pkgId = WidgetDAOReadOnly::generatePkgId();
357         LogDebug("Checking if pkg id is unique");
358         while (true) {
359             if (checkTizenPkgIdExist(DPL::ToUTF8String(pkgId))) {
360                 //path exist, chose another one
361                 pkgId = WidgetDAOReadOnly::generatePkgId();
362                 continue;
363             }
364             break;
365         }
366         m_installerContext.widgetConfig.tzPkgid = pkgId;
367         LogInfo("tizen_id name was generated by WRT: " <<
368                 m_installerContext.widgetConfig.tzPkgid);
369
370     }
371
372     if(shouldMakeAppid == true) {
373         DPL::OptionalString name;
374         DPL::OptionalString defaultLocale = configInfo.defaultlocale;
375
376         FOREACH(localizedData, configInfo.localizedDataSet)
377         {
378             Locale i = localizedData->first;
379             if (!!defaultLocale) {
380                 if (defaultLocale == i) {
381                     name = localizedData->second.name;
382                     break;
383                 }
384
385             } else {
386                 name = localizedData->second.name;
387                 break;
388             }
389         }
390         if (!!name) {
391             LogDebug("Name : " << name);
392             std::ostringstream appid;
393             appid << m_installerContext.widgetConfig.tzPkgid << "." << name;
394             LogDebug("tizen appid was generated by WRT : " << appid.str());
395             m_installerContext.widgetConfig.tzAppid =
396                 DPL::FromUTF8String(appid.str());
397         } else {
398             m_installerContext.widgetConfig.tzAppid =
399                 m_installerContext.widgetConfig.tzPkgid;
400         }
401         DPL::OptionalString appid = m_installerContext.widgetConfig.tzAppid;
402         NormalizeAndTrimSpaceString(appid);
403         m_installerContext.widgetConfig.tzAppid = *appid;
404     }
405
406     // send start signal of pkgmgr
407     getInstallerStruct().pkgmgrInterface->setPkgname(DPL::ToUTF8String(
408                 m_installerContext.widgetConfig.tzAppid));
409     getInstallerStruct().pkgmgrInterface->sendSignal(
410             PKGMGR_START_KEY,
411             PKGMGR_START_INSTALL);
412
413     LogInfo("Tizen App Id : " << m_installerContext.widgetConfig.tzAppid);
414     LogInfo("Tizen Pkg Id : " << m_installerContext.widgetConfig.tzPkgid);
415     LogInfo("W3C Widget GUID : " << m_installerContext.widgetConfig.guid);
416 }
417
418 void JobWidgetInstall::configureWidgetLocation(const std::string & widgetPath,
419                                                const std::string& tempPath)
420 {
421     m_installerContext.locations =
422         WidgetLocation(DPL::ToUTF8String(m_installerContext.widgetConfig.tzPkgid),
423                 widgetPath, tempPath,
424                 m_installerContext.widgetConfig.packagingType,
425                 m_installerContext.locationType);
426     m_installerContext.locations->registerAppid(
427             DPL::ToUTF8String(m_installerContext.widgetConfig.tzAppid));
428
429     LogInfo("widgetSource " << widgetPath);
430 }
431
432 JobWidgetInstall::ConfigureResult JobWidgetInstall::ConfigureInstallation(
433         const std::string &widgetSource,
434         const WrtDB::ConfigParserData &configData,
435         const std::string &tempPath)
436 {
437     WidgetUpdateInfo update = detectWidgetUpdate(configData,
438             m_installerContext.widgetConfig.webAppType,
439             m_installerContext.widgetConfig.tzAppid);
440     ConfigureResult result = checkWidgetUpdate(update);
441
442     // Validate tizenId
443     regex_t reg;
444     if(regcomp(&reg, REG_TIZENID_PATTERN, REG_NOSUB | REG_EXTENDED)!=0){
445         LogDebug("Regcomp failed");
446     }
447
448     if ((regexec(&reg,
449                     DPL::ToUTF8String(m_installerContext.widgetConfig.tzAppid).c_str(),
450                     static_cast<size_t>(0), NULL, 0) != REG_NOERROR) ||
451             (checkTizenPkgIdExist(DPL::ToUTF8String(m_installerContext.widgetConfig.tzPkgid)) &&
452              result != ConfigureResult::Updated))
453     {
454         //it is true when tizenId does not fit REG_TIZENID_PATTERN
455         LogError("tizen_id provided but not proper.");
456         regfree(&reg);
457         return ConfigureResult::Failed;
458     }
459     regfree(&reg);
460
461     configureWidgetLocation(widgetSource, tempPath);
462
463     // Init installer context
464     m_installerContext.installStep = InstallerContext::INSTALL_START;
465     m_installerContext.job = this;
466     m_installerContext.existingWidgetInfo = update.existingWidgetInfo;
467     m_installerContext.widgetConfig.shareHref = std::string();
468
469     return result;
470 }
471
472 JobWidgetInstall::ConfigureResult JobWidgetInstall::checkWidgetUpdate(
473         const WidgetUpdateInfo &update)
474 {
475     LogInfo(
476         "Widget install/update: incoming guid = '" <<
477         update.incomingGUID << "'");
478     LogInfo(
479         "Widget install/update: incoming version = '" <<
480         update.incomingVersion << "'");
481
482     // Check policy
483     WidgetUpdateMode::Type updateTypeCheckBit;
484
485     if (update.existingWidgetInfo.isExist == false) {
486         LogInfo("Widget info does not exist");
487         updateTypeCheckBit = WidgetUpdateMode::NotInstalled;
488     } else {
489         LogInfo("Widget info exists. appid: " <<
490                 update.existingWidgetInfo.tzAppid);
491
492         TizenAppId tzAppid = update.existingWidgetInfo.tzAppid;
493
494         LogInfo("Widget model exists. tizen app id: " << tzAppid);
495
496         // Check running state
497         int retval = APP_MANAGER_ERROR_NONE;
498         bool isRunning = false;
499         retval = app_manager_is_running(DPL::ToUTF8String(tzAppid).c_str(), &isRunning);
500         if (APP_MANAGER_ERROR_NONE != retval) {
501             LogError("Fail to get running state");
502             return ConfigureResult::Failed;
503         }
504
505         if (true == isRunning) {
506             // Must be deferred when update in progress
507             if (m_jobStruct.updateMode == WidgetUpdateMode::PolicyWac) {
508                 LogInfo(
509                     "Widget is already running. Policy is update according to WAC");
510
511                 return ConfigureResult::Deferred;
512             } else {
513                 LogInfo(
514                     "Widget is already running. Policy is not update according to WAC");
515
516                 return ConfigureResult::Failed;
517             }
518         }
519
520         m_installerContext.widgetConfig.tzAppid = tzAppid;
521         OptionalWidgetVersion existingVersion;
522         existingVersion = update.existingWidgetInfo.existingVersion;
523         OptionalWidgetVersion incomingVersion = update.incomingVersion;
524
525         updateTypeCheckBit = CalcWidgetUpdatePolicy(existingVersion,
526                                                     incomingVersion);
527         // Calc proceed flag
528         if ((m_jobStruct.updateMode & updateTypeCheckBit) > 0 ||
529             m_jobStruct.updateMode ==
530                 WidgetUpdateMode::PolicyDirectoryForceInstall)
531         {
532             LogInfo("Whether widget policy allow proceed ok");
533             return ConfigureResult::Updated;
534         }
535         else
536             return ConfigureResult::Failed;
537     }
538     return ConfigureResult::Ok;
539 }
540
541 WidgetUpdateMode::Type JobWidgetInstall::CalcWidgetUpdatePolicy(
542         const OptionalWidgetVersion &existingVersion,
543         const OptionalWidgetVersion &incomingVersion) const
544 {
545     // Widget is installed, check versions
546     if (!existingVersion && !incomingVersion) {
547         return WidgetUpdateMode::ExistingVersionEqual;
548     } else if (!existingVersion && !!incomingVersion) {
549         return WidgetUpdateMode::ExistingVersionNewer;
550     } else if (!!existingVersion && !incomingVersion) {
551         return WidgetUpdateMode::ExistingVersionOlder;
552     } else {
553         LogInfo("Existing widget: version = '" << *existingVersion << "'");
554
555         if (!existingVersion->IsWac() && !incomingVersion->IsWac()) {
556             return WidgetUpdateMode::BothVersionsNotStd;
557         } else if (!existingVersion->IsWac()) {
558             return WidgetUpdateMode::ExistingVersionNotStd;
559         } else if (!incomingVersion->IsWac()) {
560             return WidgetUpdateMode::IncomingVersionNotStd;
561         } else {
562             // Both versions are WAC-comparable. Do compare.
563             if (*incomingVersion == *existingVersion) {
564                 return WidgetUpdateMode::ExistingVersionEqual;
565             } else if (*incomingVersion > *existingVersion) {
566                 return WidgetUpdateMode::ExistingVersionOlder;
567             } else {
568                 return WidgetUpdateMode::ExistingVersionNewer;
569             }
570         }
571     }
572 }
573
574 ConfigParserData JobWidgetInstall::getWidgetDataFromXML(
575         const std::string &widgetSource,
576         const std::string &tempPath,
577         WrtDB::PackagingType pkgType,
578         bool isDRM)
579 {
580     // Parse config
581     ParserRunner parser;
582     ConfigParserData configInfo;
583
584     Try
585     {
586         if (pkgType == PKG_TYPE_HOSTED_WEB_APP) {
587             parser.Parse(widgetSource,
588                     ElementParserPtr(
589                         new RootParser<WidgetParser>(configInfo,
590                             DPL::FromUTF32String(
591                                 L"widget"))));
592         } else if (pkgType == PKG_TYPE_DIRECTORY_WEB_APP) {
593             parser.Parse(widgetSource + '/' + WITH_OSP_XML,
594                          ElementParserPtr(
595                              new RootParser<WidgetParser>(
596                              configInfo,
597                              DPL::FromUTF32String(L"widget"))));
598         } else {
599             if (!isDRM) {
600                 std::unique_ptr<DPL::ZipInput> zipFile(
601                         new DPL::ZipInput(widgetSource));
602
603                 std::unique_ptr<DPL::ZipInput::File> configFile;
604
605                 // Open config.xml file
606                 if (pkgType == PKG_TYPE_HYBRID_WEB_APP) {
607                     configFile.reset(zipFile->OpenFile(WITH_OSP_XML));
608                 } else {
609                     configFile.reset(zipFile->OpenFile(CONFIG_XML));
610                 }
611
612                 // Extract config
613                 DPL::BinaryQueue buffer;
614                 DPL::AbstractWaitableInputAdapter inputAdapter(configFile.get());
615                 DPL::AbstractWaitableOutputAdapter outputAdapter(&buffer);
616                 DPL::Copy(&inputAdapter, &outputAdapter);
617                 parser.Parse(&buffer,
618                         ElementParserPtr(
619                             new RootParser<WidgetParser>(configInfo,
620                                 DPL::FromUTF32String(
621                                     L"widget"))));
622             } else {
623                 // DRM widget
624                 std::string configFile;
625                 if (pkgType == PKG_TYPE_HYBRID_WEB_APP) {
626                     configFile = tempPath + "/" + WITH_OSP_XML;
627                 } else {
628                     configFile = tempPath + "/" + CONFIG_XML;
629                 }
630
631                 parser.Parse(configFile,
632                         ElementParserPtr(
633                             new RootParser<WidgetParser>(configInfo,
634                                 DPL::FromUTF32String(
635                                     L"widget"))));
636             }
637         }
638     }
639     Catch(DPL::ZipInput::Exception::OpenFailed)
640     {
641         LogError("Failed to open widget package");
642         return ConfigParserData();
643     }
644     Catch(DPL::ZipInput::Exception::OpenFileFailed)
645     {
646         LogError("Failed to open config.xml file");
647         return ConfigParserData();
648     }
649     Catch(DPL::CopyFailed)
650     {
651         LogError("Failed to extract config.xml file");
652         return ConfigParserData();
653     }
654     Catch(DPL::FileInput::Exception::OpenFailed)
655     {
656         LogError("Failed to open config.xml file");
657         return ConfigParserData();
658     }
659     Catch(ElementParser::Exception::ParseError)
660     {
661         LogError("Failed to parse config.xml file");
662         return ConfigParserData();
663     }
664     Catch(DPL::ZipInput::Exception::SeekFileFailed)
665     {
666         LogError("Failed to seek widget archive - corrupted package?");
667         return ConfigParserData();
668     }
669     return configInfo;
670 }
671
672 WidgetUpdateInfo JobWidgetInstall::detectWidgetUpdate(
673         const ConfigParserData &configInfo,
674         const WrtDB::WidgetType appType,
675         const WrtDB::TizenAppId &tizenId)
676 {
677     LogInfo("Checking up widget package for config.xml...");
678
679     DPL::OptionalString widgetGUID;
680     OptionalWidgetVersion widgetVersion;
681
682     // Check widget id
683     widgetGUID = configInfo.widget_id;
684
685     if (widgetGUID.IsNull()) {
686         LogWarning("Installed widget has no GUID");
687         return WidgetUpdateInfo();
688     }
689
690     LogDebug("Installed widget GUID: " << *widgetGUID);
691
692     // Locate widget ID with this GUID
693     // Incoming widget version
694     if (!configInfo.version.IsNull()) {
695         widgetVersion =
696             DPL::Optional<WidgetVersion>(
697                 WidgetVersion(*configInfo.version));
698     }
699
700     if (appType == APP_TYPE_WAC20) {
701         Try
702         {
703             // Search widget handle by GUID
704             WidgetDAOReadOnly dao(widgetGUID);
705             return WidgetUpdateInfo(
706                     widgetGUID,
707                     widgetVersion,
708                     WidgetUpdateInfo::ExistingWidgetInfo(
709                         dao.getTzAppId(), dao.getVersion()));
710         }
711         Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
712         {
713             // GUID isn't installed
714             return WidgetUpdateInfo(
715                     widgetGUID,
716                     widgetVersion,
717                     WidgetUpdateInfo::ExistingWidgetInfo());
718         }
719     } else {
720         Try
721         {
722             // Search widget handle by appId
723             WidgetDAOReadOnly dao(tizenId);
724             return WidgetUpdateInfo(
725                     widgetGUID,
726                     widgetVersion,
727                     WidgetUpdateInfo::ExistingWidgetInfo(
728                         dao.getTzAppId(), dao.getVersion()));
729         }
730         Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
731         {
732             // GUID isn't installed
733             return WidgetUpdateInfo(
734                     widgetGUID,
735                     widgetVersion,
736                     WidgetUpdateInfo::ExistingWidgetInfo());
737         }
738
739     }
740 }
741
742 void JobWidgetInstall::SendProgress()
743 {
744     using namespace PackageManager;
745     if (GetProgressFlag() != false) {
746         if (getInstallerStruct().progressCallback != NULL) {
747             // send progress signal of pkgmgr
748             std::ostringstream percent;
749             percent << static_cast<int>(GetProgressPercent());
750             getInstallerStruct().pkgmgrInterface->sendSignal(
751                         PKGMGR_PROGRESS_KEY,
752                         percent.str());
753
754             LogDebug("Call widget install progressCallbak");
755             getInstallerStruct().progressCallback(getInstallerStruct().userParam,
756                     GetProgressPercent(),GetProgressDescription());
757         }
758     }
759 }
760
761 void JobWidgetInstall::SendFinishedSuccess()
762 {
763     using namespace PackageManager;
764     // TODO : sync should move to separate task.
765     sync();
766
767
768     if (INSTALL_LOCATION_TYPE_EXTERNAL == m_installerContext.locationType) {
769         if (false == m_installerContext.existingWidgetInfo.isExist) {
770             WidgetInstallToExtSingleton::Instance().postInstallation(true);
771         } else {
772             WidgetInstallToExtSingleton::Instance().postUpgrade(true);
773         }
774         WidgetInstallToExtSingleton::Instance().deinitialize();
775     }
776
777     // remove widget install information file
778     unlink(m_installerContext.installInfo.c_str());
779
780     //inform widget info
781     JobWidgetInstall::displayWidgetInfo();
782
783     TizenAppId& tizenId = m_installerContext.widgetConfig.tzAppid;
784
785     // send signal of pkgmgr
786     getInstallerStruct().pkgmgrInterface->sendSignal(
787                 PKGMGR_END_KEY,
788                 PKGMGR_END_SUCCESS);
789
790     LogDebug("Call widget install successfinishedCallback");
791     getInstallerStruct().finishedCallback(getInstallerStruct().userParam,
792             DPL::ToUTF8String(tizenId), Exceptions::Success);
793 }
794
795 void JobWidgetInstall::SendFinishedFailure()
796 {
797     using namespace PackageManager;
798     // remove widget install information file
799     unlink(m_installerContext.installInfo.c_str());
800
801     LogError("Error in installation step: " << m_exceptionCaught);
802     LogError("Message: " << m_exceptionMessage);
803     TizenAppId & tizenId = m_installerContext.widgetConfig.tzAppid;
804
805     LogDebug("Call widget install failure finishedCallback");
806
807     // send signal of pkgmgr
808     getInstallerStruct().pkgmgrInterface->sendSignal(
809                 PKGMGR_END_KEY,
810                 PKGMGR_END_FAILURE);
811
812     getInstallerStruct().finishedCallback(getInstallerStruct().userParam,
813             DPL::ToUTF8String(tizenId), m_exceptionCaught);
814 }
815
816 void JobWidgetInstall::SaveExceptionData(const Jobs::JobExceptionBase &e)
817 {
818     m_exceptionCaught = static_cast<Exceptions::Type>(e.getParam());
819     m_exceptionMessage = e.GetMessage();
820 }
821
822 void JobWidgetInstall::displayWidgetInfo()
823 {
824     WidgetDAOReadOnly dao(m_installerContext.widgetConfig.tzAppid);
825
826     std::ostringstream out;
827     WidgetLocalizedInfo localizedInfo =
828         W3CFileLocalization::getLocalizedInfo(dao.getTzAppId());
829
830     out << std::endl <<
831         "===================================== INSTALLED WIDGET INFO ========="\
832         "============================";
833     out << std::endl << "Name:                        " << localizedInfo.name;
834     out << std::endl << "AppId:                     " << dao.getTzAppId();
835     WidgetSize size = dao.getPreferredSize();
836     out << std::endl << "Width:                       " << size.width;
837     out << std::endl << "Height:                      " << size.height;
838     out << std::endl << "Start File:                  " <<
839         W3CFileLocalization::getStartFile(dao.getTzAppId());
840     out << std::endl << "Version:                     " << dao.getVersion();
841     out << std::endl << "Licence:                     " <<
842         localizedInfo.license;
843     out << std::endl << "Licence Href:                " <<
844         localizedInfo.licenseHref;
845     out << std::endl << "Description:                 " <<
846         localizedInfo.description;
847     out << std::endl << "Widget Id:                   " << dao.getGUID();
848     out << std::endl << "Widget recognized:           " << dao.isRecognized();
849     out << std::endl << "Widget wac signed:           " << dao.isWacSigned();
850     out << std::endl << "Widget distributor signed:   " <<
851         dao.isDistributorSigned();
852     out << std::endl << "Widget trusted:              " << dao.isTrusted();
853
854     OptionalWidgetIcon icon = W3CFileLocalization::getIcon(dao.getTzAppId());
855     DPL::OptionalString iconSrc = !!icon ? icon->src : DPL::OptionalString::Null;
856     out << std::endl << "Icon:                        " << iconSrc;
857
858     out << std::endl << "Preferences:";
859     {
860         PropertyDAOReadOnly::WidgetPreferenceList list = dao.getPropertyList();
861         FOREACH(it, list)
862         {
863             out << std::endl << "  Key:                       " <<
864                 it->key_name;
865             out << std::endl << "      Readonly:              " <<
866                 it->readonly;
867         }
868     }
869
870     out << std::endl << "Features:";
871     {
872         WidgetFeatureSet list = dao.getFeaturesList();
873         FOREACH(it, list)
874         {
875             out << std::endl << "  Name:                      " << it->name;
876             out << std::endl << "      Required:              " << it->required;
877             out << std::endl << "      Params:";
878         }
879     }
880
881     out << std::endl;
882
883     LogInfo(out.str());
884 }
885
886 WrtDB::PackagingType JobWidgetInstall::checkPackageType(
887         const std::string &widgetSource,
888         const std::string &tempPath)
889 {
890     // Check installation type (direcotory/ or config.xml or widget.wgt)
891     if (WidgetUpdateMode::PolicyDirectoryForceInstall == m_jobStruct.updateMode)
892     {
893         LogDebug("Install directly from directory");
894         return PKG_TYPE_DIRECTORY_WEB_APP;
895     }
896     if (hasExtension(widgetSource, XML_EXTENSION)) {
897         LogInfo("Hosted app installation");
898         return PKG_TYPE_HOSTED_WEB_APP;
899     }
900
901     if (m_isDRM) {
902         std::string configFile = tempPath + "/" + CONFIG_XML;
903         if (WrtUtilFileExists(configFile)) {
904             return PKG_TYPE_NOMAL_WEB_APP;
905         }
906
907         configFile = tempPath + "/" + WITH_OSP_XML;
908         if (WrtUtilFileExists(configFile)) {
909             return PKG_TYPE_HYBRID_WEB_APP;
910         }
911     } else {
912         std::unique_ptr<DPL::ZipInput> zipFile;
913
914         Try
915         {
916             // Open zip file
917             zipFile.reset(new DPL::ZipInput(widgetSource));
918
919         }
920         Catch(DPL::ZipInput::Exception::OpenFailed)
921         {
922             LogDebug("Failed to open widget package");
923             return PKG_TYPE_UNKNOWN;
924         }
925         Catch(DPL::ZipInput::Exception::SeekFileFailed)
926         {
927             LogError("Failed to seek widget package file");
928             return PKG_TYPE_UNKNOWN;
929         }
930
931         Try
932         {
933             // Open config.xml file in package root
934             std::unique_ptr<DPL::ZipInput::File> configFile(
935                     zipFile->OpenFile(CONFIG_XML));
936             return PKG_TYPE_NOMAL_WEB_APP;
937         }
938         Catch(DPL::ZipInput::Exception::OpenFileFailed)
939         {
940             LogDebug("Could not find config.xml");
941         }
942
943         Try
944         {
945             // Open config.xml file in package root
946             std::unique_ptr<DPL::ZipInput::File> configFile(
947                     zipFile->OpenFile(WITH_OSP_XML));
948
949             return PKG_TYPE_HYBRID_WEB_APP;
950         }
951         Catch(DPL::ZipInput::Exception::OpenFileFailed)
952         {
953             LogDebug("Could not find wgt/config.xml");
954             return PKG_TYPE_UNKNOWN;
955         }
956     }
957
958     return PKG_TYPE_UNKNOWN;
959 }
960
961 void JobWidgetInstall::setApplicationType(
962         const WrtDB::ConfigParserData &configInfo)
963 {
964
965     FOREACH(iterator, configInfo.nameSpaces) {
966         LogInfo("namespace = [" << *iterator << "]");
967         AppType currentAppType = APP_TYPE_UNKNOWN;
968
969         if (*iterator == ConfigurationNamespace::W3CWidgetNamespaceName) {
970             continue;
971         } else if (
972             *iterator ==
973             ConfigurationNamespace::WacWidgetNamespaceNameForLinkElement ||
974             *iterator ==
975             ConfigurationNamespace::WacWidgetNamespaceName)
976         {
977             currentAppType = APP_TYPE_WAC20;
978         } else if (*iterator ==
979                 ConfigurationNamespace::TizenWebAppNamespaceName) {
980             currentAppType = APP_TYPE_TIZENWEBAPP;
981         }
982
983         if (m_installerContext.widgetConfig.webAppType ==
984                 APP_TYPE_UNKNOWN) {
985             m_installerContext.widgetConfig.webAppType = currentAppType;
986         } else if (m_installerContext.widgetConfig.webAppType ==
987                 currentAppType) {
988             continue;
989         } else {
990             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
991                      "Config.xml has more than one namespace");
992         }
993     }
994
995     // If there is no define, type set to WAC 2.0
996     if (m_installerContext.widgetConfig.webAppType == APP_TYPE_UNKNOWN) {
997         m_installerContext.widgetConfig.webAppType = APP_TYPE_WAC20;
998     }
999
1000     LogInfo("type = [" <<
1001             m_installerContext.widgetConfig.webAppType.getApptypeToString() << "]");
1002 }
1003
1004 bool JobWidgetInstall::detectResourceEncryption(const WrtDB::ConfigParserData &configData)
1005 {
1006     FOREACH(it, configData.settingsList)
1007     {
1008         if (it->m_name == SETTING_VALUE_ENCRYPTION &&
1009                 it->m_value == SETTING_VALUE_ENCRYPTION_ENABLE) {
1010             LogDebug("resource need encryption");
1011             return true;
1012         }
1013     }
1014     return false;
1015 }
1016
1017 void JobWidgetInstall::setInstallLocationType(const
1018         WrtDB::ConfigParserData &configData)
1019 {
1020     m_installerContext.locationType = INSTALL_LOCATION_TYPE_NOMAL;
1021
1022     if (true == m_jobStruct.m_preload) {
1023         m_installerContext.locationType =
1024             INSTALL_LOCATION_TYPE_PRELOAD;
1025     } else {
1026         FOREACH(it, configData.settingsList)
1027         {
1028             if (it->m_name == SETTING_VALUE_INSTALLTOEXT_NAME &&
1029                     it->m_value ==
1030                     SETTING_VALUE_INSTALLTOEXT_PREPER_EXT) {
1031                 LogDebug("This widget will be installed to sd card");
1032                 m_installerContext.locationType =
1033                     INSTALL_LOCATION_TYPE_EXTERNAL;
1034             }
1035         }
1036     }
1037 }
1038
1039 bool JobWidgetInstall::isDRMWidget(std::string widgetPath)
1040 {
1041     /* TODO :
1042     drm_bool_type_e is_drm_file = DRM_UNKNOWN;
1043     int ret = -1;
1044
1045     ret = drm_is_drm_file(widgetPath.c_str(), &is_drm_file);
1046     if(DRM_RETURN_SUCCESS == ret && DRM_TRUE == is_drm_file) {
1047     */
1048
1049     /* blow code temporary code for drm. */
1050     int ret = drm_oem_intel_isDrmFile(const_cast<char*>(widgetPath.c_str()));
1051     if ( 1 == ret) {
1052         return true;
1053     } else {
1054         return false;
1055     }
1056 }
1057
1058 bool JobWidgetInstall::DecryptDRMWidget(std::string widgetPath,
1059         std::string destPath)
1060 {
1061     /* TODO :
1062     drm_trusted_sapps_decrypt_package_info_s package_info;
1063
1064     strncpy(package_info.sadcf_filepath, widgetPath.c_str(),
1065             sizeof(package_info.sadcf_filepath));
1066     strncpy(package_info.decrypt_filepath, destPath.c_str(),
1067             sizeof(package_info.decrypt_filepath));
1068
1069     drm_trusted_request_type_e requestType =
1070         DRM_TRUSTED_REQ_TYPE_SAPPS_DECRYPT_PACKAGE;
1071
1072     int ret = drm_trusted_handle_request(requestType,
1073                                          (void *)&package_info, NULL);
1074     if (DRM_TRUSTED_RETURN_SUCCESS == ret) {
1075         return true;
1076     } else {
1077         return false;
1078     }
1079     */
1080     if (drm_oem_intel_decrypt_package(const_cast<char*>(widgetPath.c_str()),
1081                 const_cast<char*>(destPath.c_str())) != 0) {
1082         return true;
1083     } else {
1084         return false;
1085     }
1086 }
1087
1088 } //namespace WidgetInstall
1089 } //namespace Jobs