[Release] wrt-installer_0.1.37
[framework/web/wrt-installer.git] / src / jobs / widget_install / job_widget_install.cpp
old mode 100755 (executable)
new mode 100644 (file)
index 459c9aa..e2b2086
  * @version 1.0
  * @brief   Implementation file for main installer task
  */
+#include <memory>
+#include <string>
+#include <sys/time.h>
+#include <ctime>
+#include <cstdlib>
+#include <limits.h>
+#include <regex.h>
+
 #include <dpl/noncopyable.h>
 #include <dpl/abstract_waitable_input_adapter.h>
 #include <dpl/abstract_waitable_output_adapter.h>
 #include <dpl/zip_input.h>
-#include <dpl/scoped_ptr.h>
 #include <dpl/binary_queue.h>
 #include <dpl/copy.h>
 #include <dpl/assert.h>
 #include <dpl/sstream.h>
+#include <dpl/file_input.h>
+#include <dpl/utils/wrt_utility.h>
 #include <dpl/wrt-dao-ro/common_dao_types.h>
+#include <dpl/wrt-dao-ro/widget_dao_read_only.h>
+#include <dpl/wrt-dao-ro/global_config.h>
+#include <dpl/wrt-dao-ro/config_parser_data.h>
+#include <dpl/wrt-dao-rw/global_dao.h> // TODO remove
+#include <dpl/localization/w3c_file_localization.h>
+
+#include <libiriwrapper.h>
+#include <pkg-manager/pkgmgr_signal.h>
+#include <app_manager.h>
+
 #include "root_parser.h"
 #include "widget_parser.h"
 #include "parser_runner.h"
 #include <widget_install/job_widget_install.h>
-#include <widget_install/task_unzip.h>
 #include <widget_install/task_certify.h>
 #include <widget_install/task_widget_config.h>
-#include <widget_install/task_db_update.h>
+#include <widget_install/task_file_manipulation.h>
 #include <widget_install/task_ace_check.h>
 #include <widget_install/task_smack.h>
 #include <widget_install/task_manifest_file.h>
-#include <widget_install/task_private_storage.h>
 #include <widget_install/task_prepare_files.h>
 #include <widget_install/task_recovery.h>
 #include <widget_install/task_install_ospsvc.h>
 #include <widget_install/task_update_files.h>
-#include <widget_install/task_new_db_insert.h>
+#include <widget_install/task_database.h>
 #include <widget_install/task_remove_backup.h>
+#include <widget_install/task_encrypt_resource.h>
+#include <widget_install/task_certificates.h>
+#include <widget_install/task_unzip.h>
+#include <widget_install/task_commons.h>
+#include <widget_install/task_prepare_reinstall.h>
+
 #include <widget_install/widget_install_errors.h>
 #include <widget_install/widget_install_context.h>
-#include <string>
-#include <sys/time.h>
-#include <ctime>
-#include <cstdlib>
-#include <limits.h>
-#include <regex.h>
-#include <dpl/wrt-dao-ro/widget_dao_read_only.h>
-#include <dpl/wrt-dao-ro/global_config.h>
-#include <dpl/wrt-dao-rw/global_dao.h> // TODO remove
-#include <aul.h>
-#include <dpl/localization/w3c_file_localization.h>
-#include <libiriwrapper.h>
-#include <pkg-manager/pkgmgr_signal.h>
+#include <widget_install_to_external.h>
 
 using namespace WrtDB;
+using namespace Jobs::Exceptions;
 
 namespace // anonymous
 {
 const char * const CONFIG_XML = "config.xml";
 const char * const WITH_OSP_XML = "res/wgt/config.xml";
 
-//allowed: a-z, A-Z, 0-9, '.', '-', '_', ' '
-const char* REG_TIZENID_PATTERN = "^[-. a-zA-Z0-9_@+=]*$";
-const int RESERVED_COUNT = 20;  //number of chars reserved in name (e.g. for '.desktop')
-const int MAX_TIZENID_LENTH = 255 - RESERVED_COUNT;
+//allowed: a-z, A-Z, 0-9
+const char* REG_TIZENID_PATTERN = "^[a-zA-Z0-9]{10}.{1,}$";
+const char* REG_NAME_PATTERN = "^[a-zA-Z0-9._-]{1,}$";
+const size_t PACKAGE_ID_LENGTH = 10;
 
+static const DPL::String SETTING_VALUE_ENCRYPTION = L"encryption";
+static const DPL::String SETTING_VALUE_ENCRYPTION_ENABLE = L"enable";
+const DPL::String SETTING_VALUE_INSTALLTOEXT_NAME =
+    L"install-location";
+const DPL::String SETTING_VALUE_INSTALLTOEXT_PREPER_EXT =
+    L"prefer-external";
+
+const std::string XML_EXTENSION = ".xml";
+
+bool hasExtension(const std::string& filename, const std::string& extension)
+{
+    LogDebug("Looking for extension " << extension << " in: " << filename);
+    size_t fileLen = filename.length();
+    size_t extLen = extension.length();
+    if (fileLen < extLen) {
+        LogError("Filename " << filename << " is shorter than extension "
+                             << extension);
+        return false;
+    }
+    return (0 == filename.compare(fileLen - extLen, extLen, extension));
+}
+} // namespace anonymous
+
+namespace Jobs {
+namespace WidgetInstall {
 class InstallerTaskFail :
     public DPL::TaskDecl<InstallerTaskFail>
 {
   private:
-    bool m_deferred;
+    ConfigureResult m_result;
 
     void StepFail()
     {
-        if (m_deferred) {
+        if (m_result == ConfigureResult::Deferred) {
             ThrowMsg(Jobs::WidgetInstall::Exceptions::Deferred,
-                     "Widget installation or update deferred!");
+                    "widget installation or update deferred!");
+        } else if (m_result == ConfigureResult::Failed_InvalidConfig) {
+            ThrowMsg(Jobs::WidgetInstall::Exceptions::WidgetConfigFileInvalid,
+                    "invalid config");
+        } else if (m_result == ConfigureResult::Failed_LowerVersion) {
+            ThrowMsg(Jobs::WidgetInstall::Exceptions::PackageLowerVersion,
+                    "package version is lower than installed version");
+        } else if (m_result == ConfigureResult::Failed_AlreadyInstalled) {
+            ThrowMsg(Jobs::WidgetInstall::Exceptions::PackageAlreadyInstalled,
+                    "package is already installed");
+        } else if (m_result == ConfigureResult::Failed_WidgetRunning) {
+            ThrowMsg(Jobs::WidgetInstall::Exceptions::WidgetRunningError,
+                    "widget is running");
+        } else if (m_result == ConfigureResult::Failed_DrmError) {
+            ThrowMsg(Jobs::WidgetInstall::Exceptions::DRMFailed,
+                    "drm failed");
         } else {
             ThrowMsg(Jobs::WidgetInstall::Exceptions::NotAllowed,
-                     "Widget installation or update not allowed!");
+                    "widget installation or update not allowed!");
         }
     }
 
   public:
-    InstallerTaskFail(bool deferred) :
+    InstallerTaskFail(ConfigureResult result) :
         DPL::TaskDecl<InstallerTaskFail>(this),
-        m_deferred(deferred)
+        m_result(result)
     {
         AddStep(&InstallerTaskFail::StepFail);
     }
 };
 
-const std::string XML_EXTENSION = ".xml";
-
-bool hasExtension(const std::string& filename, const std::string& extension) {
-    LogDebug("Looking for extension " << extension << " in: "  << filename);
-    size_t fileLen = filename.length();
-    size_t extLen = extension.length();
-    if (fileLen < extLen) {
-        LogError("Filename " << filename << " is shorter than extension "
-                 << extension);
-        return false;
-    }
-    return (0 == filename.compare(fileLen-extLen, extLen, extension));
-}
-} // namespace anonymous
-
-namespace Jobs {
-namespace WidgetInstall {
-JobWidgetInstall::JobWidgetInstall(std::string const &widgetPath,
-        const WidgetInstallationStruct &installerStruct) :
+JobWidgetInstall::JobWidgetInstall(
+    std::string const &widgetPath,
+    const WidgetInstallationStruct &
+    installerStruct) :
     Job(Installation),
     JobContextBase<WidgetInstallationStruct>(installerStruct),
-    m_exceptionCaught(Exceptions::Success)
+    m_exceptionCaught(Jobs::Exceptions::Success)
 {
-    // Check installation type (config.xml or widget.wgt)
-    bool fromBrowser = hasExtension(widgetPath, XML_EXTENSION);
-    LogInfo("Hosted app installation: " << fromBrowser);
-
-    struct timeval tv;
-    gettimeofday(&tv, NULL);
-    srand(time(NULL) + tv.tv_usec);
-    WrtDB::DbWidgetHandle handle;
-    do {
-        handle = rand() % INT_MAX + 1;
-        LogInfo("Random widget handle: " << handle);
-    } while (WidgetDAOReadOnly::isWidgetInstalled(handle));
-
-    m_installerContext.widgetHandle = handle;
     m_installerContext.m_quiet = m_jobStruct.m_quiet;
 
-    m_installerContext.widgetConfig.pType = checkPackageType(widgetPath);
-
-    ConfigParserData configData = getWidgetDataFromXML(widgetPath, fromBrowser,
-            m_installerContext.widgetConfig.pType);
-    WidgetUpdateInfo update = detectWidgetUpdate(configData);
-
-
-    // Configure installation
-    ConfigureResult result = ConfigureInstallation(widgetPath, fromBrowser, update);
-    if (!setTizenId(configData)) {
-        result = ConfigureResult::Failed;
-    } else {
-        using namespace PackageManager;
-        LogInfo("WidgetHandle: " << m_installerContext.widgetHandle);
-        LogInfo("Tizen Id: " << m_installerContext.widgetConfig.pkgname);
-
-        // send start signal of pkgmgr
-        PkgmgrSignalSingleton::Instance().setPkgname(
-                    DPL::ToUTF8String(
-                        *m_installerContext.widgetConfig.pkgname));
-        PkgmgrSignalSingleton::Instance().sendSignal(
-                    PKGMGR_START_KEY,
-                    PKGMGR_START_INSTALL);
-    }
+    ConfigureResult result = PrePareInstallation(widgetPath);
 
     if (result == ConfigureResult::Ok) {
         LogInfo("Configure installation succeeded");
+        m_installerContext.job->SetProgressFlag(true);
 
         AddTask(new TaskRecovery(m_installerContext));
 
         // Create installation tasks
-        if (!fromBrowser) {
+        if (m_installerContext.widgetConfig.packagingType !=
+            WrtDB::PKG_TYPE_DIRECTORY_WEB_APP &&
+            m_installerContext.widgetConfig.packagingType !=
+            WrtDB::PKG_TYPE_HOSTED_WEB_APP &&
+            !m_isDRM)
+        {
             AddTask(new TaskUnzip(m_installerContext));
         }
+
         AddTask(new TaskWidgetConfig(m_installerContext));
+        if (m_installerContext.widgetConfig.packagingType ==
+            WrtDB::PKG_TYPE_HOSTED_WEB_APP)
+        {
+            AddTask(new TaskPrepareFiles(m_installerContext));
+        }
         AddTask(new TaskCertify(m_installerContext));
-        AddTask(new TaskDbUpdate(m_installerContext));
-        // TODO: Update progress information for this task
+        if (m_needEncryption) {
+            AddTask(new TaskEncryptResource(m_installerContext));
+        }
 
-        AddTask(new TaskPrivateStorage(m_installerContext));
-        AddTask(new TaskAceCheck(m_installerContext));
-        //This is sort of quick solution, because ACE verdicts are based upon
-        //data from DAO (DB). So AceCheck for now has to be AFTER DbUpdate
-        //task.
-        AddTask(new TaskSmack(m_installerContext));
+        AddTask(new TaskFileManipulation(m_installerContext));
 
         AddTask(new TaskManifestFile(m_installerContext));
-        if (m_installerContext.widgetConfig.pType ==
-                PKG_TYPE_TIZEN_WITHSVCAPP) {
+        if (m_installerContext.widgetConfig.packagingType ==
+            PKG_TYPE_HYBRID_WEB_APP)
+        {
             AddTask(new TaskInstallOspsvc(m_installerContext));
         }
+        AddTask(new TaskCertificates(m_installerContext));
+        AddTask(new TaskDatabase(m_installerContext));
+        AddTask(new TaskAceCheck(m_installerContext));
+        AddTask(new TaskSmack(m_installerContext));
     } else if (result == ConfigureResult::Updated) {
         LogInfo("Configure installation updated");
         LogInfo("Widget Update");
+        m_installerContext.job->SetProgressFlag(true);
+
+        if (m_jobStruct.m_installMode ==
+            InstallMode::REINSTALL_MODE_DIRECTORY)
+        {
+            AddTask(new TaskPrepareReinstall(m_installerContext));
+        }
 
-        if (!fromBrowser) {
+        if (m_installerContext.widgetConfig.packagingType !=
+            WrtDB::PKG_TYPE_HOSTED_WEB_APP &&
+            m_installerContext.widgetConfig.packagingType !=
+            WrtDB::PKG_TYPE_DIRECTORY_WEB_APP &&
+            !m_isDRM)
+        {
             AddTask(new TaskUnzip(m_installerContext));
         }
+
         AddTask(new TaskWidgetConfig(m_installerContext));
 
+        if (m_installerContext.widgetConfig.packagingType ==
+            WrtDB::PKG_TYPE_HOSTED_WEB_APP)
+        {
+            AddTask(new TaskPrepareFiles(m_installerContext));
+        }
+
         AddTask(new TaskCertify(m_installerContext));
-        AddTask(new TaskUpdateFiles(m_installerContext));
-        AddTask(new TaskNewDbInsert(m_installerContext));
+        if (m_needEncryption) {
+            AddTask(new TaskEncryptResource(m_installerContext));
+        }
 
-        /* TODO : To backup file, save md5 values */
-        AddTask(new TaskAceCheck(m_installerContext));
-        AddTask(new TaskSmack(m_installerContext));
+        if (m_installerContext.widgetConfig.packagingType !=
+            WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
+        {
+            AddTask(new TaskUpdateFiles(m_installerContext));
+        }
 
         AddTask(new TaskManifestFile(m_installerContext));
-        AddTask(new TaskRemoveBackupFiles(m_installerContext));
-        if (m_installerContext.widgetConfig.pType ==
-                PKG_TYPE_TIZEN_WITHSVCAPP) {
+        if (m_installerContext.widgetConfig.packagingType ==
+            PKG_TYPE_HYBRID_WEB_APP)
+        {
             AddTask(new TaskInstallOspsvc(m_installerContext));
         }
+        if (m_installerContext.widgetConfig.packagingType !=
+            WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
+        {
+            AddTask(new TaskRemoveBackupFiles(m_installerContext));
+        }
+        AddTask(new TaskDatabase(m_installerContext));
+        AddTask(new TaskAceCheck(m_installerContext));
+        //TODO: remove widgetHandle from this task and move before database task
+        // by now widget handle is needed in ace check
+        // Any error in acecheck while update will break widget
+        AddTask(new TaskSmack(m_installerContext));
     } else if (result == ConfigureResult::Deferred) {
         // Installation is deferred
         LogInfo("Configure installation deferred");
 
-        AddTask(new InstallerTaskFail(true));
-    } else if (result == ConfigureResult::Failed) {
+        AddTask(new InstallerTaskFail(result));
+    } else if (result >= ConfigureResult::Failed &&
+            result <= ConfigureResult::Failed_DrmError) {
         // Installation is not allowed to proceed due to widget update policy
         LogWarning("Configure installation failed!");
 
-        AddTask(new InstallerTaskFail(false));
+        AddTask(new InstallerTaskFail(result));
     } else {
         Assert(false && "Invalid configure result!");
     }
 }
 
-bool JobWidgetInstall::setTizenId(
-        const WrtDB::ConfigParserData &configInfo)
+ConfigureResult JobWidgetInstall::PrePareInstallation(
+    const std::string &widgetPath)
 {
-    Assert(!!m_installerContext.widgetHandle
-           && "Widget Handle should be initialized");
+    ConfigureResult result;
+    m_needEncryption = false;
 
-    regex_t reg;
-    regcomp(&reg, REG_TIZENID_PATTERN, REG_NOSUB);
-    struct stat dirStat;
-    if(!!configInfo.tizenId) {
-        LogDebug("Setting tizenId provided in config.xml");
-        if ((regexec(&reg, DPL::ToUTF8String(*(configInfo.tizenId)).c_str(),
-             static_cast<size_t>(0), NULL, 0) != 0) ||
-            (DPL::ToUTF8String(*(configInfo.tizenId)).size() > MAX_TIZENID_LENTH) ||
-            (stat((std::string(GlobalConfig::GetUserInstalledWidgetPath()) + "/"
-                   + DPL::ToUTF8String(*(configInfo.tizenId))).c_str(), &dirStat) == 0))
+    Try
+    {
+        std::string tempDir;
+        if (m_jobStruct.m_installMode ==
+            InstallMode::REINSTALL_MODE_DIRECTORY)
         {
-            //it is true when tizenId does not fit REG_TIZENID_PATTERN
-            LogError("pkgName provided but not proper.");
-            regfree(&reg);
-            return false;
+            std::ostringstream tempPathBuilder;
+            tempPathBuilder << WrtDB::GlobalConfig::GetUserInstalledWidgetPath();
+            tempPathBuilder << WrtDB::GlobalConfig::GetTmpDirPath();
+            tempPathBuilder << "/";
+            tempPathBuilder << widgetPath;
+            tempDir = tempPathBuilder.str();;
+        } else {
+            tempDir =
+                Jobs::WidgetInstall::createTempPath(
+                        m_jobStruct.m_installMode ==
+                            InstallMode::INSTALL_MODE_PRELOAD);
         }
-        m_installerContext.widgetConfig.pkgname = configInfo.tizenId;
-
-    } else {
-        LogInfo("package name is generated by WRT");
-        // tizen id should be generated by secure random algorithm
-        std::string pkgName = WrtDB::GlobalConfig::GetPkgnamePrefix();
 
-        bool named = false;
-        FOREACH(it, configInfo.localizedDataSet)
-        {
-            if (!!((it->second).name)) {
-                //there is a name provided
-                std::string name =  DPL::ToUTF8String(*(it->second).name);
-                //cut very long widget's name
-                name = name.substr(0, MAX_TIZENID_LENTH - strlen(
-                    WrtDB::GlobalConfig::GetPkgnamePrefix()));
-                //check name if all characters are supported by filesystem
-                if (regexec(&reg, name.c_str(), static_cast<size_t>(0), NULL, 0)
-                    == 0)
-                {
-                    //WidgetName is ok and can be used as package name
-                    //replace all spaces with '_'
-                    size_t pos = 0;
-                    while((pos = name.find(" ", pos)) != std::string::npos) {
-                        name.replace(pos, 1, "_");
-                        ++pos;
-                    }
-                    pkgName += name;
-                    named = true;
-                }
-                break;
+        m_isDRM = isDRMWidget(widgetPath);
+        if (true == m_isDRM) {
+            LogDebug("decrypt DRM widget");
+            if (DecryptDRMWidget(widgetPath, tempDir)) {
+                LogDebug("Failed decrypt DRM widget");
+                return ConfigureResult::Failed_DrmError;
             }
         }
 
-        if (!named) // there is no widget name provided, use widgetHandle
-        {
-            pkgName += std::to_string(*(m_installerContext.widgetHandle));
-        }
+        LogDebug("widgetPath:" << widgetPath);
+
+        m_installerContext.widgetConfig.packagingType =
+            checkPackageType(widgetPath, tempDir);
+        ConfigParserData configData = getWidgetDataFromXML(
+                widgetPath,
+                tempDir,
+                m_installerContext.widgetConfig.packagingType,
+                m_isDRM,
+                m_jobStruct.m_installMode ==
+                    InstallMode::REINSTALL_MODE_DIRECTORY);
+        LogDebug("widget packaging type : " <<
+                 m_installerContext.widgetConfig.packagingType.pkgType);
+
+        setTizenId(configData);
+        setApplicationType(configData);
+        m_needEncryption = detectResourceEncryption(configData);
+        setInstallLocationType(configData);
+
+        // Configure installation
+        result = ConfigureInstallation(widgetPath, configData, tempDir);
+    }
+    Catch(Exceptions::ExtractFileFailed)
+    {
+        LogError("Failed to create temporary path for widget");
+        result = ConfigureResult::Failed_InvalidConfig;
+    }
+
+    return result;
+}
 
-        //check if there is package with same name and if generate different name
-        std::string path = GlobalConfig::GetUserInstalledWidgetPath();
-        path += "/";
+void JobWidgetInstall::setTizenId(
+    const WrtDB::ConfigParserData &configInfo)
+{
+    bool shouldMakeAppid = false;
+    using namespace PackageManager;
+    if (!!configInfo.tizenAppId) {
+        LogDebug("Setting tizenAppId provided in config.xml: " <<
+                 configInfo.tizenAppId);
 
-        std::ostringstream newPath;
-        newPath << path << pkgName;
+        m_installerContext.widgetConfig.tzAppid = *configInfo.tizenAppId;
+        //check package id.
+        if (!!configInfo.tizenPkgId) {
+            LogDebug("Setting tizenPkgId provided in config.xml: " <<
+                     configInfo.tizenPkgId);
 
-        std::string suffix;
-        for (int i = 0;; ++i) {
-            if (stat(newPath.str().c_str(), &dirStat) == 0) {
-                //path exist, chose another one, eg. widgetName1
-                suffix = std::to_string(i + 1);
-                pkgName = pkgName.substr(
-                        0, MAX_TIZENID_LENTH - suffix.size());
-                newPath.str("");
-                newPath << path << pkgName << suffix;
+            m_installerContext.widgetConfig.tzPkgid = *configInfo.tizenPkgId;
+        } else {
+            DPL::String appid = *configInfo.tizenAppId;
+            if (appid.length() > PACKAGE_ID_LENGTH) {
+                m_installerContext.widgetConfig.tzPkgid =
+                    appid.substr(0, PACKAGE_ID_LENGTH);
+            } else {
+                //old version appid only has 10byte random character is able to install for a while.
+                //this case appid equal pkgid.
+                m_installerContext.widgetConfig.tzPkgid =
+                    *configInfo.tizenAppId;
+                shouldMakeAppid = true;
+            }
+        }
+    } else {
+        shouldMakeAppid = true;
+        TizenPkgId pkgId = WidgetDAOReadOnly::generatePkgId();
+        LogDebug("Checking if pkg id is unique");
+        while (true) {
+            if (!validateTizenPackageID(pkgId)) {
+                //path exist, chose another one
+                pkgId = WidgetDAOReadOnly::generatePkgId();
                 continue;
             }
-            pkgName += suffix;
             break;
         }
+        m_installerContext.widgetConfig.tzPkgid = pkgId;
+        LogInfo("tizen_id name was generated by WRT: " <<
+                m_installerContext.widgetConfig.tzPkgid);
+    }
+
+    if (shouldMakeAppid == true) {
+        DPL::OptionalString name;
+        DPL::OptionalString defaultLocale = configInfo.defaultlocale;
 
-        m_installerContext.widgetConfig.pkgname =
-            DPL::FromUTF8String(pkgName);
+        FOREACH(localizedData, configInfo.localizedDataSet)
+        {
+            Locale i = localizedData->first;
+            if (!!defaultLocale) {
+                if (defaultLocale == i) {
+                    name = localizedData->second.name;
+                    break;
+                }
+            } else {
+                name = localizedData->second.name;
+                break;
+            }
+        }
+        regex_t regx;
+        if (regcomp(&regx, REG_NAME_PATTERN, REG_NOSUB | REG_EXTENDED) != 0) {
+            LogDebug("Regcomp failed");
+        }
 
+        LogDebug("Name : " << name);
+        if (!name || (regexec(&regx, DPL::ToUTF8String(*name).c_str(),
+                              static_cast<size_t>(0), NULL, 0) != REG_NOERROR))
+        {
+            // TODO : generate name move to wrt-commons
+            std::string allowedString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
+            std::ostringstream genName;
+            struct timeval tv;
+            gettimeofday(&tv, NULL);
+            unsigned int seed = time(NULL) + tv.tv_usec;
+
+            genName << "_" << allowedString[rand_r(&seed) % allowedString.length()];
+            name = DPL::FromUTF8String(genName.str());
+            LogDebug("name was generated by WRT");
+        }
+        regfree(&regx);
+        LogDebug("Name : " << name);
+        std::ostringstream genid;
+        genid << m_installerContext.widgetConfig.tzPkgid << "." << name;
+        LogDebug("tizen appid was generated by WRT : " << genid.str());
+
+        DPL::OptionalString appid = DPL::FromUTF8String(genid.str());
+        NormalizeAndTrimSpaceString(appid);
+        m_installerContext.widgetConfig.tzAppid = *appid;
     }
-    regfree(&reg);
 
-    LogInfo("Tizen Id : " << m_installerContext.widgetConfig.pkgname);
+    // send start signal of pkgmgr
+    getInstallerStruct().pkgmgrInterface->setPkgname(DPL::ToUTF8String(
+                                                         m_installerContext.
+                                                             widgetConfig.
+                                                             tzPkgid));
+    LogInfo("Tizen App Id : " << m_installerContext.widgetConfig.tzAppid);
+    LogInfo("Tizen Pkg Id : " << m_installerContext.widgetConfig.tzPkgid);
     LogInfo("W3C Widget GUID : " << m_installerContext.widgetConfig.guid);
-    return true;
 }
 
-DPL::Optional<WidgetHandle> JobWidgetInstall::getNewWidgetHandle() const
+void JobWidgetInstall::configureWidgetLocation(const std::string & widgetPath,
+                                               const std::string& tempPath)
 {
-    return m_installerContext.widgetHandle;
+    if (m_jobStruct.m_installMode ==
+         InstallMode::REINSTALL_MODE_DIRECTORY)
+    {
+        // replace widget path to installed path
+        m_installerContext.locations =
+            WidgetLocation(DPL::ToUTF8String(m_installerContext.widgetConfig.
+                                                 tzPkgid),
+                           widgetPath, tempPath,
+                           m_installerContext.widgetConfig.packagingType,
+                           m_installerContext.locationType);
+    } else {
+        m_installerContext.locations =
+            WidgetLocation(DPL::ToUTF8String(m_installerContext.widgetConfig.
+                                                 tzPkgid),
+                           widgetPath, tempPath,
+                           m_installerContext.widgetConfig.packagingType,
+                           m_installerContext.locationType);
+    }
+    m_installerContext.locations->registerAppid(
+        DPL::ToUTF8String(m_installerContext.widgetConfig.tzAppid));
+
+    LogInfo("widgetSource " << widgetPath);
 }
 
-JobWidgetInstall::ConfigureResult JobWidgetInstall::ConfigureInstallation(
-        const std::string &widgetSource,
-        bool fromBrowser,
-        const WidgetUpdateInfo &update)
+ConfigureResult JobWidgetInstall::ConfigureInstallation(
+    const std::string &widgetSource,
+    const WrtDB::ConfigParserData &configData,
+    const std::string &tempPath)
 {
-    LogInfo(
-        "Widget install/update: incoming guid = '" <<
-        update.incomingGUID << "'");
-    LogInfo(
-        "Widget install/update: incoming version = '" <<
-        update.incomingVersion << "'");
-
-    // Check policy
-    WidgetUpdateMode::Type updateTypeCheckBit;
-
-    if (update.existingWidgetInfo.isExist == false) {
-        LogInfo("Widget info does not exist");
-        updateTypeCheckBit = WidgetUpdateMode::NotInstalled;
-    } else {
-        LogInfo("Widget info exists. Handle: " <<
-                update.existingWidgetInfo.existingHandle);
+    ConfigureResult result = ConfigureResult::Failed;
+    WidgetUpdateInfo update;
+
+    // checking installed web application
+    Try {
+        // checking existing application is installed
+        WidgetDAOReadOnly dao(m_installerContext.widgetConfig.tzAppid);
+        // no excpetion means, it isn't update mode
+        getInstallerStruct().pkgmgrInterface->sendSignal(
+                PKGMGR_START_KEY,
+                PKGMGR_START_UPDATE);
+
+        update = detectWidgetUpdate(configData,
+                                    m_installerContext.widgetConfig.tzAppid);
+        result = checkWidgetUpdate(update);
+        if (result != ConfigureResult::Updated) {
+            // Already installed TizenAppId. return failed
+            return ConfigureResult::Failed_AlreadyInstalled;
+        }
+        m_installerContext.isUpdateMode = true;
+    }
+    Catch(WidgetDAOReadOnly::Exception::WidgetNotExist) {
+        result = ConfigureResult::Ok;
+        getInstallerStruct().pkgmgrInterface->sendSignal(
+                PKGMGR_START_KEY,
+                PKGMGR_START_INSTALL);
+        m_installerContext.isUpdateMode = false;
+
+        if (!validateTizenApplicationID(
+            m_installerContext.widgetConfig.tzAppid))
+        {
+            LogError("tizen application ID is already used");
+            return ConfigureResult::Failed_InvalidConfig;
+        }
+        if (!validateTizenPackageID(m_installerContext.widgetConfig.tzPkgid)) {
+            LogError("tizen package ID is already used");
+            return ConfigureResult::Failed_AlreadyInstalled;
+        }
+    }
 
-        DPL::OptionalString pkgname =
-            WidgetDAOReadOnly(update.existingWidgetInfo.existingHandle).getPkgname();
+    configureWidgetLocation(widgetSource, tempPath);
 
-        if(pkgname.IsNull()) {
-            LogInfo("But package name doesn't exist");
-            return ConfigureResult::Failed;
-        }
+    // Init installer context
+    m_installerContext.installStep = InstallerContext::INSTALL_START;
+    m_installerContext.job = this;
+    m_installerContext.widgetConfig.shareHref = std::string();
 
-        LogInfo("Widget model exists. package name: " << pkgname);
-        if (aul_app_is_running(DPL::ToUTF8String(*pkgname).c_str())) {
-            // Must be deferred when update in progress
-            if (m_jobStruct.updateMode == WidgetUpdateMode::PolicyWac) {
-                LogInfo(
-                    "Widget is already running. Policy is update according to WAC");
+    return result;
+}
 
-                return ConfigureResult::Deferred;
-            } else {
-                LogInfo(
-                    "Widget is already running. Policy is not update according to WAC");
-                LogInfo("Installation aborted: " << widgetSource);
+bool JobWidgetInstall::validateTizenApplicationID(
+    const WrtDB::TizenAppId &tizenAppId)
+{
+    LogInfo("tizen application ID = [" << tizenAppId << "]");
 
-                return ConfigureResult::Failed;
-            }
-        }
+    regex_t reg;
+    if (regcomp(&reg, REG_TIZENID_PATTERN, REG_NOSUB | REG_EXTENDED) != 0) {
+        LogDebug("Regcomp failed");
+    }
 
-        m_installerContext.widgetConfig.pkgname = pkgname;
-        OptionalWidgetVersion existingVersion;
-        existingVersion = update.existingWidgetInfo.existingVersion;
-        OptionalWidgetVersion incomingVersion = update.incomingVersion;
+    if (regexec(&reg, DPL::ToUTF8String(tizenAppId).c_str(), 0, NULL, 0)
+        == REG_NOMATCH)
+    {
+        regfree(&reg);
+        return false;
+    }
+    regfree(&reg);
+    return true;
+}
+
+bool JobWidgetInstall::validateTizenPackageID(
+    const WrtDB::TizenPkgId &tizenPkgId)
+{
+    std::string pkgId = DPL::ToUTF8String(tizenPkgId);
+
+    std::string installPath =
+        std::string(GlobalConfig::GetUserInstalledWidgetPath()) +
+        "/" + pkgId;
+    std::string preinstallPath =
+        std::string(GlobalConfig::GetUserPreloadedWidgetPath()) +
+        "/" + pkgId;
+
+    struct stat dirStat;
+    if ((stat(installPath.c_str(), &dirStat) == 0) ||
+        (stat(preinstallPath.c_str(), &dirStat) == 0))
+    {
+        return false;
+    }
+    return true;
+}
 
-        updateTypeCheckBit = CalcWidgetUpdatePolicy(existingVersion,
-                                                    incomingVersion);
+ConfigureResult JobWidgetInstall::checkWidgetUpdate(
+    const WidgetUpdateInfo &update)
+{
+    LogInfo("incoming version = '" << update.incomingVersion);
+    LogInfo("Tizen AppID = " << update.tzAppId);
+
+    if (update.existingVersion.IsNull() || update.incomingVersion.IsNull()) {
+        return ConfigureResult::Failed;
     }
 
-    // Calc proceed flag
-    bool canProceed = (m_jobStruct.updateMode & updateTypeCheckBit) > 0;
+    // Check running state
+    bool isRunning = false;
+    int ret =
+        app_manager_is_running(DPL::ToUTF8String(update.tzAppId).c_str(),
+                               &isRunning);
+    if (APP_MANAGER_ERROR_NONE != ret) {
+        LogError("Fail to get running state");
+        return ConfigureResult::Failed_WidgetRunning;
+    }
 
-    LogInfo("Whether widget policy allow proceed: " << canProceed);
+    if (true == isRunning) {
+        // get app_context for running application
+        // app_context must be released with app_context_destroy
+        app_context_h appCtx = NULL;
+        ret =
+            app_manager_get_app_context(
+                DPL::ToUTF8String(update.tzAppId).c_str(),
+                &appCtx);
+        if (APP_MANAGER_ERROR_NONE != ret) {
+            LogError("Fail to get app_context");
+            return ConfigureResult::Failed_WidgetRunning;
+        }
 
-    // Init installer context
-    m_installerContext.widgetSource = widgetSource;
-    m_installerContext.tempWidgetPath = std::string();
-
-    // setup config xml path
-    if (fromBrowser) {
-        LogInfo("widgetSource " << widgetSource);
-        size_t slash = widgetSource.find_last_of("\\/");
-        if (std::string::npos != slash) {
-            m_installerContext.tempWidgetPath = widgetSource.substr(0, slash+1);
+        // terminate app_context_h
+        ret = app_manager_terminate_app(appCtx);
+        if (APP_MANAGER_ERROR_NONE != ret) {
+            LogError("Fail to terminate running application");
+            app_context_destroy(appCtx);
+            return ConfigureResult::Failed_WidgetRunning;
         } else {
-            m_installerContext.tempWidgetPath = ".";
+            app_context_destroy(appCtx);
+            // app_manager_terminate_app isn't sync API
+            // wait until application isn't running (50ms * 100)
+            bool isStillRunning = true;
+            int checkingloop = 100;
+            struct timespec duration = { 0, 50 * 1000 * 1000 };
+            while (--checkingloop >= 0) {
+                nanosleep(&duration, NULL);
+                int ret =
+                    app_manager_is_running(
+                        DPL::ToUTF8String(update.tzAppId).c_str(),
+                        &isStillRunning);
+                if (APP_MANAGER_ERROR_NONE != ret) {
+                    LogError("Fail to get running state");
+                    return ConfigureResult::Failed_WidgetRunning;
+                }
+                if (!isStillRunning) {
+                    break;
+                }
+            }
+            if (isStillRunning) {
+                LogError("Fail to terminate running application");
+                return ConfigureResult::Failed_WidgetRunning;
+            }
+            LogInfo("terminate application");
         }
     }
 
-    m_installerContext.installStep = InstallerContext::INSTALL_START;
-    m_installerContext.job = this;
-    m_installerContext.existingWidgetInfo = update.existingWidgetInfo;
-    m_installerContext.widgetConfig.shareHref = std::string();
+    m_installerContext.widgetConfig.tzAppid = update.tzAppId;
 
-    if (m_installerContext.existingWidgetInfo.isExist) {
-        return canProceed ? ConfigureResult::Updated : ConfigureResult::Failed;
+    if (isUpperVersion(update.existingVersion, update.incomingVersion) ||
+        (m_jobStruct.m_installMode == InstallMode::INSTALL_MODE_DIRECTORY) ||
+        (m_jobStruct.m_installMode == InstallMode::REINSTALL_MODE_DIRECTORY))
+    {
+        LogInfo("Whether widget policy allow proceed ok");
+        return ConfigureResult::Updated;
+    } else {
+        return ConfigureResult::Failed_LowerVersion;
     }
 
-    // Return result
-    return canProceed ? ConfigureResult::Ok : ConfigureResult::Failed;
+    return ConfigureResult::Failed;
 }
 
-WidgetUpdateMode::Type JobWidgetInstall::CalcWidgetUpdatePolicy(
-        const OptionalWidgetVersion &existingVersion,
-        const OptionalWidgetVersion &incomingVersion) const
+bool JobWidgetInstall::isUpperVersion(
+    const OptionalWidgetVersion &existingVersion,
+    const OptionalWidgetVersion &incomingVersion)
 {
-    // Widget is installed, check versions
+    LogInfo("Existing version = '" << *existingVersion);
+    LogInfo("Incoming version = '" << *incomingVersion);
+
     if (!existingVersion && !incomingVersion) {
-        return WidgetUpdateMode::ExistingVersionEqual;
+        return false;
     } else if (!existingVersion && !!incomingVersion) {
-        return WidgetUpdateMode::ExistingVersionNewer;
+        return false;
     } else if (!!existingVersion && !incomingVersion) {
-        return WidgetUpdateMode::ExistingVersionOlder;
+        return true;
     } else {
-        LogInfo("Existing widget: version = '" << *existingVersion << "'");
-
-        if (!existingVersion->IsWac() && !incomingVersion->IsWac()) {
-            return WidgetUpdateMode::BothVersionsNotStd;
-        } else if (!existingVersion->IsWac()) {
-            return WidgetUpdateMode::ExistingVersionNotStd;
-        } else if (!incomingVersion->IsWac()) {
-            return WidgetUpdateMode::IncomingVersionNotStd;
+        if (!existingVersion->IsWac() || !incomingVersion->IsWac()) {
+            return false;
         } else {
-            // Both versions are WAC-comparable. Do compare.
             if (*incomingVersion == *existingVersion) {
-                return WidgetUpdateMode::ExistingVersionEqual;
+                return false;
             } else if (*incomingVersion > *existingVersion) {
-                return WidgetUpdateMode::ExistingVersionOlder;
+                return true;
             } else {
-                return WidgetUpdateMode::ExistingVersionNewer;
+                return false;
             }
         }
     }
 }
 
 ConfigParserData JobWidgetInstall::getWidgetDataFromXML(
-        const std::string &widgetSource,
-        bool fromBrowser, WrtDB::PkgType isOspsvc)
+    const std::string &widgetSource,
+    const std::string &tempPath,
+    WrtDB::PackagingType pkgType,
+    bool isDRM,
+    bool isReinstall)
 {
+    // Parse config
+    ParserRunner parser;
+    ConfigParserData configInfo;
+
     Try
     {
-        // Parse config
-        ParserRunner parser;
-        ConfigParserData configInfo;
-
-        if (fromBrowser) {
+        if (pkgType == PKG_TYPE_HOSTED_WEB_APP) {
             parser.Parse(widgetSource,
                          ElementParserPtr(
                              new RootParser<WidgetParser>(configInfo,
                                                           DPL::FromUTF32String(
                                                               L"widget"))));
-        }
-        else {
-            // Open zip file
-            DPL::ScopedPtr<DPL::ZipInput> zipFile(
-                new DPL::ZipInput(widgetSource));
+        } else if (pkgType == PKG_TYPE_DIRECTORY_WEB_APP) {
+            std::string configPath;
+            configPath = tempPath;
+            configPath += "/";
+            configPath += WITH_OSP_XML;
+
+            if (isReinstall) {
+                // checking RDS data directory
+                if (access(configPath.c_str(), F_OK) != 0) {
+                    std::string tzAppId =
+                        widgetSource.substr(widgetSource.find_last_of("/")+1);
+                    WidgetDAOReadOnly dao(WidgetDAOReadOnly::getTzAppId(DPL::FromUTF8String(tzAppId)));
+                    configPath = DPL::ToUTF8String(*dao.getWidgetInstalledPath());
+                    configPath += "/";
+                    configPath += WITH_OSP_XML;
+                }
+            }
+            parser.Parse(configPath,
+                         ElementParserPtr(
+                             new RootParser<WidgetParser>(
+                                 configInfo,
+                                 DPL::FromUTF32String(L"widget"))));
+        } else {
+            if (!isDRM) {
+                std::unique_ptr<DPL::ZipInput> zipFile(
+                    new DPL::ZipInput(widgetSource));
 
-            DPL::ScopedPtr<DPL::ZipInput::File> configFile;
+                std::unique_ptr<DPL::ZipInput::File> configFile;
 
-            // Open config.xml file
-            if (isOspsvc == PKG_TYPE_TIZEN_WITHSVCAPP) {
-                configFile.Reset(zipFile->OpenFile(WITH_OSP_XML));
+                // Open config.xml file
+                if (pkgType == PKG_TYPE_HYBRID_WEB_APP) {
+                    configFile.reset(zipFile->OpenFile(WITH_OSP_XML));
+                } else {
+                    configFile.reset(zipFile->OpenFile(CONFIG_XML));
+                }
+
+                // Extract config
+                DPL::BinaryQueue buffer;
+                DPL::AbstractWaitableInputAdapter inputAdapter(configFile.get());
+                DPL::AbstractWaitableOutputAdapter outputAdapter(&buffer);
+                DPL::Copy(&inputAdapter, &outputAdapter);
+                parser.Parse(&buffer,
+                             ElementParserPtr(
+                                 new RootParser<WidgetParser>(configInfo,
+                                                              DPL::
+                                                                  FromUTF32String(
+                                                                  L"widget"))));
             } else {
-                configFile.Reset(zipFile->OpenFile(CONFIG_XML));
-            }
+                // DRM widget
+                std::string configFile;
+                if (pkgType == PKG_TYPE_HYBRID_WEB_APP) {
+                    configFile = tempPath + "/" + WITH_OSP_XML;
+                } else {
+                    configFile = tempPath + "/" + CONFIG_XML;
+                }
 
-            // Extract config
-            DPL::BinaryQueue buffer;
-            DPL::AbstractWaitableInputAdapter inputAdapter(configFile.Get());
-            DPL::AbstractWaitableOutputAdapter outputAdapter(&buffer);
-            DPL::Copy(&inputAdapter, &outputAdapter);
-            parser.Parse(&buffer,
-                         ElementParserPtr(
-                             new RootParser<WidgetParser>(configInfo,
-                                                          DPL::FromUTF32String(
-                                                              L"widget"))));
+                parser.Parse(configFile,
+                             ElementParserPtr(
+                                 new RootParser<WidgetParser>(configInfo,
+                                                              DPL::
+                                                                  FromUTF32String(
+                                                                  L"widget"))));
+            }
         }
-
-        return configInfo;
     }
     Catch(DPL::ZipInput::Exception::OpenFailed)
     {
-        LogDebug("Failed to open widget package");
+        LogError("Failed to open widget package");
         return ConfigParserData();
     }
     Catch(DPL::ZipInput::Exception::OpenFileFailed)
     {
-        LogDebug("Failed to open config.xml file");
+        LogError("Failed to open config.xml file");
         return ConfigParserData();
     }
     Catch(DPL::CopyFailed)
     {
-        LogDebug("Failed to extract config.xml file");
+        LogError("Failed to extract config.xml file");
+        return ConfigParserData();
+    }
+    Catch(DPL::FileInput::Exception::OpenFailed)
+    {
+        LogError("Failed to open config.xml file");
         return ConfigParserData();
     }
     Catch(ElementParser::Exception::ParseError)
     {
-        LogDebug("Failed to parse config.xml file");
+        LogError("Failed to parse config.xml file");
         return ConfigParserData();
     }
+    Catch(DPL::ZipInput::Exception::SeekFileFailed)
+    {
+        LogError("Failed to seek widget archive - corrupted package?");
+        return ConfigParserData();
+    }
+    return configInfo;
 }
 
 WidgetUpdateInfo JobWidgetInstall::detectWidgetUpdate(
-        const ConfigParserData &configInfo)
+    const ConfigParserData &configInfo,
+    const WrtDB::TizenAppId &tizenId)
 {
     LogInfo("Checking up widget package for config.xml...");
+    OptionalWidgetVersion incomingVersion;
 
-    DPL::OptionalString widgetGUID;
-    OptionalWidgetVersion widgetVersion;
-
-    // Check widget id
-    widgetGUID = configInfo.widget_id;
-
-    if (widgetGUID.IsNull()) {
-        LogDebug("Installed widget has no GUID");
-        return WidgetUpdateInfo();
-    }
-
-    LogDebug("Installed widget GUID: " << *widgetGUID);
-
-    // Locate widget ID with this GUID
-    // Incoming widget version
     if (!configInfo.version.IsNull()) {
-        widgetVersion =
+        incomingVersion =
             DPL::Optional<WidgetVersion>(
                 WidgetVersion(*configInfo.version));
     }
 
-    Try
-    {
-        // Search widget handle by GUID
-        WidgetDAOReadOnly dao(widgetGUID);
-        return WidgetUpdateInfo(
-            widgetGUID,
-            widgetVersion,
-            WidgetUpdateInfo::ExistingWidgetInfo(
-                dao.getHandle(), dao.getVersion()));
-    }
-    Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
-    {
-        // GUID isn't installed
-        return WidgetUpdateInfo(
-            widgetGUID,
-            widgetVersion,
-            WidgetUpdateInfo::ExistingWidgetInfo());
+    WidgetDAOReadOnly dao(tizenId);
+
+    OptionalWidgetVersion optVersion;
+    DPL::OptionalString version = dao.getVersion();
+    if (!version.IsNull()) {
+        optVersion = OptionalWidgetVersion(WidgetVersion(*version));
     }
+
+    return WidgetUpdateInfo(
+        dao.getTzAppId(),
+        optVersion,
+        incomingVersion);
 }
 
 void JobWidgetInstall::SendProgress()
@@ -572,13 +832,28 @@ void JobWidgetInstall::SendProgress()
             // send progress signal of pkgmgr
             std::ostringstream percent;
             percent << static_cast<int>(GetProgressPercent());
-            PkgmgrSignalSingleton::Instance().sendSignal(
-                        PKGMGR_PROGRESS_KEY,
-                        percent.str());
+            getInstallerStruct().pkgmgrInterface->sendSignal(
+                PKGMGR_PROGRESS_KEY,
+                percent.str());
 
             LogDebug("Call widget install progressCallbak");
-            getInstallerStruct().progressCallback(getInstallerStruct().userParam,
-                    GetProgressPercent(),GetProgressDescription());
+            getInstallerStruct().progressCallback(
+                getInstallerStruct().userParam,
+                GetProgressPercent(),
+                GetProgressDescription());
+        }
+    }
+}
+
+void JobWidgetInstall::SendProgressIconPath(const std::string &path)
+{
+    using namespace PackageManager;
+    if (GetProgressFlag() != false) {
+        if (getInstallerStruct().progressCallback != NULL) {
+            // send progress signal of pkgmgr
+            getInstallerStruct().pkgmgrInterface->sendSignal(
+                PKGMGR_ICON_PATH,
+                path);
         }
     }
 }
@@ -589,22 +864,32 @@ void JobWidgetInstall::SendFinishedSuccess()
     // TODO : sync should move to separate task.
     sync();
 
+    if (INSTALL_LOCATION_TYPE_EXTERNAL == m_installerContext.locationType) {
+        if (m_installerContext.isUpdateMode) {
+            WidgetInstallToExtSingleton::Instance().postUpgrade(true);
+        } else {
+            WidgetInstallToExtSingleton::Instance().postInstallation(true);
+        }
+        WidgetInstallToExtSingleton::Instance().deinitialize();
+    }
+
     // remove widget install information file
     unlink(m_installerContext.installInfo.c_str());
 
     //inform widget info
     JobWidgetInstall::displayWidgetInfo();
 
-    DPL::Optional<WidgetHandle> handle = getNewWidgetHandle();
+    TizenAppId& tizenId = m_installerContext.widgetConfig.tzAppid;
 
     // send signal of pkgmgr
-    PkgmgrSignalSingleton::Instance().sendSignal(
-                PKGMGR_END_KEY,
-                PKGMGR_END_SUCCESS);
+    getInstallerStruct().pkgmgrInterface->sendSignal(
+        PKGMGR_END_KEY,
+        PKGMGR_END_SUCCESS);
 
     LogDebug("Call widget install successfinishedCallback");
     getInstallerStruct().finishedCallback(getInstallerStruct().userParam,
-            !!handle ? *handle : WrtDB::INVALID_WIDGET_HANDLE, Exceptions::Success);
+                                          DPL::ToUTF8String(
+                                              tizenId), Jobs::Exceptions::Success);
 }
 
 void JobWidgetInstall::SendFinishedFailure()
@@ -613,63 +898,66 @@ void JobWidgetInstall::SendFinishedFailure()
     // remove widget install information file
     unlink(m_installerContext.installInfo.c_str());
 
-    LogError("Error in installation step: " << m_exceptionCaught);
+    LogError("Error number: " << m_exceptionCaught);
     LogError("Message: " << m_exceptionMessage);
-    DPL::Optional<WidgetHandle> handle = getNewWidgetHandle();
+    TizenAppId & tizenId = m_installerContext.widgetConfig.tzAppid;
 
     LogDebug("Call widget install failure finishedCallback");
+    std::stringstream errorNum;
+    errorNum << m_exceptionCaught;
 
     // send signal of pkgmgr
-    PkgmgrSignalSingleton::Instance().sendSignal(
-                PKGMGR_END_KEY,
-                PKGMGR_END_FAILURE);
+    getInstallerStruct().pkgmgrInterface->sendSignal(
+        PKGMGR_ERROR,
+        errorNum.str());
+
+    getInstallerStruct().pkgmgrInterface->sendSignal(
+        PKGMGR_END_KEY,
+        PKGMGR_END_FAILURE);
 
     getInstallerStruct().finishedCallback(getInstallerStruct().userParam,
-            !!handle ? *handle : WrtDB::INVALID_WIDGET_HANDLE, m_exceptionCaught);
+                                          DPL::ToUTF8String(
+                                              tizenId), m_exceptionCaught);
 }
 
 void JobWidgetInstall::SaveExceptionData(const Jobs::JobExceptionBase &e)
 {
-    m_exceptionCaught = static_cast<Exceptions::Type>(e.getParam());
+    m_exceptionCaught = static_cast<Jobs::Exceptions::Type>(e.getParam());
     m_exceptionMessage = e.GetMessage();
 }
 
 void JobWidgetInstall::displayWidgetInfo()
 {
-    DPL::Optional<WidgetHandle> handle = getNewWidgetHandle();
-    Assert(!!handle);
-
-    WidgetDAOReadOnly dao(*handle);
+    WidgetDAOReadOnly dao(m_installerContext.widgetConfig.tzAppid);
 
     std::ostringstream out;
     WidgetLocalizedInfo localizedInfo =
-        W3CFileLocalization::getLocalizedInfo(*handle);
+        W3CFileLocalization::getLocalizedInfo(dao.getTzAppId());
 
     out << std::endl <<
-        "===================================== INSTALLED WIDGET INFO ========="\
-        "============================";
+    "===================================== INSTALLED WIDGET INFO =========" \
+    "============================";
     out << std::endl << "Name:                        " << localizedInfo.name;
-    out << std::endl << "PkgName:                     " << dao.getPkgname();
+    out << std::endl << "AppId:                     " << dao.getTzAppId();
     WidgetSize size = dao.getPreferredSize();
     out << std::endl << "Width:                       " << size.width;
     out << std::endl << "Height:                      " << size.height;
     out << std::endl << "Start File:                  " <<
-        W3CFileLocalization::getStartFile(*handle);
+    W3CFileLocalization::getStartFile(dao.getTzAppId());
     out << std::endl << "Version:                     " << dao.getVersion();
     out << std::endl << "Licence:                     " <<
-        localizedInfo.license;
+    localizedInfo.license;
     out << std::endl << "Licence Href:                " <<
-        localizedInfo.licenseHref;
+    localizedInfo.licenseHref;
     out << std::endl << "Description:                 " <<
-        localizedInfo.description;
+    localizedInfo.description;
     out << std::endl << "Widget Id:                   " << dao.getGUID();
     out << std::endl << "Widget recognized:           " << dao.isRecognized();
-    out << std::endl << "Widget wac signed:           " << dao.isWacSigned();
     out << std::endl << "Widget distributor signed:   " <<
-        dao.isDistributorSigned();
+    dao.isDistributorSigned();
     out << std::endl << "Widget trusted:              " << dao.isTrusted();
 
-    OptionalWidgetIcon icon = W3CFileLocalization::getIcon(*handle);
+    OptionalWidgetIcon icon = W3CFileLocalization::getIcon(dao.getTzAppId());
     DPL::OptionalString iconSrc =
         !!icon ? icon->src : DPL::OptionalString::Null;
     out << std::endl << "Icon:                        " << iconSrc;
@@ -680,9 +968,9 @@ void JobWidgetInstall::displayWidgetInfo()
         FOREACH(it, list)
         {
             out << std::endl << "  Key:                       " <<
-                it->key_name;
+            it->key_name;
             out << std::endl << "      Readonly:              " <<
-                it->readonly;
+            it->readonly;
         }
     }
 
@@ -692,8 +980,6 @@ void JobWidgetInstall::displayWidgetInfo()
         FOREACH(it, list)
         {
             out << std::endl << "  Name:                      " << it->name;
-            out << std::endl << "      Required:              " << it->required;
-            out << std::endl << "      Params:";
         }
     }
 
@@ -703,56 +989,177 @@ void JobWidgetInstall::displayWidgetInfo()
 }
 
 WrtDB::PackagingType JobWidgetInstall::checkPackageType(
-        const std::string &widgetSource)
+    const std::string &widgetSource,
+    const std::string &tempPath)
 {
-    using namespace WrtDB;
-
-    PackagingType pType = PKG_TYPE_UNKNOWN;
-    DPL::ScopedPtr<DPL::ZipInput> zipFile;
-
-    Try
+    // Check installation type (direcotory/ or config.xml or widget.wgt)
+    if (m_jobStruct.m_installMode == InstallMode::INSTALL_MODE_DIRECTORY ||
+         m_jobStruct.m_installMode == InstallMode::REINSTALL_MODE_DIRECTORY)
     {
-        // Open zip file
-        zipFile.Reset(new DPL::ZipInput(widgetSource));
-
+        LogDebug("Install directly from directory");
+        return PKG_TYPE_DIRECTORY_WEB_APP;
     }
-    Catch(DPL::ZipInput::Exception::OpenFailed)
-    {
-        LogDebug("Failed to open widget package");
-        return PKG_TYPE_UNKNOWN;
+    if (hasExtension(widgetSource, XML_EXTENSION)) {
+        LogInfo("Hosted app installation");
+        return PKG_TYPE_HOSTED_WEB_APP;
     }
 
-    Try
-    {
-        // Open config.xml file in package root
-        DPL::ScopedPtr<DPL::ZipInput::File> configFile(
+    if (m_isDRM) {
+        std::string configFile = tempPath + "/" + CONFIG_XML;
+        if (WrtUtilFileExists(configFile)) {
+            return PKG_TYPE_NOMAL_WEB_APP;
+        }
+
+        configFile = tempPath + "/" + WITH_OSP_XML;
+        if (WrtUtilFileExists(configFile)) {
+            return PKG_TYPE_HYBRID_WEB_APP;
+        }
+    } else {
+        std::unique_ptr<DPL::ZipInput> zipFile;
+
+        Try
+        {
+            // Open zip file
+            zipFile.reset(new DPL::ZipInput(widgetSource));
+        }
+        Catch(DPL::ZipInput::Exception::OpenFailed)
+        {
+            LogDebug("Failed to open widget package");
+            return PKG_TYPE_UNKNOWN;
+        }
+        Catch(DPL::ZipInput::Exception::SeekFileFailed)
+        {
+            LogError("Failed to seek widget package file");
+            return PKG_TYPE_UNKNOWN;
+        }
+
+        Try
+        {
+            // Open config.xml file in package root
+            std::unique_ptr<DPL::ZipInput::File> configFile(
                 zipFile->OpenFile(CONFIG_XML));
-        pType = PKG_TYPE_TIZEN_WEBAPP;
-    }
-    Catch(DPL::ZipInput::Exception::OpenFileFailed)
-    {
-        LogDebug("Could not find config.xml");
-    }
+            return PKG_TYPE_NOMAL_WEB_APP;
+        }
+        Catch(DPL::ZipInput::Exception::OpenFileFailed)
+        {
+            LogDebug("Could not find config.xml");
+        }
 
-    Try
-    {
-        // Open config.xml file in package root
-        DPL::ScopedPtr<DPL::ZipInput::File> configFile(
+        Try
+        {
+            // Open config.xml file in package root
+            std::unique_ptr<DPL::ZipInput::File> configFile(
                 zipFile->OpenFile(WITH_OSP_XML));
-        if (pType == PKG_TYPE_TIZEN_WEBAPP) {
+
+            return PKG_TYPE_HYBRID_WEB_APP;
+        }
+        Catch(DPL::ZipInput::Exception::OpenFileFailed)
+        {
+            LogDebug("Could not find wgt/config.xml");
             return PKG_TYPE_UNKNOWN;
         }
+    }
 
-        pType = PKG_TYPE_TIZEN_WITHSVCAPP;
+    return PKG_TYPE_UNKNOWN;
+}
+
+void JobWidgetInstall::setApplicationType(
+    const WrtDB::ConfigParserData &configInfo)
+{
+    FOREACH(iterator, configInfo.nameSpaces) {
+        LogInfo("namespace = [" << *iterator << "]");
+        AppType currentAppType = APP_TYPE_UNKNOWN;
+
+        if (*iterator == ConfigurationNamespace::W3CWidgetNamespaceName) {
+            continue;
+        } else if (
+            *iterator ==
+            ConfigurationNamespace::WacWidgetNamespaceNameForLinkElement ||
+            *iterator ==
+            ConfigurationNamespace::WacWidgetNamespaceName)
+        {
+            currentAppType = APP_TYPE_WAC20;
+        } else if (*iterator ==
+                   ConfigurationNamespace::TizenWebAppNamespaceName)
+        {
+            currentAppType = APP_TYPE_TIZENWEBAPP;
+        }
+
+        if (m_installerContext.widgetConfig.webAppType ==
+            APP_TYPE_UNKNOWN)
+        {
+            m_installerContext.widgetConfig.webAppType = currentAppType;
+        } else if (m_installerContext.widgetConfig.webAppType ==
+                   currentAppType)
+        {
+            continue;
+        } else {
+            ThrowMsg(Exceptions::WidgetConfigFileInvalid,
+                     "Config.xml has more than one namespace");
+        }
     }
-    Catch(DPL::ZipInput::Exception::OpenFileFailed)
+
+    // If there is no define, type set to WAC 2.0
+    if (m_installerContext.widgetConfig.webAppType == APP_TYPE_UNKNOWN) {
+        m_installerContext.widgetConfig.webAppType = APP_TYPE_WAC20;
+    }
+
+    LogInfo("type = [" <<
+            m_installerContext.widgetConfig.webAppType.getApptypeToString() <<
+            "]");
+}
+
+bool JobWidgetInstall::detectResourceEncryption(
+    const WrtDB::ConfigParserData &configData)
+{
+    FOREACH(it, configData.settingsList)
     {
-        LogDebug("Could not find wgt/config.xml");
-        return PKG_TYPE_UNKNOWN;
+        if (it->m_name == SETTING_VALUE_ENCRYPTION &&
+            it->m_value == SETTING_VALUE_ENCRYPTION_ENABLE)
+        {
+            LogDebug("resource need encryption");
+            return true;
+        }
     }
+    return false;
+}
 
-    return pType;
+void JobWidgetInstall::setInstallLocationType(
+    const
+    WrtDB::ConfigParserData &
+    configData)
+{
+    m_installerContext.locationType = INSTALL_LOCATION_TYPE_NOMAL;
+
+    if (m_jobStruct.m_installMode == InstallMode::INSTALL_MODE_PRELOAD) {
+        m_installerContext.locationType =
+            INSTALL_LOCATION_TYPE_PRELOAD;
+    } else {
+        FOREACH(it, configData.settingsList)
+        {
+            if (it->m_name == SETTING_VALUE_INSTALLTOEXT_NAME &&
+                it->m_value ==
+                SETTING_VALUE_INSTALLTOEXT_PREPER_EXT)
+            {
+                LogDebug("This widget will be installed to sd card");
+                m_installerContext.locationType =
+                    INSTALL_LOCATION_TYPE_EXTERNAL;
+            }
+        }
+    }
 }
 
+bool JobWidgetInstall::isDRMWidget(std::string /*widgetPath*/)
+{
+    /* TODO */
+    return false;
+}
+
+bool JobWidgetInstall::DecryptDRMWidget(std::string /*widgetPath*/,
+                                        std::string /*destPath*/)
+{
+    /* TODO */
+    return false;
+}
 } //namespace WidgetInstall
 } //namespace Jobs