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