Exemplo n.º 1
0
zipFile FileUtils::mzOpenOutputFile(const std::string &path)
{
#if defined(MINIZIP_WIN32)
    zlib_filefunc64_def zFunc;
    memset(&zFunc, 0, sizeof(zFunc));
    fill_win32_filefunc64W(&zFunc);
    return zipOpen2_64(utf8::utf8ToUtf16(path).c_str(), 0, nullptr, &zFunc);
#elif defined(MINIZIP_ANDROID)
    zlib_filefunc64_def zFunc;
    memset(&zFunc, 0, sizeof(zFunc));
    fill_android_filefunc64(&zFunc);
    return zipOpen2_64(path.c_str(), 0, nullptr, &zFunc);
#else
    return zipOpen64(path.c_str(), 0);
#endif
}
Exemplo n.º 2
0
ZipCtx * MinizipUtils::open_output_file(std::string path)
{
    ZipCtx *ctx = new(std::nothrow) ZipCtx();
    if (!ctx) {
        return nullptr;
    }

#if defined(MINIZIP_WIN32)
    auto converted = utf8_to_wcs(path);
    if (!converted) {
        delete ctx;
        return nullptr;
    }
    ctx->path = std::move(converted.value());

    fill_win32_filefunc64W(&ctx->buf.filefunc64);
#elif defined(MINIZIP_ANDROID)
    fill_android_filefunc64(&ctx->buf.filefunc64);
    ctx->path = std::move(path);
#else
    fill_fopen64_filefunc(&ctx->buf.filefunc64);
    ctx->path = std::move(path);
#endif

    fill_buffer_filefunc64(&ctx->z_func, &ctx->buf);
    ctx->zf = zipOpen2_64(ctx->path.c_str(), 0, nullptr, &ctx->z_func);
    if (!ctx->zf) {
        delete ctx;
        return nullptr;
    }

    return ctx;
}
Exemplo n.º 3
0
// TODO: using this for XPS files results in documents that Microsoft XPS Viewer can't read
IStream *OpenDirAsZipStream(const WCHAR *dirPath, bool recursive)
{
    if (!dir::Exists(dirPath))
        return NULL;

    ScopedComPtr<IStream> stream;
    if (FAILED(CreateStreamOnHGlobal(NULL, TRUE, &stream)))
        return NULL;

    zlib_filefunc64_def ffunc;
    fill_win32s_filefunc64(&ffunc);
    zipFile zf = zipOpen2_64(stream, 0, NULL, &ffunc);
    if (!zf)
        return NULL;

    size_t dirLen = str::Len(dirPath);
    if (!path::IsSep(dirPath[dirLen - 1]))
        dirLen++;

    bool ok = true;
    DirIter di(dirPath, recursive);
    for (const WCHAR *filePath = di.First(); filePath && ok; filePath = di.Next()) {
        CrashIf(!str::StartsWith(filePath, dirPath));
        const WCHAR *nameInZip = filePath + dirLen;
        size_t fileSize;
        ScopedMem<char> fileData(file::ReadAll(filePath, &fileSize));
        ok = fileData && AppendFileToZip(zf, nameInZip, fileData, fileSize);
    }
    int err = zipClose(zf, NULL);
    if (!ok || err != ZIP_OK)
        return NULL;

    stream->AddRef();
    return stream;
}
Exemplo n.º 4
0
FileUtils::MzZipCtx * FileUtils::mzOpenOutputFile(std::string path)
{
    MzZipCtx *ctx = new(std::nothrow) MzZipCtx();
    if (!ctx) {
        return nullptr;
    }

#if defined(MINIZIP_WIN32)
    fill_win32_filefunc64W(&ctx->buf.filefunc64);
    ctx->path = utf8::utf8ToUtf16(path);
#elif defined(MINIZIP_ANDROID)
    fill_android_filefunc64(&ctx->buf.filefunc64);
    ctx->path = std::move(path);
#else
    fill_fopen64_filefunc(&ctx->buf.filefunc64);
    ctx->path = std::move(path);
#endif

    fill_buffer_filefunc64(&ctx->zFunc, &ctx->buf);
    ctx->zf = zipOpen2_64(ctx->path.c_str(), 0, nullptr, &ctx->zFunc);
    if (!ctx->zf) {
        free(ctx);
        return nullptr;
    }

    return ctx;
}
Exemplo n.º 5
0
bool ZipArchiveWriter::Open(const std::string& zipFileName, bool bZipExist)
{
    if (zipFileName.empty())
        return false;

    Close();

    m_errCode = Z_OK;
    m_zipFilePath = zipFileName;

#ifdef USEWIN32IOAPI
    zlib_filefunc64_def ffunc;
    fill_win32_filefunc64W(&ffunc);
    m_hZip = zipOpen2_64(TUtf8Util::UTF8StrToUniStr(m_zipFilePath).c_str(), bZipExist ? APPEND_STATUS_ADDINZIP : APPEND_STATUS_CREATE, nullptr, &ffunc);
#else
    m_hZip = zipOpen64(m_zipFilePath.c_str(), bZipExist ? APPEND_STATUS_ADDINZIP : APPEND_STATUS_CREATE);
#endif

    if (!m_hZip)
    {
        m_errCode = Z_ZIP_OPEN_ERROR;
        return false;
    }

    return true;
}
Exemplo n.º 6
0
extern "C" HZIP CreateArchiveW(WCHAR *lpstrZipFile,char *lpPassword,int dwPasswordLen,int dwCompLevel)
{
    void *r=NULL;
    if (lpstrZipFile)
    {
        ZIPCOMPRESSION *p=(ZIPCOMPRESSION *)_alloc(sizeof(ZIPCOMPRESSION));
        if (p)
        {
            p->bHandleType=HT_COMPRESSOR;

            bool bPassword=((lpPassword) && (dwPasswordLen > 0));
            if (bPassword)
            {
                memcpy(p->szPassword,lpPassword,dwPasswordLen);
                p->bEncrypted=true;
            }

            p->dwCompLevel=dwCompLevel;

            zlib_filefunc64_def ffunc;
            fill_fopen64_filefunc(&ffunc);
            p->hZip=zipOpen2_64(lpstrZipFile,0,NULL,&ffunc);
            if (p->hZip)
                r=p;
        }
        if (!r)
            MemFree(p);
    }
    else
        ArchSetLastError(ARCH_INVALID_PARAMETER);
    return r;
}
Exemplo n.º 7
0
bool ZipCreator::SaveAs(const WCHAR *zipFilePath)
{
    if (d->pathsAndZipNames.Count() == 0)
        return false;
    zlib_filefunc64_def ffunc;
    fill_win32_filefunc64(&ffunc);
    zipFile zf = zipOpen2_64(zipFilePath, 0, NULL, &ffunc);
    if (!zf)
        return false;

    bool result = true;
    for (size_t i = 0; i < d->pathsAndZipNames.Count(); i += 2) {
        const WCHAR *fileName = d->pathsAndZipNames.At(i);
        const WCHAR *nameInZip = d->pathsAndZipNames.At(i + 1);
        size_t fileSize;
        ScopedMem<char> fileData(file::ReadAll(fileName, &fileSize));
        if (!fileData) {
            result = false;
            break;
        }
        result = AppendFileToZip(zf, nameInZip, fileData, fileSize);
        if (!result)
            break;
    }
    int err = zipClose(zf, NULL);
    if (err != ZIP_OK)
        result = false;
    return result;
}
Exemplo n.º 8
0
bool ZipArchive::open()
{
	if (isOpen())
		return true;
	
	auto zip = zipOpen2_64(nullptr, APPEND_STATUS_CREATE, nullptr, &d->fileFuncs);
	d->zip = zip;
	return zip;
}
Exemplo n.º 9
0
// ////////////////////////////////////////////////////////////////////////////////
// @public @static 将指定文件名打包成指定 zip
//
bool ZipTools::Zip(LPCWSTR wzDirPath, LPCWSTR wzDestName)
{
	//
	// 检查指定路径是否存在
	//
	if ( !FileTools::Exist(wzDirPath) )
	{
		DebugTools::OutputDebugPrintfW(L"[ZipTools] [Zip] Path Not Exist. [%s]\r\n", wzDirPath);
		return false;
	}

	WCHAR wzDestDir[MAX_PATH] = {0};
	FileTools::GetFileDir(wzDestName, wzDestDir, L'\\');

	if ( !FileTools::Exist(wzDestDir) )
	{
		DebugTools::OutputDebugPrintfW(L"[ZipTools] [Zip] Path Not Exist. [%s]\r\n", wzDestDir);
		return false;
	}

	// 设置当前工作目录
	SetCurrentDirectoryW(wzDirPath);

	WCHAR wzParentDir[MAX_PATH] = {0};
	wcscpy_s(wzParentDir, wzDirPath);
	//FileTools::GetFileDir(wzDirPath, wzParentDir, L'\\');
	wcscat_s(wzParentDir, L"\\");

	//
	// 创建 zip 文件
	//
	zlib_filefunc64_def ffunc;
	fill_win32_filefunc64W(&ffunc);
	zipFile zf; zf = zipOpen2_64(wzDestName, 0, NULL, &ffunc);

	if ( NULL == zf )
	{
		DebugTools::OutputDebugPrintfW(
			L"[ZipTools] [Zip] Create Zip File Failed. [%s] \r\n", wzDestName);
		return false;
	}

	unsigned long size_read = 0;
	unsigned long size_buf = WRITEBUFFERSIZE;
	PBYTE buf = new BYTE [size_buf];

	//
	// 将文件夹下所有文件添加进 zip
	//
	AddFileToZip(zf, wzDirPath, wzParentDir, buf);

	zipClose(zf,NULL);

	delete [] buf;

	return true;
}
Exemplo n.º 10
0
zipFile FileUtils::mzOpenOutputFile(const std::string &path)
{
#ifdef USEWIN32IOAPI
    zlib_filefunc64_def zFunc;
    memset(&zFunc, 0, sizeof(zFunc));
    fill_win32_filefunc64A(&zFunc);
    return zipOpen2_64(path.c_str(), 0, nullptr, &zFunc);
#else
    return zipOpen64(path.c_str(), 0);
#endif
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
    zipFile zf = NULL;
#ifdef USEWIN32IOAPI
    zlib_filefunc64_def ffunc = {0};
#endif
    char *zipfilename = NULL;
    const char* password = NULL;
    void* buf = NULL;
    int size_buf = WRITEBUFFERSIZE;
    int zipfilenamearg = 0;
    int errclose = 0;
    int err = 0;
    int i = 0;
    int opt_overwrite = APPEND_STATUS_CREATE;
    int opt_compress_level = Z_DEFAULT_COMPRESSION;
    int opt_exclude_path = 0;

    do_banner();
    if (argc == 1)
    {
        do_help();
        return 0;
    }

    /* Parse command line options */
    for (i = 1; i < argc; i++)
    {
        if ((*argv[i]) == '-')
        {
            const char *p = argv[i]+1;

            while ((*p) != '\0')
            {
                char c = *(p++);;
                if ((c == 'o') || (c == 'O'))
                    opt_overwrite = APPEND_STATUS_CREATEAFTER;
                if ((c == 'a') || (c == 'A'))
                    opt_overwrite = APPEND_STATUS_ADDINZIP;
                if ((c >= '0') && (c <= '9'))
                    opt_compress_level = (c - '0');
                if ((c == 'j') || (c == 'J'))
                    opt_exclude_path = 1;

                if (((c == 'p') || (c == 'P')) && (i+1 < argc))
                {
                    password=argv[i+1];
                    i++;
                }
            }
        }
        else
        {
            if (zipfilenamearg == 0)
                zipfilenamearg = i;
        }
    }

    if (zipfilenamearg == 0)
    {
        do_help();
        return 0;
    }
    zipfilename = argv[zipfilenamearg];

    buf = (void*)malloc(size_buf);
    if (buf == NULL)
    {
        printf("Error allocating memory\n");
        return ZIP_INTERNALERROR;
    }

    if (opt_overwrite == 2)
    {
        /* If the file don't exist, we not append file */
        if (check_file_exists(zipfilename) == 0)
            opt_overwrite = 1;
    }
    else if (opt_overwrite == 0)
    {
        /* If ask the user what to do because append and overwrite args not set */
        //if (check_file_exists(zipfilename) != 0)
        //{
        //    char rep = 0;
        //    do
        //    {
        //        char answer[128];
        //        printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ", zipfilename);
        //        if (scanf("%1s", answer) != 1)
        //            exit(EXIT_FAILURE);
        //        rep = answer[0];

        //        if ((rep >= 'a') && (rep <= 'z'))
        //            rep -= 0x20;
        //    }
        //    while ((rep != 'Y') && (rep != 'N') && (rep != 'A'));

        //    if (rep == 'A')
        //        opt_overwrite = 2;
        //    else if (rep == 'N')
        //    {
        //        do_help();
        //        free(buf);
        //        return 0;
        //    }
        //}
    }

#ifdef USEWIN32IOAPI
    fill_win32_filefunc64A(&ffunc);
    zf = zipOpen2_64(zipfilename, opt_overwrite, NULL, &ffunc);
#else
    zf = zipOpen64(zipfilename, opt_overwrite);
#endif

    if (zf == NULL)
    {
        printf("error opening %s\n", zipfilename);
        err = ZIP_ERRNO;
    }
    else
        printf("creating %s\n", zipfilename);

    /* Go through command line args looking for files to add to zip */
    for (i = zipfilenamearg + 1; (i < argc) && (err == ZIP_OK); i++)
    {
        FILE *fin = NULL;
        int size_read = 0;
        const char* filenameinzip = argv[i];
        const char *savefilenameinzip;
        zip_fileinfo zi = {0};
        unsigned long crcFile = 0;
        int zip64 = 0;

        /* Skip command line options */
        if ((((*(argv[i])) == '-') || ((*(argv[i])) == '/')) && (strlen(argv[i]) == 2) &&
            ((argv[i][1] == 'o') || (argv[i][1] == 'O') || (argv[i][1] == 'a') || (argv[i][1] == 'A') ||
             (argv[i][1] == 'p') || (argv[i][1] == 'P') || ((argv[i][1] >= '0') && (argv[i][1] <= '9'))))
            continue;

        /* Get information about the file on disk so we can store it in zip */
        filetime(filenameinzip, &zi.tmz_date, &zi.dosDate);

        if ((password != NULL) && (err == ZIP_OK))
            err = get_file_crc(filenameinzip, buf, size_buf, &crcFile);

        zip64 = is_large_file(filenameinzip);

        /* Construct the filename that our file will be stored in the zip as.
           The path name saved, should not include a leading slash.
           If it did, windows/xp and dynazip couldn't read the zip file. */

        savefilenameinzip = filenameinzip;
        while (savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/')
            savefilenameinzip++;

        /* Should the file be stored with any path info at all? */
        if (opt_exclude_path)
        {
            const char *tmpptr = NULL;
            const char *lastslash = 0;

            for (tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
            {
                if (*tmpptr == '\\' || *tmpptr == '/')
                    lastslash = tmpptr;
            }

            if (lastslash != NULL)
                savefilenameinzip = lastslash + 1; /* base filename follows last slash. */
        }

        /* Add to zip file */
        err = zipOpenNewFileInZip3_64(zf, savefilenameinzip, &zi,
                    NULL, 0, NULL, 0, NULL /* comment*/,
                    (opt_compress_level != 0) ? Z_DEFLATED : 0,
                    opt_compress_level,0,
                    -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                    password, crcFile, zip64);

        if (err != ZIP_OK)
            printf("error in opening %s in zipfile (%d)\n", filenameinzip, err);
        else
        {
            fin = FOPEN_FUNC(filenameinzip, "rb");
            if (fin == NULL)
            {
                err = ZIP_ERRNO;
                printf("error in opening %s for reading\n", filenameinzip);
            }
        }

        if (err == ZIP_OK)
        {
            /* Read contents of file and write it to zip */
            do
            {
                size_read = (int)fread(buf, 1, size_buf, fin);
                if ((size_read < size_buf) && (feof(fin) == 0))
                {
                    printf("error in reading %s\n",filenameinzip);
                    err = ZIP_ERRNO;
                }

                if (size_read > 0)
                {
                    err = zipWriteInFileInZip(zf, buf, size_read);
                    if (err < 0)
                        printf("error in writing %s in the zipfile (%d)\n", filenameinzip, err);
                }
            }
            while ((err == ZIP_OK) && (size_read > 0));
        }

        if (fin)
            fclose(fin);

        if (err < 0)
            err = ZIP_ERRNO;
        else
        {
            err = zipCloseFileInZip(zf);
            if (err != ZIP_OK)
                printf("error in closing %s in the zipfile (%d)\n", filenameinzip, err);
        }
    }

    errclose = zipClose(zf, NULL);
    if (errclose != ZIP_OK)
        printf("error in closing %s (%d)\n", zipfilename, errclose);

    free(buf);
    return err;
}
Exemplo n.º 12
0
int TRI_ZipFile (const char* filename, 
                 const char* dir,
                 TRI_vector_string_t const* files,
                 const char* password) {
  void* buffer;
  size_t bufferSize;
  zipFile zf;
#ifdef USEWIN32IOAPI
  zlib_filefunc64_def ffunc;
#endif
  size_t i, n;
  int res;

  if (TRI_ExistsFile(filename)) {
    return TRI_ERROR_CANNOT_OVERWRITE_FILE;
  }

  bufferSize = 16384;
  buffer = TRI_Allocate(TRI_UNKNOWN_MEM_ZONE, bufferSize, false);

  if (buffer == NULL) {
    return TRI_ERROR_OUT_OF_MEMORY;
  }

#ifdef USEWIN32IOAPI
  fill_win32_filefunc64A(&ffunc);
  zf = zipOpen2_64(filename, 0, NULL, &ffunc);
#else
  zf = zipOpen64(filename, 0);
#endif

  if (zf == NULL) {
    TRI_Free(TRI_UNKNOWN_MEM_ZONE, buffer);

    return ZIP_ERRNO;
  }

  res = TRI_ERROR_NO_ERROR;

  n = files->_length;
  for (i = 0; i < n; ++i) {
    FILE* fin;
    char* file;
    char* fullfile;
    char* saveName;
    zip_fileinfo zi;
    uint32_t crc;
    int isLarge;

    file = TRI_AtVectorString(files, i);

    if (*dir == '\0') {
      fullfile = TRI_DuplicateString(file);
    }
    else {
      fullfile = TRI_Concatenate2File(dir, file);
    }

    memset(&zi, 0, sizeof(zi));

    res = TRI_Crc32File(fullfile, &crc);

    if (res != TRI_ERROR_NO_ERROR) {
      break;
    }

    isLarge = (TRI_SizeFile(file) > 0xFFFFFFFFLL);
              
    saveName = file;

    while (*saveName == '\\' || *saveName == '/') {
      ++saveName;
    }

    if (zipOpenNewFileInZip3_64(zf,
                                saveName,
                                &zi,
                                NULL,
                                0,
                                NULL,
                                0,
                                NULL, /* comment*/
                                Z_DEFLATED,
                                Z_DEFAULT_COMPRESSION,
                                0,
                                -MAX_WBITS, 
                                DEF_MEM_LEVEL, 
                                Z_DEFAULT_STRATEGY,
                                password,
                                (unsigned long) crc, 
                                isLarge) != ZIP_OK) {
    }

    fin = fopen(fullfile, "rb");
    TRI_FreeString(TRI_CORE_MEM_ZONE, fullfile);

    if (fin == NULL) {
      break;
    }

    while (true) {
      int sizeRead;

      sizeRead = (int) fread(buffer, 1, bufferSize, fin);
      if (sizeRead < bufferSize) {
        if (feof(fin) == 0) {
          res = TRI_set_errno(TRI_ERROR_SYS_ERROR);
          break;
        }
      }

      if (sizeRead > 0) {
        res = zipWriteInFileInZip(zf, buffer, sizeRead);
        if (res != 0) {
          break;
        }
      }
      else if (sizeRead <= 0) {
        break;
      }
    }

    fclose(fin);
    
    zipCloseFileInZip(zf);

    if (res != TRI_ERROR_NO_ERROR) {
      break;
    }
  }

  zipClose(zf, NULL);
  
  TRI_Free(TRI_UNKNOWN_MEM_ZONE, buffer);

  return res;
}
Exemplo n.º 13
0
void ExportEPUB::SaveFolderAsEpubToLocation(const QString &fullfolderpath, const QString &fullfilepath)
{
    QString tempFile = fullfolderpath + "-tmp.epub";
    QDateTime timeNow = QDateTime::currentDateTime();
    zip_fileinfo fileInfo;
#ifdef Q_OS_WIN32
    zlib_filefunc64_def ffunc;
    fill_win32_filefunc64W(&ffunc);
    zipFile zfile = zipOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(tempFile)).c_str(), APPEND_STATUS_CREATE, NULL, &ffunc);
#else
    zipFile zfile = zipOpen64(QDir::toNativeSeparators(tempFile).toUtf8().constData(), APPEND_STATUS_CREATE);
#endif

    if (zfile == NULL) {
        boost_throw(CannotOpenFile() << errinfo_file_fullpath(tempFile.toStdString()));
    }

    memset(&fileInfo, 0, sizeof(fileInfo));
    fileInfo.tmz_date.tm_sec = timeNow.time().second();
    fileInfo.tmz_date.tm_min = timeNow.time().minute();
    fileInfo.tmz_date.tm_hour = timeNow.time().hour();
    fileInfo.tmz_date.tm_mday = timeNow.date().day();
    fileInfo.tmz_date.tm_mon = timeNow.date().month() - 1;
    fileInfo.tmz_date.tm_year = timeNow.date().year();

    // Write the mimetype. This must be uncompressed and the first entry in the archive.
    if (zipOpenNewFileInZip64(zfile, "mimetype", &fileInfo, NULL, 0, NULL, 0, NULL, Z_NO_COMPRESSION, 0, 0) != Z_OK) {
        zipClose(zfile, NULL);
        QFile::remove(tempFile);
        boost_throw(CannotStoreFile() << errinfo_file_fullpath("mimetype"));
    }

    if (zipWriteInFileInZip(zfile, EPUB_MIME_DATA, (unsigned int)strlen(EPUB_MIME_DATA)) != Z_OK) {
        zipCloseFileInZip(zfile);
        zipClose(zfile, NULL);
        QFile::remove(tempFile);
        boost_throw(CannotStoreFile() << errinfo_file_fullpath("mimetype"));
    }

    zipCloseFileInZip(zfile);
    // Write all the files in our directory path to the archive.
    QDirIterator it(fullfolderpath, QDir::Files | QDir::NoDotAndDotDot | QDir::Readable | QDir::Hidden, QDirIterator::Subdirectories);

    while (it.hasNext()) {
        it.next();
        QString relpath = it.filePath().remove(fullfolderpath);

        while (relpath.startsWith("/")) {
            relpath = relpath.remove(0, 1);
        }

        // Add the file entry to the archive.
        // We should check the uncompressed file size. If it's over >= 0xffffffff the last parameter (zip64) should be 1.
        if (zipOpenNewFileInZip4_64(zfile, relpath.toUtf8().constData(), &fileInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, 8, 0, 15, 8, Z_DEFAULT_STRATEGY, NULL, 0, 0x0b00, 1<<11, 0) != Z_OK) {
            zipClose(zfile, NULL);
            QFile::remove(tempFile);
            boost_throw(CannotStoreFile() << errinfo_file_fullpath(relpath.toStdString()));
        }

        // Open the file on disk. We will read this and write what we read into
        // the archive.
        QFile dfile(it.filePath());

        if (!dfile.open(QIODevice::ReadOnly)) {
            zipCloseFileInZip(zfile);
            zipClose(zfile, NULL);
            QFile::remove(tempFile);
            boost_throw(CannotOpenFile() << errinfo_file_fullpath(it.fileName().toStdString()));
        }

        // Write the data from the file on disk into the archive.
        char buff[BUFF_SIZE] = {0};
        qint64 read = 0;

        while ((read = dfile.read(buff, BUFF_SIZE)) > 0) {
            if (zipWriteInFileInZip(zfile, buff, read) != Z_OK) {
                dfile.close();
                zipCloseFileInZip(zfile);
                zipClose(zfile, NULL);
                QFile::remove(tempFile);
                boost_throw(CannotStoreFile() << errinfo_file_fullpath(relpath.toStdString()));
            }
        }

        dfile.close();

        // There was an error reading the file on disk.
        if (read < 0) {
            zipCloseFileInZip(zfile);
            zipClose(zfile, NULL);
            QFile::remove(tempFile);
            boost_throw(CannotStoreFile() << errinfo_file_fullpath(relpath.toStdString()));
        }

        if (zipCloseFileInZip(zfile) != Z_OK) {
            zipClose(zfile, NULL);
            QFile::remove(tempFile);
            boost_throw(CannotStoreFile() << errinfo_file_fullpath(relpath.toStdString()));
        }
    }

    zipClose(zfile, NULL);
    // Overwrite the contents of the real file with the contents from the temp
    // file we saved the data do. We do this instead of simply copying the file
    // because a file copy will lose extended attributes such as labels on OS X.
    QFile temp_epub(tempFile);

    if (!temp_epub.open(QFile::ReadOnly)) {
        boost_throw(CannotOpenFile() << errinfo_file_fullpath(tempFile.toStdString()));
    }

    QFile real_epub(fullfilepath);

    if (!real_epub.open(QFile::WriteOnly | QFile::Truncate)) {
        temp_epub.close();
        boost_throw(CannotWriteFile() << errinfo_file_fullpath(fullfilepath.toStdString()));
    }

    // Copy the contents from the temp file to the real file.
    char buff[BUFF_SIZE] = {0};
    qint64 read = 0;
    qint64 written = 0;

    while ((read = temp_epub.read(buff, BUFF_SIZE)) > 0) {
        written = real_epub.write(buff, read);

        if (written != read) {
            temp_epub.close();
            real_epub.close();
            QFile::remove(tempFile);
            boost_throw(CannotCopyFile() << errinfo_file_fullpath(fullfilepath.toStdString()));
        }
    }

    if (read == -1) {
        temp_epub.close();
        real_epub.close();
        QFile::remove(tempFile);
        boost_throw(CannotCopyFile() << errinfo_file_fullpath(fullfilepath.toStdString()));
    }

    temp_epub.close();
    real_epub.close();
    QFile::remove(tempFile);
}
Exemplo n.º 14
0
bool DialogPackage::CreatePackage()
{
	// Create options file
	WCHAR tempFile[MAX_PATH];
	GetTempPath(MAX_PATH, tempFile);
	GetTempFileName(tempFile, L"ini", 0, tempFile);

	WritePrivateProfileString(L"rmskin", L"Name", m_Name.c_str(), tempFile);
	WritePrivateProfileString(L"rmskin", L"Author", m_Author.c_str(), tempFile);
	WritePrivateProfileString(L"rmskin", L"Version", m_Version.c_str(), tempFile);

	if (!c_Dialog->m_Load.empty())
	{
		WritePrivateProfileString(L"rmskin", L"LoadType", c_Dialog->m_LoadLayout ? L"Layout" : L"Skin", tempFile);
		WritePrivateProfileString(L"rmskin", L"Load", c_Dialog->m_Load.c_str(), tempFile);
	}

	if (!c_Dialog->m_VariableFiles.empty())
	{
		WritePrivateProfileString(L"rmskin", L"VariableFiles", m_VariableFiles.c_str(), tempFile);
	}

	if (c_Dialog->m_MergeSkins)
	{
		WritePrivateProfileString(L"rmskin", L"MergeSkins", L"1", tempFile);
	}

	WritePrivateProfileString(L"rmskin", L"MinimumRainmeter", m_MinimumRainmeter.c_str(), tempFile);
	WritePrivateProfileString(L"rmskin", L"MinimumWindows", m_MinimumWindows.c_str(), tempFile);

	// Only Skin Installer in Rainmeter 3.0.1 support UTF-8 filenames.
	m_AllowNonAsciiFilenames = DialogInstall::CompareVersions(m_MinimumRainmeter, L"3.0.1") != -1;

	// Create archive and add options file and header bitmap
	zlib_filefunc64_def zlibFileFunc;
	fill_win32_filefunc64W(&zlibFileFunc);
	m_ZipFile = zipOpen2_64(m_TargetFile.c_str(), APPEND_STATUS_CREATE, nullptr, &zlibFileFunc);

	auto cleanup = [&]()->bool
	{
		zipClose(m_ZipFile, nullptr);
		DeleteFile(m_TargetFile.c_str());
		return false;
	};

	if (!m_ZipFile ||
		(!c_Dialog->m_HeaderFile.empty() && !AddFileToPackage(c_Dialog->m_HeaderFile.c_str(), L"RMSKIN.bmp")) ||
		!AddFileToPackage(tempFile, L"RMSKIN.ini"))
	{
		std::wstring error = L"Unable to create package.";
		error += L"\n\nClick OK to close Packager.";
		MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR);
		DeleteFile(tempFile);
		return cleanup();
	}

	// Add skin
	{
		std::wstring zipPrefix = L"Skins\\" + m_SkinFolder.first;
		zipPrefix += L'\\';
		if (!AddFolderToPackage(m_SkinFolder.second, L"", zipPrefix.c_str()))
		{
			return cleanup();
		}
	}

	// Add layouts
	for (auto iter = m_LayoutFolders.cbegin(); iter != m_LayoutFolders.cend(); ++iter)
	{
		std::wstring realPath = (*iter).second + L"Rainmeter.ini";
		std::wstring zipPath = L"Layouts\\" + (*iter).first;
		zipPath += L"\\Rainmeter.ini";
		if (!AddFileToPackage(realPath.c_str(), zipPath.c_str()))
		{
			std::wstring error = L"Error adding layout '";
			error += (*iter).first;
			error += L"'.";
			error += L"\n\nClick OK to close Packager.";
			MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR);
			return cleanup();
		}
	}

	// Add plugins
	for (auto iter = m_PluginFolders.cbegin(); iter != m_PluginFolders.cend(); ++iter)
	{
		// Add 32bit and 64bit versions
		for (int i = 0; i < 2; ++i)
		{
			const std::wstring& realPath = (i == 0) ? (*iter).second.first : (*iter).second.second;
			std::wstring zipPath = ((i == 0) ? L"Plugins\\32bit\\" : L"Plugins\\64bit\\") + (*iter).first;
			if (!AddFileToPackage(realPath.c_str(), zipPath.c_str()))
			{
				std::wstring error = L"Error adding plugin '";
				error += (*iter).first;
				error += L"'.";
				error += L"\n\nClick OK to close Packager.";
				MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR);
				return cleanup();
			}
		}
	}

	// Add footer
	FILE* file;
	if (zipClose(m_ZipFile, nullptr) == ZIP_OK &&
		(file = _wfopen(m_TargetFile.c_str(), L"r+b")) != nullptr)
	{
		fseek(file, 0, SEEK_END);
		DialogInstall::PackageFooter footer = { _ftelli64(file), 0, "RMSKIN" };
		fwrite(&footer, sizeof(footer), 1, file);
		fclose(file);
	}
	else
	{
		std::wstring error = L"Unable to create package.";
		error += L"\n\nClick OK to close Packager.";
		MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR);
		return false;
	}

	return true;
}
Exemplo n.º 15
0
int _compress(const char** srcs, int src_num, const char** srcspath, int srcpath_num,
	      const char* dst, int level, const char* password, int exclude_path, PyObject* progress)
{
    zipFile zf = NULL;
    int size_buf = WRITEBUFFERSIZE;
    int opt_overwrite = APPEND_STATUS_CREATE;
    int err = ZIP_OK;
    int errclose = 0;
    int i;
#ifdef USEWIN32IOAPI
    zlib_filefunc64_def ffunc = {0};
#endif

    void* buf = NULL;
    buf = (void*)malloc(size_buf);
    if (buf == NULL)
    {
        pyerr_msg = PyErr_Format(PyExc_MemoryError, "could not allocate memory");
        return ZIP_ERRNO;
    }

    if (srcpath_num > 0)
        assert(src_num == srcpath_num);

#ifdef USEWIN32IOAPI
    fill_win32_filefunc64A(&ffunc);
    zf = zipOpen2_64(dst, opt_overwrite, NULL, &ffunc);
#else
    zf = zipOpen64(dst, opt_overwrite);
#endif

    if (zf == NULL)
    {
        pyerr_msg = PyErr_Format(PyExc_IOError, "error opening %s", dst);
        err = ZIP_ERRNO;
    }

    for (i = 0; i < src_num && (err == ZIP_OK); i++) {

        FILE *fin = NULL;
        int size_read = 0;
        const char* filenameinzip = srcs[i];
        const char* filepathnameinzip;
        const char *savefilenameinzip;
        const char *savefilepathnameinzip = NULL;
        char *fullpathfileinzip = NULL;
        unsigned long crcFile = 0;
        int zip64 = 0;

        zip_fileinfo zi;
        memset(&zi, 0, sizeof(zip_fileinfo));

        if (srcpath_num > 0)
            filepathnameinzip = srcspath[i];

        /* Get information about the file on disk so we can store it in zip */
        filetime(filenameinzip, &zi.tmz_date, &zi.dosDate);

        if ((password != NULL) && (err == ZIP_OK))
            err = get_file_crc(filenameinzip, buf, size_buf, &crcFile);

        zip64 = is_large_file(filenameinzip);

        /* Construct the filename that our file will be stored in the zip as. 
           The path name saved, should not include a leading slash. 
           If it did, windows/xp and dynazip couldn't read the zip file. */

        savefilenameinzip = filenameinzip;
        while (savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/')
            savefilenameinzip++;

        if (srcpath_num > 0) {
            savefilepathnameinzip = filepathnameinzip;
            while (savefilepathnameinzip[0] == '\\' || savefilepathnameinzip[0] == '/')
                savefilepathnameinzip++;
        }

        /* Should the file be stored with any path info at all? */
        if (exclude_path)
        {
            const char *tmpptr = NULL;
            const char *lastslash = NULL;

            for (tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
            {
                if (*tmpptr == '\\' || *tmpptr == '/')
                    lastslash = tmpptr;
            }

            if (lastslash != NULL)
                savefilenameinzip = lastslash + 1; // base filename follows last slash.

            if (srcpath_num > 0) {
                /* prepend savefilepathnameinzip for each savefilenameinzip */
                const char * slash;
#if (defined(_WIN32))
                const char default_slash = '\\';
#else
                const char default_slash = '/';
#endif
                size_t extra_len = 0;
                size_t filename_len = strlen(savefilenameinzip);
                size_t filepathname_len = strlen(savefilepathnameinzip);

                /* look for slash used in filepath */
                slash = strchr(savefilepathnameinzip, '/');
                if (slash == NULL) {
                    slash = strchr(savefilepathnameinzip, '\\');
                    if (slash == NULL) {
                        // no slash found.. use default
                        slash = &default_slash;
                    }
                }
                if (savefilepathnameinzip[filepathname_len-1] != *slash)
                    extra_len = 1;
                /* allocate buffer */
                fullpathfileinzip = (char *)malloc(filename_len + filepathname_len + extra_len + 1);
                if (fullpathfileinzip == NULL) {
                    free(buf);
                    pyerr_msg = PyErr_Format(PyExc_MemoryError, "error allocating memory on minizip compress");
                    return ZIP_INTERNALERROR;
                }

                strncpy(fullpathfileinzip, savefilepathnameinzip, filepathname_len);
                if (extra_len)
                    fullpathfileinzip[filepathname_len] = *slash;
                strncpy(fullpathfileinzip + filepathname_len + extra_len, savefilenameinzip, filename_len);
                /* terminate string */
                fullpathfileinzip[filename_len + filepathname_len + extra_len] = '\0';

                /* set pointer */
                savefilenameinzip = fullpathfileinzip;
            }
        }

        /* Add to zip file */
        err = zipOpenNewFileInZip3_64(zf, savefilenameinzip, &zi,
                    NULL, 0, NULL, 0, NULL /* comment*/,
                    (level != 0) ? Z_DEFLATED : 0, level, 0,
                    /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
                    -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                    password, crcFile, zip64);

        if (err != ZIP_OK) {
            pyerr_msg = PyErr_Format(PyExc_IOError, "error in opening %s in zipfile (%d)", filenameinzip, err);
            err = ZIP_ERRNO;
        }
        else
        {
            fin = FOPEN_FUNC(filenameinzip, "rb");
            if (fin == NULL)
            {
                pyerr_msg = PyErr_Format(PyExc_IOError, "error in opening %s for reading", filenameinzip);
                err = ZIP_ERRNO;
            }
        }

        if (err == ZIP_OK)
        {
            /* Read contents of file and write it to zip */
            do
            {
                size_read = (int)fread(buf, 1, size_buf, fin);
                if ((size_read < size_buf) && (feof(fin) == 0))
                {
                    pyerr_msg = PyErr_Format(PyExc_IOError, "error in reading %s", filenameinzip);
                    err = ZIP_ERRNO;
                }

                if (0 < size_read)
                {
                    err = zipWriteInFileInZip(zf, buf, size_read);
                    if (err < 0) {
                        pyerr_msg = PyErr_Format(PyExc_IOError, "error in writing %s in the zipfile (%d)", filenameinzip, err);
                        err = ZIP_ERRNO;
                    }
                }
            }
            while ((err == ZIP_OK) && (size_read > 0));
        }

        if (fin)
            fclose(fin);

        if (err == ZIP_OK)
        {
            err = zipCloseFileInZip(zf);
            if (err != ZIP_OK) {
                pyerr_msg = PyErr_Format(PyExc_IOError, "error in closing %s in the zipfile (%d)", filenameinzip, err);
                err = ZIP_ERRNO;
            }
        }

        if (progress != NULL)
        {
	    PyObject* args = Py_BuildValue("(I)", i + 1);
	    PyObject* result = PyObject_CallObject(progress, args);
	    if (PyErr_Occurred()) // Ignore errors in the callback, don't want them to crash this c module
	    {
                PyErr_Clear();
	    }
	    Py_XDECREF(result);
	    Py_XDECREF(args);
        }

        if(srcpath_num > 0 && fullpathfileinzip)
            free(fullpathfileinzip);
    }

    errclose = zipClose(zf, NULL);
    if (errclose != ZIP_OK) {
        pyerr_msg = PyErr_Format(PyExc_IOError, "error in closing %s (%d)", dst, errclose);
        err = ZIP_ERRNO;
    }

    free(buf);

    return err;
}
Exemplo n.º 16
0
int main(
    int argc,
    char *argv[])
{
    int i;
    int opt_overwrite=0;
    int opt_compress_level=Z_DEFAULT_COMPRESSION;
    int opt_exclude_path=0;
    int zipfilenamearg = 0;
    char filename_try[MAXFILENAME+16];
    int zipok;
    int err=0;
    int size_buf=0;
    void* buf=NULL;
    const char* password=NULL;


    do_banner();
    if (argc==1)
    {
        do_help();
        return 0;
    }
    else
    {
        for (i=1;i<argc;i++)
        {
            if ((*argv[i])=='-')
            {
                const char *p=argv[i]+1;

                while ((*p)!='\0')
                {
                    char c=*(p++);;
                    if ((c=='o') || (c=='O'))
                        opt_overwrite = 1;
                    if ((c=='a') || (c=='A'))
                        opt_overwrite = 2;
                    if ((c>='0') && (c<='9'))
                        opt_compress_level = c-'0';
                    if ((c=='j') || (c=='J'))
                        opt_exclude_path = 1;

                    if (((c=='p') || (c=='P')) && (i+1<argc))
                    {
                        password=argv[i+1];
                        i++;
                    }
                }
            }
            else
            {
                if (zipfilenamearg == 0)
                {
                    zipfilenamearg = i ;
                }
            }
        }
    }

    size_buf = WRITEBUFFERSIZE;
    buf = (void*)malloc(size_buf);
    if (buf==NULL)
    {
        printf("Error allocating memory\n");
        return ZIP_INTERNALERROR;
    }

    if (zipfilenamearg==0)
    {
        zipok=0;
    }
    else
    {
        int i,len;
        int dot_found=0;

        zipok = 1 ;
        strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1);
        /* strncpy doesnt append the trailing NULL, of the string is too long. */
        filename_try[ MAXFILENAME ] = '\0';

        len=(int)strlen(filename_try);
        for (i=0;i<len;i++)
            if (filename_try[i]=='.')
                dot_found=1;

        if (dot_found==0)
            strcat(filename_try,".zip");

        if (opt_overwrite==2)
        {
            /* if the file don't exist, we not append file */
            if (check_exist_file(filename_try)==0)
                opt_overwrite=1;
        }
        else
        if (opt_overwrite==0)
            if (check_exist_file(filename_try)!=0)
            {
                char rep=0;
                do
                {
                    char answer[128];
                    int ret;
                    printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
                    ret = scanf("%1s",answer);
                    if (ret != 1)
                    {
                       exit(EXIT_FAILURE);
                    }
                    rep = answer[0] ;
                    if ((rep>='a') && (rep<='z'))
                        rep -= 0x20;
                }
                while ((rep!='Y') && (rep!='N') && (rep!='A'));
                if (rep=='N')
                    zipok = 0;
                if (rep=='A')
                    opt_overwrite = 2;
            }
    }

    if (zipok==1)
    {
        zipFile zf;
        int errclose;
#        ifdef USEWIN32IOAPI
        zlib_filefunc64_def ffunc;
        fill_win32_filefunc64A(&ffunc);
        zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
#        else
        zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0);
#        endif

        if (zf == NULL)
        {
            printf("error opening %s\n",filename_try);
            err= ZIP_ERRNO;
        }
        else
            printf("creating %s\n",filename_try);

        for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
        {
            if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
                  ((argv[i][1]=='o') || (argv[i][1]=='O') ||
                   (argv[i][1]=='a') || (argv[i][1]=='A') ||
                   (argv[i][1]=='p') || (argv[i][1]=='P') ||
                   ((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
                  (strlen(argv[i]) == 2)))
            {
                FILE * fin;
                int size_read;
                const char* filenameinzip = argv[i];
                const char *savefilenameinzip;
                zip_fileinfo zi;
                unsigned long crcFile=0;
                int zip64 = 0;

                zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
                zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
                zi.dosDate = 0;
                zi.internal_fa = 0;
                zi.external_fa = 0;
                filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);

/*
                err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
                                 NULL,0,NULL,0,NULL / * comment * /,
                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
                                 opt_compress_level);
*/
                if ((password != NULL) && (err==ZIP_OK))
                    err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);

                zip64 = isLargeFile(filenameinzip);

                                                         /* The path name saved, should not include a leading slash. */
               /*if it did, windows/xp and dynazip couldn't read the zip file. */
                 savefilenameinzip = filenameinzip;
                 while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' )
                 {
                     savefilenameinzip++;
                 }

                 /*should the zip file contain any path at all?*/
                 if( opt_exclude_path )
                 {
                     const char *tmpptr;
                     const char *lastslash = 0;
                     for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
                     {
                         if( *tmpptr == '\\' || *tmpptr == '/')
                         {
                             lastslash = tmpptr;
                         }
                     }
                     if( lastslash != NULL )
                     {
                         savefilenameinzip = lastslash+1; // base filename follows last slash.
                     }
                 }

                 /**/
                err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi,
                                 NULL,0,NULL,0,NULL /* comment*/,
                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
                                 opt_compress_level,0,
                                 /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                                 password,crcFile, zip64);

                if (err != ZIP_OK)
                    printf("error in opening %s in zipfile\n",filenameinzip);
                else
                {
                    fin = FOPEN_FUNC(filenameinzip,"rb");
                    if (fin==NULL)
                    {
                        err=ZIP_ERRNO;
                        printf("error in opening %s for reading\n",filenameinzip);
                    }
                }

                if (err == ZIP_OK)
                    do
                    {
                        err = ZIP_OK;
                        size_read = (int)fread(buf,1,size_buf,fin);
                        if (size_read < size_buf)
                            if (feof(fin)==0)
                        {
                            printf("error in reading %s\n",filenameinzip);
                            err = ZIP_ERRNO;
                        }

                        if (size_read>0)
                        {
                            err = zipWriteInFileInZip (zf,buf,size_read);
                            if (err<0)
                            {
                                printf("error in writing %s in the zipfile\n",
                                                 filenameinzip);
                            }

                        }
                    } while ((err == ZIP_OK) && (size_read>0));

                if (fin)
                    fclose(fin);

                if (err<0)
                    err=ZIP_ERRNO;
                else
                {
                    err = zipCloseFileInZip(zf);
                    if (err!=ZIP_OK)
                        printf("error in closing %s in the zipfile\n",
                                    filenameinzip);
                }
            }
        }
        errclose = zipClose(zf,NULL);
        if (errclose != ZIP_OK)
            printf("error in closing %s\n",filename_try);
    }
    else
    {
       do_help();
    }

    free(buf);
    return 0;
}
Exemplo n.º 17
0
int TRI_ZipFile(char const* filename, char const* dir,
                std::vector<std::string> const& files, char const* password) {
  void* buffer;
#ifdef USEWIN32IOAPI
  zlib_filefunc64_def ffunc;
#endif

  if (TRI_ExistsFile(filename)) {
    return TRI_ERROR_CANNOT_OVERWRITE_FILE;
  }

  int bufferSize = 16384;
  buffer = TRI_Allocate(TRI_UNKNOWN_MEM_ZONE, (size_t)bufferSize, false);

  if (buffer == nullptr) {
    return TRI_ERROR_OUT_OF_MEMORY;
  }

#ifdef USEWIN32IOAPI
  fill_win32_filefunc64A(&ffunc);
  zipFile zf = zipOpen2_64(filename, 0, NULL, &ffunc);
#else
  zipFile zf = zipOpen64(filename, 0);
#endif

  if (zf == nullptr) {
    TRI_Free(TRI_UNKNOWN_MEM_ZONE, buffer);

    return ZIP_ERRNO;
  }

  int res = TRI_ERROR_NO_ERROR;

  size_t n = files.size();
  for (size_t i = 0; i < n; ++i) {
    std::string fullfile;

    if (*dir == '\0') {
      fullfile = files[i];
    } else {
      fullfile = arangodb::basics::FileUtils::buildFilename(dir, files[i]);
    }

    zip_fileinfo zi;
    memset(&zi, 0, sizeof(zi));

    uint32_t crc;
    res = TRI_Crc32File(fullfile.c_str(), &crc);

    if (res != TRI_ERROR_NO_ERROR) {
      break;
    }

    int isLarge = (TRI_SizeFile(files[i].c_str()) > 0xFFFFFFFFLL);

    char const* saveName = files[i].c_str();

    while (*saveName == '\\' || *saveName == '/') {
      ++saveName;
    }

    if (zipOpenNewFileInZip3_64(
            zf, saveName, &zi, NULL, 0, NULL, 0, NULL, /* comment*/
            Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL,
            Z_DEFAULT_STRATEGY, password, (unsigned long)crc,
            isLarge) != ZIP_OK) {
      res = TRI_ERROR_INTERNAL;
      break;
    }

    FILE* fin = fopen(fullfile.c_str(), "rb");

    if (fin == nullptr) {
      break;
    }

    while (true) {
      int sizeRead = (int)fread(buffer, 1, bufferSize, fin);
      if (sizeRead < bufferSize) {
        if (feof(fin) == 0) {
          res = TRI_set_errno(TRI_ERROR_SYS_ERROR);
          break;
        }
      }

      if (sizeRead > 0) {
        res = zipWriteInFileInZip(zf, buffer, sizeRead);
        if (res != 0) {
          break;
        }
      } else /* if (sizeRead <= 0) */ {
        break;
      }
    }

    fclose(fin);

    zipCloseFileInZip(zf);

    if (res != TRI_ERROR_NO_ERROR) {
      break;
    }
  }

  zipClose(zf, NULL);

  TRI_Free(TRI_UNKNOWN_MEM_ZONE, buffer);

  return res;
}
Exemplo n.º 18
0
bool MakeZip(TCHAR *tszSource, TCHAR *tszDest, TCHAR *dbname, HWND progress_dialog)
{
    bool ret = false;
    HANDLE hSrc;
    zipFile hZip;
    SYSTEMTIME st;
    WIN32_FILE_ATTRIBUTE_DATA fad = { 0 };
    zip_fileinfo fi = { 0 };
    HWND hProgBar;
    DWORD dwRead;
    MSG msg;
    char buf[(256 * 1024)];	// 256 KB
    DWORDLONG dwSrcFileSize, dwTotalBytes = 0;

    ptrA szSourceName(mir_u2a(dbname));
    ptrT tszDestPath(DoubleSlash(tszDest));

    hSrc = CreateFile(tszSource, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hSrc == INVALID_HANDLE_VALUE)
        return ret;
    if (GetFileAttributesEx(tszSource, GetFileExInfoStandard, &fad) == FALSE)
        goto err_out;
    dwSrcFileSize = ((DWORDLONG)fad.nFileSizeLow | (((DWORDLONG)fad.nFileSizeHigh) << 32));
    if (dwSrcFileSize == 0) /* Prevent division by zero error. */
        goto err_out;
    FileTimeToLocalFileTime(&fad.ftLastWriteTime, &fad.ftLastWriteTime);
    FileTimeToSystemTime(&fad.ftLastWriteTime, &st);
    hZip = zipOpen2_64(tszDestPath, APPEND_STATUS_CREATE, NULL, NULL);
    if (hZip == NULL)
        goto err_out;
    fi.tmz_date.tm_sec = st.wSecond;
    fi.tmz_date.tm_min = st.wMinute;
    fi.tmz_date.tm_hour = st.wHour;
    fi.tmz_date.tm_mday = st.wDay;
    fi.tmz_date.tm_mon = (st.wMonth - 1);
    fi.tmz_date.tm_year = st.wYear;

    if (zipOpenNewFileInZip(hZip, szSourceName, &fi, NULL, 0, NULL, 0, "", Z_DEFLATED, Z_BEST_COMPRESSION) == ZIP_OK) {
        hProgBar = GetDlgItem(progress_dialog, IDC_PROGRESS);
        while (GetWindowLongPtr(progress_dialog, GWLP_USERDATA) != 1) {
            if (!ReadFile(hSrc, buf, sizeof(buf), &dwRead, NULL))
                break;
            if (dwRead == 0) { // EOF
                ret = true;
                break;
            }
            if (zipWriteInFileInZip(hZip, buf, dwRead) != ZIP_OK)
                break;
            dwTotalBytes += dwRead;
            SendMessage(hProgBar, PBM_SETPOS, (WPARAM)((100 * dwTotalBytes) / dwSrcFileSize), 0);
            while (PeekMessage(&msg, progress_dialog, 0, 0, PM_REMOVE) != 0) {
                if (progress_dialog == NULL || !IsDialogMessage(progress_dialog, &msg)) { /* Wine fix. */
                    TranslateMessage(&msg);
                    DispatchMessage(&msg);
                }
            }
        }
        zipCloseFileInZip(hZip);
    }
    if (ret) {
        mir_snprintf(buf, "%s\r\n%s %s %d.%d.%d.%d\r\n",
                     Translate("Miranda NG database"), Translate("Created by:"),
                     __PLUGIN_NAME, __MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM);
    }
    else {
        buf[0] = 0;
    }
    zipClose(hZip, buf);

err_out:
    CloseHandle(hSrc);

    return ret;
}
Exemplo n.º 19
0
int PackerJob::createZipFile()
{
	int result = ZIP_ERRNO;

	zipFile zf = zipOpen2_64(m_tszFilePath, 0, nullptr, nullptr);

	if (zf != nullptr) {
		result = ZIP_OK;

		int size_buf = 65536;
		void *buff = (void *)mir_alloc(size_buf);

		for (UINT i = 0; i < m_files.size(); i++) {
			int size_read;
			zip_fileinfo zi;

			zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = 0;
			zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
			zi.dosDate = 0;
			zi.internal_fa = 0;
			zi.external_fa = 0;

			getFileTime(m_files[i], &zi.tmz_date, &zi.dosDate);

			char *file = mir_u2a(Utils::getFileNameFromPath(m_files[i]));
			int err = zipOpenNewFileInZip(zf, file, &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, opt.iCompressionLevel);
			FREE(file);

			if (err == ZIP_OK) {
				FILE *fin = _wfopen(m_files[i], L"rb");
				if (fin) {
					do {
						if (isCanceled()) {
							fclose(fin);
							result = STATUS_CANCELED;
							goto Cleanup;
						}

						err = ZIP_OK;
						size_read = (int)fread(buff, 1, size_buf, fin);
						if (size_read < size_buf && feof(fin) == 0) {
							fclose(fin);
							result = ZIP_ERRNO;
							goto Cleanup;
						}

						if (size_read > 0) {
							err = zipWriteInFileInZip(zf, buff, size_read);
							m_uiReaded += size_read;
						}

						updateStats();
					} while ((err == ZIP_OK) && (size_read > 0));
					fclose(fin);
				}
				else err = ZIP_ERRNO;

				err = zipCloseFileInZip(zf);
				if (err < 0) {
					result = ZIP_ERRNO;
					goto Cleanup;
				}
			}
			else {
				result = ZIP_ERRNO;
				break;
			}
		}

Cleanup:
		zipClose(zf, nullptr);
		FREE(buff);
	}

	return result;
}