ssize_t processJarFiles(Bundle* bundle, ZipFile* zip)
{
    status_t err;
    ssize_t count = 0;
    const android::Vector<const char*>& jars = bundle->getJarFiles();

    size_t N = jars.size();
    for (size_t i=0; i<N; i++) {
        ZipFile jar;
        err = jar.open(jars[i], ZipFile::kOpenReadOnly);
        if (err != 0) {
            fprintf(stderr, "ERROR: unable to open '%s' as a zip file: %d\n",
                jars[i], err);
            return err;
        }
        err += processJarFile(&jar, zip);
        if (err < 0) {
            fprintf(stderr, "ERROR: unable to process '%s'\n", jars[i]);
            return err;
        }
        count += err;
    }

    return count;
}
Exemple #2
0
Handle<Value> ZipFile::New(const Arguments& args)
{
    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())));
    }

    ZipFile* zf = new ZipFile(input_file);

    zf->archive = za;
    zf->GetNames();
    zf->Wrap(args.This());
    return args.This();

}
unsigned char* getFileDataFromZip(const char* zipFile, const char* fileName, ssize_t* size)
{
	if (nullptr == zipFile || nullptr == fileName || nullptr == size)
		return nullptr;

	Data zipData = FileUtils::getInstance()->getDataFromFile(zipFile);
	if (zipData.isNull())
		return nullptr;

	ZipFile * zip = ZipFile::createWithBuffer(zipData.getBytes(), zipData.getSize());
	if (nullptr == zip)
		return nullptr;

	*size = 0;
	unsigned char * data = zip->getFileData(fileName, size);
	delete zip;
	if (nullptr == data || size <= 0)
	{
		*size = 0;
		free(data);
		return nullptr;
	}

	return data;
}
Exemple #4
0
/* zipfile.save(callback) */
Handle<Value> ZipFile::Save(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    Local<Value> cb = args[0];
    if (!cb->IsFunction())
      return ThrowException(Exception::Error(
            String::New("Second argument should be a callback function.")));

    save_closure_t *save = new save_closure_t;

    save->done = false;
    save->zf = zf;
    save->error = NULL;
    save->save_cb = Persistent<Function>::New(Handle<Function>::Cast(cb));
    pthread_mutex_init(&save->mutex, NULL);

    saving_closures.insert(save);

    zf->saving = true;
    zf->Ref();

    ev_ref(EV_DEFAULT_UC);
    pthread_create(&save->thread, NULL, Save_Thread, save);
    
    return Undefined();
}
Exemple #5
0
// Creates new zip file object for given zip file name, then opens zip file
ZipFile* ZipFile::Open(String* FileName)
{
	ZipFile* zipFile = new ZipFile();

	zipFile->FileName = FileName;
	zipFile->Open();

	return zipFile;
}
Exemple #6
0
// Updates specified files in zip
void ZipFile::Update(String* FileSpec, UpdateOption UpdateWhen, Boolean AddNewFiles, Boolean RecurseSubdirectories, PathInclusion AddPathMethod)
{
	// If destination zip file doesn't exist, we just perform an Add
	if (!File::Exists(fileName))
	{
		if (AddNewFiles) Add(FileSpec, RecurseSubdirectories, AddPathMethod);
		return;
	}

	char* pszPassword = NULL;
	ZipFile* tempZipFile;
	OpenFileForUnzip();

	// Just wrapping in a try/catch/finally to make sure unmanaged code allocations always get released and temp zip file gets removed
	try
	{
		// Create temporary zip file to hold update results
		tempZipFile = CreateTempZipFile();

		// Get ANSI password, if one was provided
		if (password)
			if (password->get_Length())
				pszPassword = StringToCharBuffer(password);

		String* fileSpec = Path::GetFileName(FileSpec);
		String* rootPath = JustPath(FileSpec, fileSpec);

		UpdateFilesInZip(tempZipFile, fileSpec, rootPath, rootPath->get_Length(), UpdateWhen, AddNewFiles, RecurseSubdirectories, AddPathMethod, pszPassword);

		// Now make the temp file the new zip file
		Close();
		tempZipFile->Close();
		File::Delete(fileName);
		File::Move(tempZipFile->fileName, fileName);
	}
	catch (CompressionException* ex)		
	{
		// We just rethrow any errors back to user
		throw ex;
	}
	catch (Exception* ex)
	{
		throw ex;
	}
	__finally
	{
		if (pszPassword)
			free(pszPassword);

		// If everything went well, temp zip will no longer exist, but just in case we tidy up and delete the temp file...
		DeleteTempZipFile(tempZipFile);
	}

	// We'll reload the file list after update if requested...
	if (autoRefresh) Refresh();
}
Exemple #7
0
    Result unzip (const MemoryBlock& data)
    {
        setStatusMessage ("Installing...");

        File unzipTarget;
        bool isUsingTempFolder = false;

        {
            MemoryInputStream input (data, false);
            ZipFile zip (input);

            if (zip.getNumEntries() == 0)
                return Result::fail ("The downloaded file wasn't a valid JUCE file!");

            unzipTarget = targetFolder;

            if (unzipTarget.exists())
            {
                isUsingTempFolder = true;
                unzipTarget = targetFolder.getNonexistentSibling();

                if (! unzipTarget.createDirectory())
                    return Result::fail ("Couldn't create a folder to unzip the new version!");
            }

            Result r (zip.uncompressTo (unzipTarget));

            if (r.failed())
            {
                if (isUsingTempFolder)
                    unzipTarget.deleteRecursively();

                return r;
            }
        }

        if (isUsingTempFolder)
        {
            File oldFolder (targetFolder.getSiblingFile (targetFolder.getFileNameWithoutExtension() + "_old")
                                        .getNonexistentSibling());

            if (! targetFolder.moveFileTo (oldFolder))
            {
                unzipTarget.deleteRecursively();
                return Result::fail ("Could not remove the existing folder!");
            }

            if (! unzipTarget.moveFileTo (targetFolder))
            {
                unzipTarget.deleteRecursively();
                return Result::fail ("Could not overwrite the existing folder!");
            }
        }

        return Result::ok();
    }
Exemple #8
0
// Creates new zip file object for given zip file name and password, then opens zip file
ZipFile* ZipFile::Open(String* FileName, String* Password)
{
	ZipFile* zipFile = new ZipFile();

	zipFile->FileName = FileName;
	zipFile->Password = Password;
	zipFile->Open();

	return zipFile;
}
/*
 * The directory hierarchy looks like this:
 * "outputDir" and "assetRoot" are existing directories.
 *
 * On success, "bundle->numPackages" will be the number of Zip packages
 * we created.
 */
status_t writeAPK(Bundle* bundle, int fd, const sp<OutputSet>& outputSet, bool isOverlay)
{
    #if BENCHMARK
    fprintf(stdout, "BENCHMARK: Starting APK Bundling \n");
    long startAPKTime = clock();
    #endif /* BENCHMARK */

    status_t result = NO_ERROR;
    ZipFile* zip = NULL;

    status_t status;
    zip = new ZipFile;
    status = zip->openfd(fd, ZipFile::kOpenReadWrite);
    if (status != NO_ERROR) {
        fprintf(stderr, "ERROR: unable to open file as Zip file for writing\n");
        result = PERMISSION_DENIED;
        goto bail;
    }

    result = writeAPK(bundle, zip, "file_descriptor", outputSet, isOverlay);

    if (result != NO_ERROR) {
        fprintf(stderr, "ERROR: Writing apk failed\n");
        goto bail;
    }

    /* anything here? */
    if (zip->getNumEntries() == 0) {
        if (bundle->getVerbose()) {
            printf("Archive is empty -- removing\n");
        }
        delete zip;        // close the file so we can remove it in Win32
        zip = NULL;
        close(fd);
    }

    assert(result == NO_ERROR);

bail:
    delete zip;        // must close before remove in Win32
    close(fd);
    if (result != NO_ERROR) {
        if (bundle->getVerbose()) {
            printf("Removing archive due to earlier failures\n");
        }
    }

    if (result == NO_ERROR && bundle->getVerbose())
        printf("Done!\n");

    #if BENCHMARK
    fprintf(stdout, "BENCHMARK: End APK Bundling. Time Elapsed: %f ms \n",(clock() - startAPKTime)/1000.0);
    #endif /* BENCHMARK */
    return result;
}
Exemple #10
0
bool TextureHandler::Load (const char *zip) 
{
	FILE *f = fopen (zip, "rb");

	if (f) {
		ZipFile *zf = new ZipFile;
		if (zf->Init (f) == RET_FAIL) {
			logger.Trace (NL_Error, "Failed to load zip archive %s\n", zip);
			fclose (f);
			return false;
		}

		const char *imgExt[]={ "bmp", "jpg", "tga", "png", "dds", "pcx", "pic", "gif", "ico", 0 };

		// Add the zip entries to the texture set
		for (int a=0;a<zf->GetNumFiles ();a++)
		{
			char tempFile[64];
			zf->GetFilename (a, tempFile, sizeof(tempFile));

			char *ext=FixTextureName (tempFile);
			if (ext)
			{
				int x=0;
				for (x=0;imgExt[x];x++)
					if (!strcmp(imgExt[x],ext)) break;

				if (!imgExt[x])
					continue;

				if (textures.find(tempFile) != textures.end())
					continue;

				TexRef ref;
				ref.zip = zips.size();
				ref.index = a;
				ref.texture = LoadTexture (zf,a, tempFile);

				if(textures.find(tempFile)!=textures.end())
					logger.Trace(NL_Debug,"Texture %s already loaded\n", tempFile);

				TexRef &tr = textures[tempFile];
				tr.texture = ref.texture;
				tr.index = a;;
				tr.zip = zips.size();
			}
		}

		fclose (f);

		zips.push_back (zf);
	}

	return false;
}
Exemple #11
0
/* zipfile.addFile(nameInArchive, name, offset, len) */
Handle<Value> ZipFile::Add_File(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    struct zip_source *source;

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    if (!args[0]->IsString())
      return ThrowException(Exception::TypeError(
                 String::New("Argument must be a file name.")));
    std::string archive_file = TOSTR(args[0]);

    std::string name;
    if (args[1]->IsUndefined())
      name = archive_file;
    else
      if (!args[1]->IsString())
        return ThrowException(Exception::TypeError(
                   String::New("Argument must be a file name.")));
      name = TOSTR(args[1]);

    zip_int64_t off;
    if (args[2]->IsUndefined())
      off = 0;
    else
      off = args[2]->Int32Value();

    zip_int64_t len;
    if (args[3]->IsUndefined())
      len = -1;
    else
      len = args[3]->Int32Value();

    source = zip_source_file(zf->archive, name.c_str(), off, len);
    if (source == NULL) {
      std::stringstream s;
      s << "Error while adding file " << name << " to zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }
 
    int ret = zip_add(zf->archive, archive_file.c_str(), source); 
    if (ret < 0) {
      zip_source_free(source);
      std::stringstream s;
      s << "Error while adding file " << name << " to zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    zf->GetNames();

    return Undefined();
}
Exemple #12
0
int main(int argc, char** argv) {
    ZipFile *zipfile;
        zipfile=new ZipFile("啊.zip");
        zipfile->open();
qDebug()<<zipfile->readFileList();
qDebug()<<zipfile->readFile(zipfile->readFileList().at(0))<<"a";
qDebug()<<zipfile->readFile(zipfile->readFileList().at(3))<<"b";
qDebug()<<"C";
return 0;

}
Exemple #13
0
    Result unzip (const ModuleList::Module& m, const MemoryBlock& data)
    {
        setStatusMessage ("Installing " + m.uid + "...");

        MemoryInputStream input (data, false);
        ZipFile zip (input);

        if (zip.getNumEntries() == 0)
            return Result::fail ("The downloaded file wasn't a valid module file!");

        return zip.uncompressTo (targetList.getModulesFolder(), true);
    }
Exemple #14
0
// Removes specified files from zip
void ZipFile::Remove(String* FileSpec, Boolean RecurseSubdirectories)
{
	ZipFile* tempZipFile;
	OpenFileForUnzip();

	// Just wrapping in a try/catch/finally to make sure temp zip file gets removed
	try
	{
		Regex* filePattern = GetFilePatternRegularExpression(FileSpec, caseSensitive);
		IEnumerator* filesEnum = files->GetEnumerator();
		CompressedFile* file;

		// Create temporary zip file to hold remove results
		tempZipFile = CreateTempZipFile();

		// Loop through compressed file collection
		while (filesEnum->MoveNext())
		{
			file = static_cast<CompressedFile*>(filesEnum->Current);

			// We copy all files into destination zip file except those user requested to be removed...
			if (!filePattern->IsMatch(GetSearchFileName(FileSpec, file->get_FileName(), RecurseSubdirectories)))
				CopyFileInZip(file, this, tempZipFile, S"Remove Zip File");
		}

		// Now make the temp file the new zip file
		Close();
		tempZipFile->Close();
		File::Delete(fileName);
		File::Move(tempZipFile->fileName, fileName);
	}
	catch (CompressionException* ex)		
	{
		// We just rethrow any errors back to user
		throw ex;
	}
	catch (Exception* ex)
	{
		throw ex;
	}
	__finally
	{
		// If everything went well, temp zip will no longer exist, but just in case we tidy up and delete the temp file...
		DeleteTempZipFile(tempZipFile);
	}

	// We'll reload the file list after remove if requested...
	if (autoRefresh) Refresh();
}
Exemple #15
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 #16
0
bool CbxEngineImpl::FinishLoadingCbz()
{
    fileExt = L".cbz";

    Vec<const WCHAR *> allFileNames;

    for (size_t idx = 0; idx < cbzFile->GetFileCount(); idx++) {
        const WCHAR *fileName = cbzFile->GetFileName(idx);
        // bail, if we accidentally try to load an XPS file
        if (fileName && str::StartsWith(fileName, L"_rels/.rels"))
            return false;
        if (fileName && ImageEngine::IsSupportedFile(fileName) &&
            // OS X occasionally leaves metadata with image extensions
            !str::StartsWith(path::GetBaseName(fileName), L".")) {
            allFileNames.Append(fileName);
        }
        else {
            allFileNames.Append(NULL);
        }
    }
    assert(allFileNames.Count() == cbzFile->GetFileCount());

    ScopedMem<char> metadata(cbzFile->GetFileData(L"ComicInfo.xml"));
    if (metadata)
        ParseComicInfoXml(metadata);
    metadata.Set(cbzFile->GetComment());
    if (metadata)
        json::Parse(metadata, this);

    Vec<const WCHAR *> pageFileNames;
    for (const WCHAR **fn = allFileNames.IterStart(); fn; fn = allFileNames.IterNext()) {
        if (*fn)
            pageFileNames.Append(*fn);
    }
    pageFileNames.Sort(cmpAscii);
    for (const WCHAR **fn = pageFileNames.IterStart(); fn; fn = pageFileNames.IterNext()) {
        fileIdxs.Append(allFileNames.Find(*fn));
    }
    assert(pageFileNames.Count() == fileIdxs.Count());
    if (fileIdxs.Count() == 0)
        return false;

    pages.AppendBlanks(fileIdxs.Count());
    mediaboxes.AppendBlanks(fileIdxs.Count());

    return true;
}
Exemple #17
0
char *CbxEngineImpl::GetImageData(int pageNo, size_t& len)
{
    if (cbzFile) {
        ScopedCritSec scope(&fileAccess);
        return cbzFile->GetFileData(fileIdxs.At(pageNo - 1), &len);
    }
    return NULL;
}
Exemple #18
0
/* zipfile.read(buffer, pos, len, cb) -> cb(bytesRead, error) */
Handle<Value> ZipFile::Read(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    if (!Buffer::HasInstance(args[0])) {
      return ThrowException(Exception::Error(
                  String::New("First argument needs to be a buffer")));
    }
    Local<Object> buffer_obj = args[0]->ToObject();
    char *buffer_data = Buffer::Data(buffer_obj);
    size_t buffer_length = Buffer::Length(buffer_obj);

    zip_uint64_t off = args[1]->Int32Value();
    if (off >= buffer_length) {
      return ThrowException(Exception::Error(
            String::New("Offset is out of bounds")));
    }

    zip_uint64_t len = args[2]->Int32Value();
    if (off + len > buffer_length) {
      return ThrowException(Exception::Error(
            String::New("Length is extends beyond buffer")));
    }

    Local<Value> cb = args[3];
    if (!cb->IsFunction())
      return ThrowException(Exception::Error(
            String::New("Fourth argument should be a callback function.")));

    read_closure_t *closure = new read_closure_t();
    closure->zf = zf;
    closure->read = 0;
    closure->data = buffer_data+off;
    closure->len = len;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(args[3]));

    eio_custom(EIO_Read, EIO_PRI_DEFAULT, EIO_AfterRead, closure);
    zf->Ref();
    ev_ref(EV_DEFAULT_UC);

    return Undefined();
}
Exemple #19
0
/*
 * Open the file read-write.  The file will be created if it doesn't
 * already exist and "okayToCreate" is set.
 *
 * Returns NULL on failure.
 */
ZipFile* openReadWrite(const char* fileName, bool okayToCreate)
{
    ZipFile* zip = NULL;
    status_t result;
    int flags;

    flags = ZipFile::kOpenReadWrite;
    if (okayToCreate)
        flags |= ZipFile::kOpenCreate;

    zip = new ZipFile;
    result = zip->open(fileName, flags);
    if (result != NO_ERROR) {
        delete zip;
        zip = NULL;
        goto bail;
    }

bail:
    return zip;
}
Exemple #20
0
/*
 * Open the file read only.  The call fails if the file doesn't exist.
 *
 * Returns NULL on failure.
 */
ZipFile* openReadOnly(const char* fileName)
{
    ZipFile* zip;
    status_t result;

    zip = new ZipFile;
    result = zip->open(fileName, ZipFile::kOpenReadOnly);
    if (result != NO_ERROR) {
        if (result == NAME_NOT_FOUND)
            fprintf(stderr, "ERROR: '%s' not found\n", fileName);
        else if (result == PERMISSION_DENIED)
            fprintf(stderr, "ERROR: '%s' access denied\n", fileName);
        else
            fprintf(stderr, "ERROR: failed opening '%s' as Zip file\n",
                fileName);
        delete zip;
        return NULL;
    }

    return zip;
}
Exemple #21
0
/* zipfile.addDirectory(name) */
Handle<Value> ZipFile::Add_Directory(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    if (!args[0]->IsString())
      return ThrowException(Exception::TypeError(
                 String::New("Argument must be a directory name.")));
    std::string directory = TOSTR(args[0]);

    int ret = zip_add_dir(zf->archive, directory.c_str());
    if (ret < 0) {
      std::stringstream s;
      s << "Error while adding directory " << directory << " to zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    zf->GetNames();

    return Undefined();
}
Exemple #22
0
    void createSVGDrawable()
    {
        lastSVGLoadTime = Time::getCurrentTime();

        MemoryInputStream iconsFileStream (BinaryData::icons_zip, BinaryData::icons_zipSize, false);
        ZipFile icons (&iconsFileStream, false);

        // Load a random SVG file from our embedded icons.zip file.
        const ScopedPointer<InputStream> svgFileStream (icons.createStreamForEntry (Random::getSystemRandom().nextInt (icons.getNumEntries())));

        if (svgFileStream != nullptr)
        {
            svgDrawable = dynamic_cast <DrawableComposite*> (Drawable::createFromImageDataStream (*svgFileStream));

            if (svgDrawable != nullptr)
            {
                // to make our icon the right size, we'll set its bounding box to the size and position that we want.
                svgDrawable->setBoundingBox (RelativeParallelogram (Point<float> (-100, -100),
                                                                    Point<float> (100, -100),
                                                                    Point<float> (-100, 100)));
            }
        }
    }
Exemple #23
0
Handle<Value> ZipFile::Open(const Arguments& args)
{
    if (args.Length() != 1 || !args[0]->IsString())
        return ThrowException(Exception::TypeError(
          String::New("Argument must be a file name inside the zip")));

    std::string name = TOSTR(args[0]);
  
    // TODO - enforce valid index
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    zf->file_index = -1;

    std::vector<std::string>::iterator it = std::find(zf->names.begin(), zf->names.end(), name);
    if (it!=zf->names.end()) {
        zf->file_index = distance(zf->names.begin(), it);
    }

    if (zf->file_index == -1) {
        std::stringstream s;
        s << "No file found by the name of: '" << name << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    if ((zf->file=zip_fopen_index(zf->archive, zf->file_index, 0)) == NULL) {
        zip_fclose(zf->file);
        zf->file = NULL;
        std::stringstream s;
        s << "cannot open file #" << zf->file_index << " in " << name << ": archive error: " << zip_strerror(zf->archive) << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    return Undefined();
}
Exemple #24
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 #25
0
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
int main ( int argc , char **argv)
{
    if(argc != 2)
    {
        cout << "Usage: " << argv[0] << " <file name>" << endl;
        return 0;
    }

    ZipFile zfile(argv[1]);
    
    /// Zip a file
    cout << "Original File Size: " << zfile.size() << " Bytes" << endl;

    /// Compress file
    ZipFile czf = zfile.compress(zfile.getPath() + ".gz");
    cout << "Compressed File Size: " << czf.size() << " Bytes" << endl;

    /// Decompress file
    ZipFile dzf = czf.decompress(czf.getPath() + ".decom");
    cout << "Decompressed File Size: " << dzf.size() << " Bytes" << endl;
    cout << "Ratio: " << (1.f - (float)czf.size() / (float)dzf.size()) * 100.f << "%" << endl;
    
    /// Zip a buffer
    ZipMemory<GraVitoN::guchar> buff(256);
    buff.zero();
    
    for(size_t i=0; i<buff.size(); ++i)
        buff[i] =  (i % ('z' - 'a' + 1)) + 'a';

    cout << endl;
    cout << "Original buff: '" << buff << "'" << endl;

    /// Compress buffer
    ZipMemory<unsigned char> izbuff, ozbuff;
    ozbuff = buff.compress();
    cout << "Compressed buffer size: " << ozbuff.size() << " Bytes" << endl;

    /// Decompress buffer
    // cout << "Compressed Buffer: '" << GraVitoN::Utils::OptParser::hexToStr(izbuff, ib_size) << "'" << endl;
    izbuff = ozbuff.decompress();
    cout << "Decompressed Buffer Size: " << izbuff.size() << " Bytes" << endl;
    cout << "Decompressed Buffer: '" << izbuff << "'" << endl;
    cout << "Ratio: " << (1.f - (float)ozbuff.size() / (float)izbuff.size()) * 100.f << "%" << endl;
    
    cout << "Result: " << ( (buff.toString() == izbuff.toString()) ? ("Matched") : ("UNMATCHED") ) << endl;
    return 0;
}
Exemple #26
0
void FFMS_Track::Write(ZipFile &stream) const {
    stream.Write<uint8_t>(TT);
    stream.Write(TB.Num);
    stream.Write(TB.Den);
    stream.Write<int32_t>(MaxBFrames);
    stream.Write<uint8_t>(UseDTS);
    stream.Write<uint8_t>(HasTS);
    stream.Write<uint64_t>(size());

    if (empty()) return;

    FrameInfo temp{};
    for (size_t i = 0; i < size(); ++i)
        WriteFrame(stream, Frames[i], i == 0 ? temp : Frames[i - 1], TT);
}
Drawable* ResourceLoader::createSVGDrawable(const String& filename)
{
	initObjectIconMap();

    if (iconsFromZipFile.size() == 0)
    {
        // If we've not already done so, load all the images from the zip file..
        MemoryInputStream iconsFileStream (BinaryData::icons_zip, BinaryData::icons_zipSize, false);
        ZipFile icons (&iconsFileStream, false);

        for (int i = 0; i < icons.getNumEntries(); ++i)
        {
            ScopedPointer<InputStream> svgFileStream (icons.createStreamForEntry (i));

            if (svgFileStream != 0)
            {
                iconNames.add (icons.getEntry(i)->filename);
                iconsFromZipFile.add (Drawable::createFromImageDataStream (*svgFileStream));
            }
        }
    }

    return iconsFromZipFile [iconNames.indexOf (filename)];//->createCopy();
}
Exemple #28
0
void Tools::LoadImages()
{
	FILE *f = fopen("data/data.ups", "rb");
	if (!f) {
		fltk::message("Failed to load data.ups");
	}
	else
	{
		ZipFile zf;
		zf.Init(f);

		for(unsigned int a=0;a<tools.size();a++) {
			if (!tools[a]->imageFile)
				continue;

			std::string fn = tools[a]->imageFile;

			int zipIndex=-1;
			for (int fi=0;fi<zf.GetNumFiles();fi++) {
				char zfn [64];
				zf.GetFilename(fi, zfn, sizeof(zfn));
				if (!STRCASECMP(zfn, fn.c_str())) {
					zipIndex = fi;
					break;
				}
			}

			if (zipIndex>=0) {
				int len = zf.GetFileLen(zipIndex);
				char *buf = new char[len];
				zf.ReadFile(zipIndex, buf);

				tools[a]->image = FltkImage::Load(buf, len);
				if (!tools[a]->image) {
					fltk::message("Failed to load texture %s\n", fn.c_str());
					delete[] buf;
					continue;
				}
				delete[] buf;

				tools[a]->button->image(tools[a]->image->img);
				tools[a]->button->label("");
			} else
				fltk::message("Couldn't find %s", fn.c_str());
		}
		fclose(f);
	}
}
/*
 * The directory hierarchy looks like this:
 * "outputDir" and "assetRoot" are existing directories.
 *
 * On success, "bundle->numPackages" will be the number of Zip packages
 * we created.
 */
status_t writeAPK(Bundle* bundle, const String8& outputFile, const sp<OutputSet>& outputSet)
{
    #if BENCHMARK
    fprintf(stdout, "BENCHMARK: Starting APK Bundling \n");
    long startAPKTime = clock();
    #endif /* BENCHMARK */

    status_t result = NO_ERROR;
    ZipFile* zip = NULL;
    int count;

    //bundle->setPackageCount(0);

    /*
     * Prep the Zip archive.
     *
     * If the file already exists, fail unless "update" or "force" is set.
     * If "update" is set, update the contents of the existing archive.
     * Else, if "force" is set, remove the existing archive.
     */
    FileType fileType = getFileType(outputFile.string());
    if (fileType == kFileTypeNonexistent) {
        // okay, create it below
    } else if (fileType == kFileTypeRegular) {
        if (bundle->getUpdate()) {
            // okay, open it below
        } else if (bundle->getForce()) {
            if (unlink(outputFile.string()) != 0) {
                fprintf(stderr, "ERROR: unable to remove '%s': %s\n", outputFile.string(),
                        strerror(errno));
                goto bail;
            }
        } else {
            fprintf(stderr, "ERROR: '%s' exists (use '-f' to force overwrite)\n",
                    outputFile.string());
            goto bail;
        }
    } else {
        fprintf(stderr, "ERROR: '%s' exists and is not a regular file\n", outputFile.string());
        goto bail;
    }

    if (bundle->getVerbose()) {
        printf("%s '%s'\n", (fileType == kFileTypeNonexistent) ? "Creating" : "Opening",
                outputFile.string());
    }

    status_t status;
    zip = new ZipFile;
    status = zip->open(outputFile.string(), ZipFile::kOpenReadWrite | ZipFile::kOpenCreate);
    if (status != NO_ERROR) {
        fprintf(stderr, "ERROR: unable to open '%s' as Zip file for writing\n",
                outputFile.string());
        goto bail;
    }

    if (bundle->getVerbose()) {
        printf("Writing all files...\n");
    }

    count = processAssets(bundle, zip, outputSet);
    if (count < 0) {
        fprintf(stderr, "ERROR: unable to process assets while packaging '%s'\n",
                outputFile.string());
        result = count;
        goto bail;
    }

    if (bundle->getVerbose()) {
        printf("Generated %d file%s\n", count, (count==1) ? "" : "s");
    }
    
    count = processJarFiles(bundle, zip);
    if (count < 0) {
        fprintf(stderr, "ERROR: unable to process jar files while packaging '%s'\n",
                outputFile.string());
        result = count;
        goto bail;
    }
    
    if (bundle->getVerbose())
        printf("Included %d file%s from jar/zip files.\n", count, (count==1) ? "" : "s");
    
    result = NO_ERROR;

    /*
     * Check for cruft.  We set the "marked" flag on all entries we created
     * or decided not to update.  If the entry isn't already slated for
     * deletion, remove it now.
     */
    {
        if (bundle->getVerbose())
            printf("Checking for deleted files\n");
        int i, removed = 0;
        for (i = 0; i < zip->getNumEntries(); i++) {
            ZipEntry* entry = zip->getEntryByIndex(i);

            if (!entry->getMarked() && entry->getDeleted()) {
                if (bundle->getVerbose()) {
                    printf("      (removing crufty '%s')\n",
                        entry->getFileName());
                }
                zip->remove(entry);
                removed++;
            }
        }
        if (bundle->getVerbose() && removed > 0)
            printf("Removed %d file%s\n", removed, (removed==1) ? "" : "s");
    }

    /* tell Zip lib to process deletions and other pending changes */
    result = zip->flush();
    if (result != NO_ERROR) {
        fprintf(stderr, "ERROR: Zip flush failed, archive may be hosed\n");
        goto bail;
    }

    /* anything here? */
    if (zip->getNumEntries() == 0) {
        if (bundle->getVerbose()) {
            printf("Archive is empty -- removing %s\n", outputFile.getPathLeaf().string());
        }
        delete zip;        // close the file so we can remove it in Win32
        zip = NULL;
        if (unlink(outputFile.string()) != 0) {
            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string());
        }
    }

    // If we've been asked to generate a dependency file for the .ap_ package,
    // do so here
    if (bundle->getGenDependencies()) {
        // The dependency file gets output to the same directory
        // as the specified output file with an additional .d extension.
        // e.g. bin/resources.ap_.d
        String8 dependencyFile = outputFile;
        dependencyFile.append(".d");

        FILE* fp = fopen(dependencyFile.string(), "a");
        // Add this file to the dependency file
        fprintf(fp, "%s \\\n", outputFile.string());
        fclose(fp);
    }

    assert(result == NO_ERROR);

bail:
    delete zip;        // must close before remove in Win32
    if (result != NO_ERROR) {
        if (bundle->getVerbose()) {
            printf("Removing %s due to earlier failures\n", outputFile.string());
        }
        if (unlink(outputFile.string()) != 0) {
            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string());
        }
    }

    if (result == NO_ERROR && bundle->getVerbose())
        printf("Done!\n");

    #if BENCHMARK
    fprintf(stdout, "BENCHMARK: End APK Bundling. Time Elapsed: %f ms \n",(clock() - startAPKTime)/1000.0);
    #endif /* BENCHMARK */
    return result;
}
Exemple #30
0
/*
 * Handle the "list" command, which can be a simple file dump or
 * a verbose listing.
 *
 * The verbose listing closely matches the output of the Info-ZIP "unzip"
 * command.
 */
int doList(Bundle* bundle)
{
    int result = 1;
    ZipFile* zip = NULL;
    const ZipEntry* entry;
    long totalUncLen, totalCompLen;
    const char* zipFileName;

    if (bundle->getFileSpecCount() != 1) {
        fprintf(stderr, "ERROR: specify zip file name (only)\n");
        goto bail;
    }
    zipFileName = bundle->getFileSpecEntry(0);

    zip = openReadOnly(zipFileName);
    if (zip == NULL)
        goto bail;

    int count, i;

    if (bundle->getVerbose()) {
        printf("Archive:  %s\n", zipFileName);
        printf(
            " Length   Method    Size  Ratio   Offset      Date  Time  CRC-32    Name\n");
        printf(
            "--------  ------  ------- -----  -------      ----  ----  ------    ----\n");
    }

    totalUncLen = totalCompLen = 0;

    count = zip->getNumEntries();
    for (i = 0; i < count; i++) {
        entry = zip->getEntryByIndex(i);
        if (bundle->getVerbose()) {
            char dateBuf[32];
            time_t when;

            when = entry->getModWhen();
            strftime(dateBuf, sizeof(dateBuf), "%m-%d-%y %H:%M",
                localtime(&when));

            printf("%8ld  %-7.7s %7ld %3d%%  %8zd  %s  %08lx  %s\n",
                (long) entry->getUncompressedLen(),
                compressionName(entry->getCompressionMethod()),
                (long) entry->getCompressedLen(),
                calcPercent(entry->getUncompressedLen(),
                            entry->getCompressedLen()),
                (size_t) entry->getLFHOffset(),
                dateBuf,
                entry->getCRC32(),
                entry->getFileName());
        } else {
            printf("%s\n", entry->getFileName());
        }

        totalUncLen += entry->getUncompressedLen();
        totalCompLen += entry->getCompressedLen();
    }

    if (bundle->getVerbose()) {
        printf(
        "--------          -------  ---                            -------\n");
        printf("%8ld          %7ld  %2d%%                            %d files\n",
            totalUncLen,
            totalCompLen,
            calcPercent(totalUncLen, totalCompLen),
            zip->getNumEntries());
    }

    if (bundle->getAndroidList()) {
        AssetManager assets;
        if (!assets.addAssetPath(String8(zipFileName), NULL)) {
            fprintf(stderr, "ERROR: list -a failed because assets could not be loaded\n");
            goto bail;
        }

        const ResTable& res = assets.getResources(false);
        if (&res == NULL) {
            printf("\nNo resource table found.\n");
        } else {
#ifndef HAVE_ANDROID_OS
            printf("\nResource table:\n");
            res.print(false);
#endif
        }

        Asset* manifestAsset = assets.openNonAsset("AndroidManifest.xml",
                                                   Asset::ACCESS_BUFFER);
        if (manifestAsset == NULL) {
            printf("\nNo AndroidManifest.xml found.\n");
        } else {
            printf("\nAndroid manifest:\n");
            ResXMLTree tree;
            tree.setTo(manifestAsset->getBuffer(true),
                       manifestAsset->getLength());
            printXMLBlock(&tree);
        }
        delete manifestAsset;
    }

    result = 0;

bail:
    delete zip;
    return result;
}