Exemple #1
0
int
main(int argc, char *argv[])
{
    const char *archive;
    struct zip *za;
    char buf[100];
    int err;
    int i;

    prg = argv[0];

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

    archive = argv[1];
    
    if ((za=zip_open(archive, 0, &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 (zip_set_archive_comment(za, new_archive_comment,
				(zip_uint16_t)strlen(new_archive_comment)) < 0) {
	zip_error_to_str(buf, sizeof(buf), err, errno);
	fprintf(stderr, "%s: zip_set_archive_comment failed: %s\n",
		prg, buf);
    }

    for (i=0; i<zip_get_num_entries(za, 0); i++) {
	snprintf(buf, sizeof(buf), "File comment no %d", i);
	if (zip_file_set_comment(za, i, buf, (zip_uint16_t)strlen(buf), 0) < 0) {
	    zip_error_to_str(buf, sizeof(buf), err, errno);
	    fprintf(stderr, "%s: zip_set_file_comment on file %d failed: %s\n",
		    prg, i, buf);
	}
    }

    if (zip_unchange_all(za) == -1) {
	fprintf(stderr, "%s: can't revert changes to archive `%s'\n",
		prg, archive);
	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;
}
Exemple #2
0
static int
do_read(struct zip *z, const char *name, int flags,
	enum when when_ex, int ze_ex, int se_ex)
{
    struct zip_file *zf;
    enum when when_got;
    int err, ze_got, se_got;
    char b[8192];
    zip_int64_t n;
    char expected[80];
    char got[80];

    when_got = WHEN_NEVER;
    ze_got = se_got = 0;
    
    if ((zf=zip_fopen(z, name, flags)) == NULL) {
	when_got = WHEN_OPEN;
	zip_error_get(z, &ze_got, &se_got);
    }
    else {
	while ((n=zip_fread(zf, b, sizeof(b))) > 0)
	    ;
	if (n < 0) {
	    when_got = WHEN_READ;
	    zip_file_error_get(zf, &ze_got, &se_got);
	}
	err = zip_fclose(zf);
	if (when_got == WHEN_NEVER && err != 0) {
	    when_got = WHEN_CLOSE;
	    ze_got = err;
	    se_got = 0;
	}
    }

    if (when_got != when_ex || ze_got != ze_ex || se_got != se_ex) {
	zip_error_to_str(expected, sizeof(expected), ze_ex, se_ex);
	zip_error_to_str(got, sizeof(got), ze_got, se_got);
	printf("%s: %s: got %s error (%s), expected %s error (%s)\n",
	       prg, name,
	       when_name[when_got], got, 
	       when_name[when_ex], expected);
	return 1;
    }
    else if (verbose)
	printf("%s: %s: passed\n", prg, name);

    return 0;
}
static VALUE zipruby_archive_commit(VALUE self) {
    struct zipruby_archive *p_archive;
    int changed, survivors;
    int errorp;

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

    changed = _zip_changed(p_archive->archive, &survivors);

    if (zip_close(p_archive->archive) == -1) {
        zip_unchange_all(p_archive->archive);
        zip_unchange_archive(p_archive->archive);
        rb_raise(Error, "Commit archive failed: %s", zip_strerror(p_archive->archive));
    }

    if (!NIL_P(p_archive->sources)) {
        rb_ary_clear(p_archive->sources);
    }

    if (!NIL_P(p_archive->buffer) && changed) {
        rb_funcall(p_archive->buffer, rb_intern("replace"), 1, rb_funcall(self, rb_intern("read"), 0));
    }

    p_archive->archive = NULL;
    p_archive->flags = (p_archive->flags & ~(ZIP_CREATE | ZIP_EXCL));

    if ((p_archive->archive = zip_open(RSTRING_PTR(p_archive->path), p_archive->flags, &errorp)) == NULL) {
        char errstr[ERRSTR_BUFSIZE];
        zip_error_to_str(errstr, ERRSTR_BUFSIZE, errorp, errno);
        rb_raise(Error, "Commit archive failed: %s", errstr);
    }

    return Qnil;
}
Exemple #4
0
archive_t arch_zip_read(const char* name,int buf){
    archive_t arch=(archive_t)HREmalloc(NULL,sizeof(struct archive_s));
    arch_init(arch);
    int err;
    arch->archive=zip_open(name,ZIP_CHECKCONS,&err);
    if (arch->archive==NULL){
        char errstr[1024];
        zip_error_to_str(errstr, sizeof(errstr), err, errno);
        Abort("cannot open zip archive `%s': %s\n",name , errstr);
    }
    arch->stream_index=SIcreate();
#ifdef LIBZIP_VERSION
    int count=zip_get_num_entries(arch->archive,0);
#else
    int count=zip_get_num_files(arch->archive);
#endif
    for(int i=0;i<count;i++){
        struct zip_stat sb;
        int res=zip_stat_index(arch->archive,i,0,&sb);
        if (res<0) {
            Abort("cannot stat zip archive: %s\n",zip_strerror(arch->archive));
        }
        SIputAt(arch->stream_index,sb.name,i);
        Print(infoShort,"stream %d is %s",i,sb.name);
    }
    arch->procs.contains=zip_contains;
    arch->procs.read=hre_zip_read;
    arch->procs.read_raw=hre_zip_read_raw;
    arch->procs.enumerator=zip_enum;
    arch->procs.close=hre_zip_close;
    arch->buf=buf;
    return arch;
}
bool zipobject::open(QFlags<OpenModeFlag> flags){
    /*
ZIP_CREATE
    Create the archive if it does not exist.
ZIP_EXCL
    Error if archive already exists.
ZIP_CHECKCONS
    Perform additional consistency checks on the archive, and error if they fail.
     */
    int zipflags = 0 ;
    int errorp = 0;

    if(flags & Create){
        zipflags |= ZIP_CREATE;
    }
    if(flags & ErrorIfExists){
        zipflags |= ZIP_EXCL;
    }
    if(flags & CheckCons){
        zipflags |= ZIP_CHECKCONS;
    }
    m_zip = zip_open(getCharPtr(m_filePath),zipflags,&errorp);
    if(NULL == m_zip){
        qDebug()<<"open failed : "<<errorp;
        char buf[255];
        int nError = zip_error_to_str(buf, sizeof(buf), errorp, errno);
        qDebug()<<nError<<buf;
        return false;
    }
    return true;
}
Exemple #6
0
static VALUE zipruby_archive_s_encrypt(VALUE self, VALUE path, VALUE password) {
  int res;
  int errorp;
  long pwdlen;

  Check_Type(path, T_STRING);
  Check_Type(password, T_STRING);
  pwdlen = RSTRING_LEN(password);

  if (pwdlen < 1) {
    rb_raise(Error, "Encrypt archive failed - %s: Password is empty", RSTRING_PTR(path));
  } else if (pwdlen > 0xff) {
    rb_raise(Error, "Encrypt archive failed - %s: Password is too long", RSTRING_PTR(path));
  }

  res = zip_encrypt(RSTRING_PTR(path), RSTRING_PTR(password), pwdlen, &errorp);

  if (res == -1) {
    char errstr[ERRSTR_BUFSIZE];
    zip_error_to_str(errstr, ERRSTR_BUFSIZE, errorp, errno);
    rb_raise(Error, "Encrypt archive failed - %s: %s", RSTRING_PTR(path), errstr);
  }

  return (res > 0) ? Qtrue : Qfalse;
}
Exemple #7
0
Handle<Value> Zipper::New(const Arguments& args)
{
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args.Length() != 1 || !args[0]->IsString())
        return ThrowException(Exception::TypeError(
          String::New("first argument must be a path to a zipfile")));

    std::string input_file = TOSTR(args[0]);
    struct zip *za;
    int err;
    char errstr[1024];
    if ((za=zip_open(input_file.c_str(), ZIP_CREATE, &err)) == NULL) {
        zip_error_to_str(errstr, sizeof(errstr), err, errno);
        std::stringstream s;
        s << "cannot open file: " << input_file << " error: " << errstr << "\n";
        return ThrowException(Exception::Error(
            String::New(s.str().c_str())));
    }

    Zipper* zf = new Zipper(input_file);
    zf->archive_ = za;
    zf->Wrap(args.This());
    return args.This();

}
size_t Unzip(const char *dst_path_, const char *archive, const UnzipFileHandler& handler)
{
    struct zip *za;
    struct zip_file *zf;
    struct zip_stat sb;
    char buf[1024];
    size_t ret = 0;
    std::string dst_path = dst_path_;

    int err;
    if ((za = zip_open(archive, 0, &err)) == nullptr) {
        zip_error_to_str(buf, sizeof(buf), err, errno);
        return false;
    }

    for (int i = 0; i < zip_get_num_entries(za, 0); ++i) {
        if (zip_stat_index(za, i, 0, &sb) == 0) {
            std::string dstpath = dst_path + '/' + sb.name;

            if (dstpath.back() == '/') {
                std::experimental::filesystem::create_directories(dstpath.c_str());
            }
            else {
                zf = zip_fopen_index(za, i, 0);
                if (!zf) {
                    goto bail_out;
                }

                FILE *of = fopen(dstpath.c_str(), "wb");
                if (of == nullptr) {
                    goto bail_out;
                }

                size_t sum = 0;
                while (sum != sb.size) {
                    size_t len = (size_t)zip_fread(zf, buf, sizeof(buf));
                    if (len < 0) {
                        fclose(of);
                        goto bail_out;
                    }
                    fwrite(buf, 1, len, of);
                    sum += len;
                }
                fclose(of);
                zip_fclose(zf);
                if (handler) { handler(dstpath.c_str()); }
                ++ret;
            }
        }
    }

    if (zip_close(za) == -1) {
        return false;
    }
    return ret;

bail_out:
    zip_close(za);
    return ret;
}
Exemple #9
0
static int directory_init(struct directory *d, const char *pathname)
{
    struct stat statbuf;

    if (stat(pathname, &statbuf) < 0) {
        sf_log(SF_LOG_ERR, "failed to stat file %s", pathname);
        return SF_ERR;
    }

    strncpy(d->name, pathname, NAME_MAX);

    if (S_ISDIR(statbuf.st_mode)) {
        d->isopened = 0;
        d->iszip  = 0;
    } else {
        int err;
        if ((d->zip = zip_open(pathname, 0, &err)) == NULL) {
            char buf[1024];
            zip_error_to_str(buf, 1024, err, errno);
            sf_log(SF_LOG_ERR, "failed to open %s: %s\n",
                   pathname, buf);
            return SF_ERR;
        }
        d->iszip = 1;
        d->isopened = 1;
    }

    d->nopens = 0;

    return SF_OK;
}
int
main(int argc, char *argv[])
{
    const char *archive;
    struct zip *za;
    char buf[100];
    int err;
    int i;

    prg = argv[0];

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

    archive = argv[1];
    
    if ((za=zip_open(archive, 0, &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;
    }

    for (i=0; i<zip_get_num_files(za); i++) {
	snprintf(buf, sizeof(buf), "File comment no %d", i);
	if (zip_set_file_comment(za, i, buf, strlen(buf)) < 0) {
	    zip_error_to_str(buf, sizeof(buf), err, errno);
	    fprintf(stderr, "%s: zip_set_file_comment on file %d failed: %s\n",
		    prg, i, buf);
	}
    }
    /* remove comment for third file */
    if (zip_set_file_comment(za, 2, NULL, 0) < 0) {
	zip_error_to_str(buf, sizeof(buf), err, errno);
	fprintf(stderr, "%s: zip_set_file_comment on file %d failed: %s\n",
		prg, i, buf);
    }

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

    return 0;
}
Exemple #11
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);
}
Exemple #12
0
Handle<Value> Zipper::addFile(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 3)
        return ThrowException(Exception::TypeError(
          String::New("requires three arguments, the path of a file, a filename and a callback")));
    
    // first arg must be path
    if(!args[0]->IsString())
        return ThrowException(Exception::TypeError(
          String::New("first argument must be a file path to add to the zip")));
    
    // second arg must be name
    if(!args[1]->IsString())
        return ThrowException(Exception::TypeError(
          String::New("second argument must be a file name to add to the zip")));
    
    // last arg must be function callback
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                  String::New("last argument must be a callback function")));
  
    std::string path = TOSTR(args[0]);
    std::string name = TOSTR(args[1]);
  
    Zipper* zf = ObjectWrap::Unwrap<Zipper>(args.This());
    zf->Ref();

    uv_work_t *req = new uv_work_t();
    closure_t *closure = new closure_t();

    // libzip is not threadsafe so we cannot use the zf->archive_
    // instead we open a new zip archive for each thread
    struct zip *za;
    int err;
    char errstr[1024];
    if ((za=zip_open(zf->file_name_.c_str() , ZIP_CREATE, &err)) == NULL) {
        zip_error_to_str(errstr, sizeof(errstr), err, errno);
        std::stringstream s;
        s << "cannot open file: " << zf->file_name_ << " error: " << errstr << "\n";
        zip_close(za);
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    closure->zf = zf;
    closure->za = za;
    closure->error = false;
    closure->path = path;
    closure->name = name;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(args[args.Length()-1]));
    req->data = closure;

    uv_queue_work(uv_default_loop(), req, _AddFile, (uv_after_work_cb)_AfterAddFile);
    return Undefined();
}
Exemple #13
0
/* If zip_error is non-zero, then push an appropriate error message
 * onto the top of the Lua stack and return zip_error.  Otherwise,
 * just return 0.
 */
static int S_push_error(lua_State* L, int zip_error, int sys_error) {
    char buff[1024];
    if ( 0 == zip_error ) return 0;

    int len = zip_error_to_str(buff, sizeof(buff), zip_error, sys_error);
    if ( len >= sizeof(buff) ) len = sizeof(buff)-1;
    lua_pushlstring(L, buff, len);

    return zip_error;
}
Exemple #14
0
static VALUE zipruby_archive_s_open(int argc, VALUE *argv, VALUE self) {
  VALUE path, flags, comp_level;
  VALUE archive;
  struct zipruby_archive *p_archive;
  int i_flags = 0;
  int errorp;
  int i_comp_level = Z_BEST_COMPRESSION;

  rb_scan_args(argc, argv, "12", &path, &flags, &comp_level);
  Check_Type(path, T_STRING);

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

  if (!NIL_P(comp_level)) {
    i_comp_level = NUM2INT(comp_level);

    if (i_comp_level != Z_DEFAULT_COMPRESSION && i_comp_level != Z_NO_COMPRESSION && (i_comp_level < Z_BEST_SPEED || Z_BEST_COMPRESSION < i_comp_level)) {
      rb_raise(rb_eArgError, "Wrong compression level %d", i_comp_level);
    }
  }

  archive = rb_funcall(Archive, rb_intern("new"), 0);
  Data_Get_Struct(archive, struct zipruby_archive, p_archive);

  if ((p_archive->archive = zip_open(RSTRING_PTR(path), i_flags, &errorp)) == NULL) {
    char errstr[ERRSTR_BUFSIZE];
    zip_error_to_str(errstr, ERRSTR_BUFSIZE, errorp, errno);
    rb_raise(Error, "Open archive failed - %s: %s", RSTRING_PTR(path), errstr);
  }

  //  p_archive->archive->comp_level = i_comp_level;
  p_archive->path = path;
  p_archive->flags = i_flags;
  p_archive->sources = rb_ary_new();

  if (rb_block_given_p()) {
    VALUE retval;
    int status;

    retval = rb_protect(rb_yield, archive, &status);
    zipruby_archive_close(archive);

    if (status != 0) {
      rb_jump_tag(status);
    }

    return retval;
  } else {
    return archive;
  }
}
Exemple #15
0
int
main(int argc, char *argv[])
{
    const char *archive;
    const char *file;
    const char *name;
    struct zip *za;
    struct zip_source *zs;
    char buf[100];
    int err;

    prg = argv[0];

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

    archive = argv[1];
    file = argv[2];
    
    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_file(za, file, 0, -1)) == NULL) {
	fprintf(stderr, "%s: error creating file source for `%s': %s\n", prg,
		file, zip_strerror(za));
	return 1;
    }

    if ((name=strrchr(file, '/')) == NULL)
	name = file;

    if (zip_add(za, name, 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'\n", prg,
		archive);
	return 1;
    }

    return 0;
}
int
main(int argc, char *argv[])
{
    const char *archive;
    struct zip *za;
    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, 0, &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 (zip_set_archive_comment(za, NULL, 0) < 0) {
	zip_error_to_str(buf, sizeof(buf), err, errno);
	fprintf(stderr, "%s: zip_set_archive_comment failed: %s\n",
		prg, buf);
    }

    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;
}
Exemple #17
0
Handle<Value> ZipFile::readFile(const Arguments& args) {
    HandleScope scope;

    if (args.Length() < 2)
        return ThrowException(Exception::TypeError(
                                  String::New("requires two arguments, the name of a file and a callback")));

    // first arg must be name
    if (!args[0]->IsString())
        return ThrowException(Exception::TypeError(
                                  String::New("first argument must be a file name inside the zip")));

    // last arg must be function callback
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));

    std::string name = TOSTR(args[0]);

    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    closure_t *closure = new closure_t();
    closure->request.data = closure;

    // libzip is not threadsafe so we cannot use the zf->archive_
    // instead we open a new zip archive for each thread
    struct zip *za;
    int err;
    char errstr[1024];
    if ((za = zip_open(zf->file_name_.c_str() , 0, &err)) == NULL) {
        zip_error_to_str(errstr, sizeof(errstr), err, errno);
        std::stringstream s;
        s << "cannot open file: " << zf->file_name_ << " error: " << errstr << "\n";
        zip_close(za);
        return ThrowException(Exception::Error(
                                  String::New(s.str().c_str())));
    }

    closure->zf = zf;
    closure->za = za;
    closure->error = false;
    closure->name = name;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(args[args.Length()-1]));
    uv_queue_work(uv_default_loop(), &closure->request, Work_ReadFile, Work_AfterReadFile);
    uv_ref(uv_default_loop());
    zf->Ref();
    return Undefined();
}
Exemple #18
0
static struct zip*
open_zip(YogEnv* env, YogVal pkg, YogVal path, int flags)
{
    SAVE_ARGS2(env, pkg, path);

    int error;
    YogVal bin = YogString_to_bin_in_default_encoding(env, VAL2HDL(env, path));
    struct zip* archive = zip_open(BINARY_CSTR(bin), flags, &error);
    if (archive == NULL) {
        char buf[256];
        zip_error_to_str(buf, array_sizeof(buf), error, errno);
        raise_ZipError(env, pkg, buf);
    }

    RETURN(env, archive);
}
Exemple #19
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;
}
int
main(int argc, char *argv[])
{
    const char *archive;
    struct zip *za;
    char buf[100];
    int err;
    const char *com;
    int i, len;

    prg = argv[0];

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

    archive = argv[1];
    
    if ((za=zip_open(archive, 0, &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 ((com=zip_get_archive_comment(za, &len, 0)) == NULL)
	printf("No archive comment\n");
    else
	printf("Archive comment: %.*s\n", len, com);

    for (i=0; i<zip_get_num_files(za); i++) {
	if ((com=zip_get_file_comment(za, i, &len, 0)) == NULL)
	    printf("No comment for `%s'\n", zip_get_name(za, i, 0));
	else
	    printf("File comment for `%s': %.*s\n", zip_get_name(za, i, 0), len, com);
    }	

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

    return 0;
}
Exemple #21
0
static VALUE zipruby_archive_encrypt(VALUE self, VALUE password) {
  VALUE retval;
  struct zipruby_archive *p_archive;
  long pwdlen;
  int changed;
  zip_uint64_t survivors;
  int errorp;

  Check_Type(password, T_STRING);
  pwdlen = RSTRING_LEN(password);

  if (pwdlen < 1) {
    rb_raise(Error, "Encrypt archive failed: Password is empty");
  } else if (pwdlen > 0xff) {
    rb_raise(Error, "Encrypt archive failed: Password is too long");
  }

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

  changed = _zip_changed(p_archive->archive, &survivors);

  if (zip_close(p_archive->archive) == -1) {
    zip_unchange_all(p_archive->archive);
    zip_unchange_archive(p_archive->archive);
    rb_raise(Error, "Encrypt archive failed: %s", zip_strerror(p_archive->archive));
  }

  if (!NIL_P(p_archive->buffer) && changed) {
    rb_funcall(p_archive->buffer, rb_intern("replace"), 1, rb_funcall(self, rb_intern("read"), 0));
  }

  p_archive->archive = NULL;
  p_archive->flags = (p_archive->flags & ~(ZIP_CREATE | ZIP_EXCL));

  retval = zipruby_archive_s_encrypt(Archive, p_archive->path, password);

  if ((p_archive->archive = zip_open(RSTRING_PTR(p_archive->path), p_archive->flags, &errorp)) == NULL) {
    char errstr[ERRSTR_BUFSIZE];
    zip_error_to_str(errstr, ERRSTR_BUFSIZE, errorp, errno);
    rb_raise(Error, "Encrypt archive failed: %s", errstr);
  }

  return retval;
}
int
find_fail(struct zip *z, const char *name, int flags, int zerr)
{
    int ze, se;
    char expected[80];

    if (zip_name_locate(z, name, flags) < 0) {
	zip_error_get(z, &ze, &se);
	if (ze != zerr) {
	    zip_error_to_str(expected, sizeof(expected), zerr, 0);
	    printf("%s: unexpected error while looking for ``%s'': "
		   "got ``%s'', expected ``%s''\n", prg, name,
		   zip_strerror(z), expected);
	    return 1;
	}

	return 0;
    }

    return 1;
}
Exemple #23
0
static int
torrentzip(const char *fname, int flags)
{
    struct zip *za;
    int err;
    char errstr[1024];

    if ((za=zip_open(fname, 0, &err)) == NULL) {
	zip_error_to_str(errstr, sizeof(errstr), err, errno);
	fprintf(stderr, "%s: cannot open zip archive `%s': %s\n",
		prg, fname, errstr);
	return -1;
    }

    if (flags & FLAG_VERBOSE) {
	if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0))
	    printf("%s: already torrentzipped\n", fname);
	else
	    printf("%s: torrentzipping\n", fname);
    }

    if ((flags & FLAG_DRYRUN) == 0) {
        if (zip_set_archive_flag(za, ZIP_AFL_TORRENT, 1) < 0) {
	    fprintf(stderr,	"%s: cannot set torrentzip flag in `%s': %s\n",
		    prg, fname, zip_strerror(za));
	    zip_close(za);
	    return -1;
        }
    }

    if (zip_close(za) < 0) {
	fprintf(stderr,	"%s: cannot torrentzip `%s': %s\n",
		prg, fname, zip_strerror(za));
	zip_unchange_all(za);
	zip_close(za);
	return -1;
    }

    return 0;
}
Exemple #24
0
ZIPProvider::ZIPHandle * ZIPProvider::getZIPHandle(
													const std::string & archiveFileName,
													bool createFile) {
	ZIPHandle * handle = nullptr;

	// Check if archive is already opened.
	auto it = openHandles.find(archiveFileName);
	if (it != openHandles.end()) {
		return it->second;
	}

	int flags = ZIP_CHECKCONS;

	// Check if archive exists.
	if (!FileUtils::isFile(FileName(archiveFileName))) {
		if (!createFile) {
			return nullptr;
		} else {
			flags |= ZIP_CREATE;
		}
	}

	// Open archive.
	int error;
	zip * zipHandle = zip_open(archiveFileName.c_str(), flags, &error);

	if (zipHandle == nullptr) {
		char errorString[256];
		zip_error_to_str(errorString, 256, error, errno);
		WARN(errorString+std::string(" File: ")+archiveFileName);
		return nullptr;
	}
	FileName archiveRoot;
	archiveRoot.setFSName("zip");
	archiveRoot.setDir( archiveFileName+'$' );
	handle = new ZIPHandle(archiveRoot,zipHandle);
	openHandles[archiveFileName] = handle;
	return handle;
}
Exemple #25
0
Handle<Value> ZipFile::New(const Arguments& args) {
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args.Length() != 1 || !args[0]->IsString())
        return ThrowException(Exception::TypeError(
                                  String::New("first argument must be a path to a zipfile")));

    std::string input_file = TOSTR(args[0]);
    struct zip *za;
    int err;
    char errstr[1024];
    if ((za = zip_open(input_file.c_str(), 0, &err)) == NULL) {
        zip_error_to_str(errstr, sizeof(errstr), err, errno);
        std::stringstream s;
        s << "cannot open file: " << input_file << " error: " << errstr << "\n";
        return ThrowException(Exception::Error(
                                  String::New(s.str().c_str())));
    }

    ZipFile* zf = new ZipFile(input_file);

    int num = zip_get_num_files(za);
    zf->names_.reserve(num);
    int i = 0;
    for (i = 0; i < num; i++) {
        struct zip_stat st;
        zip_stat_index(za, i, 0, &st);
        zf->names_.push_back(st.name);
    }

    zf->archive_ = za;
    zf->Wrap(args.This());
    return args.This();
}
Exemple #26
0
int
main(int argc, char *argv[])
{
    struct zip *za;
    struct zip **zs;
    int c, err, i;
    char errstr[1024], *tname;

    prg = argv[0];

    confirm = CONFIRM_ALL_YES;
    name_flags = 0;

    while ((c=getopt(argc, argv, OPTIONS)) != -1) {
	switch (c) {
	case 'D':
	    name_flags |= ZIP_FL_NODIR;
	    break;
	case 'i':
	    confirm &= ~CONFIRM_ALL_YES;
	    break;
	case 'I':
	    name_flags |= ZIP_FL_NOCASE;
	    break;
	case 's':
	    confirm &= ~CONFIRM_SAME_NO;
	    confirm |= CONFIRM_SAME_YES;
	    break;
	case 'S':
	    confirm &= ~CONFIRM_SAME_YES;
	    confirm |= CONFIRM_SAME_NO;
	    break;

	case 'h':
	    fputs(help_head, stdout);
	    printf(usage, prg);
	    fputs(help, stdout);
	    exit(0);
	case 'V':
	    fputs(version_string, stdout);
	    exit(0);

	default:
	    fprintf(stderr, usage, prg);
	    exit(2);
	}
    }

    if (argc < optind+2) {
	fprintf(stderr, usage, prg);
	exit(2);
    }

    tname = argv[optind++];

    if ((zs=malloc(sizeof(zs[0])*(argc-optind))) == NULL) {
	fprintf(stderr, "%s: out of memory\n", prg);
	exit(1);
    }

    if ((za=zip_open(tname, ZIP_CREATE, &err)) == NULL) {
	zip_error_to_str(errstr, sizeof(errstr), err, errno);
	fprintf(stderr, "%s: cannot open zip archive `%s': %s\n",
		prg, tname, errstr);
	exit(1);
    }

    for (i=0; i<argc-optind; i++) {
	if (merge_zip(za, tname, argv[optind+i], zs+i) < 0)
	    exit(1);
    }

    if (zip_close(za) < 0) {
	fprintf(stderr, "%s: cannot write zip archive `%s': %s\n",
		prg, tname, zip_strerror(za));
	exit(1);
    }

    for (i=0; i<argc-optind; i++)
	zip_close(zs[i]);

    exit(0);
}
Exemple #27
0
static int
merge_zip(struct zip *za, const char *tname, const char *sname,
	  struct zip **zsp)
{
    struct zip *zs;
    struct zip_source *source;
    int i, idx, err;
    char errstr[1024];
    const char *fname;
    
    if ((zs=zip_open(sname, 0, &err)) == NULL) {
	zip_error_to_str(errstr, sizeof(errstr), err, errno);
	fprintf(stderr, "%s: cannot open zip archive `%s': %s\n",
		prg, sname, errstr);
	return -1;
    }

    for (i=0; i<zip_get_num_files(zs); i++) {
	fname = zip_get_name(zs, i, 0);

	if ((idx=zip_name_locate(za, fname, name_flags)) != -1) {
	    switch (confirm_replace(za, tname, idx, zs, sname, i)) {
	    case 0:
		break;
		
	    case 1:
		if ((source=zip_source_zip(za, zs, i, 0, 0, 0)) == NULL
		    || zip_replace(za, idx, source) < 0) {
		    zip_source_free(source);
		    fprintf(stderr,
			    "%s: cannot replace `%s' in `%s': %s\n",
			    prg, fname, tname, zip_strerror(za));
		    return -1;
		}
		break;

	    case -1:
		zip_close(zs);
		return -1;
		
	    default:
		fprintf(stderr,	"%s: internal error: "
			"unexpected return code from confirm (%d)\n",
			prg, err);
		zip_close(zs);
		return -1;
	    }
	}
	else {
	    if ((source=zip_source_zip(za, zs, i, 0, 0, 0)) == NULL
		|| zip_add(za, fname, source) < 0) {
		zip_source_free(source);
		fprintf(stderr,
			"%s: cannot add `%s' to `%s': %s\n",
			prg, fname, tname, zip_strerror(za));
		zip_close(zs);
		return -1;
	    }
	}
    }

    *zsp = zs;
    return 0;
}
Exemple #28
0
int extract_to_cache(const char *archive, const char *cache_path)
{
  struct zip *ziparchive;
  struct zip_file *zipfile;
  struct zip_stat zipstat;
  char buf[4096];
  int err;
  int i, len;
  int fd;
  int dirname_len;
  long long sum;
  char *full_path;
  char *dir_name;
  Stat localfile;
  utimbuf modified;
  android_printf("unzip: Preparing to cache. This could take a while...");

  if ((ziparchive = zip_open(archive, 0, &err)) == NULL)
  {
    zip_error_to_str(buf, sizeof(buf), err, errno);
    android_printf("unzip error: can't open archive %s/n",archive);
    return 1;
  }

  mkpath(cache_path);

  for (i = 0; i < zip_get_num_entries(ziparchive, 0); i++)
  {
    if (zip_stat_index(ziparchive, i, 0, &zipstat) != 0)
    {
      android_printf("unzip error: can't open entry: %i/n",i);
      continue;
    }

    if(strncmp (zipstat.name,"assets/",7) != 0)
      continue;

    modified.modtime = modified.actime = zipstat.mtime;

    full_path = (char*)malloc( sizeof(char*) * (strlen(cache_path) + 1 + strlen(zipstat.name) + 1));
    sprintf(full_path, "%s/%s",cache_path,zipstat.name);

    if (zipstat.name[strlen(zipstat.name) - 1] == '/')
    {
      mkpath(full_path);
      free(full_path);
      continue;
    }

    zipfile = zip_fopen_index(ziparchive, i, 0);
    if (!zipfile)
    {
      android_printf("unzip error: can't open index");
      free(full_path);
      continue;
    }

    if (stat(full_path, &localfile) != 0)
    {
      dirname_len = strrchr(zipstat.name,'/') - zipstat.name;
      dir_name = (char*)malloc( sizeof(char*) * (strlen(cache_path) + 1 + dirname_len + 1));
      strncpy(dir_name, full_path, strlen(cache_path) + dirname_len + 1);
      dir_name[strlen(cache_path) + dirname_len + 1] = '\0';
      mkpath(dir_name);
      free(dir_name);
    }
    else if (localfile.st_mtime == zipstat.mtime)
    {
      free(full_path);
      continue;
    }

    fd = open(full_path, O_RDWR | O_TRUNC | O_CREAT, 0644);
    if(fd < 0)
    {
      android_printf("unzip error: could not open %s",full_path);
      free(full_path);
      continue;
    }

    sum = 0;
    while (sum != zipstat.size)
    {
      len = zip_fread(zipfile, buf, 4096);
      if (len < 0)
      {
        android_printf("unzip error: no data in %s",full_path);
        free(full_path);
        continue;
      }
      write(fd, buf, len);
      sum += len;
    }
    close(fd);
    zip_fclose(zipfile);

    if (stat(full_path, &localfile) == 0)
    {
      // save the zip time. this way we know for certain if we need to refresh.
      utime(full_path, &modified);
    }
    else
    {
      android_printf("unzip error: failed to extract %s",full_path);
    }

    free(full_path);
  }

  if (zip_close(ziparchive) == -1)
    android_printf("unzip error: can't close zip archive `%s'/n", archive);

  return 0;
}
Exemple #29
0
int
main(int argc, char *argv[])
{
    const char *fname;
    char buf[100];
    struct zip *z;
    int c, flags, ze;
    struct zip_stat sb;
    int index;

    flags = 0;
    prg = argv[0];

    while ((c=getopt(argc, argv, "grs")) != -1) {
	switch (c) {
	case 'g':
	    flags = ZIP_FL_ENC_GUESS;
	    break;
	case 'r':
	    flags = ZIP_FL_ENC_RAW;
	    break;
	case 's':
	    flags = ZIP_FL_ENC_STRICT;
	    break;

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

    fname = argv[optind++];
    errno = 0;

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

    while (optind < argc) {
        index = atoi(argv[optind++]);

	if (zip_stat_index(z, index, flags, &sb) < 0) {
	    fprintf(stderr, "%s: zip_stat_index failed on '%d' failed: %s\n",
		    prg, index, zip_strerror(z));
	    return 1;
	}

	if (sb.valid & ZIP_STAT_NAME)
	    printf("name: '%s'\n", sb.name);
	if (sb.valid & ZIP_STAT_INDEX)
	    printf("index: '%"PRIu64"'\n", sb.index);
	if (sb.valid & ZIP_STAT_SIZE)
	    printf("size: '%"PRIu64"'\n", sb.size);
	if (sb.valid & ZIP_STAT_COMP_SIZE)
	    printf("compressed size: '%"PRIu64"'\n", sb.comp_size);
	if (sb.valid & ZIP_STAT_MTIME) {
	    struct tm *tpm;
	    tpm = localtime(&sb.mtime);
	    strftime(buf, sizeof(buf), "%a %b %d %Y %T", tpm);
	    printf("mtime: '%s'\n", buf);
	}
	if (sb.valid & ZIP_STAT_CRC)
	    printf("crc: '%0x'\n", sb.crc);
	if (sb.valid & ZIP_STAT_COMP_METHOD)
	    printf("compression method: '%d'\n", sb.comp_method);
	if (sb.valid & ZIP_STAT_ENCRYPTION_METHOD)
	    printf("encryption method: '%d'\n", sb.encryption_method);
	if (sb.valid & ZIP_STAT_FLAGS)
	    printf("flags: '%ld'\n", (long)sb.flags);
	printf("\n");
    }

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

    return 0;
}
// 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;
		}
	}