Example #1
0
int
main(int argc, char *argv[])
{
    int fail, ze;
    struct zip *z;
    struct zip_source *zs;
    char *archive;
    char errstr[1024];

    fail = 0;

    prg = argv[0];

    if (argc != 2) {
        fprintf(stderr, "usage: %s archive\n", prg);
        return 1;
    }

    archive = argv[1];

    if ((z=zip_open(archive, 0, &ze)) == NULL) {
	zip_error_to_str(errstr, sizeof(errstr), ze, errno);
	printf("%s: opening zip archive ``%s'' failed: %s\n",
	       prg, archive, errstr);
	return 1;
    }

    fail += do_read(z, "storedok", 0, WHEN_NEVER, 0, 0);
    fail += do_read(z, "deflateok", 0, WHEN_NEVER, 0, 0);
    fail += do_read(z, "storedcrcerror", 0, WHEN_READ, ZIP_ER_CRC, 0);
    fail += do_read(z, "deflatecrcerror", 0, WHEN_READ, ZIP_ER_CRC, 0);
    fail += do_read(z, "deflatezliberror", 0, WHEN_READ, ZIP_ER_ZLIB, -3);
    fail += do_read(z, NULL, 0, WHEN_OPEN, ZIP_ER_INVAL, 0);
    fail += do_read(z, "nosuchfile", 0, WHEN_OPEN, ZIP_ER_NOENT, 0);
    fail += do_read(z, "deflatezliberror", ZIP_FL_COMPRESSED, WHEN_NEVER, 0,0);
    fail += do_read(z, "deflatecrcerror", ZIP_FL_COMPRESSED, WHEN_NEVER, 0, 0);
    fail += do_read(z, "storedcrcerror", ZIP_FL_COMPRESSED,
		    WHEN_READ, ZIP_ER_CRC, 0);
    fail += do_read(z, "storedok", ZIP_FL_COMPRESSED, WHEN_NEVER, 0, 0);

    zs = zip_source_buffer(z, "asdf", 4, 0);
    zip_replace(z, zip_name_locate(z, "storedok", 0), zs);
    fail += do_read(z, "storedok", 0, WHEN_OPEN, ZIP_ER_CHANGED, 0);
    fail += do_read(z, "storedok", ZIP_FL_UNCHANGED, WHEN_NEVER, 0, 0);
    zip_delete(z, zip_name_locate(z, "storedok", 0));
    fail += do_read(z, "storedok", 0, WHEN_OPEN, ZIP_ER_NOENT, 0);
    fail += do_read(z, "storedok", ZIP_FL_UNCHANGED, WHEN_NEVER, 0, 0);
    zs = zip_source_buffer(z, "asdf", 4, 0);
    zip_add(z, "new_file", zs);
    fail += do_read(z, "new_file", 0, WHEN_OPEN, ZIP_ER_CHANGED, 0);
    zip_unchange_all(z);

    if (zip_close(z) == -1) {
        fprintf(stderr, "%s: can't close zip archive `%s'\n", prg, archive);
        return 1;
    }

    exit(fail ? 1 : 0);
}
Example #2
0
int r_io_zip_flush_file(RIOZipFileObj *zfo) {
	int res = false;
	struct zip * zipArch;

	if (!zfo) {
		return res;
	}

	zipArch = r_io_zip_open_archive (
		zfo->archivename, zfo->perm, zfo->mode, zfo->rw);
	if (!zipArch) {
		return res;
	}

	struct zip_source *s = zip_source_buffer (zipArch, zfo->b->buf, zfo->b->length, 0);
	if (s && zfo->entry != -1) {
		if (zip_replace(zipArch, zfo->entry, s) == 0) {
			res = true;
		}
	} else if (s && zfo->name) {
		if (zip_add (zipArch, zfo->name, s) == 0) {
			zfo->entry = zip_name_locate (zipArch, zfo->name, 0);
			res = true;
		}
	}
	// s (zip_source) is freed when the archive is closed, i think - dso
	zip_close (zipArch);
	if (s) {
		zip_source_free (s);
	}
	return res;
}
Example #3
0
bool zipobject::writeData(const QByteArray& data,const QString& inZipPath){
    TEST_ZIP;
    int length=data.length();
    void* p=new char[length+1];
    // 此处不得不复制。
    // 由于 libzip 只会在 close 的时候才会真正将数据写入zip文件
    // 如果不复制,写入数据时 data 已经析构,数据内容全部为空
    memcpy(p,data.constData(),length);
    zip_source* pSource = zip_source_buffer(m_zip,p,length,1);
    if(NULL == pSource){
        const char* pStr = zip_strerror(m_zip);
        qDebug()<<"create source failed : "<<pStr;
        return false;
    }else{
        int index = zip_name_locate(m_zip,getCharPtr(inZipPath),0);
        if( -1 == index ){
            int rAdd = zip_add(m_zip,getCharPtr(inZipPath),pSource);
            if( -1 == rAdd ){
                qDebug()<<"add source failed : "<<zip_strerror(m_zip);
            }
            return -1 == rAdd ;
        }else{
            int rReplace = zip_replace(m_zip,index,pSource);
            if( -1 == rReplace ){
                qDebug()<<"replace source failed : "<<zip_strerror(m_zip);
            }
            return -1 == rReplace ;
        }
    }
}
Example #4
0
static VALUE zipruby_archive_add_buffer(VALUE self, VALUE name, VALUE source) {
  struct zipruby_archive *p_archive;
  struct zip_source *zsource;
  char *data;
  size_t len;

  Check_Type(name, T_STRING);
  Check_Type(source, T_STRING);
  Data_Get_Struct(self, struct zipruby_archive, p_archive);
  Check_Archive(p_archive);

  len = RSTRING_LEN(source);

  if ((data = malloc(len)) == NULL) {
    rb_raise(rb_eRuntimeError, "Add file failed: Cannot allocate memory");
  }

  memset(data, 0, len);
  memcpy(data, RSTRING_PTR(source), len);

  if ((zsource = zip_source_buffer(p_archive->archive, data, len, 1)) == NULL) {
    free(data);
    rb_raise(Error, "Add file failed - %s: %s", RSTRING_PTR(name), zip_strerror(p_archive->archive));
  }

  if (zip_add(p_archive->archive, RSTRING_PTR(name), zsource) == -1) {
    zip_source_free(zsource);
    zip_unchange_all(p_archive->archive);
    zip_unchange_archive(p_archive->archive);
    rb_raise(Error, "Add file failed - %s: %s", RSTRING_PTR(name), zip_strerror(p_archive->archive));
  }

  return Qnil;
}
Example #5
0
int r_io_zip_flush_file(RIOZipFileObj *zip_file_obj) {
	int result = R_FALSE;
	struct zip * zipArch = r_io_zip_open_archive(zip_file_obj->archivename, zip_file_obj->flags, zip_file_obj->mode, zip_file_obj->rw);  

	if (!zipArch) {
		return result;
	}

	if (zip_file_obj) {
		struct zip_source *s = zip_source_buffer(zipArch, zip_file_obj->b, zip_file_obj->b->length, 0);
		if (s && zip_file_obj->entry != -1) {

			if (zip_replace(zipArch, zip_file_obj->entry, s) == 0)
				result = R_TRUE;

		}else if (s && zip_file_obj->name) {

			if (zip_add(zipArch, zip_file_obj->name, s) == 0) {

				zip_file_obj->entry = zip_name_locate(zipArch, zip_file_obj->name, 0);
				result = R_TRUE;
			}
		}
		if (s)
			zip_source_free(s);		

	}

	if (zipArch)
		zip_close(zipArch);

	return result;
}
Example #6
0
static struct zip_source* S_create_source_string(lua_State* L, struct zip* ar) {
    size_t             len;
    const char*        str = luaL_checklstring(L, 4, &len);
    struct zip_source* src = zip_source_buffer(ar, str, len, 0);

    if ( NULL != src ) return src;

    S_archive_add_ref(L, 0, 1, 4);

    lua_pushstring(L, zip_strerror(ar));
    lua_error(L);
}
Example #7
0
 void SetFileData(const utf8 * path, void * data, size_t dataSize) override
 {
     zip_source_t * source = zip_source_buffer(_zip, data, dataSize, 0);
     sint64 index = zip_name_locate(_zip, path, 0);
     if (index == -1)
     {
         zip_add(_zip, path, source);
     }
     else
     {
         zip_replace(_zip, index, source);
     }
 }
Example #8
0
ZIP_EXTERN zip_int64_t
zip_dir_add(struct zip *za, const char *name, zip_flags_t flags)
{
    size_t len;
    zip_int64_t idx;
    char *s;
    struct zip_source *source;

    if (ZIP_IS_RDONLY(za)) {
	_zip_error_set(&za->error, ZIP_ER_RDONLY, 0);
	return -1;
    }

    if (name == NULL) {
	_zip_error_set(&za->error, ZIP_ER_INVAL, 0);
	return -1;
    }

    s = NULL;
    len = strlen(name);

    if (name[len-1] != '/') {
	if ((s=(char *)malloc(len+2)) == NULL) {
	    _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
	    return -1;
	}
	strcpy(s, name);
	s[len] = '/';
	s[len+1] = '\0';
    }

    if ((source=zip_source_buffer(za, NULL, 0, 0)) == NULL) {
	free(s);
	return -1;
    }
	
    idx = _zip_file_replace(za, ZIP_UINT64_MAX, s ? s : name, source, flags);

    free(s);

    if (idx < 0)
	zip_source_free(source);
    else {
	if (zip_file_set_external_attributes(za, (zip_uint64_t)idx, 0, ZIP_OPSYS_DEFAULT, ZIP_EXT_ATTRIB_DEFAULT_DIR) < 0) {
	    zip_delete(za, (zip_uint64_t)idx);
	    return -1;
	}
    }

    return idx;
}
Example #9
0
static VALUE zipruby_archive_replace_buffer(int argc, VALUE *argv, VALUE self) {
  struct zipruby_archive *p_archive;
  struct zip_source *zsource;
  VALUE index, source, flags;
  int i_index, i_flags = 0;
  char *data;
  size_t len;

  rb_scan_args(argc, argv, "21", &index, &source, &flags);

  if (TYPE(index) != T_STRING && !FIXNUM_P(index)) {
    rb_raise(rb_eTypeError, "wrong argument type %s (expected Fixnum or String)", rb_class2name(CLASS_OF(index)));
  }

  if (!NIL_P(flags)) {
    i_flags = NUM2INT(flags);
  }

  Check_Type(source, T_STRING);
  Data_Get_Struct(self, struct zipruby_archive, p_archive);
  Check_Archive(p_archive);

  if (FIXNUM_P(index)) {
    i_index = NUM2INT(index);
  } else if ((i_index = zip_name_locate(p_archive->archive, RSTRING_PTR(index), i_flags)) == -1) {
    rb_raise(Error, "Replace file failed - %s: Archive does not contain a file", RSTRING_PTR(index));
  }

  len = RSTRING_LEN(source);

  if ((data = malloc(len)) == NULL) {
    rb_raise(rb_eRuntimeError, "Replace file failed: Cannot allocate memory");
  }

  memcpy(data, RSTRING_PTR(source), len);

  if ((zsource = zip_source_buffer(p_archive->archive, data, len, 1)) == NULL) {
    free(data);
    rb_raise(Error, "Replace file failed at %d: %s", i_index, zip_strerror(p_archive->archive));
  }

  if (zip_replace(p_archive->archive, i_index, zsource) == -1) {
    zip_source_free(zsource);
    zip_unchange_all(p_archive->archive);
    zip_unchange_archive(p_archive->archive);
    rb_raise(Error, "Replace file failed at %d: %s", i_index, zip_strerror(p_archive->archive));
  }

  return Qnil;
}
Example #10
0
static int
add(int argc, char *argv[]) {
    zip_source_t *zs;

    if ((zs=zip_source_buffer(za, argv[1], strlen(argv[1]), 0)) == NULL) {
	fprintf(stderr, "can't create zip_source from buffer: %s\n", zip_strerror(za));
	return -1;
    }

    if (zip_add(za, argv[0], zs) == -1) {
	zip_source_free(zs);
	fprintf(stderr, "can't add file '%s': %s\n", argv[0], zip_strerror(za));
	return -1;
    }
    return 0;
}
Example #11
0
int
main(int argc, char *argv[])
{
    const char *archive;
    struct zip *za;
    struct zip_source *zs;
    char buf[100];
    int err;

    prg = argv[0];

    if (argc != 2) {
	fprintf(stderr, "usage: %s archive\n", prg);
	return 1;
    }

    archive = argv[1];
    
    if ((za=zip_open(archive, ZIP_CREATE, &err)) == NULL) {
	zip_error_to_str(buf, sizeof(buf), err, errno);
	fprintf(stderr, "%s: can't open zip archive '%s': %s\n", prg,
		archive, buf);
	return 1;
    }

    if ((zs=zip_source_buffer(za, teststr, strlen(teststr), 0)) == NULL) {
	fprintf(stderr, "%s: can't create zip_source from buffer: %s\n", prg,
		zip_strerror(za));
	exit(1);
    }

    if (zip_add(za, file, zs) == -1) {
	zip_source_free(zs);
	fprintf(stderr, "%s: can't add file '%s': %s\n", prg,
		file, zip_strerror(za));
	return 1;
    }

    if (zip_close(za) == -1) {
	fprintf(stderr, "%s: can't close zip archive '%s': %s\n", prg,
		archive, zip_strerror(za));
	return 1;
    }

    return 0;
}
Example #12
0
AbstractFSProvider::status_t ZIPProvider::ZIPHandle::writeFile(const FileName & file, const std::vector<uint8_t> & data, bool overwrite) {
	if (file.getFile().empty()) {
		return FAILURE;
	}

	bool replace = false;

	int index = zip_name_locate(handle, file.getPath().c_str(), 0);
	if (index != -1) {
		// File already exists.
		if (!overwrite) {
			return FAILURE;
		} else {
			replace = true;
		}
	}

	// Store data temporary because libzip writes data not until zip_close.
	tempStore.emplace_back(data);

	zip_source * source = zip_source_buffer(handle,
			tempStore.back().data(), static_cast<off_t>(tempStore.back().size()), 0);
	if (source == nullptr) {
		WARN(zip_strerror(handle));
		zip_source_free(source);
		tempStore.pop_back();
		return FAILURE;
	}

	int newIndex;
	if (replace) {
		newIndex = zip_replace(handle, index, source);
	} else {
		newIndex = zip_add(handle, file.getPath().c_str(), source);
	}
	if (newIndex == -1) {
		WARN(zip_strerror(handle));
		zip_source_free(source);
		tempStore.pop_back();
		return FAILURE;
	}
	dataWritten = true;
	return OK;
}
Example #13
0
ZIP_EXTERN zip_int64_t
zip_dir_add(struct zip *za, const char *name, zip_flags_t flags)
{
    size_t len;
    zip_int64_t ret;
    char *s;
    struct zip_source *source;

    if (ZIP_IS_RDONLY(za)) {
	_zip_error_set(&za->error, ZIP_ER_RDONLY, 0);
	return -1;
    }

    if (name == NULL) {
	_zip_error_set(&za->error, ZIP_ER_INVAL, 0);
	return -1;
    }

    s = NULL;
    len = strlen(name);

    if (name[len-1] != '/') {
	if ((s=(char *)malloc(len+2)) == NULL) {
	    _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
	    return -1;
	}
	strcpy(s, name);
	s[len] = '/';
	s[len+1] = '\0';
    }

    if ((source=zip_source_buffer(za, NULL, 0, 0)) == NULL) {
	free(s);
	return -1;
    }
	
    ret = _zip_file_replace(za, ZIP_UINT64_MAX, s ? s : name, source, flags);

    free(s);
    if (ret < 0)
	zip_source_free(source);

    return ret;
}
Example #14
0
 void ZipFileOutput::dumpFile()
 {
     if(m_currentFile)
     {
         m_bufferedFiles.push_back(m_currentFile->str());
         std::string & fileContent = m_bufferedFiles.back();
         
         zip_source* source = zip_source_buffer(m_archiveHandle, fileContent.c_str(), fileContent.size(), 0);
         if(! source)
             throw FileAccessFailed(m_currentFilename, m_archive, "Failed to allocate ZLib source.");
         
         // check if the file exists
         struct zip_stat stat;
         if(zip_stat(m_archiveHandle, m_currentFilename.c_str(), 0, &stat) < 0)
         { 
             // the file does not exist
             // add it to the archive
             if(zip_add(m_archiveHandle, m_currentFilename.c_str(), source) < 0)
             {
                 zip_source_free(source);
                 throw FileAccessFailed(m_currentFilename, m_archive, "Failed to add file to zip archive.");
             }
         }
         else
         {
             // the file exists
             // replace it in the archive
             if(zip_replace(m_archiveHandle, stat.index, source) < 0)
             {
                 zip_source_free(source);
                 throw FileAccessFailed(m_currentFilename, m_archive, "Failed to replace file in zip archive.");
             }
         }
         
         delete m_currentFile;
         m_currentFile = 0;
     }
 }
Example #15
0
ZIP_EXTERN int
zip_add_dir(struct zip *za, const char *name)
{
    int len, ret;
    char *s;
    struct zip_source *source;

    if (name == NULL) {
	_zip_error_set(&za->error, ZIP_ER_INVAL, 0);
	return -1;
    }

    s = NULL;
    len = (int)strlen(name);

    if (name[len-1] != '/') {
	if ((s=(char *)malloc(len+2)) == NULL) {
	    _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
	    return -1;
	}
	strcpy(s, name);
	s[len] = '/';
	s[len+1] = '\0';
    }

    if ((source=zip_source_buffer(za, NULL, 0, 0)) == NULL) {
	free(s);
	return -1;
    }
	
    ret = _zip_replace(za, -1, s ? s : name, source);

    free(s);
    if (ret < 0)
	zip_source_free(source);

    return ret;
}
Example #16
0
struct zip_source *
_zip_source_zip_new(struct zip *za, struct zip *srcza, zip_uint64_t srcidx, zip_flags_t flags,
		    zip_uint64_t start, zip_uint64_t len, const char *password)
{
    zip_compression_implementation comp_impl;
    zip_encryption_implementation enc_impl;
    struct zip_source *src, *s2;
    zip_uint64_t offset;
    struct zip_stat st;

    if (za == NULL)
	return NULL;

    if (srcza == NULL ||  srcidx >= srcza->nentry) {
	_zip_error_set(&za->error, ZIP_ER_INVAL, 0);
	return NULL;
    }

    if ((flags & ZIP_FL_UNCHANGED) == 0
	&& (ZIP_ENTRY_DATA_CHANGED(srcza->entry+srcidx) || srcza->entry[srcidx].deleted)) {
	_zip_error_set(&za->error, ZIP_ER_CHANGED, 0);
	return NULL;
    }

    if (zip_stat_index(srcza, srcidx, flags|ZIP_FL_UNCHANGED, &st) < 0) {
	_zip_error_set(&za->error, ZIP_ER_INTERNAL, 0);
	return NULL;
    }

    if (flags & ZIP_FL_ENCRYPTED)
	flags |= ZIP_FL_COMPRESSED;

    if ((start > 0 || len > 0) && (flags & ZIP_FL_COMPRESSED)) {
	_zip_error_set(&za->error, ZIP_ER_INVAL, 0);
	return NULL;
    }

    /* overflow or past end of file */
    if ((start > 0 || len > 0) && (start+len < start || start+len > st.size)) {
	_zip_error_set(&za->error, ZIP_ER_INVAL, 0);
	return NULL;
    }

    enc_impl = NULL;
    if (((flags & ZIP_FL_ENCRYPTED) == 0) && (st.encryption_method != ZIP_EM_NONE)) {
	if (password == NULL) {
	    _zip_error_set(&za->error, ZIP_ER_NOPASSWD, 0);
	    return NULL;
	}
	if ((enc_impl=_zip_get_encryption_implementation(st.encryption_method)) == NULL) {
	    _zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0);
	    return NULL;
	}
    }

    comp_impl = NULL;
    if ((flags & ZIP_FL_COMPRESSED) == 0) {
	if (st.comp_method != ZIP_CM_STORE) {
	    if ((comp_impl=_zip_get_compression_implementation(st.comp_method)) == NULL) {
		_zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0);
		return NULL;
	    }
	}
    }

    if ((offset=_zip_file_get_offset(srcza, srcidx, &za->error)) == 0)
	return NULL;

    if (st.comp_size == 0) {
	if ((src=zip_source_buffer(za, NULL, 0, 0)) == NULL)
	    return NULL;
    }
    else {
	if (start+len > 0 && enc_impl == NULL && comp_impl == NULL) {
	    struct zip_stat st2;

	    st2.size = len ? len : st.size-start;
	    st2.comp_size = st2.size;
	    st2.comp_method = ZIP_CM_STORE;
	    st2.mtime = st.mtime;
	    st2.valid = ZIP_STAT_SIZE|ZIP_STAT_COMP_SIZE|ZIP_STAT_COMP_METHOD|ZIP_STAT_MTIME;

            /* XXX: check for overflow of st2.size */
	    if ((src=_zip_source_file_or_p(za, NULL, srcza->zp, offset+start, (zip_int64_t)st2.size, 0, &st2)) == NULL)
		return NULL;
	}
	else {
            /* XXX: check for overflow of st.comp_size */
	    if ((src=_zip_source_file_or_p(za, NULL, srcza->zp, offset, (zip_int64_t)st.comp_size, 0, &st)) == NULL)
		return NULL;
	}
	
	if (enc_impl) {
	    if ((s2=enc_impl(za, src, st.encryption_method, 0, password)) == NULL) {
		zip_source_free(src);
		/* XXX: set error (how?) */
		return NULL;
	    }
	    src = s2;
	}
	if (comp_impl) {
	    if ((s2=comp_impl(za, src, st.comp_method, 0)) == NULL) {
		zip_source_free(src);
		/* XXX: set error (how?) */
		return NULL;
	    }
	    src = s2;
	}
	if (((flags & ZIP_FL_COMPRESSED) == 0 || st.comp_method == ZIP_CM_STORE)
	    && (len == 0 || len == st.comp_size)) {
	    /* when reading the whole file, check for crc errors */
	    if ((s2=zip_source_crc(za, src, 1)) == NULL) {
		zip_source_free(src);
		/* XXX: set error (how?) */
		return NULL;
	    }
	    src = s2;
	}

	if (start+len > 0 && (comp_impl || enc_impl)) {
	    if ((s2=zip_source_window(za, src, start, len ? len : st.size-start)) == NULL) {
		zip_source_free(src);
		/* XXX: set error (how?) (why?) */
		return NULL;
	    }
	    src = s2;
	}
    }

    return src;
}
Example #17
0
static int zip_create(const struct sr_output *o)
{
	struct out_context *outc;
	struct sr_channel *ch;
	FILE *meta;
	struct zip *zipfile;
	struct zip_source *versrc, *metasrc;
	GVariant *gvar;
	GSList *l;
	int tmpfile, ret;
	char version[1], metafile[32], *s;

	outc = o->priv;
	if (outc->samplerate == 0) {
		if (sr_config_get(o->sdi->driver, o->sdi, NULL, NULL, SR_CONF_SAMPLERATE,
				&gvar) == SR_OK) {
			outc->samplerate = g_variant_get_uint64(gvar);
			g_variant_unref(gvar);
		}
	}

	/* Quietly delete it first, libzip wants replace ops otherwise. */
	unlink(outc->filename);
	if (!(zipfile = zip_open(outc->filename, ZIP_CREATE, &ret)))
		return SR_ERR;

	/* "version" */
	version[0] = '2';
	if (!(versrc = zip_source_buffer(zipfile, version, 1, 0)))
		return SR_ERR;
	if (zip_add(zipfile, "version", versrc) == -1) {
		sr_info("Error saving version into zipfile: %s.",
			zip_strerror(zipfile));
		return SR_ERR;
	}

	/* init "metadata" */
	strcpy(metafile, "sigrok-meta-XXXXXX");
	if ((tmpfile = g_mkstemp(metafile)) == -1)
		return SR_ERR;
	close(tmpfile);
	meta = g_fopen(metafile, "wb");
	fprintf(meta, "[global]\n");
	fprintf(meta, "sigrok version = %s\n", PACKAGE_VERSION);
	fprintf(meta, "[device 1]\ncapturefile = logic-1\n");
	fprintf(meta, "total probes = %d\n", g_slist_length(o->sdi->channels));
	s = sr_samplerate_string(outc->samplerate);
	fprintf(meta, "samplerate = %s\n", s);
	g_free(s);

	for (l = o->sdi->channels; l; l = l->next) {
		ch = l->data;
		if (ch->type != SR_CHANNEL_LOGIC)
			continue;
		if (!ch->enabled)
			continue;
		fprintf(meta, "probe%d = %s\n", ch->index + 1, ch->name);
	}
	fclose(meta);

	if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1))) {
		unlink(metafile);
		return SR_ERR;
	}
	if (zip_add(zipfile, "metadata", metasrc) == -1) {
		unlink(metafile);
		return SR_ERR;
	}

	if ((ret = zip_close(zipfile)) == -1) {
		sr_info("Error saving zipfile: %s.", zip_strerror(zipfile));
		unlink(metafile);
		return SR_ERR;
	}

	unlink(metafile);

	return SR_OK;
}
Example #18
0
static int zip_append(const struct sr_output *o, unsigned char *buf,
		int unitsize, int length)
{
	struct out_context *outc;
	struct zip *archive;
	struct zip_source *logicsrc;
	zip_int64_t num_files;
	struct zip_file *zf;
	struct zip_stat zs;
	struct zip_source *metasrc;
	GKeyFile *kf;
	GError *error;
	gsize len;
	int chunk_num, next_chunk_num, tmpfile, ret, i;
	const char *entry_name;
	char *metafile, tmpname[32], chunkname[16];

	outc = o->priv;
	if (!(archive = zip_open(outc->filename, 0, &ret)))
		return SR_ERR;

	if (zip_stat(archive, "metadata", 0, &zs) == -1)
		return SR_ERR;

	metafile = g_malloc(zs.size);
	zf = zip_fopen_index(archive, zs.index, 0);
	zip_fread(zf, metafile, zs.size);
	zip_fclose(zf);

	/*
	 * If the file was only initialized but doesn't yet have any
	 * data it in, it won't have a unitsize field in metadata yet.
	 */
	error = NULL;
	kf = g_key_file_new();
	if (!g_key_file_load_from_data(kf, metafile, zs.size, 0, &error)) {
		sr_err("Failed to parse metadata: %s.", error->message);
		return SR_ERR;
	}
	g_free(metafile);
	tmpname[0] = '\0';
	if (!g_key_file_has_key(kf, "device 1", "unitsize", &error)) {
		if (error && error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND) {
			sr_err("Failed to check unitsize key: %s", error ? error->message : "?");
			return SR_ERR;
		}
		/* Add unitsize field. */
		g_key_file_set_integer(kf, "device 1", "unitsize", unitsize);
		metafile = g_key_file_to_data(kf, &len, &error);
		strcpy(tmpname, "sigrok-meta-XXXXXX");
		if ((tmpfile = g_mkstemp(tmpname)) == -1)
			return SR_ERR;
		if (write(tmpfile, metafile, len) < 0) {
			sr_dbg("Failed to create new metadata: %s", strerror(errno));
			g_free(metafile);
			unlink(tmpname);
			return SR_ERR;
		}
		close(tmpfile);
		if (!(metasrc = zip_source_file(archive, tmpname, 0, -1))) {
			sr_err("Failed to create zip source for metadata.");
			g_free(metafile);
			unlink(tmpname);
			return SR_ERR;
		}
		if (zip_replace(archive, zs.index, metasrc) == -1) {
			sr_err("Failed to replace metadata file.");
			g_free(metafile);
			unlink(tmpname);
			return SR_ERR;
		}
		g_free(metafile);
	}
	g_key_file_free(kf);

	next_chunk_num = 1;
	num_files = zip_get_num_entries(archive, 0);
	for (i = 0; i < num_files; i++) {
		entry_name = zip_get_name(archive, i, 0);
		if (strncmp(entry_name, "logic-1", 7))
			continue;
		if (strlen(entry_name) == 7) {
			/* This file has no extra chunks, just a single "logic-1".
			 * Rename it to "logic-1-1" * and continue with chunk 2. */
			if (zip_rename(archive, i, "logic-1-1") == -1) {
				sr_err("Failed to rename 'logic-1' to 'logic-1-1'.");
				unlink(tmpname);
				return SR_ERR;
			}
			next_chunk_num = 2;
			break;
		} else if (strlen(entry_name) > 8 && entry_name[7] == '-') {
			chunk_num = strtoull(entry_name + 8, NULL, 10);
			if (chunk_num >= next_chunk_num)
				next_chunk_num = chunk_num + 1;
		}
	}
	snprintf(chunkname, 15, "logic-1-%d", next_chunk_num);
	if (!(logicsrc = zip_source_buffer(archive, buf, length, FALSE))) {
		unlink(tmpname);
		return SR_ERR;
	}
	if (zip_add(archive, chunkname, logicsrc) == -1) {
		unlink(tmpname);
		return SR_ERR;
	}
	if ((ret = zip_close(archive)) == -1) {
		sr_info("error saving session file: %s", zip_strerror(archive));
		unlink(tmpname);
		return SR_ERR;
	}
	unlink(tmpname);

	return SR_OK;
}
Example #19
0
zip_fopen_index_encrypted(struct zip *za, zip_uint64_t fileno, int flags,
			  const char *password)
{
    struct zip_file *zf;
    zip_compression_implementation comp_impl;
    zip_encryption_implementation enc_impl;
    struct zip_source *src, *s2;
    zip_uint64_t start;
    struct zip_stat st;

    if (fileno >= za->nentry) {
	_zip_error_set(&za->error, ZIP_ER_INVAL, 0);
	return NULL;
    }

    if ((flags & ZIP_FL_UNCHANGED) == 0
	&& ZIP_ENTRY_DATA_CHANGED(za->entry+fileno)) {
	_zip_error_set(&za->error, ZIP_ER_CHANGED, 0);
	return NULL;
    }

    if (fileno >= za->cdir->nentry) {
	_zip_error_set(&za->error, ZIP_ER_INVAL, 0);
	return NULL;
    }

    if (flags & ZIP_FL_ENCRYPTED)
	flags |= ZIP_FL_COMPRESSED;

    zip_stat_index(za, fileno, flags, &st);

    enc_impl = NULL;
    if ((flags & ZIP_FL_ENCRYPTED) == 0) {
	if (st.encryption_method != ZIP_EM_NONE) {
	    if (password == NULL) {
		_zip_error_set(&za->error, ZIP_ER_NOPASSWD, 0);
		return NULL;
	    }
	    if ((enc_impl=zip_get_encryption_implementation(
		     st.encryption_method)) == NULL) {
		_zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0);
		return NULL;
	    }
	}
    }

    comp_impl = NULL;
    if ((flags & ZIP_FL_COMPRESSED) == 0) {
	if (st.comp_method != ZIP_CM_STORE) {
	    if ((comp_impl=zip_get_compression_implementation(
		     st.comp_method)) == NULL) {
		_zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0);
		return NULL;
	    }
	}
    }

    if ((start=_zip_file_get_offset(za, fileno)) == 0)
	return NULL;

    if (st.comp_size == 0) {
	if ((src=zip_source_buffer(za, NULL, 0, 0)) == NULL)
	    return NULL;
    }
    else {
	if ((src=_zip_source_file_or_p(za, NULL, za->zp, start, st.comp_size,
				       0, &st)) == NULL)
	    return NULL;
	if (enc_impl) {
	    if ((s2=enc_impl(za, src, ZIP_EM_TRAD_PKWARE, 0,
			     password)) == NULL) {
		zip_source_free(src);
		/* XXX: set error (how?) */
		return NULL;
	    }
	    src = s2;
	}
	if (comp_impl) {
	    if ((s2=comp_impl(za, src, za->cdir->entry[fileno].comp_method,
			      0)) == NULL) {
		zip_source_free(src);
		/* XXX: set error (how?) */
		return NULL;
	    }
	    src = s2;
	}
	if ((flags & ZIP_FL_COMPRESSED) == 0
	    || st.comp_method == ZIP_CM_STORE ) {
	    if ((s2=zip_source_crc(za, src, 1)) == NULL) {
		zip_source_free(src);
		/* XXX: set error (how?) */
		return NULL;
	    }
	    src = s2;
	}
    }

    if (zip_source_open(src) < 0) {
	_zip_error_set_from_source(&za->error, src);
	zip_source_free(src);
	return NULL;
    }

    zf = _zip_file_new(za);

    zf->src = src;

    return zf;
}
// TODO: This looks like should be ported to C code. or a big part of it.
bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, const bool selected)
{
	static const char errPrefix[] = "divelog.de-upload:";
	if (!amount_selected) {
		report_error(tr("no dives were selected").toUtf8());
		return false;
	}

	xsltStylesheetPtr xslt = NULL;
	struct zip *zip;

	xslt = get_stylesheet("divelogs-export.xslt");
	if (!xslt) {
		qDebug() << errPrefix << "missing stylesheet";
		return false;
	}


	int error_code;
	zip = zip_open(QFile::encodeName(QDir::toNativeSeparators(tempfile)), ZIP_CREATE, &error_code);
	if (!zip) {
		char buffer[1024];
		zip_error_to_str(buffer, sizeof buffer, error_code, errno);
		report_error(tr("failed to create zip file for upload: %s").toUtf8(), buffer);
		return false;
	}

	/* walk the dive list in chronological order */
	int i;
	struct dive *dive;
	struct membuffer mb = { 0 };
	for_each_dive (i, dive) {
		FILE *f;
		char filename[PATH_MAX];
		int streamsize;
		const char *membuf;
		xmlDoc *transformed;
		struct zip_source *s;

		/*
		 * Get the i'th dive in XML format so we can process it.
		 * We need to save to a file before we can reload it back into memory...
		 */
		if (selected && !dive->selected)
			continue;
		/* make sure the buffer is empty and add the dive */
		mb.len = 0;
		save_one_dive_to_mb(&mb, dive);
		membuf = mb_cstring(&mb);
		streamsize = strlen(membuf);
		/*
		 * Parse the memory buffer into XML document and
		 * transform it to divelogs.de format, finally dumping
		 * the XML into a character buffer.
		 */
		xmlDoc *doc = xmlReadMemory(membuf, streamsize, "divelog", NULL, 0);
		if (!doc) {
			qWarning() << errPrefix << "could not parse back into memory the XML file we've just created!";
			report_error(tr("internal error").toUtf8());
			goto error_close_zip;
		}
		free((void *)membuf);

		transformed = xsltApplyStylesheet(xslt, doc, NULL);
		xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize);
		xmlFreeDoc(doc);
		xmlFreeDoc(transformed);

		/*
		 * Save the XML document into a zip file.
		 */
		snprintf(filename, PATH_MAX, "%d.xml", i + 1);
		s = zip_source_buffer(zip, membuf, streamsize, 1);
		if (s) {
			int64_t ret = zip_add(zip, filename, s);
			if (ret == -1)
				qDebug() << errPrefix << "failed to include dive:" << i;
		}
	}
Example #21
0
int
main(int argc, char *argv[])
{
    const char *archive;
    struct zip *za, *z_in;
    struct zip_source *zs;
    char buf[100];
    int c, arg, err, flags, idx;

    flags = 0;
    prg = argv[0];

    if (argc < 2) {
	fprintf(stderr, usage, prg);
	return 1;
    }

    while ((c=getopt(argc, argv, "cent")) != -1) {
	switch (c) {
	case 'c':
	    flags |= ZIP_CHECKCONS;
	    break;
	case 'e':
	    flags |= ZIP_EXCL;
	    break;
	case 'n':
	    flags |= ZIP_CREATE;
	    break;
	case 't':
	    flags |= ZIP_TRUNCATE;
	    break;

	default:
	    fprintf(stderr, usage, argv[0]);
	    return 1;
	}
    }
    
    arg = optind;

    archive = argv[arg++];

    if (flags == 0)
	flags = ZIP_CREATE;

    if ((za=zip_open(archive, flags, &err)) == NULL) {
	zip_error_to_str(buf, sizeof(buf), err, errno);
	fprintf(stderr, "can't open zip archive `%s': %s\n", archive, buf);
	return 1;
    }

    err = 0;
    while (arg < argc) {
	if (strcmp(argv[arg], "add") == 0 && arg+2 < argc) {
	    /* add */
    	    if ((zs=zip_source_buffer(za, argv[arg+2], strlen(argv[arg+2]), 0)) == NULL) {
		fprintf(stderr, "can't create zip_source from buffer: %s\n", zip_strerror(za));
		err = 1;
		break;
	    }

	    if (zip_add(za, argv[arg+1], zs) == -1) {
		zip_source_free(zs);
		fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 3;
	} else if (strcmp(argv[arg], "add_dir") == 0 && arg+1 < argc) {
	    /* add directory */
	    if (zip_add_dir(za, argv[arg+1]) < 0) {
		fprintf(stderr, "can't add directory `%s': %s\n", argv[arg+1], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 2;
	} else if (strcmp(argv[arg], "add_file") == 0 && arg+4 < argc) {
	    /* add */
    	    if ((zs=zip_source_file(za, argv[arg+2], atoi(argv[arg+3]), atoi(argv[arg+4]))) == NULL) {
		fprintf(stderr, "can't create zip_source from file: %s\n", zip_strerror(za));
		err = 1;
		break;
	    }

	    if (zip_add(za, argv[arg+1], zs) == -1) {
		zip_source_free(zs);
		fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 5;
	} else if (strcmp(argv[arg], "add_from_zip") == 0 && arg+5 < argc) {
	    /* add from another zip file */
	    idx = atoi(argv[arg+3]);
	    if ((z_in=zip_open(argv[arg+2], ZIP_CHECKCONS, &err)) == NULL) {
		zip_error_to_str(buf, sizeof(buf), err, errno);
		fprintf(stderr, "can't open source zip archive `%s': %s\n", argv[arg+2], buf);
		err = 1;
		break;
	    }
	    if ((zs=zip_source_zip(za, z_in, idx, 0, atoi(argv[arg+4]), atoi(argv[arg+5]))) == NULL) {
		fprintf(stderr, "error creating file source from `%s' index '%d': %s\n", argv[arg+2], idx, zip_strerror(za));
		zip_close(z_in);
		err = 1;
		break;
	    }
	    if (zip_add(za, argv[arg+1], zs) == -1) {
		fprintf(stderr, "can't add file `%s': %s\n", argv[arg+1], zip_strerror(za));
		zip_source_free(zs);
		zip_close(z_in);
		err = 1;
		break;
	    }
	    arg += 6;
	} else if (strcmp(argv[arg], "count_extra") == 0 && arg+2 < argc) {
	    zip_int16_t count;
	    zip_flags_t ceflags = 0;
	    idx = atoi(argv[arg+1]);
	    ceflags = get_flags(argv[arg+2]);
	    if ((count=zip_file_extra_fields_count(za, idx, ceflags)) < 0) {
		fprintf(stderr, "can't get extra field count for file at index `%d': %s\n", idx, zip_strerror(za));
		err = 1;
		break;
	    } else {
		printf("Extra field count: %d\n", count);
	    }
	    arg += 3;
	} else if (strcmp(argv[arg], "count_extra_by_id") == 0 && arg+3 < argc) {
	    zip_int16_t count, eid;
	    zip_flags_t ceflags = 0;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    ceflags = get_flags(argv[arg+3]);
	    if ((count=zip_file_extra_fields_count_by_id(za, idx, eid, ceflags)) < 0) {
		fprintf(stderr, "can't get extra field count for file at index `%d' and for id `%d': %s\n", idx, eid, zip_strerror(za));
		err = 1;
		break;
	    } else {
		printf("Extra field count: %d\n", count);
	    }
	    arg += 4;
	} else if (strcmp(argv[arg], "delete") == 0 && arg+1 < argc) {
	    /* delete */
	    idx = atoi(argv[arg+1]);
	    if (zip_delete(za, idx) < 0) {
		fprintf(stderr, "can't delete file at index `%d': %s\n", idx, zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 2;
	} else if (strcmp(argv[arg], "delete_extra") == 0 && arg+1 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t eid;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    geflags = get_flags(argv[arg+3]);
	    if ((zip_file_extra_field_delete(za, idx, eid, geflags)) < 0) {
		fprintf(stderr, "can't delete extra field data for file at index `%d', extra field id `%d': %s\n", idx, eid, zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 4;
	} else if (strcmp(argv[arg], "delete_extra_by_id") == 0 && arg+1 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t eid, eidx;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    eidx = atoi(argv[arg+3]);
	    geflags = get_flags(argv[arg+4]);
	    if ((zip_file_extra_field_delete_by_id(za, idx, eid, eidx, geflags)) < 0) {
		fprintf(stderr, "can't delete extra field data for file at index `%d', extra field id `%d', extra field idx `%d': %s\n", idx, eid, eidx, zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 5;
	} else if (strcmp(argv[arg], "get_archive_comment") == 0) {
	    const char *comment;
	    int len;
	    /* get archive comment */
	    if ((comment=zip_get_archive_comment(za, &len, 0)) == NULL)
		printf("No archive comment\n");
	    else
		printf("Archive comment: %.*s\n", len, comment);
	    arg += 1;
	} else if (strcmp(argv[arg], "get_extra") == 0 && arg+3 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t id, eidx, eflen;
	    const zip_uint8_t *efdata;
	    /* get extra field data */
	    idx = atoi(argv[arg+1]);
	    eidx = atoi(argv[arg+2]);
	    geflags = get_flags(argv[arg+3]);
	    if ((efdata=zip_file_extra_field_get(za, idx, eidx, &id, &eflen, geflags)) == NULL) {
		fprintf(stderr, "can't get extra field data for file at index %d, extra field %d, flags %u: %s\n", idx, eidx, geflags, zip_strerror(za));
		err = 1;
	    } else {
		printf("Extra field 0x%04x: len %d", id, eflen);
		if (eflen > 0) {
		    printf(", data ");
		    hexdump(efdata, eflen);
		}
		printf("\n");
	    }
	    arg += 4;
	} else if (strcmp(argv[arg], "get_extra_by_id") == 0 && arg+4 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t eid, eidx, eflen;
	    const zip_uint8_t *efdata;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    eidx = atoi(argv[arg+3]);
	    geflags = get_flags(argv[arg+4]);
	    if ((efdata=zip_file_extra_field_get_by_id(za, idx, eid, eidx, &eflen, geflags)) == NULL) {
		fprintf(stderr, "can't get extra field data for file at index %d, extra field id %d, ef index %d, flags %u: %s\n", idx, eid, eidx, geflags, zip_strerror(za));
		err = 1;
	    } else {
		printf("Extra field 0x%04x: len %d", eid, eflen);
		if (eflen > 0) {
		    printf(", data ");
		    hexdump(efdata, eflen);
		}
		printf("\n");
	    }
	    arg += 5;
	} else if (strcmp(argv[arg], "get_file_comment") == 0 && arg+1 < argc) {
	    const char *comment;
	    int len;
	    /* get file comment */
	    idx = atoi(argv[arg+1]);
	    if ((comment=zip_get_file_comment(za, idx, &len, 0)) == NULL) {
		fprintf(stderr, "can't get comment for `%s': %s\n", zip_get_name(za, idx, 0), zip_strerror(za));
		err = 1;
		break;
	    } else if (len == 0)
		printf("No comment for `%s'\n", zip_get_name(za, idx, 0));
	    else
		printf("File comment for `%s': %.*s\n", zip_get_name(za, idx, 0), len, comment);
	    arg += 2;
	} else if (strcmp(argv[arg], "rename") == 0 && arg+2 < argc) {
	    /* rename */
	    idx = atoi(argv[arg+1]);
	    if (zip_rename(za, idx, argv[arg+2]) < 0) {
		fprintf(stderr, "can't rename file at index `%d' to `%s': %s\n", idx, argv[arg+2], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 3;
	} else if (strcmp(argv[arg], "set_extra") == 0 && arg+5 < argc) {
	    zip_flags_t geflags;
	    zip_uint16_t eid, eidx;
	    const zip_uint8_t *efdata;
	    idx = atoi(argv[arg+1]);
	    eid = atoi(argv[arg+2]);
	    eidx = atoi(argv[arg+3]);
	    geflags = get_flags(argv[arg+4]);
	    efdata = (zip_uint8_t *)argv[arg+5];
	    if ((zip_file_extra_field_set(za, idx, eid, eidx, efdata, (zip_uint16_t)strlen((const char *)efdata), geflags)) < 0) {
		fprintf(stderr, "can't set extra field data for file at index `%d', extra field id `%d', index `%d': %s\n", idx, eid, eidx, zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 6;
	} else if (strcmp(argv[arg], "set_file_comment") == 0 && arg+2 < argc) {
	    /* set file comment */
	    idx = atoi(argv[arg+1]);
	    if (zip_file_set_comment(za, idx, argv[arg+2], (zip_uint16_t)strlen(argv[arg+2]), 0) < 0) {
		fprintf(stderr, "can't set file comment at index `%d' to `%s': %s\n", idx, argv[arg+2], zip_strerror(za));
		err = 1;
		break;
	    }
	    arg += 3;
        } else if (strcmp(argv[arg], "set_file_compression") == 0 && arg+3 < argc) {
            /* set file compression */
            zip_int32_t method;
            zip_uint32_t flags;
            idx = atoi(argv[arg+1]);
            method = get_compression_method(argv[arg+2]);
            flags = atoi(argv[arg+3]);
            if (zip_set_file_compression(za, idx, method, flags) < 0) {
		fprintf(stderr, "can't set file compression method at index `%d' to `%s', flags `%d': %s\n", idx, argv[arg+2], flags, zip_strerror(za));
		err = 1;
		break;
            }
            arg += 4;
	} else {
	    fprintf(stderr, "unrecognized command `%s', or not enough arguments\n", argv[arg]);
	    err = 1;
	    break;
	}
    }

    if (zip_close(za) == -1) {
	fprintf(stderr, "can't close zip archive `%s': %s\n", archive, zip_strerror(za));
	return 1;
    }

    return err;
}
Example #22
0
int session_save(char *filename)
{
	GSList *l, *d;
	struct device *device;
	struct datastore *ds;
	struct zip *zipfile;
	struct zip_source *src;
	int bufcnt, devcnt, tmpfile, ret, error;
	char version[1], rawname[16], metafile[32], *buf;

	/* Quietly delete it first, libzip wants replace ops otherwise. */
	unlink(filename);

	if (!(zipfile = zip_open(filename, ZIP_CREATE, &error)))
		return SIGROK_ERR;

	/* Version */
	version[0] = '1';
	if (!(src = zip_source_buffer(zipfile, version, 1, 0)))
		return SIGROK_ERR;
	if (zip_add(zipfile, "version", src) == -1) {
		g_message("error saving version into zipfile: %s",
			  zip_strerror(zipfile));
		return SIGROK_ERR;
	}

	/* Metadata */
	strcpy(metafile, "sigrok-meta-XXXXXX");
	if ((tmpfile = g_mkstemp(metafile)) == -1)
		return SIGROK_ERR;
	close(tmpfile);
	make_metadata(metafile);
	if (!(src = zip_source_file(zipfile, metafile, 0, -1)))
		return SIGROK_ERR;
	if (zip_add(zipfile, "metadata", src) == -1)
		return SIGROK_ERR;
	unlink(metafile);

	/* Raw */
	devcnt = 1;
	for (l = session->devices; l; l = l->next) {
		device = l->data;
		ds = device->datastore;
		if (ds) {
			buf = malloc(ds->num_units * ds->ds_unitsize +
				   DATASTORE_CHUNKSIZE);
			bufcnt = 0;
			for (d = ds->chunklist; d; d = d->next) {
				memcpy(buf + bufcnt, d->data,
				       DATASTORE_CHUNKSIZE);
				bufcnt += DATASTORE_CHUNKSIZE;
			}
			if (!(src = zip_source_buffer(zipfile, buf,
				       ds->num_units * ds->ds_unitsize, TRUE)))
				return SIGROK_ERR;
			snprintf(rawname, 15, "raw-%d", devcnt);
			if (zip_add(zipfile, rawname, src) == -1)
				return SIGROK_ERR;
		}
		devcnt++;
	}

	if ((ret = zip_close(zipfile)) == -1) {
		g_message("error saving zipfile: %s", zip_strerror(zipfile));
		return SIGROK_ERR;
	}

	return SIGROK_OK;
}
Example #23
0
int sr_session_save(const char *filename)
{
	GSList *l, *p, *d;
	FILE *meta;
	struct sr_device *device;
	struct sr_probe *probe;
	struct sr_datastore *ds;
	struct zip *zipfile;
	struct zip_source *versrc, *metasrc, *logicsrc;
	int bufcnt, devcnt, tmpfile, ret, error, probecnt;
	uint64_t samplerate;
	char version[1], rawname[16], metafile[32], *buf, *s;

	/* Quietly delete it first, libzip wants replace ops otherwise. */
	unlink(filename);
	if (!(zipfile = zip_open(filename, ZIP_CREATE, &error)))
		return SR_ERR;

	/* "version" */
	version[0] = '1';
	if (!(versrc = zip_source_buffer(zipfile, version, 1, 0)))
		return SR_ERR;
	if (zip_add(zipfile, "version", versrc) == -1) {
		sr_info("error saving version into zipfile: %s",
			zip_strerror(zipfile));
		return SR_ERR;
	}

	/* init "metadata" */
	strcpy(metafile, "sigrok-meta-XXXXXX");
	if ((tmpfile = g_mkstemp(metafile)) == -1)
		return SR_ERR;
	close(tmpfile);
	meta = g_fopen(metafile, "wb");
	fprintf(meta, "[global]\n");
	fprintf(meta, "sigrok version = %s\n", PACKAGE_VERSION);
	/* TODO: save protocol decoders used */

	/* all datastores in all devices */
	devcnt = 1;
	for (l = session->devices; l; l = l->next) {
		device = l->data;
		/* metadata */
		fprintf(meta, "[device %d]\n", devcnt);
		if (device->plugin)
			fprintf(meta, "driver = %s\n", device->plugin->name);

		ds = device->datastore;
		if (ds) {
			/* metadata */
			fprintf(meta, "capturefile = logic-%d\n", devcnt);
			fprintf(meta, "unitsize = %d\n", ds->ds_unitsize);
			fprintf(meta, "total probes = %d\n", g_slist_length(device->probes));
			if (sr_device_has_hwcap(device, SR_HWCAP_SAMPLERATE)) {
				samplerate = *((uint64_t *) device->plugin->get_device_info(
						device->plugin_index, SR_DI_CUR_SAMPLERATE));
				s = sr_samplerate_string(samplerate);
				fprintf(meta, "samplerate = %s\n", s);
				free(s);
			}
			probecnt = 1;
			for (p = device->probes; p; p = p->next) {
				probe = p->data;
				if (probe->enabled) {
					if (probe->name)
						fprintf(meta, "probe%d = %s\n", probecnt, probe->name);
					if (probe->trigger)
						fprintf(meta, " trigger%d = %s\n", probecnt, probe->trigger);
					probecnt++;
				}
			}

			/* dump datastore into logic-n */
			buf = malloc(ds->num_units * ds->ds_unitsize +
				   DATASTORE_CHUNKSIZE);
			bufcnt = 0;
			for (d = ds->chunklist; d; d = d->next) {
				memcpy(buf + bufcnt, d->data,
				       DATASTORE_CHUNKSIZE);
				bufcnt += DATASTORE_CHUNKSIZE;
			}
			if (!(logicsrc = zip_source_buffer(zipfile, buf,
				       ds->num_units * ds->ds_unitsize, TRUE)))
				return SR_ERR;
			snprintf(rawname, 15, "logic-%d", devcnt);
			if (zip_add(zipfile, rawname, logicsrc) == -1)
				return SR_ERR;
		}
		devcnt++;
	}
	fclose(meta);

	if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1)))
		return SR_ERR;
	if (zip_add(zipfile, "metadata", metasrc) == -1)
		return SR_ERR;

	if ((ret = zip_close(zipfile)) == -1) {
		sr_info("error saving zipfile: %s", zip_strerror(zipfile));
		return SR_ERR;
	}

	unlink(metafile);

	return SR_OK;
}
Example #24
0
/**
 * Initialize a saved session file.
 *
 * @param filename The name of the filename to save the current session as.
 *                 Must not be NULL.
 * @param samplerate The samplerate to store for this session.
 * @param channels A NULL-terminated array of strings containing the names
 * of all the channels active in this session.
 *
 * @retval SR_OK Success
 * @retval SR_ERR_ARG Invalid arguments
 * @retval SR_ERR Other errors
 *
 * @since 0.3.0
 */
SR_API int sr_session_save_init(const char *filename, uint64_t samplerate,
        char **channels)
{
    FILE *meta;
    struct zip *zipfile;
    struct zip_source *versrc, *metasrc;
    int tmpfile, cnt, ret, i;
    char version[1], metafile[32], *s;

    if (!filename) {
        sr_err("%s: filename was NULL", __func__);
        return SR_ERR_ARG;
    }

    /* Quietly delete it first, libzip wants replace ops otherwise. */
    unlink(filename);
    if (!(zipfile = zip_open(filename, ZIP_CREATE, &ret)))
        return SR_ERR;

    /* "version" */
    version[0] = '2';
    if (!(versrc = zip_source_buffer(zipfile, version, 1, 0)))
        return SR_ERR;
    if (zip_add(zipfile, "version", versrc) == -1) {
        sr_info("error saving version into zipfile: %s",
            zip_strerror(zipfile));
        return SR_ERR;
    }

    /* init "metadata" */
    strcpy(metafile, "sigrok-meta-XXXXXX");
    if ((tmpfile = g_mkstemp(metafile)) == -1)
        return SR_ERR;
    close(tmpfile);
    meta = g_fopen(metafile, "wb");
    fprintf(meta, "[global]\n");
    fprintf(meta, "sigrok version = %s\n", PACKAGE_VERSION);

    /* metadata */
    fprintf(meta, "[device 1]\n");

    /* metadata */
    fprintf(meta, "capturefile = logic-1\n");
    cnt = 0;
    for (i = 0; channels[i]; i++)
        cnt++;
    fprintf(meta, "total probes = %d\n", cnt);
    s = sr_samplerate_string(samplerate);
    fprintf(meta, "samplerate = %s\n", s);
    g_free(s);

    for (i = 0; channels[i]; i++)
        fprintf(meta, "probe%d = %s\n", i + 1, channels[i]);

    fclose(meta);

    if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1))) {
        unlink(metafile);
        return SR_ERR;
    }
    if (zip_add(zipfile, "metadata", metasrc) == -1) {
        unlink(metafile);
        return SR_ERR;
    }

    if ((ret = zip_close(zipfile)) == -1) {
        sr_info("error saving zipfile: %s", zip_strerror(zipfile));
        unlink(metafile);
        return SR_ERR;
    }

    unlink(metafile);

    return SR_OK;
}
Example #25
0
/**
 * Save the current session to the specified file.
 *
 * @param filename The name of the filename to save the current session as.
 *                 Must not be NULL.
 * @param sdi The device instance from which the data was captured.
 * @param buf The data to be saved.
 * @param unitsize The number of bytes per sample.
 * @param units The number of samples.
 *
 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or SR_ERR
 *         upon other errors.
 */
SR_API int sr_session_save(const char *filename, const struct sr_dev_inst *sdi,
		unsigned char *buf, int unitsize, int units)
{
    GSList *l;
    GVariant *gvar;
    FILE *meta;
    struct sr_channel *probe;
    struct zip *zipfile;
    struct zip_source *versrc, *metasrc, *logicsrc;
    int tmpfile, ret, probecnt;
    uint64_t samplerate, timeBase, tmp_u64;
    char rawname[16], metafile[32], *s;
    struct sr_status status;

	if (!filename) {
		sr_err("%s: filename was NULL", __func__);
		return SR_ERR_ARG;
	}

	/* Quietly delete it first, libzip wants replace ops otherwise. */
	unlink(filename);
	if (!(zipfile = zip_open(filename, ZIP_CREATE, &ret)))
		return SR_ERR;

    /* init "metadata" */
    strcpy(metafile, "DSView-meta-XXXXXX");
    if ((tmpfile = g_mkstemp(metafile)) == -1)
        return SR_ERR;
    close(tmpfile);
    meta = g_fopen(metafile, "wb");
    fprintf(meta, "[version]\n");
    fprintf(meta, "DSView version = %s\n", PACKAGE_VERSION);

    /* metadata */
    fprintf(meta, "[header]\n");
    if (sdi->driver) {
        fprintf(meta, "driver = %s\n", sdi->driver->name);
        fprintf(meta, "device mode = %d\n", sdi->mode);
    }

    /* metadata */
    fprintf(meta, "capturefile = data\n");
    fprintf(meta, "unitsize = %d\n", unitsize);
    fprintf(meta, "total samples = %d\n", units);
    fprintf(meta, "total probes = %d\n", g_slist_length(sdi->channels));
    if (sr_config_get(sdi->driver, sdi, NULL, NULL, SR_CONF_SAMPLERATE,
            &gvar) == SR_OK) {
        samplerate = g_variant_get_uint64(gvar);
        s = sr_samplerate_string(samplerate);
        fprintf(meta, "samplerate = %s\n", s);
        g_free(s);
        g_variant_unref(gvar);
    }
    if (sdi->mode == DSO &&
        sr_config_get(sdi->driver, sdi, NULL, NULL, SR_CONF_TIMEBASE, &gvar) == SR_OK) {
        timeBase = g_variant_get_uint64(gvar);
        fprintf(meta, "hDiv = %d\n", timeBase);
        g_variant_unref(gvar);
    }
    probecnt = 1;
    for (l = sdi->channels; l; l = l->next) {
        probe = l->data;
        if (probe->enabled || sdi->mode == DSO) {
            if (probe->name)
                fprintf(meta, "probe%d = %s\n", probe->index, probe->name);
            if (probe->trigger)
                fprintf(meta, " trigger%d = %s\n", probe->index, probe->trigger);
            if (sdi->mode == DSO) {
                fprintf(meta, " enable%d = %d\n", probe->index, probe->enabled);
                fprintf(meta, " coupling%d = %d\n", probe->index, probe->coupling);
                fprintf(meta, " vDiv%d = %d\n", probe->index, probe->vdiv);
                fprintf(meta, " vFactor%d = %d\n", probe->index, probe->vfactor);
                fprintf(meta, " vPos%d = %lf\n", probe->index, probe->vpos);
                if (sr_status_get(sdi, &status, 0, 0) == SR_OK) {
                    if (probe->index == 0) {
                        fprintf(meta, " period%d = %d\n", probe->index, status.ch0_period);
                        fprintf(meta, " pcnt%d = %d\n", probe->index, status.ch0_pcnt);
                        fprintf(meta, " max%d = %d\n", probe->index, status.ch0_max);
                        fprintf(meta, " min%d = %d\n", probe->index, status.ch0_min);
                    } else {
                        fprintf(meta, " period%d = %d\n", probe->index, status.ch1_period);
                        fprintf(meta, " pcnt%d = %d\n", probe->index, status.ch1_pcnt);
                        fprintf(meta, " max%d = %d\n", probe->index, status.ch1_max);
                        fprintf(meta, " min%d = %d\n", probe->index, status.ch1_min);
                    }
                }
            }
            probecnt++;
        }
    }

    if (!(logicsrc = zip_source_buffer(zipfile, buf,
               units * unitsize, FALSE)))
        return SR_ERR;
    snprintf(rawname, 15, "data");
    if (zip_add(zipfile, rawname, logicsrc) == -1)
        return SR_ERR;
    fclose(meta);

    if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1)))
        return SR_ERR;
    if (zip_add(zipfile, "header", metasrc) == -1)
        return SR_ERR;

    if ((ret = zip_close(zipfile)) == -1) {
        sr_info("error saving zipfile: %s", zip_strerror(zipfile));
        return SR_ERR;
    }

    unlink(metafile);

    return SR_OK;
}
Example #26
0
static VALUE zipruby_archive_update(int argc, VALUE *argv, VALUE self) {
  struct zipruby_archive *p_archive, *p_srcarchive;
  VALUE srcarchive, flags;
  int i, num_files, i_flags = 0;

  rb_scan_args(argc, argv, "11", &srcarchive, &flags);

  if (!rb_obj_is_instance_of(srcarchive, Archive)) {
    rb_raise(rb_eTypeError, "wrong argument type %s (expected Zip::Archive)", rb_class2name(CLASS_OF(srcarchive)));
  }

  if (!NIL_P(flags)) {
    i_flags = NUM2INT(flags);
  }

  Data_Get_Struct(self, struct zipruby_archive, p_archive);
  Check_Archive(p_archive);
  Data_Get_Struct(srcarchive, struct zipruby_archive, p_srcarchive);
  Check_Archive(p_srcarchive);

  num_files = zip_get_num_files(p_srcarchive->archive);

  for (i = 0; i < num_files; i++) {
    struct zip_source *zsource;
    struct zip_file *fzip;
    struct zip_stat sb;
    char *buf;
    const char *name;
    int index, error;

    zip_stat_init(&sb);

    if (zip_stat_index(p_srcarchive->archive, i, 0, &sb)) {
      zip_unchange_all(p_archive->archive);
      zip_unchange_archive(p_archive->archive);
      rb_raise(Error, "Update archive failed: %s", zip_strerror(p_srcarchive->archive));
    }

    if ((buf = malloc(sb.size)) == NULL) {
      zip_unchange_all(p_archive->archive);
      zip_unchange_archive(p_archive->archive);
      rb_raise(rb_eRuntimeError, "Update archive failed: Cannot allocate memory");
    }

    fzip = zip_fopen_index(p_srcarchive->archive, i, 0);

    if (fzip == NULL) {
      free(buf);
      zip_unchange_all(p_archive->archive);
      zip_unchange_archive(p_archive->archive);
      rb_raise(Error, "Update archive failed: %s", zip_strerror(p_srcarchive->archive));
    }

    if (zip_fread(fzip, buf, sb.size) == -1) {
      free(buf);
      zip_fclose(fzip);
      zip_unchange_all(p_archive->archive);
      zip_unchange_archive(p_archive->archive);
      rb_raise(Error, "Update archive failed: %s", zip_file_strerror(fzip));
    }

    if ((error = zip_fclose(fzip)) != 0) {
      char errstr[ERRSTR_BUFSIZE];
      free(buf);
      zip_unchange_all(p_archive->archive);
      zip_unchange_archive(p_archive->archive);
      zip_error_to_str(errstr, ERRSTR_BUFSIZE, error, errno);
      rb_raise(Error, "Update archive failed: %s", errstr);
    }

    if ((zsource = zip_source_buffer(p_archive->archive, buf, sb.size, 1)) == NULL) {
      free(buf);
      zip_unchange_all(p_archive->archive);
      zip_unchange_archive(p_archive->archive);
      rb_raise(Error, "Update archive failed: %s", zip_strerror(p_archive->archive));
    }

    if ((name = zip_get_name(p_srcarchive->archive, i, 0)) == NULL) {
      zip_source_free(zsource);
      zip_unchange_all(p_archive->archive);
      zip_unchange_archive(p_archive->archive);
      rb_raise(Error, "Update archive failed: %s", zip_strerror(p_srcarchive->archive));
    }

    index = zip_name_locate(p_archive->archive, name, i_flags);

    if (index >= 0) {
      if (zip_replace(p_archive->archive, i, zsource) == -1) {
        zip_source_free(zsource);
        zip_unchange_all(p_archive->archive);
        zip_unchange_archive(p_archive->archive);
        rb_raise(Error, "Update archive failed: %s", zip_strerror(p_archive->archive));
      }
    } else {
      if (zip_add(p_archive->archive, name, zsource) == -1) {
        zip_source_free(zsource);
        zip_unchange_all(p_archive->archive);
        zip_unchange_archive(p_archive->archive);
        rb_raise(Error, "Update archive failed: %s", zip_strerror(p_archive->archive));
      }
    }
  }

  return Qnil;
}
Example #27
0
File: fifoman.c Project: dezi/raspi
void kappa_fifo_save_jpeg(char *group,kafifo_t *info,AVFrame *stillframe,char *filename,int isscene)
{
	struct jpeg_compress_struct cinfo;
	struct jpeg_error_mgr jerr;
	
	JSAMPROW row_pointer[ 1 ];
	FILE *outfile;
	
	unsigned char *mem = NULL;
	unsigned long memsize = 0;
	
	cinfo.err = jpeg_std_error(&jerr);	
	jpeg_create_compress(&cinfo);
	
	jpeg_mem_dest(&cinfo,&mem,&memsize);

	cinfo.image_width      = stillframe->width;
	cinfo.image_height     = stillframe->height;
	cinfo.input_components = 3;     
	cinfo.in_color_space   = JCS_RGB;

	jpeg_set_defaults(&cinfo);
	
	jpeg_start_compress(&cinfo,TRUE);

	row_pointer[ 0 ] = stillframe->data[ 0 ];
	
    while (cinfo.next_scanline < cinfo.image_height) 
	{
		jpeg_write_scanlines(&cinfo,row_pointer,1);
		
		row_pointer[ 0 ] += stillframe->linesize[ 0 ];
	}
	
	jpeg_finish_compress(&cinfo);
	jpeg_destroy_compress(&cinfo);
	
	if (isscene)
	{
		struct zip_source *source = zip_source_buffer(info->scenezip,mem,memsize,1);
		
		char *zipname = strncmp(filename,"../",3) ? filename : (filename + 3);
		
		if (zip_file_add(info->scenezip,zipname,source,ZIP_FL_ENC_UTF_8) < 0)
		{
			fprintf(stderr,"Could not add still to zip %s => %s, exitting now...\n",
					group,info->scenezipname,
					zip_strerror(info->scenezip)
					);
					
			exit(1);
		}
	}
	else
	{
		if ((outfile = fopen(filename,"wb")) == NULL) 
		{
			fprintf(stderr,"Could not create still %s, exitting now...\n",filename);
			exit(1);
		}

		fwrite(mem,memsize,1,outfile);
		fclose(outfile);
		
		free(mem);
		
		fprintf(stderr,"Stillimage:%s\n",filename);
		fflush(stderr);
	}
}
bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, const bool selected)
{
	static const char errPrefix[] = "divelog.de-upload:";
	if (!amount_selected) {
		report_error(tr("no dives were selected").toUtf8());
		return false;
	}

	xsltStylesheetPtr xslt = NULL;
	struct zip *zip;

	xslt = get_stylesheet("divelogs-export.xslt");
	if (!xslt) {
		qDebug() << errPrefix << "missing stylesheet";
		return false;
	}


	int error_code;
	zip = zip_open(QFile::encodeName(tempfile), ZIP_CREATE, &error_code);
	if (!zip) {
		char buffer[1024];
		zip_error_to_str(buffer, sizeof buffer, error_code, errno);
		report_error(tr("failed to create zip file for upload: %s").toUtf8(), buffer);
		return false;
	}

	/* walk the dive list in chronological order */
	for (int i = 0; i < dive_table.nr; i++) {
		FILE *f;
		char filename[PATH_MAX];
		int streamsize;
		char *membuf;
		xmlDoc *transformed;
		struct zip_source *s;

		/*
		 * Get the i'th dive in XML format so we can process it.
		 * We need to save to a file before we can reload it back into memory...
		 */
		struct dive *dive = get_dive(i);
		if (!dive)
			continue;
		if (selected && !dive->selected)
			continue;
		f = tmpfile();
		if (!f) {
			report_error(tr("cannot create temporary file: %s").toUtf8(), qt_error_string().toUtf8().data());
			goto error_close_zip;
		}
		save_dive(f, dive);
		fseek(f, 0, SEEK_END);
		streamsize = ftell(f);
		rewind(f);

		membuf = (char *)malloc(streamsize + 1);
		if (!membuf || (streamsize = fread(membuf, streamsize, 1, f)) == 0) {
			report_error(tr("internal error: %s").toUtf8(), qt_error_string().toUtf8().data());
			fclose(f);
			free((void *)membuf);
			goto error_close_zip;
		}
		membuf[streamsize] = 0;
		fclose(f);

		/*
		 * Parse the memory buffer into XML document and
		 * transform it to divelogs.de format, finally dumping
		 * the XML into a character buffer.
		 */
		xmlDoc *doc = xmlReadMemory(membuf, streamsize, "divelog", NULL, 0);
		if (!doc) {
			qWarning() << errPrefix << "could not parse back into memory the XML file we've just created!";
			report_error(tr("internal error").toUtf8());
			free((void *)membuf);
			goto error_close_zip;
		}
		free((void *)membuf);

		transformed = xsltApplyStylesheet(xslt, doc, NULL);
		xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize);
		xmlFreeDoc(doc);
		xmlFreeDoc(transformed);

		/*
		 * Save the XML document into a zip file.
		 */
		snprintf(filename, PATH_MAX, "%d.xml", i + 1);
		s = zip_source_buffer(zip, membuf, streamsize, 1);
		if (s) {
			int64_t ret = zip_add(zip, filename, s);
			if (ret == -1)
				qDebug() << errPrefix << "failed to include dive:" << i;
		}
	}
	zip_close(zip);
	xsltFreeStylesheet(xslt);
	return true;

error_close_zip:
	zip_close(zip);
	QFile::remove(tempfile);
	xsltFreeStylesheet(xslt);
	return false;
}
Example #29
0
int
main(int argc, char *argv[])
{
    int fail, ze;
    int c;
    struct zip *z;
    struct zip_source *zs;
    char *archive;
    char errstr[1024];

    verbose = 0;
    fail = 0;

    prg = argv[0];

    while ((c=getopt(argc, argv, "v")) != -1) {
	switch (c) {
            case 'v':
                verbose = 1;
                break;

            default:
                fprintf(stderr, usage, prg);
                return 1;
	}
    }

    
    if (argc-optind != 1) {
        fprintf(stderr, usage, prg);
        return 1;
    }

    archive = argv[optind];

    if ((z=zip_open(archive, 0, &ze)) == NULL) {
	zip_error_to_str(errstr, sizeof(errstr), ze, errno);
	printf("%s: can't open zip archive '%s': %s\n",
	       prg, archive, errstr);
	return 1;
    }

    fail += do_read(z, "storedok", 0, WHEN_NEVER, 0, 0);
    fail += do_read(z, "deflateok", 0, WHEN_NEVER, 0, 0);
    fail += do_read(z, "storedcrcerror", 0, WHEN_READ, ZIP_ER_CRC, 0);
    fail += do_read(z, "deflatecrcerror", 0, WHEN_READ, ZIP_ER_CRC, 0);
    fail += do_read(z, "deflatezliberror", 0, WHEN_READ, ZIP_ER_ZLIB, -3);
    fail += do_read(z, NULL, 0, WHEN_OPEN, ZIP_ER_INVAL, 0);
    fail += do_read(z, "nosuchfile", 0, WHEN_OPEN, ZIP_ER_NOENT, 0);
    fail += do_read(z, "deflatezliberror", ZIP_FL_COMPRESSED, WHEN_NEVER, 0,0);
    fail += do_read(z, "deflatecrcerror", ZIP_FL_COMPRESSED, WHEN_NEVER, 0, 0);
    fail += do_read(z, "storedcrcerror", ZIP_FL_COMPRESSED,
		    WHEN_READ, ZIP_ER_CRC, 0);
    fail += do_read(z, "storedok", ZIP_FL_COMPRESSED, WHEN_NEVER, 0, 0);

    fail += do_read(z, "cryptok", 0, WHEN_OPEN, ZIP_ER_NOPASSWD, 0);
    zip_set_default_password(z, "crypt");
    fail += do_read(z, "cryptok", 0, WHEN_NEVER, 0, 0);
    zip_set_default_password(z, "wrong");
    fail += do_read(z, "cryptok", 0, WHEN_OPEN, ZIP_ER_WRONGPASSWD, 0);
    zip_set_default_password(z, NULL);

    zs = zip_source_buffer(z, "asdf", 4, 0);
    zip_replace(z, zip_name_locate(z, "storedok", 0), zs);
    fail += do_read(z, "storedok", 0, WHEN_OPEN, ZIP_ER_CHANGED, 0);
    fail += do_read(z, "storedok", ZIP_FL_UNCHANGED, WHEN_NEVER, 0, 0);
    zip_delete(z, zip_name_locate(z, "storedok", 0));
    fail += do_read(z, "storedok", 0, WHEN_OPEN, ZIP_ER_NOENT, 0);
    fail += do_read(z, "storedok", ZIP_FL_UNCHANGED, WHEN_NEVER, 0, 0);
    zs = zip_source_buffer(z, "asdf", 4, 0);
    if (zip_file_add(z, "new_file", zs, 0) < 0)
        fprintf(stderr, "%s: can't add file to zip archive '%s': %s\n", prg, archive, zip_strerror(z));
    fail += do_read(z, "new_file", 0, WHEN_OPEN, ZIP_ER_CHANGED, 0);
    zip_unchange_all(z);

    if (zip_close(z) == -1) {
        fprintf(stderr, "%s: can't close zip archive '%s': %s\n", prg, archive, zip_strerror(z));
        return 1;
    }

    exit(fail ? 1 : 0);
}