BackupPC-XS

 view release on metacpan or  search on metacpan

bpc_fileZIO.c  view on Meta::CPAN

/*
 * Routines for reading and writing compressed files using zlib
 *
 * Copyright (C) 2013 Craig Barratt.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, visit the http://fsf.org website.
 */

#include "backuppc.h"

/*
 * A freelist of unused data buffers.
 * We use the first sizeof(void*) bytes of the buffer as a single-linked
 * list, with a NULL at the end.
 */
static void *DataBufferFreeList = (void*)NULL;

/*
 * Open a regular or compressed file for reading or writing/create
 */
int bpc_fileZIO_open(bpc_fileZIO_fd *fd, char *fileName, int writeFile, int compressLevel)
{
    fd->strm.next_out  = NULL;
    fd->strm.zalloc    = NULL;
    fd->strm.zfree     = NULL;
    fd->strm.opaque    = NULL;

    fd->compressLevel  = compressLevel;
    fd->first          = 1;
    fd->write          = writeFile;
    fd->eof            = 0;
    fd->error          = 0;
    fd->writeTeeStderr = 0;

    fd->lineBuf        = NULL;
    fd->lineBufSize    = 0;
    fd->lineBufLen     = 0;
    fd->lineBufIdx     = 0;
    fd->lineBufEof     = 0;

    fd->bufSize = 1 << 20;       /* 1MB */
    if ( writeFile ) {
        fd->fd = open(fileName, O_WRONLY | O_CREAT | O_TRUNC, 0660);
        if ( fd->fd < 0 ) {
            /*
             * try removing first
             */
            unlink(fileName);
            fd->fd = open(fileName, O_WRONLY | O_CREAT | O_TRUNC, 0660);
        }
        if ( fd->fd < 0 ) return -1;
        if ( fd->compressLevel ) {
            if (deflateInit2(&fd->strm, compressLevel, Z_DEFLATED, MAX_WBITS, 8,
                                         Z_DEFAULT_STRATEGY) != Z_OK) {
                bpc_logErrf("bpc_fileZIO_open: compression init failed\n");
                return -1;
            }
            fd->strm.next_out  = (Bytef*)fd->buf;
            fd->strm.avail_out = fd->bufSize;
        }
    } else {
        fd->fd = open(fileName, O_RDONLY);
        if ( fd->fd < 0 ) return -1;
        if ( fd->compressLevel ) {
            if ( inflateInit(&fd->strm) != Z_OK ) {
                bpc_logErrf("bpc_fileZIO_open: compression init failed\n");
                return -1;
            }
            fd->strm.avail_in = 0;



( run in 0.562 second using v1.01-cache-2.11-cpan-39bf76dae61 )