Example #1
0
int
vfs_zip_scandir (const char *dir, struct dirent ***namelist, int (*selector) (const struct dirent *), int (*cmp) (const struct dirent **, const struct dirent **)) {
    trace ("vfs_zip_scandir: %s\n", dir);
    int error;
    struct zip *z = zip_open (dir, 0, &error);
    if (!z) {
        trace ("zip_open failed (code: %d)\n", error);
        return -1;
    }

    int num_files = 0;
    const int n = zip_get_num_files(z);
    *namelist = malloc(sizeof(void *) * n);
    for (int i = 0; i < n; i++) {
        const char *nm = zip_get_name(z, i, 0);
        struct dirent entry;
        strncpy(entry.d_name, nm, sizeof(entry.d_name)-1);
        entry.d_name[sizeof(entry.d_name)-1] = '\0';
        if (!selector || selector && selector(&entry)) {
            (*namelist)[num_files] = calloc(1, sizeof(struct dirent));
            strcpy((*namelist)[num_files]->d_name, entry.d_name);
            num_files++;
            trace("vfs_zip: %s\n", nm);
        }
    }

    zip_close (z);
    trace ("vfs_zip: scandir done\n");
    return num_files;
}
Example #2
0
int main(int argc, char *argv[]){
	int errorp = 0;
	struct zip* zipObj = NULL;
	int num_entries = 0;
	int i;

	if( argc < 2){
		usage();
		return 1;
	}

	zipObj = zip_open(argv[1],0,&errorp);
	if( NULL == zipObj ){
		printf("open zip file failed , error code : %d\n",errorp);
		return 2;
	}

	num_entries = zip_get_num_files(zipObj) ;
	for( i = 0 ; i < num_entries ; ++i ){
		printf("%s\n",zip_get_name(zipObj,i,0) );
	}

	zip_close(zipObj);
	zipObj = NULL ;

	return 0;
};
Example #3
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;
}
Example #4
0
bool zipobject::extractTo(const QString& dirPath){
    int num_entries = zip_get_num_files(m_zip) ;
    for( int i = 0 ; i < num_entries ; ++i ){
        qDebug()<<zip_get_name(m_zip,i,0);
        zip_file* pFile = zip_fopen_index(m_zip,i,0);
        struct zip_stat stat ;
        zip_stat_index(m_zip,i,0,&stat);
        
        const int length = stat.size ;
        char buffer[length +1 ] ;
        int rRead = zip_fread(pFile,buffer,sizeof(buffer));
        if( -1 == rRead ){
            qDebug()<<"read failed : "<<zip_strerror(m_zip);
            return false;
        }
        
        QFileInfo fileInfo(dirPath + '/' + stat.name);
        QDir dir = fileInfo.absoluteDir() ;
        if(!dir.mkpath(".")){
            return false;
        }
        
        QFile file(dirPath + '/' + stat.name);
        file.open(QIODevice::WriteOnly);
        file.write(QByteArray(buffer,length));
        file.close();
    }
    return true;
}
Example #5
0
/*************************************************
 Function:		readZipFileName
 Descroption:
 Input:
	1.zip* z
	2.filetype
 Output:
 Return:
 Other:
*************************************************/
int readZipFileName(struct zip* z, char* filetype)
{
    int i;
    struct zip_stat fstat;

    if(z != NULL)
    {
        zip_stat_init(&fstat);
        int c = zip_get_num_files(z);
        if(c > 0)
        {
            for (i = 0 ; i < c; i++)
            {
                const char* name = zip_get_name(z, i, 0);
                if(name != NULL)
                {
                    zip_stat(z, name,0,&fstat);
                    //LOGI("File %i:%s Size: %lld Size2: %lld\n", i,fstat.name,fstat.size ,fstat.comp_size);
                }
            }
        }
    }
    else
    {
        return -1;
    }

    return 0;
}
Example #6
0
RList * r_io_zip_get_files(char *archivename, ut32 flags, int mode, int rw) {
	ut64 num_entries = 0, i = 0;
	struct zip * zipArch = r_io_zip_open_archive(archivename, flags, mode, rw);
	struct zip_stat sb; 
	RList *files = NULL; 
	//eprintf("Slurping file");
	if (zipArch) {
		files = r_list_new();
		num_entries = zip_get_num_files(zipArch);

		for (i=0; i < num_entries; i++) {
			char *name = NULL;	
			zip_stat_init(&sb );
			zip_stat_index(zipArch, i, 0, &sb );	
			//eprintf("Comparing %s == %s = %d\n", sb.name, filename, strcmp(sb.name, filename));
			name = strdup(sb.name);
			if (name) {
				r_list_append(files, name);
			}

		}
	}
	if (zipArch)
		zip_close(zipArch);

	return files;
}
Example #7
0
/* The file can be a file in the archive or ::[num].  */
RIOZipFileObj* r_io_zip_alloc_zipfileobj(const char *archivename, const char *filename, ut32 perm, int mode, int rw) {
	RIOZipFileObj *zfo = NULL;
	ut64 i, num_entries;
	struct zip_stat sb;
	struct zip *zipArch = r_io_zip_open_archive (archivename, perm, mode, rw);
	if (!zipArch) {
		return NULL;
	}
	num_entries = zip_get_num_files (zipArch);

	for (i = 0; i < num_entries; i++) {
		zip_stat_init (&sb);
		zip_stat_index (zipArch, i, 0, &sb);
		if (sb.name != NULL) {
			if (strcmp (sb.name, filename) == 0) {
				zfo = r_io_zip_create_new_file (
					archivename, filename, &sb,
					perm, mode, rw);
				r_io_zip_slurp_file (zfo);
				break;
			}
		}
	}
	if (!zfo) {
		zfo = r_io_zip_create_new_file (archivename,
			filename, NULL, perm, mode, rw);
	}
	zip_close (zipArch);
	return zfo;
}
Example #8
0
bool ZipAssetReader::GetFileListing(const char *path, std::vector<FileInfo> *listing, const char *filter = 0)
{
	ILOG("Zip path: %s", path);
	// We just loop through the whole ZIP file and deduce what files are in this directory, and what subdirectories there are.
	std::set<std::string> files;
	std::set<std::string> directories;
	int numFiles = zip_get_num_files(zip_file_);
	size_t pathlen = strlen(path);
	if (path[pathlen-1] == '/')
		pathlen--;
	for (int i = 0; i < numFiles; i++) {
		const char* name = zip_get_name(zip_file_, i, 0);
		if (!name)
			continue;
		ILOG("Comparing %s %s %i", name, path, pathlen);
		if (!memcmp(name, path, pathlen)) {
			// The prefix is right. Let's see if this is a file or path.
			char *slashPos = strchr(name + pathlen + 1, '/');
			if (slashPos != 0) {
				// A directory.
				std::string dirName = std::string(name + pathlen + 1, slashPos - (name + pathlen + 1));
				directories.insert(dirName);
			} else {
				files.insert(std::string(name + pathlen + 1));
			}
		}
	}

	for (auto diter = directories.begin(); diter != directories.end(); ++diter) {
		FileInfo info;
		info.name = *diter;
		info.fullName = std::string(path);
		if (info.fullName[info.fullName.size()-1] == '/')
			info.fullName = info.fullName.substr(0, info.fullName.size() - 1);
		info.fullName += "/" + *diter;
		info.exists = true;
		info.isWritable = false;
		info.isDirectory = true;
		listing->push_back(info);
	}

	for (auto fiter = files.begin(); fiter != files.end(); ++fiter) {
		FileInfo info;
		info.name = *fiter;
		info.fullName = std::string(path);
		if (info.fullName[info.fullName.size()-1] == '/')
			info.fullName = info.fullName.substr(0, info.fullName.size() - 1);
		info.fullName += "/" + *fiter;
		info.exists = true;
		info.isWritable = false;
		info.isDirectory = false;
		listing->push_back(info);
	}
	
	std::sort(listing->begin(), listing->end());
	return true;
}
Example #9
0
static int S_archive_get_num_files(lua_State* L) {
    struct zip** ar = check_archive(L, 1);

    if ( ! *ar ) return 0;

    lua_pushinteger(L, zip_get_num_files(*ar));

    return 1;
}
Example #10
0
static VALUE zipruby_archive_num_files(VALUE self) {
  struct zipruby_archive *p_archive;
  int num_files;

  Data_Get_Struct(self, struct zipruby_archive, p_archive);
  Check_Archive(p_archive);
  num_files = zip_get_num_files(p_archive->archive);

  return INT2NUM(num_files);
}
Example #11
0
void show(zip_t *archive, const char *text)
{
	fprintf(stderr, "--- %s ---\n", text);
	int files_total = zip_get_num_files(archive);
	int i;
	for (i = 0; i<files_total; i++) {
		const char *filename =  zip_get_name(archive, i, 0);
		fprintf(stderr, "file index %d: %s\n", i, filename);
	}
}
static int zip_get_app_directory(struct zip* zf, char** path)
{
	int i = 0;
	int c = zip_get_num_files(zf);
	int len = 0;
	const char* name = NULL;

	/* look through all filenames in the archive */
	do {
		/* get filename at current index */
		name = zip_get_name(zf, i++, 0);
		if (name != NULL) {
			/* check if we have a "Payload/.../" name */
			len = strlen(name);
			if (!strncmp(name, "Payload/", 8) && (len > 8)) {
				/* locate the second directory delimiter */
				const char* p = name + 8;
				do {
					if (*p == '/') {
						break;
					}
				} while(p++ != NULL);

				/* try next entry if not found */
				if (p == NULL)
					continue;

				len = p - name + 1;

				if (*path != NULL) {
					free(*path);
					*path = NULL;
				}

				/* allocate and copy filename */
				*path = (char*)malloc(len + 1);
				strncpy(*path, name, len);

				/* add terminating null character */
				char* t = *path + len;
				*t = '\0';
				break;
			}
		}
	} while(i < c);

	/* check if the path actually exists */
	int zindex = zip_name_locate(zf, *path, 0);
	if (zindex < 0) {
		return -1;
	}

	return 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,
				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_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);
	}
    }

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

    return 0;
}
Example #14
0
void ZipFile::GetNames()
{
    int num = zip_get_num_files(this->archive);
    this->names.clear();
    this->names.reserve(num);
    int i = 0;
    for (i=0; i<num; i++) {
        struct zip_stat st;
        zip_stat_index(this->archive, i, 0, &st);
        this->names.push_back(st.name);
    }
}
Example #15
0
static arch_enum_t zip_enum(archive_t archive,char *regex){
    if (regex!=NULL) Abort("regex not supported");
    arch_enum_t e=(arch_enum_t)HREmalloc(NULL,sizeof(struct arch_enum));
    e->procs.enumerate=zip_enumerate;
    e->procs.free=zip_enum_free;
    e->archive=archive;
    e->next=0;
#ifdef LIBZIP_VERSION
    e->count=zip_get_num_entries(archive->archive,0);
#else
    e->count=zip_get_num_files(archive->archive);
#endif
    return e;
}
Example #16
0
ResourceManager::ResourceManager(const char *apkFilename): archive(0) {
	archive = zip_open(apkFilename, 0, NULL);

	if(archive) {
		//Just for debug, print APK contents
		int numFiles = zip_get_num_files(archive);
		for (int i=0; i<numFiles; i++) {
			const char* name = zip_get_name(archive, i, 0);
			if (name == NULL) {
	//			LOGE("Error reading zip file name at index %i : %s", zip_strerror(APKArchive));
				return;
			}
	//		LOGI("File %i : %s\n", i, name);
		}
	}
}
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;
}
Example #18
0
void setAPK (const char* apkPath) {
  LOGI("Loading APK %s", apkPath);
  APKArchive = zip_open(apkPath, 0, NULL);
  if (APKArchive == NULL) {
    LOGE("Error loading APK");
    return;
  }

  //Just for debug, print APK contents
  int numFiles = zip_get_num_files(APKArchive);
  for (int i=0; i<numFiles; i++) {
    const char* name = zip_get_name(APKArchive, i, 0);
    if (name == NULL) {
      LOGE("Error reading zip file name at index %i : %s", i, zip_strerror(APKArchive));
      return;
    }
    LOGI("File %i : %s\n", i, name);
  }
}
Example #19
0
 ZipFileOutput::ZipFileOutput(const std::string& archive)
   : m_archiveHandle(0),
     m_initialized(false),
     m_archive(archive),
     m_currentFile(0)
 {
     int error = 0;
     m_archiveHandle = zip_open(m_archive.c_str(), ZIP_CREATE, &error);
     
     if(! m_archiveHandle)
         throw FileAccessFailed(m_archive, "Failed to open zip archive.");
     
     // delete all files in the archive
     int numFiles = zip_get_num_files(m_archiveHandle);
     for(int i = 0; i < numFiles; ++i)
     {
         if(zip_delete(m_archiveHandle, i) < 0)
             throw FileAccessFailed(m_archive, "Failed to delete files in zip archive.");
     }
 }
Example #20
0
/*************************************************
 Function:		readDexFile
 Descroption:
 Input:
	1.zip* z
	2.filename
	3.char* buf
 Output:
 Return:
 Other:
*************************************************/
long readDexFile(struct zip* z, char* filename, unsigned char** buf)
{
    int i;
    long ReadNum = 0;
    struct zip_stat fstat;

    if(z != NULL && NULL != buf)
    {
        zip_stat_init(&fstat);
        int c = zip_get_num_files(z);
        if(c > 0)
        {
            for (i = 0 ; i < c; i++)
            {
                const char* name = zip_get_name(z, i, 0);
                if(0 == strcmp(name,filename))
                {
                    zip_stat(z, name,0,&fstat);
                    //LOGI("File %i:%s Size1: %lld Size2: %lld\n", i,fstat.name,fstat.size ,fstat.comp_size);

                    struct zip_file* file = zip_fopen(z, filename, 0);
                    if (file)
                    {
                        *buf =(unsigned char *)malloc(fstat.size+1);
                        memset(*buf,0,(fstat.size+1));
                        ReadNum = zip_fread(file, *buf,fstat.size);
                        zip_fclose(file);
                    }
                    break;
                }
            }
        }
    }
    else
    {
        return 0;
    }

    return ReadNum;
}
Example #21
0
static YogVal
compress(YogEnv* env, YogVal self, YogVal pkg, YogVal args, YogVal kw, YogVal block)
{
    SAVE_ARGS5(env, self, pkg, args, kw, block);
    YogVal path = YUNDEF;
    YogVal files = YUNDEF;
    PUSH_LOCALS2(env, path, files);
    YogCArg params[] = { { "path", &path }, { "*", &files }, { NULL, NULL } };
    YogGetArgs_parse_args(env, "compress", params, args, kw);
    if (!IS_PTR(path) || (BASIC_OBJ_TYPE(path) != TYPE_STRING)) {
        YogError_raise_TypeError(env, "path must be String");
    }

    struct zip* archive = open_zip(env, pkg, path, ZIP_CREATE);
    int n = zip_get_num_files(archive);
    int i;
    for (i = 0; i < n; i++) {
        if (zip_delete(archive, i) != 0) {
            raise_ZipError(env, pkg, zip_strerror(archive));
        }
    }
    uint_t size = YogArray_size(env, files);
    uint_t j;
    for (j = 0; j < size; j++) {
        YogHandle* name = VAL2HDL(env, YogArray_at(env, files, j));
        YogMisc_check_String(env, name, "Filename");
        YogVal bin = YogString_to_bin_in_default_encoding(env, name);
        const char* fname = BINARY_CSTR(bin);
        struct zip_source* source = zip_source_file(archive, fname, 0, 0);
        if (source == NULL) {
            raise_ZipError(env, pkg, zip_strerror(archive));
        }
        if (zip_add(archive, fname, source) < 0) {
            raise_ZipError(env, pkg, zip_strerror(archive));
        }
    }
    close_zip(env, pkg, archive);

    RETURN(env, YNIL);
}
Example #22
0
static VALUE zipruby_archive_each(VALUE self) {
  struct zipruby_archive *p_archive;
  int i, num_files;

  Data_Get_Struct(self, struct zipruby_archive, p_archive);
  Check_Archive(p_archive);
  num_files = zip_get_num_files(p_archive->archive);

  for (i = 0; i < num_files; i++) {
    VALUE file;
    int status;

    file = rb_funcall(File, rb_intern("new"), 2, self, INT2NUM(i));
    rb_protect(rb_yield, file, &status);
    rb_funcall(file, rb_intern("close"), 0);

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

  return Qnil;
}
Example #23
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();
}
Example #24
0
RList * r_io_zip_get_files(char *archivename, ut32 perm, int mode, int rw) {
	struct zip *zipArch = r_io_zip_open_archive (archivename, perm, mode, rw);
	ut64 num_entries = 0, i = 0;
	RList *files = NULL;
	struct zip_stat sb;
	char *name;
	if (zipArch) {
		files = r_list_newf (free);
		if (!files) {
			zip_close (zipArch);
			return NULL;
		}
		num_entries = zip_get_num_files (zipArch);
		for (i = 0; i < num_entries; i++) {
			zip_stat_init (&sb);
			zip_stat_index (zipArch, i, 0, &sb);
			if ((name = strdup (sb.name))) {
				r_list_append (files, name);
			}
		}
	}
	zip_close (zipArch);
	return files;
}
Example #25
0
bool QgsZipUtils::unzip( const QString &zipFilename, const QString &dir, QStringList &files )
{
  files.clear();

  if ( !QFileInfo::exists( zipFilename ) )
  {
    QgsMessageLog::logMessage( QObject::tr( "Error zip file does not exist: '%1'" ).arg( zipFilename ) );
    return false;
  }
  else if ( zipFilename.isEmpty() )
  {
    QgsMessageLog::logMessage( QObject::tr( "Error zip filename is empty" ) );
    return false;
  }
  else if ( !QDir( dir ).exists( dir ) )
  {
    QgsMessageLog::logMessage( QObject::tr( "Error output dir does not exist: '%1'" ).arg( dir ) );
    return false;
  }
  else if ( !QFileInfo( dir ).isDir() )
  {
    QgsMessageLog::logMessage( QObject::tr( "Error output dir is not a directory: '%1'" ).arg( dir ) );
    return false;
  }
  else if ( !QFileInfo( dir ).isWritable() )
  {
    QgsMessageLog::logMessage( QObject::tr( "Error output dir is not writable: '%1'" ).arg( dir ) );
    return false;
  }

  int rc = 0;
  const QByteArray fileNamePtr = zipFilename.toUtf8();
  struct zip *z = zip_open( fileNamePtr.constData(), ZIP_CHECKCONS, &rc );

  if ( rc == ZIP_ER_OK && z )
  {
    int count = zip_get_num_files( z );
    if ( count != -1 )
    {
      struct zip_stat stat;

      for ( int i = 0; i < count; i++ )
      {
        zip_stat_index( z, i, 0, &stat );
        size_t len = stat.size;

        struct zip_file *file = zip_fopen_index( z, i, 0 );
        std::unique_ptr< char[] > buf( new char[len] );
        if ( zip_fread( file, buf.get(), len ) != -1 )
        {
          QString fileName( stat.name );
          QFileInfo newFile( QDir( dir ), fileName );

          // Create path for a new file if it does not exist.
          if ( !newFile.absoluteDir().exists() )
          {
            if ( !QDir( dir ).mkpath( newFile.absolutePath() ) )
              QgsMessageLog::logMessage( QObject::tr( "Failed to create a subdirectory %1/%2" ).arg( dir ).arg( fileName ) );
          }

          QFile outFile( newFile.absoluteFilePath() );
          if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
          {
            QgsMessageLog::logMessage( QObject::tr( "Could not write to %1" ).arg( newFile.absoluteFilePath() ) );
          }
          else
          {
            outFile.write( buf.get(), len );
          }
          zip_fclose( file );
          files.append( newFile.absoluteFilePath() );
        }
        else
        {
          zip_fclose( file );
          QgsMessageLog::logMessage( QObject::tr( "Error reading file: '%1'" ).arg( zip_strerror( z ) ) );
          return false;
        }
      }
    }
    else
    {
      zip_close( z );
      QgsMessageLog::logMessage( QObject::tr( "Error getting files: '%1'" ).arg( zip_strerror( z ) ) );
      return false;
    }

    zip_close( z );
  }
  else
  {
    QgsMessageLog::logMessage( QObject::tr( "Error opening zip archive: '%1' (Error code: %2)" ).arg( z ? zip_strerror( z ) : zipFilename, rc ) );
    return false;
  }

  return true;
}
Example #26
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;
}
Example #27
0
AbstractFSProvider::status_t ZIPProvider::ZIPHandle::dir(
															const std::string & localDirectory,
															std::list<FileName> & result,
															const uint8_t flags) {
	int num = zip_get_num_files(handle);
	if (num == -1) {
		WARN(zip_strerror(handle));
		return FAILURE;
	}
	struct zip_stat sb;
	zip_stat_init(&sb);

	// Iterate over indices.
	for (int i = 0; i < num; ++i) {
		if (zip_stat_index(handle, i, 0, &sb) == -1) {
			WARN(zip_strerror(handle));
			return FAILURE;
		}

		FileName entryFileName(sb.name);

		// Determine if the entry is a file or a directory.
		if (entryFileName.getFile().empty()) {
			if(!(flags & FileUtils::DIR_DIRECTORIES)) {
				continue;
			}

			if (!(flags & FileUtils::DIR_RECURSIVE)) {
				std::string entryDirectory = entryFileName.getDir();

				if(entryDirectory == localDirectory) {
					continue;
				}

				if(entryDirectory.back() == '/') {
					entryDirectory.resize(entryDirectory.size() - 1);
				}
				const auto slashPos = entryDirectory.find_last_of('/');
				if(slashPos != std::string::npos) {
					entryDirectory = entryDirectory.substr(0, slashPos + 1);
				} else {
					entryDirectory.clear();
				}
				// Compare the parent directory of the directory with the requested localDirectory.
				if(entryDirectory != localDirectory) {
					continue;
				}
			}
		} else {
			if(!(flags & FileUtils::DIR_FILES)) {
				continue;
			}

			// Compare the directory of the file with the requested localDirectory.
			if (!(flags & FileUtils::DIR_RECURSIVE) && entryFileName.getDir() != localDirectory) {
				continue;
			}
		}

		// Check for hidden files beginning with '.' (files only).
		if (entryFileName.getFile().front() == '.' && !(flags & FileUtils::DIR_HIDDEN_FILES)) {
			continue;
		}

		FileName f;
		f.setFSName(archiveRoot.getFSName());
		f.setDir(archiveRoot.getDir() + entryFileName.getDir());
		f.setFile(entryFileName.getFile());
		result.push_back(f);
	}
	return OK;
}
Example #28
0
bool FlpImport::tryZIPImport( trackContainer * _tc )
{
	// see if the file is a zip file
	closeFile();
	const QFile &thefile = file();

	int err = 0;
	struct zip *zfile = zip_open(qPrintable(thefile.fileName()), 0, &err);

	if( zfile == NULL )
	{
		if( err == ZIP_ER_NOZIP )
		{
			printf("flp import (zip): not a valid zip file\n");
		}
		else if( err == ZIP_ER_OPEN )
		{
			printf("flp import (zip): error opening file\n");
		}
		else if( err == ZIP_ER_READ || err == ZIP_ER_SEEK )
		{
			printf("flp import (zip): error reading file\n");
		}
		else
		{
			printf("flp import (zip): unknown error opening zip file\n");
		}
		return false;
	}
	// valid zip file
	// get temporary directory
	QString tmpName;
	
	{
		QTemporaryFile qtmp;
		if( qtmp.open() )
		{
			tmpName = qtmp.fileName();
		}
		else
		{
			zip_close(zfile);
			printf("flp import (zip): error getting temporary folder\n");
			return false;
		}
	}
	QDir tmpDir = QDir::temp();
	tmpDir.mkdir(tmpName);
	tmpDir.cd(tmpName);
	
	// unzip everything to the temp folder
	int buf_size = getpagesize();
	char buf[buf_size];
	int numFiles = zip_get_num_files(zfile);
	int i;
	bool foundFLP = false;
	QString flpFile = "";
	for( i=0; i<numFiles; ++i )
	{
		const char* fileName = zip_get_name(zfile, i, 0);
		if( fileName != NULL )
		{
			struct zip_file *unzipFile = zip_fopen_index(zfile, i, 0); 
			if( unzipFile != NULL )
			{
				// we have a handle to read, now get a handle to the outfile
				QFile out(tmpDir.absolutePath() + QDir::separator() + 
					fileName);
				out.open(QIODevice::WriteOnly);
				// ok we have handles on both, now do buffered writing
				bool readErr = false;
				while(true)
				{
					// read into buffer
					int numRead = zip_fread(unzipFile, buf, buf_size);
					if( numRead == -1 )
					{
						readErr = true;
						printf("flp import (zip): error while reading %s "
							"from zip file\n", fileName);
						break;
					}
					out.write( buf, numRead );
					if( numRead < buf_size ) break;
				}
				// we successfully read this file, check if it is 
				// the .flp file
				QString qFileName(fileName);
				if( qFileName.endsWith(".flp") )
				{
					foundFLP = true;
					flpFile = out.fileName();
				}

				// clean up
				out.close();
				zip_fclose(unzipFile);
			}
			else
			{
				printf("flp import (zip): unable to get %s out of %s\n",
					fileName, qPrintable(thefile.fileName()) );
			}
		}
	}
	zip_close(zfile);

	// make sure there was a .flp file in the archive	
	if( ! foundFLP )
	{
		printf("flp import (zip): no .flp file found in archive\n");
		return false;
	}

	// use the flp_import plugin to load the .flp file
	// which was extracted to the temp dir
	setFile(flpFile);
	m_fileBase = QFileInfo( flpFile ).path();
	return tryFLPImport( _tc );
}
Example #29
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;
}
int cepgdata2xmltv::Process(int argc, char *argv[])
{
    FILE *f=fopen("/var/lib/epgsources/epgdata2xmltv","r");
    if (!f)
    {
        esyslog("failed to open epgdata2xmltv config");
        return 1;
    }
    char *line=NULL,*lptr=NULL;
    size_t size;
    if (getline(&line,&size,f)==(ssize_t) -1)
    {
        fclose(f);
        esyslog("failed to read epgdata2xmltv config");
        return 1;
    }
    if (getline(&line,&size,f)==(ssize_t) -1)
    {
        fclose(f);
        if (line) free(line);
        esyslog("failed to read epgdata2xmltv config");
        return 1;
    }
    char *sc=strchr(line,';');
    if (sc)
    {
        *sc=0;
        sc++;
    }
    else
    {
        sc=line;
    }
    int daysmax=atoi(sc);
    if (daysmax<0) daysmax=1;
    int daysinadvance=atoi(argv[1]);
    if (daysinadvance<0) daysinadvance=1;
    if (daysinadvance>daysmax) daysinadvance=daysmax;

    bool head=false;
    char *xmlmem=NULL;

    time_t t=time(NULL);

    int carg=3;
    if (!strcmp(argv[3],"1") || !strcmp(argv[3],"0"))  carg++;

    for (int day=0; day<=daysinadvance; day++)
    {
        time_t td=t+(day*86400);
        struct tm *tm;
        tm=localtime(&td);
        char vgl[10];
        sprintf(vgl,"%04i%02i%02i",tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday);

        char *dest=NULL;
        if (asprintf(&dest,"/tmp/%s_epgdata.zip",vgl)==-1)
        {
            esyslog("failed to allocate string");
            continue;
        }

        bool ok=false;
        do
        {
            bool offline=true;
            struct stat statbuf;
            if (stat(dest,&statbuf)==-1)
            {
                if (Fetch(dest,argv[2],day))
                {
                    ok=true;
                    break;
                }
                offline=false;
            }

            struct zip *zip=zip_open(dest,0,NULL);
            if (!zip)
            {
                if (offline)
                {
                    if (unlink(dest)==-1)
                    {
                        esyslog("cannot unlink %s",dest);
                        ok=true;
                        break;
                    }
                    continue;
                }
                esyslog("failed to open %s",dest);
                ok=true;
                break;
            }

            int i=zip_name_locate(zip,"qy.dtd",ZIP_FL_NOCASE);
            if (i==-1)
            {
                if (offline)
                {
                    if (unlink(dest)==-1)
                    {
                        esyslog("cannot unlink %s",dest);
                        ok=true;
                        break;
                    }
                    continue;
                }
                esyslog("failed read qy.dtd in %s",dest);
                ok=true;
                break;
            }

            struct zip_file *zfile=zip_fopen_index(zip,i,0);
            if (!zfile)
            {
                if (offline)
                {
                    if (unlink(dest)==-1)
                    {
                        esyslog("cannot unlink %s",dest);
                        ok=true;
                        break;
                    }
                    continue;
                }
                esyslog("failed to read qy.dtd from %s",dest);
                ok=true;
                break;
            }
            struct zip_stat sb;
            memset(&sb,0,sizeof(sb));
            if (zip_stat_index(zip,i,ZIP_FL_UNCHANGED,&sb)==-1)
            {
                if (offline)
                {
                    if (unlink(dest)==-1)
                    {
                        zip_fclose(zfile);
                        esyslog("cannot unlink %s",dest);
                        ok=true;
                        break;
                    }
                    continue;
                }
                zip_fclose(zfile);
                esyslog("failed to stat qy.dtd in %s",dest);
                ok=true;
                break;
            }
            if (sizeof(sb.size>4)) sb.size &= 0x00FFFFFF; // just to be sure
            if (dtdmem) {
                free(dtdmem);
                dtdmem=NULL;
            }
            dtdmem=(char *) malloc(sb.size+1);
            int size=zip_fread(zfile,dtdmem,sb.size);
            if (size!=sb.size)
            {
                zip_fclose(zfile);
                esyslog("failed to read qy.dtd from %s",dest);
                ok=true;
                break;
            }
            dtdmem[size]=0;
            zip_fclose(zfile);

            int entries=zip_get_num_files(zip);
            for (int i=0; i<entries; i++)
            {
                const char *name=zip_get_name(zip,i,0);
                if (strstr(name,"xml"))
                {
                    // check date of xml
                    if (strstr(name,vgl))
                    {
                        struct zip_file *zfile=zip_fopen_index(zip,i,0);
                        if (!zfile)
                        {
                            if (offline)
                            {
                                if (unlink(dest)==-1)
                                {
                                    esyslog("cannot unlink %s",dest);
                                    ok=true;
                                    break;
                                }
                                continue;
                            }
                            esyslog("failed to read %s from %s",name,dest);
                            ok=true;
                            break;
                        }

                        struct zip_stat sb;
                        memset(&sb,0,sizeof(sb));
                        if (zip_stat_index(zip,i,ZIP_FL_UNCHANGED,&sb)==-1)
                        {
                            if (offline)
                            {
                                if (unlink(dest)==-1)
                                {
                                    esyslog("cannot unlink %s",dest);
                                    ok=true;
                                    break;
                                }
                                continue;
                            }
                            esyslog("failed to stat %s in %s",name,dest);
                            ok=true;
                            break;
                        }
                        if (sizeof(sb.size>4)) sb.size &= 0x00FFFFFF; // just to be sure
                        xmlmem=(char *) malloc(sb.size+1);
                        int size=zip_fread(zfile,xmlmem,sb.size);
                        if (size!=sb.size)
                        {
                            zip_fclose(zfile);
                            free(xmlmem);
                            xmlmem=NULL;
                            esyslog("failed to read %s from %s",name,dest);
                            ok=true;
                            break;
                        }
                        xmlmem[size]=0;
                        xmlmem=strreplace(xmlmem,"iso-8859-1","Windows-1252");
                        zip_fclose(zfile);
                        ok=true;
                        break;
                    }
                }
            }

            if (!strcmp(argv[3],"1")) {
                int entries=zip_get_num_files(zip);
                for (int i=0; i<entries; i++)
                {
                    const char *name=zip_get_name(zip,i,0);
                    if (strstr(name,"jpg")) {

                        char *destjpg;
                        if (asprintf(&destjpg,"/var/lib/epgsources/epgdata2xmltv-img/%s",name)!=-1) {
                            struct stat statbuf;
                            if (stat(destjpg,&statbuf)==-1) {
                                struct zip_file *zfile=zip_fopen_index(zip,i,0);
                                if (zfile)
                                {
                                    struct zip_stat sb;
                                    memset(&sb,0,sizeof(sb));
                                    if (zip_stat_index(zip,i,ZIP_FL_UNCHANGED,&sb)!=-1) {
                                        if (sizeof(sb.size>4)) sb.size &= 0x00FFFFFF; // just to be sure
                                        char *jpg=(char *) malloc(sb.size+1);
                                        if (jpg) {
                                            int size=zip_fread(zfile,jpg,sb.size);
                                            if (size==sb.size) {
                                                FILE *j=fopen(destjpg,"w+");
                                                if (j) {
                                                    fwrite(jpg,size,1,j);
                                                    fclose(j);
                                                }
                                            }
                                        }
                                    }
                                    zip_fclose(zfile);
                                }
                            }
                            free(destjpg);
                        }
                    }
                }
            }

            zip_close(zip);
            if (!ok)
            {
                if (offline)
                {
                    if (unlink(dest)==-1)
                    {
                        ok=true;
                        break;
                    }
                    continue;
                }
                else
                {
                    esyslog("found no valid data in %s",dest);
                    if (xmlmem) free(xmlmem);
                    xmlmem=NULL;
                    ok=true;
                    break;
                }
            }
        }
        while (ok==false);
        free(dest);

        if (!line)
        {
            line=(char *) malloc(81);
            size=80;
        }
        if (!xmlmem) continue;
        long offset=ftell(f);

        xmlDocPtr pxmlDoc;
        if (!pxsltStylesheet) LoadXSLT();
        int xmlsize=strlen(xmlmem);
        if ((pxmlDoc=xmlParseMemory(xmlmem,xmlsize))==NULL)
        {
            EncaAnalyser analyser=enca_analyser_alloc("__");
            if (analyser) {
                EncaEncoding encoding=enca_analyse_const(analyser, (unsigned char *) xmlmem,xmlsize);
                const char *cs=enca_charset_name(encoding.charset, ENCA_NAME_STYLE_ICONV);
                if (cs) {
                    if (!strcmp(cs,"UTF-8")) {
                        xmlmem=strreplace(xmlmem,"Windows-1252","UTF-8");
                    } else {
                        esyslog("enca returned %s, please report!",cs);
                    }
                }
                enca_analyser_free(analyser);
            }

            string s = xmlmem;
            int reps=pcrecpp::RE("&(?![a-zA-Z]{1,8};)").GlobalReplace("%amp;",&s);
            if (reps) {
                xmlmem = (char *)realloc(xmlmem, s.size()+1);
                xmlsize = s.size();
                strcpy(xmlmem,s.c_str());
            }

            if ((pxmlDoc=xmlParseMemory(xmlmem,xmlsize))==NULL)
            {
                esyslog("failed parsing xml");
                free(xmlmem);
                xmlmem=NULL;
                continue;
            }
        }

        for (;;)
        {
            lptr=line+1;
            line[0]=' ';
            if (getline(&lptr,&size,f)==-1) break;
            char *channel=line;
            char *sc=strchr(channel,';');
            if (sc) *sc=0;

            bool use=false;
            for (int i=carg; i<argc; i++)
            {
                if (!strcasecmp(lptr,argv[i]))
                {
                    use=true;
                    break;
                }
            }

            if (use)
            {
                if (!head)
                {
                    printf("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
                    printf("<tv generator-info-name=\"epgdata2xmltv\">\n");

                    for (int i=carg; i<argc; i++)
                    {
                        printf("<channel id=\"%s\">\n",argv[i]);
                        printf("<display-name lang=\"de\">%s</display-name>\n",argv[i]);
                        printf("</channel>\n");
                    }
                    head=true;
                }

                int num=atoi(sc+1);
                if (num>0)
                {
                    char *channelnum=strdup(sc+1);
                    char *lf=strchr(channelnum,10);
                    if (lf) *lf=0;
                    channel[0]='"';
                    *sc++='"';
                    *sc=0;
                    const char *params[5] =
                    {
                        "channelid", channel, "channelnum",channelnum,NULL
                    };
                    Translate(pxmlDoc,params);
                    if (channelnum) free(channelnum);
                }
            }
        }
        xmlFreeDoc (pxmlDoc);
        fseek(f,offset,SEEK_SET);
        if (dtdmem) {
            free(dtdmem);
            dtdmem=NULL;
        }
        if (xmlmem) {
            free(xmlmem);
            xmlmem=NULL;
        }
    }
    if (line) free(line);
    fclose(f);

    if (head) printf("</tv>\n");
    return head ? 0 : 1;
}