[Release]wrt-installer_0.1.6
[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     LogInfo("Tizen App Id : " << m_installerContext.widgetConfig.tzAppid);
432     LogInfo("Tizen Pkg Id : " << m_installerContext.widgetConfig.tzPkgid);
433     LogInfo("W3C Widget GUID : " << m_installerContext.widgetConfig.guid);
434 }
435
436 void JobWidgetInstall::configureWidgetLocation(const std::string & widgetPath,
437                                                const std::string& tempPath)
438 {
439     m_installerContext.locations =
440         WidgetLocation(DPL::ToUTF8String(m_installerContext.widgetConfig.
441                                              tzPkgid),
442                        widgetPath, tempPath,
443                        m_installerContext.widgetConfig.packagingType,
444                        m_installerContext.locationType);
445     m_installerContext.locations->registerAppid(
446         DPL::ToUTF8String(m_installerContext.widgetConfig.tzAppid));
447
448     LogInfo("widgetSource " << widgetPath);
449 }
450
451 JobWidgetInstall::ConfigureResult JobWidgetInstall::ConfigureInstallation(
452     const std::string &widgetSource,
453     const WrtDB::ConfigParserData &configData,
454     const std::string &tempPath)
455 {
456     WidgetUpdateInfo update = detectWidgetUpdate(
457             configData,
458             m_installerContext.
459                 widgetConfig.webAppType,
460             m_installerContext.
461                 widgetConfig.tzAppid);
462     ConfigureResult result = checkWidgetUpdate(update);
463
464     // Validate tizenId
465     regex_t reg;
466     if (regcomp(&reg, REG_TIZENID_PATTERN, REG_NOSUB | REG_EXTENDED) != 0) {
467         LogDebug("Regcomp failed");
468     }
469
470     if ((regexec(&reg,
471                  DPL::ToUTF8String(m_installerContext.widgetConfig.tzAppid).
472                      c_str(),
473                      static_cast<size_t>(0), NULL, 0) == REG_NOMATCH) ||
474         (checkTizenPkgIdExist(DPL::ToUTF8String(m_installerContext.widgetConfig
475                                                     .tzPkgid)) &&
476          result != ConfigureResult::Updated))
477     {
478         //it is true when tizenId does not fit REG_TIZENID_PATTERN
479         LogError("tizen_id provided but not proper or pkgId directory exists");
480         //TODO(t.iwanek): appId is unique, what about installation of
481         // abcdefghij.test1 and abcdefghij.test2?
482         regfree(&reg);
483         return ConfigureResult::Failed;
484     }
485     regfree(&reg);
486
487     configureWidgetLocation(widgetSource, tempPath);
488
489     // Init installer context
490     m_installerContext.installStep = InstallerContext::INSTALL_START;
491     m_installerContext.job = this;
492     m_installerContext.existingWidgetInfo = update.existingWidgetInfo;
493     m_installerContext.widgetConfig.shareHref = std::string();
494
495     return result;
496 }
497
498 JobWidgetInstall::ConfigureResult JobWidgetInstall::checkWidgetUpdate(
499     const WidgetUpdateInfo &update)
500 {
501     LogInfo(
502         "Widget install/update: incoming guid = '" <<
503         update.incomingGUID << "'");
504     LogInfo(
505         "Widget install/update: incoming version = '" <<
506         update.incomingVersion << "'");
507
508     // Check policy
509     WidgetUpdateMode::Type updateTypeCheckBit;
510
511     if (update.existingWidgetInfo.isExist == false) {
512         LogInfo("Widget info does not exist");
513         updateTypeCheckBit = WidgetUpdateMode::NotInstalled;
514
515         getInstallerStruct().pkgmgrInterface->sendSignal(
516                 PKGMGR_START_KEY,
517                 PKGMGR_START_INSTALL);
518
519     } else {
520         LogInfo("Widget info exists. appid: " <<
521                 update.existingWidgetInfo.tzAppid);
522
523         getInstallerStruct().pkgmgrInterface->sendSignal(
524                 PKGMGR_START_KEY,
525                 PKGMGR_START_UPDATE);
526
527         TizenAppId tzAppid = update.existingWidgetInfo.tzAppid;
528
529         LogInfo("Widget model exists. tizen app id: " << tzAppid);
530
531         // Check running state
532         int retval = APP_MANAGER_ERROR_NONE;
533         bool isRunning = false;
534         retval = app_manager_is_running(DPL::ToUTF8String(
535                                             tzAppid).c_str(), &isRunning);
536         if (APP_MANAGER_ERROR_NONE != retval) {
537             LogError("Fail to get running state");
538             return ConfigureResult::Failed;
539         }
540
541         if (true == isRunning) {
542             // Must be deferred when update in progress
543             if (m_jobStruct.updateMode == WidgetUpdateMode::PolicyWac) {
544                 LogInfo(
545                     "Widget is already running. Policy is update according to WAC");
546
547                 return ConfigureResult::Deferred;
548             } else {
549                 LogInfo(
550                     "Widget is already running. Policy is not update according to WAC");
551
552                 return ConfigureResult::Failed;
553             }
554         }
555
556         m_installerContext.widgetConfig.tzAppid = tzAppid;
557         OptionalWidgetVersion existingVersion;
558         existingVersion = update.existingWidgetInfo.existingVersion;
559         OptionalWidgetVersion incomingVersion = update.incomingVersion;
560
561         updateTypeCheckBit = CalcWidgetUpdatePolicy(existingVersion,
562                                                     incomingVersion);
563         // Calc proceed flag
564         if ((m_jobStruct.updateMode & updateTypeCheckBit) > 0 ||
565             m_jobStruct.updateMode ==
566             WidgetUpdateMode::PolicyDirectoryForceInstall)
567         {
568             LogInfo("Whether widget policy allow proceed ok");
569             return ConfigureResult::Updated;
570         } else {
571             return ConfigureResult::Failed;
572         }
573     }
574     return ConfigureResult::Ok;
575 }
576
577 WidgetUpdateMode::Type JobWidgetInstall::CalcWidgetUpdatePolicy(
578     const OptionalWidgetVersion &existingVersion,
579     const OptionalWidgetVersion &incomingVersion) const
580 {
581     // Widget is installed, check versions
582     if (!existingVersion && !incomingVersion) {
583         return WidgetUpdateMode::ExistingVersionEqual;
584     } else if (!existingVersion && !!incomingVersion) {
585         return WidgetUpdateMode::ExistingVersionNewer;
586     } else if (!!existingVersion && !incomingVersion) {
587         return WidgetUpdateMode::ExistingVersionOlder;
588     } else {
589         LogInfo("Existing widget: version = '" << *existingVersion << "'");
590
591         if (!existingVersion->IsWac() && !incomingVersion->IsWac()) {
592             return WidgetUpdateMode::BothVersionsNotStd;
593         } else if (!existingVersion->IsWac()) {
594             return WidgetUpdateMode::ExistingVersionNotStd;
595         } else if (!incomingVersion->IsWac()) {
596             return WidgetUpdateMode::IncomingVersionNotStd;
597         } else {
598             // Both versions are WAC-comparable. Do compare.
599             if (*incomingVersion == *existingVersion) {
600                 return WidgetUpdateMode::ExistingVersionEqual;
601             } else if (*incomingVersion > *existingVersion) {
602                 return WidgetUpdateMode::ExistingVersionOlder;
603             } else {
604                 return WidgetUpdateMode::ExistingVersionNewer;
605             }
606         }
607     }
608 }
609
610 ConfigParserData JobWidgetInstall::getWidgetDataFromXML(
611     const std::string &widgetSource,
612     const std::string &tempPath,
613     WrtDB::PackagingType pkgType,
614     bool isDRM)
615 {
616     // Parse config
617     ParserRunner parser;
618     ConfigParserData configInfo;
619
620     Try
621     {
622         if (pkgType == PKG_TYPE_HOSTED_WEB_APP) {
623             parser.Parse(widgetSource,
624                          ElementParserPtr(
625                              new RootParser<WidgetParser>(configInfo,
626                                                           DPL::FromUTF32String(
627                                                               L"widget"))));
628         } else if (pkgType == PKG_TYPE_DIRECTORY_WEB_APP) {
629             parser.Parse(widgetSource + '/' + WITH_OSP_XML,
630                          ElementParserPtr(
631                              new RootParser<WidgetParser>(
632                                  configInfo,
633                                  DPL::FromUTF32String(L"widget"))));
634         } else {
635             if (!isDRM) {
636                 std::unique_ptr<DPL::ZipInput> zipFile(
637                     new DPL::ZipInput(widgetSource));
638
639                 std::unique_ptr<DPL::ZipInput::File> configFile;
640
641                 // Open config.xml file
642                 if (pkgType == PKG_TYPE_HYBRID_WEB_APP) {
643                     configFile.reset(zipFile->OpenFile(WITH_OSP_XML));
644                 } else {
645                     configFile.reset(zipFile->OpenFile(CONFIG_XML));
646                 }
647
648                 // Extract config
649                 DPL::BinaryQueue buffer;
650                 DPL::AbstractWaitableInputAdapter inputAdapter(configFile.get());
651                 DPL::AbstractWaitableOutputAdapter outputAdapter(&buffer);
652                 DPL::Copy(&inputAdapter, &outputAdapter);
653                 parser.Parse(&buffer,
654                              ElementParserPtr(
655                                  new RootParser<WidgetParser>(configInfo,
656                                                               DPL::
657                                                                   FromUTF32String(
658                                                                   L"widget"))));
659             } else {
660                 // DRM widget
661                 std::string configFile;
662                 if (pkgType == PKG_TYPE_HYBRID_WEB_APP) {
663                     configFile = tempPath + "/" + WITH_OSP_XML;
664                 } else {
665                     configFile = tempPath + "/" + CONFIG_XML;
666                 }
667
668                 parser.Parse(configFile,
669                              ElementParserPtr(
670                                  new RootParser<WidgetParser>(configInfo,
671                                                               DPL::
672                                                                   FromUTF32String(
673                                                                   L"widget"))));
674             }
675         }
676     }
677     Catch(DPL::ZipInput::Exception::OpenFailed)
678     {
679         LogError("Failed to open widget package");
680         return ConfigParserData();
681     }
682     Catch(DPL::ZipInput::Exception::OpenFileFailed)
683     {
684         LogError("Failed to open config.xml file");
685         return ConfigParserData();
686     }
687     Catch(DPL::CopyFailed)
688     {
689         LogError("Failed to extract config.xml file");
690         return ConfigParserData();
691     }
692     Catch(DPL::FileInput::Exception::OpenFailed)
693     {
694         LogError("Failed to open config.xml file");
695         return ConfigParserData();
696     }
697     Catch(ElementParser::Exception::ParseError)
698     {
699         LogError("Failed to parse config.xml file");
700         return ConfigParserData();
701     }
702     Catch(DPL::ZipInput::Exception::SeekFileFailed)
703     {
704         LogError("Failed to seek widget archive - corrupted package?");
705         return ConfigParserData();
706     }
707     return configInfo;
708 }
709
710 WidgetUpdateInfo JobWidgetInstall::detectWidgetUpdate(
711     const ConfigParserData &configInfo,
712     const WrtDB::WidgetType appType,
713     const WrtDB::TizenAppId &tizenId)
714 {
715     LogInfo("Checking up widget package for config.xml...");
716
717     DPL::OptionalString widgetGUID;
718     OptionalWidgetVersion widgetVersion;
719
720     // Check widget id
721     widgetGUID = configInfo.widget_id;
722
723     if (widgetGUID.IsNull()) {
724         LogWarning("Installed widget has no GUID");
725         return WidgetUpdateInfo();
726     }
727
728     LogDebug("Installed widget GUID: " << *widgetGUID);
729
730     // Locate widget ID with this GUID
731     // Incoming widget version
732     if (!configInfo.version.IsNull()) {
733         widgetVersion =
734             DPL::Optional<WidgetVersion>(
735                 WidgetVersion(*configInfo.version));
736     }
737
738     if (appType == APP_TYPE_WAC20) {
739         Try
740         {
741             // Search widget handle by GUID
742             WidgetDAOReadOnly dao(widgetGUID);
743             return WidgetUpdateInfo(
744                        widgetGUID,
745                        widgetVersion,
746                        WidgetUpdateInfo::ExistingWidgetInfo(
747                            dao.getTzAppId(), dao.getVersion()));
748         }
749         Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
750         {
751             // GUID isn't installed
752             return WidgetUpdateInfo(
753                        widgetGUID,
754                        widgetVersion,
755                        WidgetUpdateInfo::ExistingWidgetInfo());
756         }
757     } else {
758         Try
759         {
760             // Search widget handle by appId
761             WidgetDAOReadOnly dao(tizenId);
762             return WidgetUpdateInfo(
763                        widgetGUID,
764                        widgetVersion,
765                        WidgetUpdateInfo::ExistingWidgetInfo(
766                            dao.getTzAppId(), dao.getVersion()));
767         }
768         Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
769         {
770             // GUID isn't installed
771             return WidgetUpdateInfo(
772                        widgetGUID,
773                        widgetVersion,
774                        WidgetUpdateInfo::ExistingWidgetInfo());
775         }
776     }
777 }
778
779 void JobWidgetInstall::SendProgress()
780 {
781     using namespace PackageManager;
782     if (GetProgressFlag() != false) {
783         if (getInstallerStruct().progressCallback != NULL) {
784             // send progress signal of pkgmgr
785             std::ostringstream percent;
786             percent << static_cast<int>(GetProgressPercent());
787             getInstallerStruct().pkgmgrInterface->sendSignal(
788                 PKGMGR_PROGRESS_KEY,
789                 percent.str());
790
791             LogDebug("Call widget install progressCallbak");
792             getInstallerStruct().progressCallback(
793                 getInstallerStruct().userParam,
794                 GetProgressPercent(),
795                 GetProgressDescription());
796         }
797     }
798 }
799
800 void JobWidgetInstall::SendProgressIconPath(const std::string &path)
801 {
802     using namespace PackageManager;
803     if (GetProgressFlag() != false) {
804         if (getInstallerStruct().progressCallback != NULL) {
805             // send progress signal of pkgmgr
806             getInstallerStruct().pkgmgrInterface->sendSignal(
807                 PKGMGR_ICON_PATH,
808                 path);
809         }
810     }
811 }
812
813 void JobWidgetInstall::SendFinishedSuccess()
814 {
815     using namespace PackageManager;
816     // TODO : sync should move to separate task.
817     sync();
818
819     if (INSTALL_LOCATION_TYPE_EXTERNAL == m_installerContext.locationType) {
820         if (false == m_installerContext.existingWidgetInfo.isExist) {
821             WidgetInstallToExtSingleton::Instance().postInstallation(true);
822         } else {
823             WidgetInstallToExtSingleton::Instance().postUpgrade(true);
824         }
825         WidgetInstallToExtSingleton::Instance().deinitialize();
826     }
827
828     // remove widget install information file
829     unlink(m_installerContext.installInfo.c_str());
830
831     //inform widget info
832     JobWidgetInstall::displayWidgetInfo();
833
834     TizenAppId& tizenId = m_installerContext.widgetConfig.tzAppid;
835
836     // send signal of pkgmgr
837     getInstallerStruct().pkgmgrInterface->sendSignal(
838         PKGMGR_END_KEY,
839         PKGMGR_END_SUCCESS);
840
841     LogDebug("Call widget install successfinishedCallback");
842     getInstallerStruct().finishedCallback(getInstallerStruct().userParam,
843                                           DPL::ToUTF8String(
844                                               tizenId), Exceptions::Success);
845 }
846
847 void JobWidgetInstall::SendFinishedFailure()
848 {
849     using namespace PackageManager;
850     // remove widget install information file
851     unlink(m_installerContext.installInfo.c_str());
852
853     LogError("Error in installation step: " << m_exceptionCaught);
854     LogError("Message: " << m_exceptionMessage);
855     TizenAppId & tizenId = m_installerContext.widgetConfig.tzAppid;
856
857     LogDebug("Call widget install failure finishedCallback");
858
859     // send signal of pkgmgr
860     getInstallerStruct().pkgmgrInterface->sendSignal(
861         PKGMGR_END_KEY,
862         PKGMGR_END_FAILURE);
863
864     getInstallerStruct().finishedCallback(getInstallerStruct().userParam,
865                                           DPL::ToUTF8String(
866                                               tizenId), m_exceptionCaught);
867 }
868
869 void JobWidgetInstall::SaveExceptionData(const Jobs::JobExceptionBase &e)
870 {
871     m_exceptionCaught = static_cast<Exceptions::Type>(e.getParam());
872     m_exceptionMessage = e.GetMessage();
873 }
874
875 void JobWidgetInstall::displayWidgetInfo()
876 {
877     WidgetDAOReadOnly dao(m_installerContext.widgetConfig.tzAppid);
878
879     std::ostringstream out;
880     WidgetLocalizedInfo localizedInfo =
881         W3CFileLocalization::getLocalizedInfo(dao.getTzAppId());
882
883     out << std::endl <<
884     "===================================== INSTALLED WIDGET INFO =========" \
885     "============================";
886     out << std::endl << "Name:                        " << localizedInfo.name;
887     out << std::endl << "AppId:                     " << dao.getTzAppId();
888     WidgetSize size = dao.getPreferredSize();
889     out << std::endl << "Width:                       " << size.width;
890     out << std::endl << "Height:                      " << size.height;
891     out << std::endl << "Start File:                  " <<
892     W3CFileLocalization::getStartFile(dao.getTzAppId());
893     out << std::endl << "Version:                     " << dao.getVersion();
894     out << std::endl << "Licence:                     " <<
895     localizedInfo.license;
896     out << std::endl << "Licence Href:                " <<
897     localizedInfo.licenseHref;
898     out << std::endl << "Description:                 " <<
899     localizedInfo.description;
900     out << std::endl << "Widget Id:                   " << dao.getGUID();
901     out << std::endl << "Widget recognized:           " << dao.isRecognized();
902     out << std::endl << "Widget wac signed:           " << dao.isWacSigned();
903     out << std::endl << "Widget distributor signed:   " <<
904     dao.isDistributorSigned();
905     out << std::endl << "Widget trusted:              " << dao.isTrusted();
906
907     OptionalWidgetIcon icon = W3CFileLocalization::getIcon(dao.getTzAppId());
908     DPL::OptionalString iconSrc =
909         !!icon ? icon->src : DPL::OptionalString::Null;
910     out << std::endl << "Icon:                        " << iconSrc;
911
912     out << std::endl << "Preferences:";
913     {
914         PropertyDAOReadOnly::WidgetPreferenceList list = dao.getPropertyList();
915         FOREACH(it, list)
916         {
917             out << std::endl << "  Key:                       " <<
918             it->key_name;
919             out << std::endl << "      Readonly:              " <<
920             it->readonly;
921         }
922     }
923
924     out << std::endl << "Features:";
925     {
926         WidgetFeatureSet list = dao.getFeaturesList();
927         FOREACH(it, list)
928         {
929             out << std::endl << "  Name:                      " << it->name;
930             out << std::endl << "      Required:              " << it->required;
931             out << std::endl << "      Params:";
932         }
933     }
934
935     out << std::endl;
936
937     LogInfo(out.str());
938 }
939
940 WrtDB::PackagingType JobWidgetInstall::checkPackageType(
941     const std::string &widgetSource,
942     const std::string &tempPath)
943 {
944     // Check installation type (direcotory/ or config.xml or widget.wgt)
945     if (WidgetUpdateMode::PolicyDirectoryForceInstall ==
946         m_jobStruct.updateMode)
947     {
948         LogDebug("Install directly from directory");
949         return PKG_TYPE_DIRECTORY_WEB_APP;
950     }
951     if (hasExtension(widgetSource, XML_EXTENSION)) {
952         LogInfo("Hosted app installation");
953         return PKG_TYPE_HOSTED_WEB_APP;
954     }
955
956     if (m_isDRM) {
957         std::string configFile = tempPath + "/" + CONFIG_XML;
958         if (WrtUtilFileExists(configFile)) {
959             return PKG_TYPE_NOMAL_WEB_APP;
960         }
961
962         configFile = tempPath + "/" + WITH_OSP_XML;
963         if (WrtUtilFileExists(configFile)) {
964             return PKG_TYPE_HYBRID_WEB_APP;
965         }
966     } else {
967         std::unique_ptr<DPL::ZipInput> zipFile;
968
969         Try
970         {
971             // Open zip file
972             zipFile.reset(new DPL::ZipInput(widgetSource));
973         }
974         Catch(DPL::ZipInput::Exception::OpenFailed)
975         {
976             LogDebug("Failed to open widget package");
977             return PKG_TYPE_UNKNOWN;
978         }
979         Catch(DPL::ZipInput::Exception::SeekFileFailed)
980         {
981             LogError("Failed to seek widget package file");
982             return PKG_TYPE_UNKNOWN;
983         }
984
985         Try
986         {
987             // Open config.xml file in package root
988             std::unique_ptr<DPL::ZipInput::File> configFile(
989                 zipFile->OpenFile(CONFIG_XML));
990             return PKG_TYPE_NOMAL_WEB_APP;
991         }
992         Catch(DPL::ZipInput::Exception::OpenFileFailed)
993         {
994             LogDebug("Could not find config.xml");
995         }
996
997         Try
998         {
999             // Open config.xml file in package root
1000             std::unique_ptr<DPL::ZipInput::File> configFile(
1001                 zipFile->OpenFile(WITH_OSP_XML));
1002
1003             return PKG_TYPE_HYBRID_WEB_APP;
1004         }
1005         Catch(DPL::ZipInput::Exception::OpenFileFailed)
1006         {
1007             LogDebug("Could not find wgt/config.xml");
1008             return PKG_TYPE_UNKNOWN;
1009         }
1010     }
1011
1012     return PKG_TYPE_UNKNOWN;
1013 }
1014
1015 void JobWidgetInstall::setApplicationType(
1016     const WrtDB::ConfigParserData &configInfo)
1017 {
1018     FOREACH(iterator, configInfo.nameSpaces) {
1019         LogInfo("namespace = [" << *iterator << "]");
1020         AppType currentAppType = APP_TYPE_UNKNOWN;
1021
1022         if (*iterator == ConfigurationNamespace::W3CWidgetNamespaceName) {
1023             continue;
1024         } else if (
1025             *iterator ==
1026             ConfigurationNamespace::WacWidgetNamespaceNameForLinkElement ||
1027             *iterator ==
1028             ConfigurationNamespace::WacWidgetNamespaceName)
1029         {
1030             currentAppType = APP_TYPE_WAC20;
1031         } else if (*iterator ==
1032                    ConfigurationNamespace::TizenWebAppNamespaceName)
1033         {
1034             currentAppType = APP_TYPE_TIZENWEBAPP;
1035         }
1036
1037         if (m_installerContext.widgetConfig.webAppType ==
1038             APP_TYPE_UNKNOWN)
1039         {
1040             m_installerContext.widgetConfig.webAppType = currentAppType;
1041         } else if (m_installerContext.widgetConfig.webAppType ==
1042                    currentAppType)
1043         {
1044             continue;
1045         } else {
1046             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
1047                      "Config.xml has more than one namespace");
1048         }
1049     }
1050
1051     // If there is no define, type set to WAC 2.0
1052     if (m_installerContext.widgetConfig.webAppType == APP_TYPE_UNKNOWN) {
1053         m_installerContext.widgetConfig.webAppType = APP_TYPE_WAC20;
1054     }
1055
1056     LogInfo("type = [" <<
1057             m_installerContext.widgetConfig.webAppType.getApptypeToString() <<
1058             "]");
1059 }
1060
1061 bool JobWidgetInstall::detectResourceEncryption(
1062     const WrtDB::ConfigParserData &configData)
1063 {
1064     FOREACH(it, configData.settingsList)
1065     {
1066         if (it->m_name == SETTING_VALUE_ENCRYPTION &&
1067             it->m_value == SETTING_VALUE_ENCRYPTION_ENABLE)
1068         {
1069             LogDebug("resource need encryption");
1070             return true;
1071         }
1072     }
1073     return false;
1074 }
1075
1076 void JobWidgetInstall::setInstallLocationType(
1077     const
1078     WrtDB::ConfigParserData &
1079     configData)
1080 {
1081     m_installerContext.locationType = INSTALL_LOCATION_TYPE_NOMAL;
1082
1083     if (true == m_jobStruct.m_preload) {
1084         m_installerContext.locationType =
1085             INSTALL_LOCATION_TYPE_PRELOAD;
1086     } else {
1087         FOREACH(it, configData.settingsList)
1088         {
1089             if (it->m_name == SETTING_VALUE_INSTALLTOEXT_NAME &&
1090                 it->m_value ==
1091                 SETTING_VALUE_INSTALLTOEXT_PREPER_EXT)
1092             {
1093                 LogDebug("This widget will be installed to sd card");
1094                 m_installerContext.locationType =
1095                     INSTALL_LOCATION_TYPE_EXTERNAL;
1096             }
1097         }
1098     }
1099 }
1100
1101 bool JobWidgetInstall::isDRMWidget(std::string widgetPath)
1102 {
1103     /* TODO :
1104      * drm_bool_type_e is_drm_file = DRM_UNKNOWN;
1105      * int ret = -1;
1106      *
1107      * ret = drm_is_drm_file(widgetPath.c_str(), &is_drm_file);
1108      * if(DRM_RETURN_SUCCESS == ret && DRM_TRUE == is_drm_file) {
1109      */
1110
1111     /* blow code temporary code for drm. */
1112     int ret = drm_oem_intel_isDrmFile(const_cast<char*>(widgetPath.c_str()));
1113     if (1 == ret) {
1114         return true;
1115     } else {
1116         return false;
1117     }
1118 }
1119
1120 bool JobWidgetInstall::DecryptDRMWidget(std::string widgetPath,
1121                                         std::string destPath)
1122 {
1123     /* TODO :
1124      * drm_trusted_sapps_decrypt_package_info_s package_info;
1125      *
1126      * strncpy(package_info.sadcf_filepath, widgetPath.c_str(),
1127      *      sizeof(package_info.sadcf_filepath));
1128      * strncpy(package_info.decrypt_filepath, destPath.c_str(),
1129      *      sizeof(package_info.decrypt_filepath));
1130      *
1131      * drm_trusted_request_type_e requestType =
1132      *  DRM_TRUSTED_REQ_TYPE_SAPPS_DECRYPT_PACKAGE;
1133      *
1134      * int ret = drm_trusted_handle_request(requestType,
1135      *                                   (void *)&package_info, NULL);
1136      * if (DRM_TRUSTED_RETURN_SUCCESS == ret) {
1137      *  return true;
1138      * } else {
1139      *  return false;
1140      * }
1141      */
1142     if (drm_oem_intel_decrypt_package(const_cast<char*>(widgetPath.c_str()),
1143                                       const_cast<char*>(destPath.c_str())) != 0)
1144     {
1145         return true;
1146     } else {
1147         return false;
1148     }
1149 }
1150 } //namespace WidgetInstall
1151 } //namespace Jobs