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