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