[Release] wrt-installer_0.1.114
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_encrypt_resource.cpp
index bee8e00..7e3b18a 100644 (file)
 #undef __USE_FILE_OFFSET64
 
 #include <unistd.h>
-#include <string>
 #include <sys/stat.h>
 #include <fts.h>
 #include <string.h>
 #include <errno.h>
+#include <cstdio>
+#include <sstream>
+#include<iostream>
+
+#include <memory>
 
 #include <dpl/log/log.h>
 #include <dpl/errno_string.h>
 #include <dpl/foreach.h>
+#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 = 8192; // bytes
+const std::size_t ENCRYPTION_DEC_CHUNK_SIZE = 4; // bytes
+
 std::set<std::string>& getSupportedForEncryption()
 {
     static std::set<std::string> encryptSet;
@@ -63,6 +72,107 @@ bool isSupportedForEncryption(const std::string &file)
     }
     return false;
 }
+
+/**
+ * Opens a file.
+ *
+ * @param path Path to a file.
+ * @param mode Mode.
+ * @return Stream handle.
+ * @throw ExtractFileFailed If error (other than EINTR) occurs.
+ */
+FILE* openFile(const std::string& path, const std::string& mode)
+{
+    FILE* result = NULL;
+
+    do
+    {
+        result = fopen(path.c_str(), mode.c_str());
+    } while ((NULL == result) && (EINTR == errno));
+
+    if (NULL == result)
+    {
+        ThrowMsg(Jobs::WidgetInstall::Exceptions::EncryptionFailed,
+                 "Could not open file " << path);
+    }
+
+    return result;
+}
+
+/**
+ * Reads bytes from a stream.
+ *
+ * @param buffer Buffer to read the bytes into.
+ * @param count Number of bytes to read.
+ * @param stream Stream to read from.
+ * @return Number of bytes read
+ * @throw ExtractFileFailed If error (other than EINTR) occurs.
+ */
+std::size_t readBytes(unsigned char* buffer, std::size_t count, FILE* stream)
+{
+    std::size_t result = std::fread(buffer,
+                                    sizeof(unsigned char),
+                                    count,
+                                    stream);
+
+    if (result != count)
+    {
+        int error = errno;
+        if (0 != std::ferror(stream))
+        {
+            if (EINTR != error)
+            {
+                ThrowMsg(Jobs::WidgetInstall::Exceptions::ErrorExternalInstallingFailure,
+                         "Error while reading data" <<
+                         " [" << DPL::GetErrnoString(error) << "]");
+            }
+        }
+    }
+
+    return result;
+}
+
+/**
+ * Writes bytes to a stream.
+ *
+ * @param buffer Data to write.
+ * @param count Number of bytes.
+ * @param stream Stream to write to.
+ * @throw ExtractFileFailed If error (other than EINTR) occurs.
+ */
+void writeBytes(unsigned char* buffer, std::size_t count, FILE* stream)
+{
+    std::size_t bytesWritten = 0;
+    std::size_t bytesToWrite = 0;
+    do
+    {
+        bytesToWrite = count - bytesWritten;
+        bytesWritten = std::fwrite(buffer + bytesWritten,
+                                   sizeof(unsigned char),
+                                   count - bytesWritten,
+                                   stream);
+        if ((bytesWritten != bytesToWrite) && (EINTR != errno))
+        {
+            int error = errno;
+            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 {
@@ -71,15 +181,14 @@ TaskEncryptResource::TaskEncryptResource(InstallerContext& context) :
     DPL::TaskDecl<TaskEncryptResource>(this),
     m_context(context)
 {
+    AddStep(&TaskEncryptResource::StartStep);
     AddStep(&TaskEncryptResource::StepEncryptResource);
+    AddStep(&TaskEncryptResource::EndStep);
 }
 
 void TaskEncryptResource::StepEncryptResource()
 {
     LogDebug("Step Encrypt resource");
-    m_resEnc = new ResourceEncryptor;
-    m_resEnc->CreateEncryptionKey(DPL::ToUTF8String(m_context.
-                widgetConfig.pkgname_NOTNULL));
 
     EncryptDirectory(m_context.locations->getTemporaryRootDir());
 }
@@ -88,124 +197,158 @@ void TaskEncryptResource::EncryptDirectory(std::string path)
 {
     FTS *fts;
     FTSENT *ftsent;
-    char * const paths[] = {const_cast<char * const>(path.c_str()), NULL};
+    char * const paths[] = { const_cast<char * const>(path.c_str()), NULL };
 
-    if ((fts = fts_open(paths, FTS_PHYSICAL|FTS_NOCHDIR, NULL)) == NULL) {
+    if ((fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR, NULL)) == NULL) {
         //ERROR
         int error = errno;
         LogWarning(__PRETTY_FUNCTION__ << ": fts_open failed with error: "
-                << strerror(error));
-        ThrowMsg(Exceptions::InternalError, "Error reading directory: "
-                << path);
+                                       << strerror(error));
+        ThrowMsg(Exceptions::EncryptionFailed, "Error reading directory: "
+                 << path);
     }
 
     while ((ftsent = fts_read(fts)) != NULL) {
         switch (ftsent->fts_info) {
-            case FTS_DP:
-            case FTS_DC:
-            case FTS_D:
-            case FTS_DEFAULT:
-            case FTS_SLNONE:
-                //directories, non-regular files, dangling symbolic links
-                break;
-            case FTS_F:
-            case FTS_NSOK:
-            case FTS_SL:
-                //regular files and other objects that can be counted
-                if (isSupportedForEncryption(ftsent->fts_path)) {
-                    EncryptFile(ftsent->fts_path);
-                }
-                break;
-            case FTS_NS:
-            case FTS_DOT:
-            case FTS_DNR:
-            case FTS_ERR:
-            default:
-                LogWarning(__PRETTY_FUNCTION__
-                        << ": traversal failed on file: "
-                        << ftsent->fts_path
-                        << " with error: "
-                        << strerror(ftsent->fts_errno));
-                ThrowMsg(Exceptions::InternalError, "Error reading file");
+        case FTS_DP:
+        case FTS_DC:
+        case FTS_D:
+        case FTS_DEFAULT:
+        case FTS_SLNONE:
+            //directories, non-regular files, dangling symbolic links
+            break;
+        case FTS_F:
+        case FTS_NSOK:
+        case FTS_SL:
+            //regular files and other objects that can be counted
+            if (isSupportedForEncryption(ftsent->fts_path)) {
+                EncryptFile(ftsent->fts_path);
+            }
+            break;
+        case FTS_NS:
+        case FTS_DOT:
+        case FTS_DNR:
+        case FTS_ERR:
+        default:
+            LogWarning(__PRETTY_FUNCTION__
+                       << ": traversal failed on file: "
+                       << ftsent->fts_path
+                       << " with error: "
+                       << strerror(ftsent->fts_errno));
+            ThrowMsg(Exceptions::EncryptionFailed, "Error reading file");
+            break;
         }
     }
 
     if (fts_close(fts) == -1) {
         int error = errno;
         LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: "
-                << strerror(error));
+                                       << strerror(error));
     }
 }
 
 void TaskEncryptResource::EncryptFile(const std::string &fileName)
 {
-    Try
-    {
-        LogDebug("Need to ecnrypt file Name " << fileName);
-        std::string encFile = fileName + ".enc";
-
-        struct stat buf;
-        int ret = stat(fileName.c_str(), &buf);
-        if(ret == 0) {
-            size_t fileSize = buf.st_size;
-
-            FILE* resFp = fopen(fileName.c_str(), "r");
-            if ( NULL == resFp) {
-                LogError("Couldnot open file : " << fileName);
-                return;
-            }
+    LogDebug("Encrypt file: " << fileName);
+    std::string encFile = fileName + ".enc";
 
-            int blockSize = m_resEnc->GetBlockSize(fileSize);
-            LogDebug("Get block size : " << blockSize);
+    struct stat info;
+    memset(&info, 0, sizeof(info));
+    if (stat(fileName.c_str(), &info) != 0)
+    {
+        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;
+    }
 
-            unsigned char readBuf[fileSize];
-            unsigned char outEncBuf[blockSize];
-            memset(readBuf, 0, fileSize);
-            memset(outEncBuf, 0, blockSize);
+    // 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)) {
 
-            ret = fread(readBuf, sizeof(unsigned char), fileSize, resFp);
-            if (ret!=fileSize){
-                LogError("Failed to read ecryption buffer with error: " << strerror(errno) );
-                fclose(resFp);
-               return;
-            }
+        DPL::ScopedFClose inFile(openFile(fileName, "r"));
+        DPL::ScopedFClose outFile(openFile(encFile, "w"));
 
-            m_resEnc->EncryptChunk(readBuf, outEncBuf, fileSize);
+        const std::size_t chunkSize = (fileSize > ENCRYPTION_CHUNK_MAX_SIZE
+                ? ENCRYPTION_CHUNK_MAX_SIZE : fileSize);
 
-            FILE* encFp = fopen(encFile.c_str(), "w");
-            if (NULL == encFp) {
-                LogError("Failed to open ecryption file");
-                fclose(resFp);
-                return;
-            }
-            fwrite(outEncBuf, sizeof(unsigned char), blockSize, encFp);
+        std::unique_ptr<unsigned char[]> inChunk(new unsigned char[chunkSize]);
+        std::size_t bytesRead = 0;
+        /* TODO : pkgId should change to appId after wrt-client label changed. */
+        std::string pkgId = DPL::ToUTF8String(m_context.widgetConfig.tzPkgid);
 
-            fclose(resFp);
-            fclose(encFp);
+        do
+        {
+            bytesRead = readBytes(inChunk.get(), chunkSize, inFile.Get());
+            if (0 != bytesRead) {
+                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");
+                }
 
-            LogDebug("Success to encrypt file");
-            LogDebug("Remove unecrypted file : " << fileName);
+                std::stringstream toString;
+                toString << outDecSize;
 
-            unlink(fileName.c_str());
-            if ((rename(encFile.c_str(), fileName.c_str())) != 0) {
-                ThrowMsg(Exceptions::ExtractFileFailed, fileName);
+                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]);
 
-            std::string realPath = fileName;
-            realPath.replace(0, m_context.locations->getTemporaryRootDir().length(),
-                    m_context.locations->getSourceDir());
+        } while (0 == std::feof(inFile.Get()));
 
-            WrtDB::EncryptedFileInfo info;
-            info.fileName = DPL::FromUTF8String(realPath);
-            info.fileSize = fileSize;
+        outFile.Reset();
+        inFile.Reset();
 
-            m_context.widgetConfig.encryptedFiles.insert(info);
+        LogDebug("File encrypted successfully");
+        LogDebug("Remove plain-text file: " << fileName);
+        if (0 != unlink(fileName.c_str()))
+        {
+            Throw(Exceptions::EncryptionFailed);
+        }
+
+        LogDebug("Rename encrypted file");
+        if (0 != std::rename(encFile.c_str(), fileName.c_str()))
+        {
+            Throw(Exceptions::EncryptionFailed);
         }
     }
-    Catch(ResourceEncryptor::Exception::Base)
-    {
-        ReThrowMsg(Exceptions::ExtractFileFailed, fileName);
-    }
+
+    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;
+
+    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