示例#1
0
void ZipWriter::addFile(std::string name, const void* ptr, unsigned size) {
    auto t = time(nullptr);
    auto tm = *localtime(&t);
    zip_fileinfo info{{(unsigned)tm.tm_sec,
                       (unsigned)tm.tm_min,
                       (unsigned)tm.tm_hour,
                       (unsigned)tm.tm_mday,
                       (unsigned)tm.tm_mon,
                       (unsigned)tm.tm_year + 1900},
                      0,
                      0,
                      0};
    auto ret = zipOpenNewFileInZip64(_zip,
                          name.c_str(),
                          &info,
                          nullptr,
                          0,
                          nullptr,
                          0,
                          nullptr,
                          Z_DEFLATED,
                          Z_DEFAULT_COMPRESSION,
                          1);
    if (ret)
        throw std::runtime_error("can't add a new file to zip");
    ret = zipWriteInFileInZip(_zip, ptr, size);
    if (ret)
        throw std::runtime_error("can't write to zip");
    ret = zipCloseFileInZip(_zip);
    if (ret)
        throw std::runtime_error("can't save zip");
}
示例#2
0
int ZipArchiveWriter::AddFileItem(IStreamBase* inputStream, const std::string& strNameInZip, int compressFlag)
{
    if (!inputStream || !inputStream->Open())
        return -1;

    zip_fileinfo zi = {0};
    zi.dosDate = (uLong)time(nullptr);

    m_errCode = zipOpenNewFileInZip64(m_hZip, strNameInZip.c_str(), &zi, NULL, 0, NULL, 0, NULL, compressFlag, Z_DEFAULT_COMPRESSION, 1);
    if (m_errCode == ZIP_OK)
    {
        int nRead = 0;
        unsigned char buffer[32768];

        while (m_errCode == ZIP_OK)
        {
            nRead = inputStream->Read(buffer, sizeof(buffer)/sizeof(buffer[0]));
            if (nRead <= 0)
                break;

            m_errCode = zipWriteInFileInZip(m_hZip, buffer, nRead);
        }

        zipCloseFileInZip(m_hZip);

        if (m_errCode == ZIP_OK)
        {
            return 0;
        }
    }

    return -2;
}
示例#3
0
static duk_ret_t dukzip_zip_newfile(duk_context *ctx) {
	zip_fileinfo zi = {0};
	int res = ZIP_OK;
	zipFile archive = dukzip_zip_from_this(ctx);
	
	const char *filename = "";
	duk_int_t level = Z_DEFAULT_COMPRESSION;
	duk_int_t method = Z_DEFLATED;
	const char *comment = "";


	if (duk_is_object(ctx, 0)) {
		dukzip_zip_checkoptions(ctx, 0, &filename, &level, &method, &comment);
	} else {
		filename = duk_require_string(ctx, 0);

		if (duk_is_number(ctx, 1)) {
			level = duk_get_int(ctx, 1);
		}
	}

	res = zipOpenNewFileInZip64(archive, filename, &zi, NULL, 0, NULL, 0, comment, method, level, 1);

	if (res == ZIP_OK) {
		duk_push_true(ctx);
	} else {
		duk_push_false(ctx);
	}
	return 1;
}
示例#4
0
static bool AppendFileToZip(zipFile& zf, const WCHAR *nameInZip, const char *fileData, size_t fileSize)
{
    ScopedMem<char> nameInZipUtf(str::conv::ToUtf8(nameInZip));
    str::TransChars(nameInZipUtf, "\\", "/");
    zip_fileinfo zi = { 0 };
    int err = zipOpenNewFileInZip64(zf, nameInZipUtf, &zi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 1);
    if (ZIP_OK == err) {
        err = zipWriteInFileInZip(zf, fileData, fileSize);
        if (ZIP_OK == err)
            err = zipCloseFileInZip(zf);
        else
            zipCloseFileInZip(zf);
    }
    return ZIP_OK == err;
}
示例#5
0
int ZipArchiveWriter::AddDirItem(const std::string& dirPath)
{
    if (dirPath.empty())
        return -1;

    std::string folderNameInZip = ReplaceWin32PathSep(dirPath);

    std::string::size_type slen = folderNameInZip.size();

    if (folderNameInZip[slen - 1] != '/')
    {
        folderNameInZip.push_back('/');
    }

    zip_fileinfo zi = {0};
    m_errCode = zipOpenNewFileInZip64(m_hZip, folderNameInZip.c_str(), &zi, NULL, 0, NULL, 0, NULL, 0, Z_DEFAULT_COMPRESSION, 0);
    if (m_errCode == ZIP_OK)
    {
        m_errCode = zipCloseFileInZip(m_hZip);
    }

    return (m_errCode == ZIP_OK) ? 0 : -1;
}
示例#6
0
文件: zip.cpp 项目: h2so5/PaintField
bool ZipFile::open()
{
	if (d->filepath.isEmpty())
	{
		PAINTFIELD_WARNING << "file path not specified";
		return false;
	}
	
	if (d->archive->d->currentZipFile)
	{
		PAINTFIELD_WARNING << "another ZipFile already opened";
		return false;
	}
	
	if (zipOpenNewFileInZip64(d->archive->d->zip, d->filepath.toLocal8Bit(), 0, 0, 0, 0, 0, 0, (d->method == MethodStored) ? 0 : Z_DEFLATED, Z_DEFAULT_COMPRESSION, 1) != ZIP_OK)
	{
		PAINTFIELD_WARNING << "cannot open file in archive";
		return false;
	}
	
	setOpenMode(WriteOnly);
	return true;
}
示例#7
0
  void ZipWriter::OpenFile(const char* path)
  {
    Open();

    zip_fileinfo zfi;
    PrepareFileInfo(zfi);

    int result;

    if (isZip64_)
    {
      result = zipOpenNewFileInZip64(pimpl_->file_, path,
                                     &zfi,
                                     NULL,   0,
                                     NULL,   0,
                                     "",  // Comment
                                     Z_DEFLATED,
                                     compressionLevel_, 1);
    }
    else
    {
      result = zipOpenNewFileInZip(pimpl_->file_, path,
                                   &zfi,
                                   NULL,   0,
                                   NULL,   0,
                                   "",  // Comment
                                   Z_DEFLATED,
                                   compressionLevel_);
    }

    if (result != 0)
    {
      throw OrthancException(ErrorCode_CannotWriteFile);
    }

    hasFileInZip_ = true;
  }
示例#8
0
文件: smzip.cpp 项目: pmrowla/sm-zip
static cell_t Zip_AddFile(IPluginContext *pCtx, const cell_t *params)
{
    Handle_t handle = static_cast<Handle_t>(params[1]);
    HandleError err;
    HandleSecurity sec;
    cell_t ret = true;

    sec.pOwner = NULL;
    sec.pIdentity = myself->GetIdentity();

    zipFile zf;
    err = handlesys->ReadHandle(handle, g_ZipFileType, &sec, (void **)&zf);
    if (HandleError_None != err)
    {
        return pCtx->ThrowNativeError("Invalid Zip file handle %x (error %d)", handle, err);
    }

    char path[PLATFORM_MAX_PATH];
    char *filename;
    pCtx->LocalToString(params[2], &filename);
    g_pSM->BuildPath(Path_Game, path, sizeof(path), "%s", filename);

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

    int zipErr = zipOpenNewFileInZip64(zf, filename, &zi, NULL, 0, NULL, 0, NULL,
            Z_DEFLATED, Z_DEFAULT_COMPRESSION, isLargeFile(path));
    if (ZIP_OK != zipErr)
    {
        g_pSM->LogError(myself, "Could not open new file %s in zip (%d)", filename, err);
        return false;
    }

    FILE *fp = fopen64(path, "rb");
    if (NULL == fp)
    {
        g_pSM->LogError(myself, "fopen64(%s) failed", path);
        ret = false;
    }

    if (ret)
    {
        char buf[4096];
        size_t bytesRead = 0;

        do
        {
            zipErr = ZIP_OK;
            bytesRead = fread(buf, 1, sizeof(buf), fp);
            if (bytesRead < sizeof(buf) && feof(fp) != 0)
            {
                zipErr = ZIP_ERRNO;
            }

            if (bytesRead > 0)
            {
                zipErr = zipWriteInFileInZip(zf, buf, bytesRead);
            }

            if (ZIP_ERRNO == zipErr && EAGAIN == errno)
                zipErr = ZIP_OK;

        } while (ZIP_OK == zipErr && bytesRead > 0);

        if (ZIP_OK != zipErr)
        {
            if (ZIP_ERRNO == zipErr)
                g_pSM->LogError(myself, "Failed to write to zip archive (%s)", strerror(errno));
            else
                g_pSM->LogError(myself, "Failed to write to zip archive (%d)", zipErr);
            ret = false;
        }
    }

    if (fp)
        fclose(fp);

    zipCloseFileInZip(zf);
    return ret;
}
示例#9
0
static duk_ret_t dukzip_zip_add(duk_context *ctx) {
	zip_fileinfo zi = {0};
	int res = ZIP_OK;
	zipFile archive = dukzip_zip_from_this(ctx);
	
	const char *filename = "";
	duk_int_t level = Z_DEFAULT_COMPRESSION;
	duk_int_t method = Z_DEFLATED;
	const char *comment = "";

	int datalen = 0;
	void *data = NULL;

	if (duk_is_object(ctx, 0)) {
		dukzip_zip_checkoptions(ctx, 0, &filename, &level, &method, &comment);

		duk_get_prop_string(ctx, 0, "data");
		if (duk_is_string(ctx, -1)) {
			data = (void *)duk_get_lstring(ctx, -1, &datalen);
		} else if (duk_is_buffer(ctx, -1) || duk_is_object(ctx, -1)) {
			data = duk_require_buffer_data(ctx, -1, &datalen);
		} else {
			duk_error(ctx, DUK_ERR_TYPE_ERROR, "unable to write data to zip file (supported types: string, buffer)");
			return -1;
		}

	} else {
		filename = duk_require_string(ctx, 0);

		if (duk_is_string(ctx, 1)) {
			data = (void *)duk_get_lstring(ctx, 1, &datalen);
		} else if (duk_is_buffer(ctx, 1) || duk_is_object(ctx, 1)) {
			data = duk_require_buffer_data(ctx, 1, &datalen);
		} else {
			duk_error(ctx, DUK_ERR_TYPE_ERROR, "unable to write argument to zip file (supported types: string, buffer)");
			return -1;
		}

		if (duk_is_number(ctx, 2)) {
			level = duk_get_int(ctx, 2);
		}

		/* push dummy to normalize stack */
		duk_push_string(ctx, "dummy");
	}

	res = zipOpenNewFileInZip64(archive, filename, &zi, NULL, 0, NULL, 0, comment, method, level, 1);
	if (res != ZIP_OK) {
		goto error;
	}

	res = zipWriteInFileInZip(archive, data, datalen);
	if (res != ZIP_OK) {
		goto error;
	}

	res = zipCloseFileInZip(archive);
	duk_pop(ctx); /* pop buffer (or dummy) from stack */

	if (res == ZIP_OK) {
		duk_push_true(ctx);
	} else {
		duk_push_false(ctx);
	}
	return 1;

error:
	zipCloseFileInZip(archive);
	duk_error(ctx, DUK_ERR_INTERNAL_ERROR, "could not write file '%s'", filename);
	return -1;

}
示例#10
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);
}