[Release] wrt-installer_0.1.114
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_encrypt_resource.cpp
index 98faa16..7e3b18a 100644 (file)
@@ -29,6 +29,8 @@
 #include <string.h>
 #include <errno.h>
 #include <cstdio>
+#include <sstream>
+#include<iostream>
 
 #include <memory>
 
 #include <dpl/scoped_fclose.h>
 #include <dpl/wrt-dao-ro/global_config.h>
 #include <dpl/string.h>
+#include <ss_manager.h>
 
 #include <widget_install/job_widget_install.h>
 #include <widget_install/widget_install_context.h>
 #include <widget_install/widget_install_errors.h>
 
 using namespace WrtDB;
-using namespace WRTEncryptor;
 
 namespace {
-const std::size_t ENCRYPTION_CHUNK_MAX_SIZE = 1008; // bytes
+const std::size_t ENCRYPTION_CHUNK_MAX_SIZE = 8192; // bytes
+const std::size_t ENCRYPTION_DEC_CHUNK_SIZE = 4; // bytes
 
 std::set<std::string>& getSupportedForEncryption()
 {
@@ -89,7 +92,7 @@ FILE* openFile(const std::string& path, const std::string& mode)
 
     if (NULL == result)
     {
-        ThrowMsg(Jobs::WidgetInstall::Exceptions::InternalError,
+        ThrowMsg(Jobs::WidgetInstall::Exceptions::EncryptionFailed,
                  "Could not open file " << path);
     }
 
@@ -119,7 +122,7 @@ std::size_t readBytes(unsigned char* buffer, std::size_t count, FILE* stream)
         {
             if (EINTR != error)
             {
-                ThrowMsg(Jobs::WidgetInstall::Exceptions::InternalError,
+                ThrowMsg(Jobs::WidgetInstall::Exceptions::ErrorExternalInstallingFailure,
                          "Error while reading data" <<
                          " [" << DPL::GetErrnoString(error) << "]");
             }
@@ -151,33 +154,43 @@ void writeBytes(unsigned char* buffer, std::size_t count, FILE* stream)
         if ((bytesWritten != bytesToWrite) && (EINTR != errno))
         {
             int error = errno;
-            ThrowMsg(Jobs::WidgetInstall::Exceptions::InternalError,
+            ThrowMsg(Jobs::WidgetInstall::Exceptions::EncryptionFailed,
                      "Error while writing data" <<
                      " [" << DPL::GetErrnoString(error) << "]");
         }
     } while ((bytesWritten != bytesToWrite) && (EINTR == errno));
 }
+
+int ssmEncrypt(InstallMode::RootPath rootPath, std::string pkgId, const char*
+        inChunk, int inBytes, char** outChunk, int *outBytes)
+{
+    if (rootPath == InstallMode::RootPath::RO) {
+        return ssm_encrypt_preloaded_application(inChunk, inBytes,
+                outChunk, outBytes);
+    } else {
+        return ssm_encrypt(pkgId.c_str(), pkgId.length(),
+                inChunk, inBytes,
+                outChunk, outBytes);
+    }
+}
 }
 
 namespace Jobs {
 namespace WidgetInstall {
 TaskEncryptResource::TaskEncryptResource(InstallerContext& context) :
     DPL::TaskDecl<TaskEncryptResource>(this),
-    m_context(context),
-    m_resEnc(NULL)
+    m_context(context)
 {
+    AddStep(&TaskEncryptResource::StartStep);
     AddStep(&TaskEncryptResource::StepEncryptResource);
+    AddStep(&TaskEncryptResource::EndStep);
 }
 
 void TaskEncryptResource::StepEncryptResource()
 {
     LogDebug("Step Encrypt resource");
-    m_resEnc = new ResourceEncryptor;
 
     EncryptDirectory(m_context.locations->getTemporaryRootDir());
-    m_context.job->UpdateProgress(
-            InstallerContext::INSTALL_ECRYPTION_FILES,
-            "Ecrypt resource files");
 }
 
 void TaskEncryptResource::EncryptDirectory(std::string path)
@@ -191,7 +204,7 @@ void TaskEncryptResource::EncryptDirectory(std::string path)
         int error = errno;
         LogWarning(__PRETTY_FUNCTION__ << ": fts_open failed with error: "
                                        << strerror(error));
-        ThrowMsg(Exceptions::InternalError, "Error reading directory: "
+        ThrowMsg(Exceptions::EncryptionFailed, "Error reading directory: "
                  << path);
     }
 
@@ -222,7 +235,7 @@ void TaskEncryptResource::EncryptDirectory(std::string path)
                        << ftsent->fts_path
                        << " with error: "
                        << strerror(ftsent->fts_errno));
-            ThrowMsg(Exceptions::InternalError, "Error reading file");
+            ThrowMsg(Exceptions::EncryptionFailed, "Error reading file");
             break;
         }
     }
@@ -236,86 +249,106 @@ void TaskEncryptResource::EncryptDirectory(std::string path)
 
 void TaskEncryptResource::EncryptFile(const std::string &fileName)
 {
-    try
+    LogDebug("Encrypt file: " << fileName);
+    std::string encFile = fileName + ".enc";
+
+    struct stat info;
+    memset(&info, 0, sizeof(info));
+    if (stat(fileName.c_str(), &info) != 0)
     {
-        LogDebug("Encrypt file: " << fileName);
-        std::string encFile = fileName + ".enc";
+        int error = errno;
+        ThrowMsg(Exceptions::EncryptionFailed,
+                "Could not access file " << fileName <<
+                "[" << DPL::GetErrnoString(error) << "]");
+    }
+    const std::size_t fileSize = info.st_size;
+    if (0 == fileSize) {
+        LogDebug(fileName << " size is 0, so encryption is skiped");
+        return;
+    }
 
-        struct stat info;
-        memset(&info, 0, sizeof(info));
-        if (stat(fileName.c_str(), &info) != 0)
-        {
-            int error = errno;
-            ThrowMsg(Exceptions::InternalError,
-                     "Could not access file " << fileName <<
-                     "[" << DPL::GetErrnoString(error) << "]");
-        }
-        const std::size_t fileSize = info.st_size;
+    // If update installed preload web, should skip encryption.
+    if (!(m_context.mode.rootPath == InstallMode::RootPath::RO &&
+                m_context.mode.installTime == InstallMode::InstallTime::PRELOAD
+                && m_context.mode.extension == InstallMode::ExtensionType::DIR)) {
 
         DPL::ScopedFClose inFile(openFile(fileName, "r"));
         DPL::ScopedFClose outFile(openFile(encFile, "w"));
 
         const std::size_t chunkSize = (fileSize > ENCRYPTION_CHUNK_MAX_SIZE
                 ? ENCRYPTION_CHUNK_MAX_SIZE : fileSize);
-        const int maxBlockSize = m_resEnc->GetBlockSize(chunkSize);
 
         std::unique_ptr<unsigned char[]> inChunk(new unsigned char[chunkSize]);
-        std::unique_ptr<unsigned char[]> outChunk;
-
         std::size_t bytesRead = 0;
-        int curBlockSize = 0;
+        /* TODO : pkgId should change to appId after wrt-client label changed. */
+        std::string pkgId = DPL::ToUTF8String(m_context.widgetConfig.tzPkgid);
+
         do
         {
             bytesRead = readBytes(inChunk.get(), chunkSize, inFile.Get());
             if (0 != bytesRead) {
-                int decBufSize = m_resEnc->EncryptChunkByTrustZone(DPL::ToUTF8String(
-                            m_context.widgetConfig.tzAppid),
-                        inChunk.get(), bytesRead);
-                outChunk.reset(new unsigned char[decBufSize]);
-                m_resEnc->getEncStringByTrustZone(outChunk.get());
-
-                writeBytes(outChunk.get(), decBufSize, outFile.Get());
+                int outDecSize = 0;
+                char *outChunk = NULL;
+                if (0 != ssmEncrypt(m_context.mode.rootPath, pkgId,
+                            (char*)inChunk.get(), (int)bytesRead,
+                            &outChunk, &outDecSize)) {
+                    ThrowMsg(Exceptions::EncryptionFailed,
+                            "Encryption Failed using TrustZone");
+                }
+
+                std::stringstream toString;
+                toString << outDecSize;
+
+                writeBytes((unsigned char*)toString.str().c_str(),
+                        sizeof(int), outFile.Get());
+                writeBytes((unsigned char*)outChunk, outDecSize, outFile.Get());
+                delete outChunk;
             }
+            inChunk.reset(new unsigned char[chunkSize]);
 
         } while (0 == std::feof(inFile.Get()));
 
-        LogDebug("File encrypted successfully");
-
         outFile.Reset();
         inFile.Reset();
 
+        LogDebug("File encrypted successfully");
         LogDebug("Remove plain-text file: " << fileName);
         if (0 != unlink(fileName.c_str()))
         {
-            Throw(Exceptions::InternalError);
+            Throw(Exceptions::EncryptionFailed);
         }
 
         LogDebug("Rename encrypted file");
         if (0 != std::rename(encFile.c_str(), fileName.c_str()))
         {
-            Throw(Exceptions::InternalError);
+            Throw(Exceptions::EncryptionFailed);
         }
+    }
 
-        std::string realPath = fileName;
-        realPath.replace(0,
-                         m_context.locations->getTemporaryRootDir().length(),
-                         m_context.locations->getSourceDir());
+    std::string realPath = fileName;
+    realPath.replace(0,
+            m_context.locations->getTemporaryRootDir().length(),
+            m_context.locations->getSourceDir());
 
-        WrtDB::EncryptedFileInfo fileInfo;
-        fileInfo.fileName = DPL::FromUTF8String(realPath);
-        fileInfo.fileSize = fileSize;
+    WrtDB::EncryptedFileInfo fileInfo;
+    fileInfo.fileName = DPL::FromUTF8String(realPath);
+    fileInfo.fileSize = fileSize;
 
-        m_context.widgetConfig.encryptedFiles.insert(fileInfo);
-    }
-    Catch (Exceptions::InternalError)
-    {
-        ReThrowMsg(Exceptions::ExtractFileFailed, fileName);
-    }
-    Catch (ResourceEncryptor::Exception::Base)
-    {
-        ReThrowMsg(Exceptions::ExtractFileFailed, fileName);
-    }
+    m_context.widgetConfig.encryptedFiles.insert(fileInfo);
 }
 
+void TaskEncryptResource::StartStep()
+{
+    LogDebug("--------- <TaskEncryptResource> : START ----------");
+}
+
+void TaskEncryptResource::EndStep()
+{
+    m_context.job->UpdateProgress(
+            InstallerContext::INSTALL_ECRYPTION_FILES,
+            "Ecrypt resource files");
+
+    LogDebug("--------- <TaskEncryptResource> : END ----------");
+}
 } //namespace WidgetInstall
 } //namespace Jobs