Source code formating unification
[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::SendFinishedSuccess()
796 {
797     using namespace PackageManager;
798     // TODO : sync should move to separate task.
799     sync();
800
801     if (INSTALL_LOCATION_TYPE_EXTERNAL == m_installerContext.locationType) {
802         if (false == m_installerContext.existingWidgetInfo.isExist) {
803             WidgetInstallToExtSingleton::Instance().postInstallation(true);
804         } else {
805             WidgetInstallToExtSingleton::Instance().postUpgrade(true);
806         }
807         WidgetInstallToExtSingleton::Instance().deinitialize();
808     }
809
810     // remove widget install information file
811     unlink(m_installerContext.installInfo.c_str());
812
813     //inform widget info
814     JobWidgetInstall::displayWidgetInfo();
815
816     TizenAppId& tizenId = m_installerContext.widgetConfig.tzAppid;
817
818     // send signal of pkgmgr
819     getInstallerStruct().pkgmgrInterface->sendSignal(
820         PKGMGR_END_KEY,
821         PKGMGR_END_SUCCESS);
822
823     LogDebug("Call widget install successfinishedCallback");
824     getInstallerStruct().finishedCallback(getInstallerStruct().userParam,
825                                           DPL::ToUTF8String(
826                                               tizenId), Exceptions::Success);
827 }
828
829 void JobWidgetInstall::SendFinishedFailure()
830 {
831     using namespace PackageManager;
832     // remove widget install information file
833     unlink(m_installerContext.installInfo.c_str());
834
835     LogError("Error in installation step: " << m_exceptionCaught);
836     LogError("Message: " << m_exceptionMessage);
837     TizenAppId & tizenId = m_installerContext.widgetConfig.tzAppid;
838
839     LogDebug("Call widget install failure finishedCallback");
840
841     // send signal of pkgmgr
842     getInstallerStruct().pkgmgrInterface->sendSignal(
843         PKGMGR_END_KEY,
844         PKGMGR_END_FAILURE);
845
846     getInstallerStruct().finishedCallback(getInstallerStruct().userParam,
847                                           DPL::ToUTF8String(
848                                               tizenId), m_exceptionCaught);
849 }
850
851 void JobWidgetInstall::SaveExceptionData(const Jobs::JobExceptionBase &e)
852 {
853     m_exceptionCaught = static_cast<Exceptions::Type>(e.getParam());
854     m_exceptionMessage = e.GetMessage();
855 }
856
857 void JobWidgetInstall::displayWidgetInfo()
858 {
859     WidgetDAOReadOnly dao(m_installerContext.widgetConfig.tzAppid);
860
861     std::ostringstream out;
862     WidgetLocalizedInfo localizedInfo =
863         W3CFileLocalization::getLocalizedInfo(dao.getTzAppId());
864
865     out << std::endl <<
866     "===================================== INSTALLED WIDGET INFO =========" \
867     "============================";
868     out << std::endl << "Name:                        " << localizedInfo.name;
869     out << std::endl << "AppId:                     " << dao.getTzAppId();
870     WidgetSize size = dao.getPreferredSize();
871     out << std::endl << "Width:                       " << size.width;
872     out << std::endl << "Height:                      " << size.height;
873     out << std::endl << "Start File:                  " <<
874     W3CFileLocalization::getStartFile(dao.getTzAppId());
875     out << std::endl << "Version:                     " << dao.getVersion();
876     out << std::endl << "Licence:                     " <<
877     localizedInfo.license;
878     out << std::endl << "Licence Href:                " <<
879     localizedInfo.licenseHref;
880     out << std::endl << "Description:                 " <<
881     localizedInfo.description;
882     out << std::endl << "Widget Id:                   " << dao.getGUID();
883     out << std::endl << "Widget recognized:           " << dao.isRecognized();
884     out << std::endl << "Widget wac signed:           " << dao.isWacSigned();
885     out << std::endl << "Widget distributor signed:   " <<
886     dao.isDistributorSigned();
887     out << std::endl << "Widget trusted:              " << dao.isTrusted();
888
889     OptionalWidgetIcon icon = W3CFileLocalization::getIcon(dao.getTzAppId());
890     DPL::OptionalString iconSrc =
891         !!icon ? icon->src : DPL::OptionalString::Null;
892     out << std::endl << "Icon:                        " << iconSrc;
893
894     out << std::endl << "Preferences:";
895     {
896         PropertyDAOReadOnly::WidgetPreferenceList list = dao.getPropertyList();
897         FOREACH(it, list)
898         {
899             out << std::endl << "  Key:                       " <<
900             it->key_name;
901             out << std::endl << "      Readonly:              " <<
902             it->readonly;
903         }
904     }
905
906     out << std::endl << "Features:";
907     {
908         WidgetFeatureSet list = dao.getFeaturesList();
909         FOREACH(it, list)
910         {
911             out << std::endl << "  Name:                      " << it->name;
912             out << std::endl << "      Required:              " << it->required;
913             out << std::endl << "      Params:";
914         }
915     }
916
917     out << std::endl;
918
919     LogInfo(out.str());
920 }
921
922 WrtDB::PackagingType JobWidgetInstall::checkPackageType(
923     const std::string &widgetSource,
924     const std::string &tempPath)
925 {
926     // Check installation type (direcotory/ or config.xml or widget.wgt)
927     if (WidgetUpdateMode::PolicyDirectoryForceInstall ==
928         m_jobStruct.updateMode)
929     {
930         LogDebug("Install directly from directory");
931         return PKG_TYPE_DIRECTORY_WEB_APP;
932     }
933     if (hasExtension(widgetSource, XML_EXTENSION)) {
934         LogInfo("Hosted app installation");
935         return PKG_TYPE_HOSTED_WEB_APP;
936     }
937
938     if (m_isDRM) {
939         std::string configFile = tempPath + "/" + CONFIG_XML;
940         if (WrtUtilFileExists(configFile)) {
941             return PKG_TYPE_NOMAL_WEB_APP;
942         }
943
944         configFile = tempPath + "/" + WITH_OSP_XML;
945         if (WrtUtilFileExists(configFile)) {
946             return PKG_TYPE_HYBRID_WEB_APP;
947         }
948     } else {
949         std::unique_ptr<DPL::ZipInput> zipFile;
950
951         Try
952         {
953             // Open zip file
954             zipFile.reset(new DPL::ZipInput(widgetSource));
955         }
956         Catch(DPL::ZipInput::Exception::OpenFailed)
957         {
958             LogDebug("Failed to open widget package");
959             return PKG_TYPE_UNKNOWN;
960         }
961         Catch(DPL::ZipInput::Exception::SeekFileFailed)
962         {
963             LogError("Failed to seek widget package file");
964             return PKG_TYPE_UNKNOWN;
965         }
966
967         Try
968         {
969             // Open config.xml file in package root
970             std::unique_ptr<DPL::ZipInput::File> configFile(
971                 zipFile->OpenFile(CONFIG_XML));
972             return PKG_TYPE_NOMAL_WEB_APP;
973         }
974         Catch(DPL::ZipInput::Exception::OpenFileFailed)
975         {
976             LogDebug("Could not find config.xml");
977         }
978
979         Try
980         {
981             // Open config.xml file in package root
982             std::unique_ptr<DPL::ZipInput::File> configFile(
983                 zipFile->OpenFile(WITH_OSP_XML));
984
985             return PKG_TYPE_HYBRID_WEB_APP;
986         }
987         Catch(DPL::ZipInput::Exception::OpenFileFailed)
988         {
989             LogDebug("Could not find wgt/config.xml");
990             return PKG_TYPE_UNKNOWN;
991         }
992     }
993
994     return PKG_TYPE_UNKNOWN;
995 }
996
997 void JobWidgetInstall::setApplicationType(
998     const WrtDB::ConfigParserData &configInfo)
999 {
1000     FOREACH(iterator, configInfo.nameSpaces) {
1001         LogInfo("namespace = [" << *iterator << "]");
1002         AppType currentAppType = APP_TYPE_UNKNOWN;
1003
1004         if (*iterator == ConfigurationNamespace::W3CWidgetNamespaceName) {
1005             continue;
1006         } else if (
1007             *iterator ==
1008             ConfigurationNamespace::WacWidgetNamespaceNameForLinkElement ||
1009             *iterator ==
1010             ConfigurationNamespace::WacWidgetNamespaceName)
1011         {
1012             currentAppType = APP_TYPE_WAC20;
1013         } else if (*iterator ==
1014                    ConfigurationNamespace::TizenWebAppNamespaceName)
1015         {
1016             currentAppType = APP_TYPE_TIZENWEBAPP;
1017         }
1018
1019         if (m_installerContext.widgetConfig.webAppType ==
1020             APP_TYPE_UNKNOWN)
1021         {
1022             m_installerContext.widgetConfig.webAppType = currentAppType;
1023         } else if (m_installerContext.widgetConfig.webAppType ==
1024                    currentAppType)
1025         {
1026             continue;
1027         } else {
1028             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
1029                      "Config.xml has more than one namespace");
1030         }
1031     }
1032
1033     // If there is no define, type set to WAC 2.0
1034     if (m_installerContext.widgetConfig.webAppType == APP_TYPE_UNKNOWN) {
1035         m_installerContext.widgetConfig.webAppType = APP_TYPE_WAC20;
1036     }
1037
1038     LogInfo("type = [" <<
1039             m_installerContext.widgetConfig.webAppType.getApptypeToString() <<
1040             "]");
1041 }
1042
1043 bool JobWidgetInstall::detectResourceEncryption(
1044     const WrtDB::ConfigParserData &configData)
1045 {
1046     FOREACH(it, configData.settingsList)
1047     {
1048         if (it->m_name == SETTING_VALUE_ENCRYPTION &&
1049             it->m_value == SETTING_VALUE_ENCRYPTION_ENABLE)
1050         {
1051             LogDebug("resource need encryption");
1052             return true;
1053         }
1054     }
1055     return false;
1056 }
1057
1058 void JobWidgetInstall::setInstallLocationType(
1059     const
1060     WrtDB::ConfigParserData &
1061     configData)
1062 {
1063     m_installerContext.locationType = INSTALL_LOCATION_TYPE_NOMAL;
1064
1065     if (true == m_jobStruct.m_preload) {
1066         m_installerContext.locationType =
1067             INSTALL_LOCATION_TYPE_PRELOAD;
1068     } else {
1069         FOREACH(it, configData.settingsList)
1070         {
1071             if (it->m_name == SETTING_VALUE_INSTALLTOEXT_NAME &&
1072                 it->m_value ==
1073                 SETTING_VALUE_INSTALLTOEXT_PREPER_EXT)
1074             {
1075                 LogDebug("This widget will be installed to sd card");
1076                 m_installerContext.locationType =
1077                     INSTALL_LOCATION_TYPE_EXTERNAL;
1078             }
1079         }
1080     }
1081 }
1082
1083 bool JobWidgetInstall::isDRMWidget(std::string widgetPath)
1084 {
1085     /* TODO :
1086      * drm_bool_type_e is_drm_file = DRM_UNKNOWN;
1087      * int ret = -1;
1088      *
1089      * ret = drm_is_drm_file(widgetPath.c_str(), &is_drm_file);
1090      * if(DRM_RETURN_SUCCESS == ret && DRM_TRUE == is_drm_file) {
1091      */
1092
1093     /* blow code temporary code for drm. */
1094     int ret = drm_oem_intel_isDrmFile(const_cast<char*>(widgetPath.c_str()));
1095     if (1 == ret) {
1096         return true;
1097     } else {
1098         return false;
1099     }
1100 }
1101
1102 bool JobWidgetInstall::DecryptDRMWidget(std::string widgetPath,
1103                                         std::string destPath)
1104 {
1105     /* TODO :
1106      * drm_trusted_sapps_decrypt_package_info_s package_info;
1107      *
1108      * strncpy(package_info.sadcf_filepath, widgetPath.c_str(),
1109      *      sizeof(package_info.sadcf_filepath));
1110      * strncpy(package_info.decrypt_filepath, destPath.c_str(),
1111      *      sizeof(package_info.decrypt_filepath));
1112      *
1113      * drm_trusted_request_type_e requestType =
1114      *  DRM_TRUSTED_REQ_TYPE_SAPPS_DECRYPT_PACKAGE;
1115      *
1116      * int ret = drm_trusted_handle_request(requestType,
1117      *                                   (void *)&package_info, NULL);
1118      * if (DRM_TRUSTED_RETURN_SUCCESS == ret) {
1119      *  return true;
1120      * } else {
1121      *  return false;
1122      * }
1123      */
1124     if (drm_oem_intel_decrypt_package(const_cast<char*>(widgetPath.c_str()),
1125                                       const_cast<char*>(destPath.c_str())) != 0)
1126     {
1127         return true;
1128     } else {
1129         return false;
1130     }
1131 }
1132 } //namespace WidgetInstall
1133 } //namespace Jobs