Ejemplo n.º 1
0
static int CreatePlaylist( stream_t *s, char **pp_buffer )
{
    stream_sys_t *p_sys = s->p_sys;

    unzFile file = p_sys->zipFile;
    if( !file )
        return -1;

    /* Get some infos about zip archive */
    int i_ret = 0;
    vlc_array_t *p_filenames = vlc_array_new(); /* Will contain char* */

    /* List all file names in Zip archive */
    i_ret = GetFilesInZip( s, file, p_filenames, NULL );
    if( i_ret < 0 )
    {
        i_ret = -1;
        goto exit;
    }

    /* Construct the xspf playlist */
    i_ret = WriteXSPF( pp_buffer, p_filenames, p_sys->psz_path );
    if( i_ret > 0 )
        i_ret = 1;
    else if( i_ret < 0 )
        i_ret = -1;

exit:
    /* Close archive */
    unzClose( file );
    p_sys->zipFile = NULL;

    for( int i = 0; i < vlc_array_count( p_filenames ); i++ )
    {
        free( vlc_array_item_at_index( p_filenames, i ) );
    }
    vlc_array_destroy( p_filenames );
    return i_ret;
}
Ejemplo n.º 2
0
bool FileUtils::isFileExisted(const char* pFilePath)
{
    bool bRet = false;

    if (strlen(s_ZipFilePath) != 0)
    {
        // if have set the zip file path,find the resource in the zip file
        unzFile pZipFile = unzOpen(s_ZipFilePath);
        do 
        {
            BREAK_IF(!pZipFile);

            Int32 nPos = unzLocateFile(pZipFile, pFilePath, 1);
            BREAK_IF(nPos != UNZ_OK);

            bRet = true;
            unzClose(pZipFile);
        } while (0);
    }
    else
    {
        char fullPath[EOS_FILE_MAX_PATH];
        fullPathFromRelativePath(pFilePath, fullPath);

        if (strlen(fullPath) > 0)
        {
            TUChar FilePath[EOS_FILE_MAX_PATH] = {0};
            TUString::StrGBToUnicode(FilePath, (const Char *) fullPath);

            // find in the hardware
            if (EOS_IsFileExist(FilePath))
            {
                bRet = true;
            }
        }
    }

    return bRet;
}
Ejemplo n.º 3
0
/*
================
FS_Shutdown

Frees all resources and closes all files
================
*/
void FS_Shutdown( qboolean closemfp ) {
	searchpath_t	*p, *next;
	int	i;

	for(i = 0; i < MAX_FILE_HANDLES; i++) {
		if (fsh[i].fileSize) {
			FS_FCloseFile(i);
		}
	}

	// free everything
	for ( p = fs_searchpaths ; p ; p = next ) {
		next = p->next;

		if ( p->pack ) {
			unzClose(p->pack->handle);
			Z_Free( p->pack->buildBuffer );
			Z_Free( p->pack );
		}
		if ( p->dir ) {
			Z_Free( p->dir );
		}
		Z_Free( p );
	}

	// any FS_ calls will now be an error until reinitialized
	fs_searchpaths = NULL;

	Cmd_RemoveCommand( "path" );
	Cmd_RemoveCommand( "dir" );
	Cmd_RemoveCommand( "fdir" );
	Cmd_RemoveCommand( "touchFile" );

#ifdef FS_MISSING
	if (closemfp) {
		fclose(missingFiles);
	}
#endif
}
Ejemplo n.º 4
0
/**doc
$TOC_MEMBER $INAME
 $INAME( filename )
  Constructs a new inflater or deflater object.
  $H example
  {{{
  var f = new ZipFile('test.zip');
  f.open(ZipFile.CREATE);
  f.select('file1.txt');
  f.write('data1');
  f.close();
  }}}
**/
DEFINE_CONSTRUCTOR() {

	Private *pv = NULL;

	JL_DEFINE_ARGS;

	JL_ASSERT_CONSTRUCTING();
	JL_ASSERT_ARGC(1);
	JL_DEFINE_CONSTRUCTOR_OBJ;
	
	//JL_CHK( JL_SetReservedSlot(JL_OBJ, SLOT_FILENAME, JL_ARG(1)) );
	JL_CHK( jl::setSlot(cx, JL_OBJ, SLOT_FILENAME, JL_ARG(1)) );

	pv = (Private*)jl_calloc(sizeof(Private), 1);
	JL_ASSERT_ALLOC(pv);
	pv->uf = NULL;
	pv->zf = NULL;

	JL_updateMallocCounter(cx, sizeof(Private));
	JL_ASSERT( !pv->uf && !pv->zf );
	JL_ASSERT( !pv->inZipOpened );

	//JL_CHK( ReserveStreamReadInterface(cx, obj) );
	JL_CHK( jl::setStreamReadInterface(cx, JL_OBJ, NativeInterfaceStreamRead) );

	JL_SetPrivate(JL_OBJ, pv);
	return true;

bad:
	if ( pv ) {

		if ( pv->zf )
			zipClose(pv->zf, NULL);
		if ( pv->uf )
			unzClose(pv->uf);
		jl_free(pv);
	}
	return false;
}
Ejemplo n.º 5
0
unsigned char* FileUtils::getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size)
{
    unsigned char * buffer = nullptr;
    unzFile file = nullptr;
    *size = 0;

    do 
    {
        CC_BREAK_IF(zipFilePath.empty());

        file = unzOpen(zipFilePath.c_str());
        CC_BREAK_IF(!file);

        int ret = unzLocateFile(file, filename.c_str(), 1);
        CC_BREAK_IF(UNZ_OK != ret);

        char filePathA[260];
        unz_file_info fileInfo;
        ret = unzGetCurrentFileInfo(file, &fileInfo, filePathA, sizeof(filePathA), nullptr, 0, nullptr, 0);
        CC_BREAK_IF(UNZ_OK != ret);

        ret = unzOpenCurrentFile(file);
        CC_BREAK_IF(UNZ_OK != ret);

        buffer = (unsigned char*)malloc(fileInfo.uncompressed_size);
        int CC_UNUSED readedSize = unzReadCurrentFile(file, buffer, static_cast<unsigned>(fileInfo.uncompressed_size));
        CCASSERT(readedSize == 0 || readedSize == (int)fileInfo.uncompressed_size, "the file size is wrong");

        *size = fileInfo.uncompressed_size;
        unzCloseCurrentFile(file);
    } while (0);

    if (file)
    {
        unzClose(file);
    }

    return buffer;
}
Ejemplo n.º 6
0
void FileUtils::extractFromZip(const char* zipFilePath, const char* src, const char* dest) throw (IOException)
{
	unzFile zipFile = unzOpen(zipFilePath);
	int result = unzLocateFile(zipFile,src,0);
	if (result == UNZ_OK)
	{
		// found a match which is now the current file
		unzOpenCurrentFile(zipFile);
		const int chunkSize = 4096;
		char buffer[chunkSize];

		std::ofstream outputFile(dest,std::ofstream::binary);
		if (!outputFile.good())
		{
			throw IOException("Unable to write to file " + std::string(dest));
		}
		while (true)
		{
			int count = unzReadCurrentFile(zipFile,buffer,chunkSize);
			if (count <= 0)
			{
				if (count < 0)
				{
					throw IOException("Error extracting file from archive " + std::string(src));
				}
				break;
			}
			outputFile.write(buffer,count);
		}
		outputFile.close();

		unzCloseCurrentFile(zipFile);
	}
	else
	{
		throw IOException("Unable to find file " + std::string(src) + " in zip archive " + std::string(zipFilePath));
	}
	unzClose(zipFile);
}
Ejemplo n.º 7
0
// ////////////////////////////////////////////////////////////////////////////////
// @public @static 将指定 zip 解压至指定路径下
//
bool ZipTools::UnZip(LPCWSTR wzZipName, LPCWSTR wzDestPath)
{
	//
	// 检查指定文件和文件夹是否存在
	//
	if ( !FileTools::Exist(wzZipName) )
	{
		DebugTools::OutputDebugPrintfW(L"[ZipTools] [UnZip] File Not Exist. [%s]\r\n", wzZipName);
		return false;
	}

	if ( !FileTools::Exist(wzDestPath) )
	{
		DebugTools::OutputDebugPrintfW(L"[ZipTools] [Zip] Path Not Exist. [%s]\r\n", wzDestPath);
		return false;
	}

	// 打开 zip 文件
	zlib_filefunc64_def ffunc;
	fill_win32_filefunc64W(&ffunc);
	unzFile uf = unzOpen2_64(wzZipName, &ffunc);

	if ( NULL == uf )
	{
		DebugTools::OutputDebugPrintfW(
			L"[ZipTools] [Zip] Open Zip File Failed.[%s]\r\n", wzZipName);
	}

	// 设置指定目录为工作目录
	SetCurrentDirectoryW(wzDestPath);

	// 释放文件
	ExtractFile(uf);

	unzClose(uf);

	return true;
}
Ejemplo n.º 8
0
int dxsmp_sh_start(const struct dxsmpinterface *intf) {
  char *str;
  const char *stream_names[2] = { "DX Sample L", "DX Sample R"};

  if ((str = exists_emudx_file(intf->dx_name))) {
    unzFile dat;
    int vol[2];
    vol[0] = intf->mixing_level & 0xffff;
    vol[1] = intf->mixing_level >> 16;

    dat = unzOpen(str);
    if (!dat) {
      raine_nb_samples = 0;
      return 1;
    }
    unzClose(dat);
    strcpy(dx_file,str);
    read_dx_file();
    if (stream_init_multim(2, stream_names, vol, audio_sample_rate, 0, dxsmp_update) == -1)
      return 1;

    return 0;
  }
Ejemplo n.º 9
0
Archivo: zipk.cpp Proyecto: wangch/zipk
static int btn_click0(Button* btn) {
	OPENFILENAME ofn;       // common dialog box structure
	wchar_t szFile[260];       // buffer for file name

	// Initialize OPENFILENAME
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
   ofn.hwndOwner = g_lv.pw;
	ofn.lpstrFile = szFile;
	// Set lpstrFile[0] to '\0' so that GetOpenFileName does not 
	// use the contents of szFile to initialize itself.
	ofn.lpstrFile[0] = L'\0';
	ofn.nMaxFile = sizeof(szFile);
	ofn.lpstrFilter = L"zip file\0*.zip\0";
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = NULL;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = NULL;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

	// Display the Open dialog box. 
	if (::GetOpenFileName(&ofn) == TRUE) {
      std::string path = utf8util::UTF8FromUTF16(ofn.lpstrFile);
      unzClose(g_lv.unz);
      delete g_lv.root;
      g_lv.root = new node;
      g_lv.n = g_lv.root;
      unzFile uf = unzOpen(path.c_str());
      if (!uf) {
         ::MessageBox(0, L"zip 文件错误", L"错误", 0);
         return -1;
      }
      read_file_info(uf);
   }
   ::SendMessage(g_lv.lv, LVM_SETVIEW, LV_VIEW_ICON, 0);
   return 0;
}
Ejemplo n.º 10
0
gboolean
managed_unzip_stream_to_stream (ManagedStreamCallbacks *source, ManagedStreamCallbacks *dest, const char *partname)
{
	zlib_filefunc_def funcs;
	unzFile zipFile;
	gboolean ret;

	ret = FALSE;

	funcs.zopen_file = managed_stream_open;
	funcs.zread_file = managed_stream_read;
	funcs.zwrite_file = managed_stream_write;
	funcs.ztell_file = managed_stream_tell;
	funcs.zseek_file = managed_stream_seek;
	funcs.zclose_file = managed_stream_close;
	funcs.zerror_file = managed_stream_error;
	funcs.opaque = source;

	zipFile = unzOpen2 (NULL, &funcs);

	if (!zipFile)
		return FALSE;

	if (unzLocateFile (zipFile, partname, 2) != UNZ_OK)
		goto cleanup;	

	if (unzOpenCurrentFile (zipFile) != UNZ_OK)
		goto cleanup;

	ret = managed_unzip_extract_to_stream (zipFile, dest);

cleanup:
	unzCloseCurrentFile (zipFile);
	unzClose (zipFile);

	return ret;
}
Ejemplo n.º 11
0
/*
================
FS_Shutdown

Frees all resources and closes all files
================
*/
void FS_Shutdown( void ) {
	searchpath_t	*p, *next;
	int	i;

	for(i = 0; i < MAX_FILE_HANDLES; i++) {
		if (fsh[i].fileSize) {
			FS_FCloseFile(i);
		}
	}

	// free everything
	for ( p = fs_searchpaths ; p ; p = next ) {
		next = p->next;

		if ( p->pack ) {
#ifndef _XBOX
			unzClose(p->pack->handle);
#endif
			Z_Free( p->pack->buildBuffer );
			Z_Free( p->pack );
		}
		if ( p->dir ) {
			Z_Free( p->dir );
		}
		Z_Free( p );
	}

	// any FS_ calls will now be an error until reinitialized
	fs_searchpaths = NULL;

	Cmd_RemoveCommand( "path" );
	Cmd_RemoveCommand( "dir" );
	Cmd_RemoveCommand( "touchFile" );

	initialized = qfalse;
}
Ejemplo n.º 12
0
HRESULT WINAPI CZipFsEnum::Enum(__in IFsEnumContext *context)
{
	HRESULT hr;
	zlib_filefunc64_def ffunc;
	BSTR lpFileName = NULL;
	IVirtualFs * container = NULL;

	if (context == NULL) return E_INVALIDARG;

	hr = context->GetSearchContainer(&container);
	if (FAILED(hr)) return hr;
	
	FillFunctions64((voidpf)container, &ffunc);
	hr = container->GetFullPath(&lpFileName);
	if (FAILED(hr))
	{
		container->Release();
		return hr;
	}

	unzFile uf = NULL;
	uf = unzOpen2_64(lpFileName, &ffunc);
	SysFreeString(lpFileName);

	if (uf == NULL)
	{
		container->Release();
		return E_FAIL;
	}

	hr = ReadArchiver(container, context, uf);

	unzClose(uf);
	container->Release();
	return hr;
}
Ejemplo n.º 13
0
enum ApkResult
apk_uncompress_internal(AndroidApk *apk, char **buffer, size_t *size)
{
    zlib_filefunc_def filefunc;
    fill_memory_filefunc(&filefunc);
    char *old_buffer = *buffer;
    char path[1024];
    sprintf(path, "%x+%x", *buffer, *size);

    /* Decompress a single file in a .zip from memory */
    unz_file_info info;
    unzFile *unz = unzOpen2(path, &filefunc);
    unzGoToFirstFile(unz);
    unzGetCurrentFileInfo(unz, &info, NULL, 0, NULL, 0, NULL, 0);
    *size = info.uncompressed_size;
    *buffer = malloc(*size);
    unzOpenCurrentFile(unz);
    unzReadCurrentFile(unz, *buffer, *size);
    unzCloseCurrentFile(unz);
    unzClose(unz);
    free(old_buffer);

    return APK_OK;
}
Ejemplo n.º 14
0
MessageRef ReadZipFile(DataIO & readFrom, bool loadData)
{
   TCHECKPOINT;

   static const int NAME_BUF_LEN = 8*1024;  // names longer than 8KB are ridiculous anyway!
   char * nameBuf = newnothrow_array(char, NAME_BUF_LEN);
   if (nameBuf)
   {
      MessageRef ret = GetMessageFromPool();
      if (ret())
      {
         zlib_filefunc_def zdefs = {
            fopen_dataio_func,
            fread_dataio_func,
            fwrite_dataio_func,
            ftell_dataio_func,
            fseek_dataio_func,
            fclose_dataio_func,
            ferror_dataio_func,
            &readFrom
         };
         zipFile zf = unzOpen2(NULL, &zdefs);
         if (zf != NULL)
         {
            if (ReadZipFileAux(zf, *ret(), nameBuf, NAME_BUF_LEN, loadData) != B_NO_ERROR) ret.Reset();
            unzClose(zf);
         }
         else ret.Reset();  // failure!
      }
      delete [] nameBuf;
      return ret;
   }
   else WARN_OUT_OF_MEMORY;

   return MessageRef();
}
Ejemplo n.º 15
0
	bool ExtractFiles(const wchar_t* zip_file_path, const ExtractedFileCallback& callback, void* pParam)
	{
		unzFile unzip_file_handle = unzOpenHelp(zip_file_path);
		if ( unzip_file_handle != NULL )
		{		  
			do 
			{
				unz_file_info file_info;
				unzGetCurrentFileInfo(unzip_file_handle, &file_info, NULL, 0, NULL, 0, NULL, 0);

				BYTE* pData = new BYTE[file_info.uncompressed_size];
				if(file_info.uncompressed_size == 0 || get_file(unzip_file_handle, pData, file_info.uncompressed_size))
				{
					callback(get_filename_from_unzfile(unzip_file_handle), pData, file_info.uncompressed_size, pParam);
				}
				RELEASEARRAYOBJECTS(pData);
				// else just skip the erroneous file
			} while (UNZ_OK == unzGoToNextFile(unzip_file_handle));
					
			unzClose( unzip_file_handle );
			return true;
		}
		return false;
	}
Ejemplo n.º 16
0
unzFile ZipArchive::get_file_handle(String p_file) const {

	ERR_FAIL_COND_V(!file_exists(p_file), NULL);
	File file = files[p_file];

	FileAccess* f = FileAccess::open(packages[file.package].filename, FileAccess::READ);
	ERR_FAIL_COND_V(!f, NULL);

	zlib_filefunc_def io;
	zeromem(&io, sizeof(io));

	io.opaque = f;
	io.zopen_file = godot_open;
	io.zread_file = godot_read;
	io.zwrite_file = godot_write;

	io.ztell_file = godot_tell;
	io.zseek_file = godot_seek;
	io.zclose_file = godot_close;
	io.zerror_file = godot_testerror;

	io.alloc_mem = godot_alloc;
	io.free_mem = godot_free;

	unzFile pkg = unzOpen2(packages[file.package].filename.utf8().get_data(), &io);
	ERR_FAIL_COND_V(!pkg, NULL);
	int unz_err = unzGoToFilePos(pkg, &file.file_pos);
	ERR_FAIL_COND_V(unz_err != UNZ_OK, NULL);
	if (unzOpenCurrentFile(pkg) != UNZ_OK) {

		unzClose(pkg);
		ERR_FAIL_V(NULL);
	};

	return pkg;
};
Ejemplo n.º 17
0
int TRI_UnzipFile (const char* filename,
                   const char* outPath, 
                   const bool skipPaths,
                   const bool overwrite,
                   const char* password) {
  unzFile uf;
#ifdef USEWIN32IOAPI
  zlib_filefunc64_def ffunc;
#endif
  void* buffer;
  size_t bufferSize;
  int res;
  
  bufferSize = 16384;
  buffer = (void*) TRI_Allocate(TRI_UNKNOWN_MEM_ZONE, bufferSize, false);

  if (buffer == NULL) {
    return TRI_ERROR_OUT_OF_MEMORY;
  }


#ifdef USEWIN32IOAPI
  fill_win32_filefunc64A(&ffunc);
  uf = unzOpen2_64(filename, &ffunc);
#else
  uf = unzOpen64(filename);
#endif

  res = UnzipFile(uf, buffer, bufferSize, outPath, skipPaths, overwrite, password);

  unzClose(uf);

  TRI_Free(TRI_UNKNOWN_MEM_ZONE, buffer);

  return res;
}
Ejemplo n.º 18
0
void ExportTemplateManager::_install_from_file(const String &p_file, bool p_use_progress) {

	FileAccess *fa = NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&fa);

	unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::get_singleton()->show_warning(TTR("Can't open export templates zip."));
		return;
	}
	int ret = unzGoToFirstFile(pkg);

	int fc = 0; //count them and find version
	String version;

	while (ret == UNZ_OK) {

		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		if (file.ends_with("version.txt")) {

			Vector<uint8_t> data;
			data.resize(info.uncompressed_size);

			//read
			unzOpenCurrentFile(pkg);
			ret = unzReadCurrentFile(pkg, data.ptrw(), data.size());
			unzCloseCurrentFile(pkg);

			String data_str;
			data_str.parse_utf8((const char *)data.ptr(), data.size());
			data_str = data_str.strip_edges();

			// Version number should be of the form major.minor[.patch].status[.module_config]
			// so it can in theory have 3 or more slices.
			if (data_str.get_slice_count(".") < 3) {
				EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid version.txt format inside templates: %s."), data_str));
				unzClose(pkg);
				return;
			}

			version = data_str;
		}

		if (file.get_file().size() != 0) {
			fc++;
		}

		ret = unzGoToNextFile(pkg);
	}

	if (version == String()) {
		EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside templates."));
		unzClose(pkg);
		return;
	}

	String template_path = EditorSettings::get_singleton()->get_templates_dir().plus_file(version);

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	Error err = d->make_dir_recursive(template_path);
	if (err != OK) {
		EditorNode::get_singleton()->show_warning(TTR("Error creating path for templates:") + "\n" + template_path);
		unzClose(pkg);
		return;
	}

	memdelete(d);

	ret = unzGoToFirstFile(pkg);

	EditorProgress *p = NULL;
	if (p_use_progress) {
		p = memnew(EditorProgress("ltask", TTR("Extracting Export Templates"), fc));
	}

	fc = 0;

	while (ret == UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = String(fname).get_file();

		if (file.size() == 0) {
			ret = unzGoToNextFile(pkg);
			continue;
		}

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg, data.ptrw(), data.size());
		unzCloseCurrentFile(pkg);

		if (p) {
			p->step(TTR("Importing:") + " " + file, fc);
		}

		FileAccess *f = FileAccess::open(template_path.plus_file(file), FileAccess::WRITE);

		if (!f) {
			ret = unzGoToNextFile(pkg);
			fc++;
			ERR_CONTINUE(!f);
		}

		f->store_buffer(data.ptr(), data.size());

		memdelete(f);

		ret = unzGoToNextFile(pkg);
		fc++;
	}

	if (p) {
		memdelete(p);
	}

	unzClose(pkg);

	_update_template_list();
}
Ejemplo n.º 19
0
bool zip::ZipArchiveInput::Close()
{
	int errClose = unzClose(uf);
	m_nameToEntry.clear();
	return errClose == UNZ_OK;
}
Ejemplo n.º 20
0
/******************************************************************************
*** Description
***     Load a file in a zip file into memory.
***
*** Arguments
***     zipName     - Name of zip file
***     fileName    - Name of file insize zipfile to load
***     size        - Output of size of file
***
*** Return
***     Pointer to allocate memory buffer with file content or NULL on
***     failure.
***
*******************************************************************************
*/
void* _zipLoadFile(const char* zipName, const char* fileName, int* size, zlib_filefunc_def* filefunc)
{
    void* buf;
    char name[256];
    unzFile zip;
    unz_file_info info;

    *size = 0;

    if (fileName[0] == '*') {
        strcpy(name, zipName);
        name[strlen(zipName) - 3] = fileName[strlen(fileName) - 3];
        name[strlen(zipName) - 2] = fileName[strlen(fileName) - 2];
        name[strlen(zipName) - 1] = fileName[strlen(fileName) - 1];
    }
    else {
        strcpy(name, fileName);
    }

    zip = unzOpen2(zipName, filefunc);
    if (!zip) {
        return NULL;
    }

#ifdef __APPLE__
    // Most OS X installs are on a case-insensitive FS
    if (unzLocateFile(zip, name, 2) == UNZ_END_OF_LIST_OF_FILE) {
#else
    if (unzLocateFile(zip, name, 1) == UNZ_END_OF_LIST_OF_FILE) {
#endif
        unzClose(zip);
        return NULL;
    }

    if (unzOpenCurrentFile(zip) != UNZ_OK) {
        return NULL;
    }

    unzGetCurrentFileInfo(zip,&info,NULL,0,NULL,0,NULL,0);

    buf = malloc(info.uncompressed_size);
    *size = info.uncompressed_size;

    if (!buf) {
        unzCloseCurrentFile(zip);
        unzClose(zip);
        return NULL;
    }

    unzReadCurrentFile(zip, buf, info.uncompressed_size);
    unzCloseCurrentFile(zip);
    unzClose(zip);

    return buf;
}


/******************************************************************************
*** Description
***     Read cache to speed-up reading multiple files from one zip.
***
******************************************************************************/

static char *cacheData = NULL, cacheFile[512];
static zlib_filefunc_def cacheFilefunc;

void* zipLoadFile(const char* zipName, const char* fileName, int* size)
{
    if (strncmp(zipName, "mem", 3) == 0) {
        return memFileLoad(zipName, fileName, size);
    }
    if( cacheData != NULL && *cacheFile != '\0' && 0==strcmp(cacheFile, zipName) ) {
        return _zipLoadFile(cacheData, fileName, size, &cacheFilefunc);
    }else{
        return _zipLoadFile(zipName, fileName, size, NULL);
    }
}

void zipCacheReadOnlyZip(const char* zipName)
{
    if (zipName != NULL && strncmp(zipName, "mem", 3) == 0) {
        return;
    }

    *cacheFile = '\0';
    if( cacheData != NULL ) {
        free(cacheData);
        cacheData = NULL;
        free_fopen_memfunc(&cacheFilefunc);
    }
    if( zipName != NULL ) {
        FILE *file;
        file = fopen(zipName, "rb");
        if( file != NULL ) {
            unsigned int filesize;
            fseek(file, 0, SEEK_END);
            filesize = ftell(file);
            fill_fopen_memfunc(&cacheFilefunc, filesize);
            fseek(file, 0, SEEK_SET);
            cacheData = malloc(filesize);
            if( cacheData != NULL ) {
                size_t size = fread(cacheData, 1, filesize, file);
                if( size == filesize ) {
                    strcpy(cacheFile, zipName);
                }
            }
            fclose(file);
        }
    }
}


/******************************************************************************
*** Description
***     Load a file in a zip file into memory.
***
*** Arguments
***     zipName     - Name of zip file
***     fileName    - Name of file insize zipfile to save
***     buffer      - Buffer to save
***     size        - Size of buffer to save
***
*******************************************************************************
*/
int zipSaveFile(const char* zipName, const char* fileName, int append, void* buffer, int size)
{
    zipFile zip;
    zip_fileinfo zi;
    int err;

    if (strncmp(zipName, "mem", 3) == 0) {
        return memFileSave(zipName, fileName, append, buffer, size);
    }

    zip = zipOpen(zipName, append ? 2 : 0);
    if (zip == NULL) {
        return 0;
    }

    memset(&zi, 0, sizeof(zi));

    err = zipOpenNewFileInZip(zip, fileName, &zi,
                              NULL, 0, NULL, 0, NULL,
                              Z_DEFLATED, Z_DEFAULT_COMPRESSION);
    if (err == ZIP_OK) {
        err = zipWriteInFileInZip(zip, buffer, size);
    }

    zipClose(zip, NULL);

    return err >= 0;
}
Ejemplo n.º 21
0
/******************************************************************************
*** Description
***     Checks if a file exists in a zip file.
***
*** Arguments
***     zipName     - Name of zip file
***     fileName    - Name of file insize zipfile to load
***
*** Return
***     1 = file exists, 0 = non existing zip or file in zip does not exists
***     failure.
***
*******************************************************************************
*/
int zipFileExists(const char* zipName, const char* fileName)
{
    char name[256];
    unzFile zip;

    if (fileName[0] == '*') {
        strcpy(name, zipName);
        name[strlen(zipName) - 3] = fileName[strlen(fileName) - 3];
        name[strlen(zipName) - 2] = fileName[strlen(fileName) - 2];
        name[strlen(zipName) - 1] = fileName[strlen(fileName) - 1];
    }
    else {
        strcpy(name, fileName);
    }

    zip = unzOpen(zipName);
    if (!zip) {
        return 0;
    }

#ifdef __APPLE__
    // Most OS X installs are on a case-insensitive FS
    if (unzLocateFile(zip, name, 2) == UNZ_END_OF_LIST_OF_FILE) {
#else
    if (unzLocateFile(zip, name, 1) == UNZ_END_OF_LIST_OF_FILE) {
#endif
        unzClose(zip);
        return 0;
    }else{
        unzClose(zip);
        return 1;
    }
}

/******************************************************************************
*** Description
***     Creates a list of file names inside a zip that matches a given
***     extension.
***
*** Arguments
***     zipName     - Name of zip file
***     ext         - Extension to check
***     count       - Output for number of matching files in zip file.
***
*** Return
***     1 if files with the given extension exists in the zip file,
***     0 otherwise.
***
*******************************************************************************
*/
char* zipGetFileList(const char* zipName, const char* ext, int* count) {
    char tempName[256];
    char extension[8];
    unzFile zip;
    unz_file_info info;
    char* fileArray = NULL;
    int totalLen = 0;
    int status;

    *count = 0;

    zip = unzOpen(zipName);
    if (!zip) {
        return 0;
    }

    strcpy(extension, ext);
    toLower(extension);

    status = unzGoToFirstFile(zip);
    unzGetCurrentFileInfo(zip,&info,tempName,256,NULL,0,NULL,0);

    while (status == UNZ_OK) {
        char tmp[256];

        unzGetCurrentFileInfo(zip, &info, tempName, 256, NULL, 0, NULL, 0);

        strcpy(tmp, tempName);

        toLower(tmp);
        if (strstr(tmp, extension) != NULL) {
            int entryLen = strlen(tempName) + 1;
            fileArray = realloc(fileArray, totalLen +  entryLen + 1);
            strcpy(fileArray + totalLen, tempName);
            totalLen += entryLen;
            fileArray[totalLen] = '\0'; // double null termination at end

            *count = *count + 1;
        }

        status = unzGoToNextFile(zip);
    }

    unzClose(zip);

    return fileArray;
}
Ejemplo n.º 22
0
/*
=================
idFile_InZip::~idFile_InZip
=================
*/
idFile_InZip::~idFile_InZip( void ) {
    unzCloseCurrentFile( z );
    unzClose( z );
}
Ejemplo n.º 23
0
unzFile UnCompressZip::unzOpenInternal (const void *path,
                               zlib_filefunc64_32_def* pzlib_filefunc64_32_def,
                               int is64bitOpenFunction)
{
    unz64_s us;
    unz64_s *s;
    ZPOS64_T central_pos;
    uLong   uL;

    uLong number_disk;          /* number of the current dist, used for
                                   spaning ZIP, unsupported, always 0*/
    uLong number_disk_with_CD;  /* number the the disk with central dir, used
                                   for spaning ZIP, unsupported, always 0*/
    ZPOS64_T number_entry_CD;      /* total number of entries in
                                   the central dir
                                   (same than number_entry on nospan) */

    int err=UNZ_OK;

    //if (unz_copyright[0]!=' ')
        //return NULL;

    us.z_filefunc.zseek32_file = NULL;
    us.z_filefunc.ztell32_file = NULL;
    if (pzlib_filefunc64_32_def==NULL)
        fill_fopen64_filefunc(&us.z_filefunc.zfile_func64);
    else
        us.z_filefunc = *pzlib_filefunc64_32_def;
    us.is64bitOpenFunction = is64bitOpenFunction;

    us.filestream = ZOPEN64(us.z_filefunc, path, ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_EXISTING);
    if (us.filestream==NULL)
        return NULL;

    central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream);
    if (central_pos)
    {
       uLong uS;
       ZPOS64_T uL64;

       us.isZip64 = 1;

       if (ZSEEK64(us.z_filefunc, us.filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
         err=UNZ_ERRNO;

       if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
         err=UNZ_ERRNO;

        
       if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK)
         err=UNZ_ERRNO;

        
       if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
            err=UNZ_ERRNO;

       
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        if ((number_entry_CD!=us.gi.number_entry) ||
            (number_disk_with_CD!=0) ||
            (number_disk!=0))
            err=UNZ_BADZIPFILE;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK)
            err=UNZ_ERRNO;

        us.gi.size_comment = 0;
    }
    else
    {
        central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream);
        if (central_pos==0)
            err=UNZ_ERRNO;

        us.isZip64 = 0;

        if (ZSEEK64(us.z_filefunc, us.filestream,
                                        central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;

       
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.gi.number_entry = uL;

       
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        number_entry_CD = uL;

        if ((number_entry_CD!=us.gi.number_entry) ||
            (number_disk_with_CD!=0) ||
            (number_disk!=0))
            err=UNZ_BADZIPFILE;

     
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.size_central_dir = uL;

        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.offset_central_dir = uL;


        if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK)
            err=UNZ_ERRNO;
    }

    if ((central_pos<us.offset_central_dir+us.size_central_dir) &&
        (err==UNZ_OK))
        err=UNZ_BADZIPFILE;

    if (err!=UNZ_OK)
    {
        ZCLOSE64(us.z_filefunc, us.filestream);
        return NULL;
    }

    us.byte_before_the_zipfile = central_pos - (us.offset_central_dir+us.size_central_dir);
    us.central_pos = central_pos;
    us.pfile_in_zip_read = NULL;
    us.encrypted = 0;

    s=(unz64_s*)ALLOC(sizeof(unz64_s));
    if( s != NULL)
    {
        *s=us;
        Bytef buf[UNZ_BUFSIZE];
        char  name[100];
        if (unzGoToFirstFile((unzFile)s) != UNZ_OK)
          return (unzFile)UNZ_ERRNO;
        ::CreateDirectory(m_uncompresspath.GetBuffer(MAX_PATH), NULL);
        m_uncompresspath.ReleaseBuffer();
        do 
        {
          
          unzOpenCurrentFile((unzFile)s);
          uInt filelength = unzReadCurrentFile((unzFile)s, buf, UNZ_BUFSIZE);
          unz64local_GetCurrentFileInfoInternal((unzFile)s, &s->cur_file_info,
             &s->cur_file_info_internal, name,100,NULL,0,NULL,0);

          std::wstring path = m_uncompresspath.GetString();
          path += L"\\";
          std::wstring filename = Strings::StringToWString(name);
          path += filename;

          HANDLE hfile = CreateFile(path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
          CloseHandle(hfile);

          FILE* file;
          _wfopen_s(&file, path.c_str(), L"wb");
          fwrite(buf, 1, filelength, file);
          fclose(file);
        }
        while(unzGoToNextFile((unzFile)s) == UNZ_OK);
       
        unzClose((unzFile)s);
    }
    return (unzFile)s;
}
Ejemplo n.º 24
0
bool CSystem::ContextLoad(char *context)
{
	LSS_FILE *fp;
	bool status=1;
	UBYTE *filememory=NULL;
	ULONG filesize=0;

	// First check for ZIP file
	if(IsZip(context))
	{
		// Find the file and read into memory
		// Try and find a file in the zip
		unzFile *fp;
		unz_file_info info;
		char filename_buf[0x100], *ptr;
		bool gotIt;
		
		if((fp=(unzFile*)unzOpen(context))!=NULL)
		{
			if(unzGoToFirstFile(fp)!=UNZ_OK)
			{
				unzClose(fp);
				gError->Warning("ContextLoad(): ZIP File select problems, could not read zip file");
				return 1;
			}
			
			gotIt = FALSE;
			for (;;)
			{
				// Get file descriptor and analyse
				if(unzGetCurrentFileInfo(fp, &info, filename_buf, 0x100, NULL, 0, NULL, 0) != UNZ_OK)
				{
					break;
				}
				else
				{
					ptr = strchr(filename_buf, '.');
					if (ptr != NULL)
					{
						char buf[4];
					
						ptr++; buf[0] = tolower(*ptr);
						ptr++; buf[1] = tolower(*ptr);
						ptr++; buf[2] = tolower(*ptr);
						buf[3] = 0;
						if (!strcmp(buf, "lss"))
						{
							// Found a likely file so signal
							gotIt = TRUE;
							break;
						}
					}

					// No match so lets try the next file
					if(unzGoToNextFile(fp)!=UNZ_OK)	break;
				}
			}
			
			// Did we strike gold ?
			if(gotIt)
			{
				if(unzOpenCurrentFile(fp)==UNZ_OK)
				{
					// Allocate memory for the rom
					filesize=info.uncompressed_size;
					filememory=(UBYTE*) new UBYTE[filesize];

					// Read it into memory					
					if(unzReadCurrentFile(fp,filememory,filesize)!=(int)info.uncompressed_size)
					{
						unzCloseCurrentFile(fp);
						unzClose(fp);
						delete filememory;
						// Throw a wobbly
						gError->Warning("ContextLoad(): ZIP File load problems, could not read data from the zip file");
						return 1;
					}

					// Got it!
					unzCloseCurrentFile(fp);
					unzClose(fp);
				}
				
			}
			else
			{
				gError->Warning("ContextLoad(): ZIP File load problems, could not find an LSS file in the zip archive");
				return 1;
			}
		}
		else
		{
			gError->Warning("ContextLoad(): ZIP File load problems, could not open the zip archive");
			return 1;
		}

	}
	else
	{
		FILE *fp;
		// Just open an read into memory
		if((fp=fopen(context,"rb"))==NULL) status=0;

		fseek(fp,0,SEEK_END);
		filesize=ftell(fp);
		fseek(fp,0,SEEK_SET);
		filememory=(UBYTE*) new UBYTE[filesize];

		if(fread(filememory,sizeof(char),filesize,fp)!=filesize)
		{
			fclose(fp);
			return 1;
		}
		fclose(fp);
	}

	// Setup our read structure
	fp = new LSS_FILE;
	fp->memptr=filememory;
	fp->index=0;
	fp->index_limit=filesize;

	char teststr[100];
	// Check identifier
	if(!lss_read(teststr,sizeof(char),4,fp)) status=0;
	teststr[4]=0;

	if(strcmp(teststr,LSS_VERSION)==0 || strcmp(teststr,LSS_VERSION_OLD)==0)
	{
		bool legacy=FALSE;
		if(strcmp(teststr,LSS_VERSION_OLD)==0)
		{
			legacy=TRUE;
		}
		else
		{
			ULONG checksum;
			// Read CRC32 and check against the CART for a match
			lss_read(&checksum,sizeof(ULONG),1,fp);
			if(mCart->CRC32()!=checksum)
			{
				delete fp;
				delete filememory;
				gError->Warning("LSS Snapshot CRC does not match the loaded cartridge image, aborting load");
				return 0;
			}
		}

		// Check our block header
		if(!lss_read(teststr,sizeof(char),20,fp)) status=0;
		teststr[20]=0;
		if(strcmp(teststr,"CSystem::ContextSave")!=0) status=0;

		if(!lss_read(&mCycleCountBreakpoint,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemCycleCount,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gNextTimerEvent,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gCPUWakeupTime,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gCPUBootAddress,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gIRQEntryCycle,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gBreakpointHit,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSingleStepMode,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemIRQ,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemNMI,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemCPUSleep,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemCPUSleep_Saved,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gSystemHalt,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gThrottleMaxPercentage,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gThrottleLastTimerCount,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gThrottleNextCycleCheckpoint,sizeof(ULONG),1,fp)) status=0;

		ULONG tmp;
		if(!lss_read(&tmp,sizeof(ULONG),1,fp)) status=0;
		gTimerCount=tmp;

		if(!lss_read(gAudioBuffer,sizeof(UBYTE),HANDY_AUDIO_BUFFER_SIZE,fp)) status=0;
		if(!lss_read(&gAudioBufferPointer,sizeof(ULONG),1,fp)) status=0;
		if(!lss_read(&gAudioLastUpdateCycle,sizeof(ULONG),1,fp)) status=0;

		if(!mMemMap->ContextLoad(fp)) status=0;
		// Legacy support
		if(legacy)
		{
			if(!mCart->ContextLoadLegacy(fp)) status=0;
			if(!mRom->ContextLoad(fp)) status=0;
		}
		else
		{
			if(!mCart->ContextLoad(fp)) status=0;
		}
		if(!mRam->ContextLoad(fp)) status=0;
		if(!mMikie->ContextLoad(fp)) status=0;
		if(!mSusie->ContextLoad(fp)) status=0;
		if(!mCpu->ContextLoad(fp)) status=0;
	}
	else
	{
		gError->Warning("Not a recognised LSS file");
	}

	delete fp;
	delete filememory;

	return status;
}
Ejemplo n.º 25
0
CSystem::CSystem(char* gamefile,char* romfile)
	:mCart(NULL),
	mRom(NULL),
	mMemMap(NULL),
	mRam(NULL),
	mCpu(NULL),
	mMikie(NULL),
	mSusie(NULL)
{

#ifdef _LYNXDBG
	mpDebugCallback=NULL;
	mDebugCallbackObject=0;
#endif

	// Select the default filetype
	UBYTE *filememory=NULL;
	UBYTE *howardmemory=NULL;
	ULONG filesize=0;
	ULONG howardsize=0;

	mFileType=HANDY_FILETYPE_LNX;
	if(strcmp(gamefile,"")==0)
	{
		// No file
		filesize=0;
		filememory=NULL;
	}
	else if(IsZip(gamefile))
	{
		// Try and find a file in the zip
		unzFile *fp;
		unz_file_info info;
		char filename_buf[0x100], *ptr;
		bool gotIt;
		
		if((fp=(unzFile*)unzOpen(gamefile))!=NULL)
		{
			if(unzGoToFirstFile(fp)!=UNZ_OK)
			{
				unzClose(fp);
				CLynxException lynxerr;
				lynxerr.Message() << "Handy Error: ZIP File select problems" ;
				lynxerr.Description()
					<< "The file you selected could not be read." << endl
					<< "(The ZIP file may be corrupted)." << endl ;
				throw(lynxerr);
			}
			
			gotIt = FALSE;
			for (;;)
			{
				// Get file descriptor and analyse
				if(unzGetCurrentFileInfo(fp, &info, filename_buf, 0x100, NULL, 0, NULL, 0) != UNZ_OK)
				{
					break;
				}
				else
				{
					ptr = strchr(filename_buf, '.');
					if (ptr != NULL)
					{
						char buf[4];
					
						ptr++; buf[0] = tolower(*ptr);
						ptr++; buf[1] = tolower(*ptr);
						ptr++; buf[2] = tolower(*ptr);
						buf[3] = 0;
						if (!strcmp(buf, "lnx") || !strcmp(buf, "com") || !strcmp(buf, "o"))
						{
							// Found a likely file so signal
							gotIt = TRUE;
							break;
						}
					}

					// No match so lets try the next file
					if(unzGoToNextFile(fp)!=UNZ_OK)	break;
				}
			}
			
			// Did we strike gold ?
			if(gotIt)
			{
				if(unzOpenCurrentFile(fp)==UNZ_OK)
				{
					// Allocate memory for the rom
					filesize=info.uncompressed_size;
					filememory=(UBYTE*) new UBYTE[filesize];

					// Read it into memory					
					if(unzReadCurrentFile(fp,filememory,filesize)!=(int)info.uncompressed_size)
					{
						unzCloseCurrentFile(fp);
						unzClose(fp);
						delete filememory;
						// Throw a wobbly
						CLynxException lynxerr;
						lynxerr.Message() << "Handy Error: ZIP File load problems" ;
						lynxerr.Description()
							<< "The zip file you selected could not be loaded." << endl
							<< "(The ZIP file may be corrupted)." << endl ;
						throw(lynxerr);
					}

					// Got it!
					unzCloseCurrentFile(fp);
					unzClose(fp);
				}
				
			}
			else
			{
				CLynxException lynxerr;
				lynxerr.Message() << "Handy Error: ZIP File load problems" ;
				lynxerr.Description()
					<< "The file you selected could not be loaded." << endl
					<< "Could not find a Lynx file in the ZIP archive." << endl ;
				throw(lynxerr);
			}
		}
		else
		{
			CLynxException lynxerr;
			lynxerr.Message() << "Handy Error: ZIP File open problems" ;
			lynxerr.Description()
				<< "The file you selected could not be opened." << endl
				<< "(The ZIP file may be corrupted)." << endl ;
			throw(lynxerr);
		}
	}
	else
	{
		// Open the file and load the file
		FILE	*fp;

		// Open the cartridge file for reading
		if((fp=fopen(gamefile,"rb"))==NULL)
		{
			CLynxException lynxerr;

			lynxerr.Message() << "Handy Error: File Open Error";
			lynxerr.Description()
				<< "The lynx emulator will not run without a cartridge image." << endl
				<< "\"" << gamefile << "\" was not found in the place you " << endl
				<< "specified. (see the Handy User Guide for more information).";
			throw(lynxerr);
		}

		// How big is the file ??
		fseek(fp,0,SEEK_END);
		filesize=ftell(fp);
		fseek(fp,0,SEEK_SET);
		filememory=(UBYTE*) new UBYTE[filesize];

		if(fread(filememory,sizeof(char),filesize,fp)!=filesize)
		{
			CLynxException lynxerr;
			delete filememory;

			lynxerr.Message() << "Handy Error: Unspecified Load error (Header)";
			lynxerr.Description()
				<< "The lynx emulator will not run without a cartridge image." << endl
				<< "It appears that your cartridge image may be corrupted or there is" << endl
				<< "some other error.(see the Handy User Guide for more information)";
			throw(lynxerr);
		}

		fclose(fp);
	}

	// Now try and determine the filetype we have opened
	if(filesize)
	{
		char clip[11];
		memcpy(clip,filememory,11);
		clip[4]=0;
		clip[10]=0;

		if(!strcmp(&clip[6],"BS93")) mFileType=HANDY_FILETYPE_HOMEBREW;
		else if(!strcmp(&clip[0],"LYNX")) mFileType=HANDY_FILETYPE_LNX;
		else if(!strcmp(&clip[0],LSS_VERSION_OLD)) mFileType=HANDY_FILETYPE_SNAPSHOT;
		else
		{
			CLynxException lynxerr;
			delete filememory;
			mFileType=HANDY_FILETYPE_ILLEGAL;
			lynxerr.Message() << "Handy Error: File format invalid!";
			lynxerr.Description()
				<< "The image you selected was not a recognised game cartridge format." << endl
				<< "(see the Handy User Guide for more information).";
			throw(lynxerr);
		}
	}
	
	mCycleCountBreakpoint=0xffffffff;

// Create the system objects that we'll use

	// Attempt to load the cartridge errors caught above here...

	mRom = new CRom(romfile);

	// An exception from this will be caught by the level above

	switch(mFileType)
	{
		case HANDY_FILETYPE_LNX:
			mCart = new CCart(filememory,filesize);
			if(mCart->CartHeaderLess())
			{
				FILE	*fp;
				char drive[3],dir[256],cartgo[256];
				mFileType=HANDY_FILETYPE_HOMEBREW;
				_splitpath(romfile,drive,dir,NULL,NULL);
				strcpy(cartgo,drive);
				strcat(cartgo,dir);
				strcat(cartgo,"howard.o");

				// Open the howard file for reading
				if((fp=fopen(cartgo,"rb"))==NULL)
				{
					CLynxException lynxerr;
					delete filememory;
					lynxerr.Message() << "Handy Error: Howard.o File Open Error";
					lynxerr.Description()
						<< "Headerless cartridges need howard.o bootfile to ." << endl
						<< "be able to run correctly, could not open file. " << endl;
					throw(lynxerr);
				}

				// How big is the file ??
				fseek(fp,0,SEEK_END);
				howardsize=ftell(fp);
				fseek(fp,0,SEEK_SET);
				howardmemory=(UBYTE*) new UBYTE[filesize];

				if(fread(howardmemory,sizeof(char),howardsize,fp)!=howardsize)
				{
					CLynxException lynxerr;
					delete filememory;
					delete howardmemory;
					lynxerr.Message() << "Handy Error: Howard.o load error (Header)";
					lynxerr.Description()
						<< "Howard.o could not be read????." << endl;
					throw(lynxerr);
				}

				fclose(fp);

				// Pass it to RAM to load
				mRam = new CRam(howardmemory,howardsize);
			}
			else
			{
				mRam = new CRam(0,0);
			}
			break;
		case HANDY_FILETYPE_HOMEBREW:
			mCart = new CCart(0,0);
			mRam = new CRam(filememory,filesize);
			break;
		case HANDY_FILETYPE_SNAPSHOT:
		case HANDY_FILETYPE_ILLEGAL:
		default:
			mCart = new CCart(0,0);
			mRam = new CRam(0,0);
			break;
	}

	// These can generate exceptions

	mMikie = new CMikie(*this);
	mSusie = new CSusie(*this);

// Instantiate the memory map handler

	mMemMap = new CMemMap(*this);

// Now the handlers are set we can instantiate the CPU as is will use handlers on reset

	mCpu = new C65C02(*this);

// Now init is complete do a reset, this will cause many things to be reset twice
// but what the hell, who cares, I don't.....

	Reset();

// If this is a snapshot type then restore the context

	if(mFileType==HANDY_FILETYPE_SNAPSHOT)
	{
		if(!ContextLoad(gamefile))
		{
			Reset();
			CLynxException lynxerr;
			lynxerr.Message() << "Handy Error: Snapshot load error" ;
			lynxerr.Description()
				<< "The snapshot you selected could not be loaded." << endl
				<< "(The file format was not recognised by Handy)." << endl ;
			throw(lynxerr);
		}
	}
	if(filesize) delete filememory;
	if(howardsize) delete howardmemory;
}
Ejemplo n.º 26
0
	Zip::~Zip()
	{
		unzClose(_zipFile);
	}
Ejemplo n.º 27
0
ZipArchive::~ZipArchive() {
	unzClose(_zipFile);
}
Ejemplo n.º 28
0
int F3DFile::ReadMD3(const char *pFilename)
{
	pModel = this;

	char *pBuffer = NULL;

	// open .pk3 file
	unzFile zipFile = unzOpen(pFilename);

	// iterate files in zip
	int zipFileIndex = unzGoToFirstFile(zipFile);

	while(zipFileIndex != UNZ_END_OF_LIST_OF_FILE)
	{
		MFDebug_Assert(zipFileIndex == UNZ_OK, "Error in .zip file.");

		char fileNameBuf[256];
		unz_file_info fileInfo;
		unzGetCurrentFileInfo(zipFile, &fileInfo, fileNameBuf, sizeof(fileNameBuf), NULL, 0, NULL, 0);
		MFString fileName = fileNameBuf;

		if(fileName.EndsWith(".md3"))
		{
			// read fle from zip
			pBuffer = (char*)malloc(fileInfo.uncompressed_size);

			unzOpenCurrentFile(zipFile);
			uint32 bytesRead = unzReadCurrentFile(zipFile, pBuffer, fileInfo.uncompressed_size);
			unzCloseCurrentFile(zipFile);

			MFDebug_Assert(bytesRead == fileInfo.uncompressed_size, "Incorrect number of bytes read..");

			// get subobject and model name..
			int slash = MFMax(fileName.FindCharReverse('/'), fileName.FindCharReverse('\\'));
			MFString subobjectName = fileName.SubStr(slash + 1);

			MFString modelName = fileName.SubStr(0, slash);
			slash = MFMax(modelName.FindCharReverse('/'), modelName.FindCharReverse('\\'));
			pModel->name = modelName.SubStr(slash + 1);

			// search for skin file
			MFString skinFilename = fileName;
			skinFilename.TruncateExtension();
			skinFilename += "_";
			skinFilename += pModel->name;
			skinFilename += ".skin";

			// attempt to read skin..
			char *pSkinFile = NULL;

			zipFileIndex = unzLocateFile(zipFile, skinFilename.CStr(), 0);

			if(zipFileIndex != UNZ_END_OF_LIST_OF_FILE)
			{
				// read skin file from zip
				unz_file_info skinInfo;
				char skinName[256];

				unzGetCurrentFileInfo(zipFile, &skinInfo, skinName, 256, NULL, 0, NULL, 0);

				pSkinFile = (char*)MFHeap_TAlloc(skinInfo.uncompressed_size + 1);
				pSkinFile[skinInfo.uncompressed_size] = 0;

				unzOpenCurrentFile(zipFile);
				uint32 skinBytesRead = unzReadCurrentFile(zipFile, pSkinFile, skinInfo.uncompressed_size);
				unzCloseCurrentFile(zipFile);

				MFDebug_Assert(skinBytesRead == skinInfo.uncompressed_size, "Incorrect number of bytes read..");
			}

			zipFileIndex = unzLocateFile(zipFile, fileName.CStr(), 0);

			// parse MD3
			ParseMD3File(pBuffer, fileInfo.uncompressed_size, subobjectName.CStr(), pSkinFile);

			// free file
			MFHeap_Free(pBuffer);
			pBuffer = NULL;
		}
/*
		else if(!MFString_CaseCmp(".skin", &fileName[Max(filenameLen - 5, 0)]))
		{
			int a, b;
			char skinName[256];

			// get subobject and model name
			for(a = filenameLen - 5; a >= 0; a--)
			{
				if(fileName[a] == '/' || fileName[a] == '\\')
					break;
			}

			char *pSkinName = &fileName[a+1];

			for(b = a-1; b >= 0; b--)
			{
				if(fileName[b] == '/' || fileName[b] == '\\')
					break;
			}

			MFString_Copy(skinName, &fileName[b+1]);
			skinName[a-b-1] = 0;

			pSkinName = strchr(pSkinName, '_');
			DBGASSERT(pSkinName, "Incorrectly named .skin file in .pk3");
			++pSkinName;

			// check that this is the default skin for this model
			if(!MFString_CaseCmpN(pSkinName, skinName, MFString_Length(skinName)))
			{
				// read material file from zip
				pBuffer = (char*)malloc(fileInfo.uncompressed_size);

				unzOpenCurrentFile(zipFile);
				uint32 bytesRead = unzReadCurrentFile(zipFile, pBuffer, fileInfo.uncompressed_size);
				unzCloseCurrentFile(zipFile);

				// parse .skin file

				free(pBuffer);
				pBuffer = NULL;
			}
			else
			{
				// we have an alternate skin.. do nothing..
			}
		}
*/

		zipFileIndex = unzGoToNextFile(zipFile);
	}

	// close .pk3 file
	unzClose(zipFile);

	return 0;
}
Ejemplo n.º 29
0
bool UpdateManager::uncompressFile(int index)
{
	VersionInfo vi=downloadInfo[index];
	CCLog("start to uncompressed name %s",vi.getName());
	string outFileName=getFileFullName(vi.getPath());
	if(getFileExtention(vi.getPath())==string("apk"))
	{
		haveApk=true;
		return true;
	}

	// Open the zip file
	unzFile zipfile = unzOpen(outFileName.c_str());
	if (! zipfile)
	{
		CCLog("can not open downloaded zip file %s", outFileName.c_str());
		return false;
	}

	// Get info about the zip file
	unz_global_info global_info;
	if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK)
	{
		CCLog("can not read file global info of %s", outFileName.c_str());
		unzClose(zipfile);
		return false;
	}

	// Buffer to hold data read from the zip file
	char readBuffer[BUFFER_SIZE];

	CCLog("start uncompressing");

	// Loop to extract all files.
	uLong i;
	for (i = 0; i < global_info.number_entry; ++i)
	{
		// Get info about current file.
		unz_file_info fileInfo;
		char fileName[MAX_FILENAME];
		if (unzGetCurrentFileInfo(zipfile,
			&fileInfo,
			fileName,
			MAX_FILENAME,
			NULL,
			0,
			NULL,
			0) != UNZ_OK)
		{
			CCLog("can not read file info");
			unzClose(zipfile);
			return false;
		}

		string fullPath = resourcesPath +"/"+ fileName;
		CCLog("uncompressed dir is %s",fullPath.c_str());

		// Check if this entry is a directory or a file.
		const size_t filenameLength = strlen(fileName);
		if (fileName[filenameLength-1] == '/')
		{
			// Entry is a direcotry, so create it.
			// If the directory exists, it will failed scilently.
			if (!createDirectory(fullPath.c_str()))
			{
				CCLog("can not create directory %s", fullPath.c_str());
				unzClose(zipfile);
				return false;
			}
		}
		else
		{
			// Entry is a file, so extract it.

			// Open current file.
			if (unzOpenCurrentFile(zipfile) != UNZ_OK)
			{
				CCLog("can not open file %s", fileName);
				unzClose(zipfile);
				return false;
			}

			// Create a file to store current file.
			FILE *out = fopen(fullPath.c_str(), "wb");
			if (! out)
			{
				CCLog("can not open destination file %s", fullPath.c_str());
				unzCloseCurrentFile(zipfile);
				unzClose(zipfile);
				return false;
			}

			// Write current file content to destinate file.
			int error = UNZ_OK;
			do
			{
				error = unzReadCurrentFile(zipfile, readBuffer, BUFFER_SIZE);
				if (error < 0)
				{
					CCLog("can not read zip file %s, error code is %d", fileName, error);
					unzCloseCurrentFile(zipfile);
					unzClose(zipfile);
					return false;
				}

				if (error > 0)
				{
					fwrite(readBuffer, error, 1, out);
				}
			} while(error > 0);

			fclose(out);
		}

		unzCloseCurrentFile(zipfile);

		// Goto next entry listed in the zip file.
		if ((i+1) < global_info.number_entry)
		{
			if (unzGoToNextFile(zipfile) != UNZ_OK)
			{
				CCLog("can not read next file");
				unzClose(zipfile);
				return false;
			}
		}
	}

	CCLog("end uncompressing");

	return true;
}
Ejemplo n.º 30
0
/*
    Load a normal file, or ZIP/GZ archive.
    Returns NULL if an error occured.
*/
uint8 *load_archive(char *filename, int *file_size)
{
    int size = 0;
    uint8 *buf = NULL;

    if(check_zip(filename))
    {
        unzFile *fd = NULL;
        unz_file_info info;
        int ret = 0;

        /* Attempt to open the archive */
        fd = unzOpen(filename);
        if(!fd) return (NULL);

        /* Go to first file in archive */
        ret = unzGoToFirstFile(fd);
        if(ret != UNZ_OK)
        {
            unzClose(fd);
            return (NULL);
        }

        ret = unzGetCurrentFileInfo(fd, &info, NULL, 0, NULL, 0, NULL, 0);
        if(ret != UNZ_OK)
        {
            unzClose(fd);
            return (NULL);
        }

        /* Open the file for reading */
        ret = unzOpenCurrentFile(fd);
        if(ret != UNZ_OK)
        {
            unzClose(fd);
            return (NULL);
        }

        /* Allocate file data buffer */
        size = info.uncompressed_size;
        buf = malloc(size);
        if(!buf)
        {
            unzClose(fd);
            return (NULL);
        }

        /* Read (decompress) the file */
        ret = unzReadCurrentFile(fd, buf, info.uncompressed_size);
        if(ret != info.uncompressed_size)
        {
            free(buf);
            unzCloseCurrentFile(fd);
            unzClose(fd);
            return (NULL);
        }

        /* Close the current file */
        ret = unzCloseCurrentFile(fd);
        if(ret != UNZ_OK)
        {
            free(buf);
            unzClose(fd);
            return (NULL);
        }

        /* Close the archive */
        ret = unzClose(fd);
        if(ret != UNZ_OK)
        {
            free(buf);
            return (NULL);
        }

        /* Update file size and return pointer to file data */
        *file_size = size;
        return (buf);
    }
    else
    {
        gzFile *gd = NULL;

        /* Open file */
        gd = gzopen(filename, "rb");
        if(!gd) return (0);

        /* Get file size */
        size = gzsize(gd);

        /* Allocate file data buffer */
        buf = malloc(size);
        if(!buf)
        {
            gzclose(gd);
            return (0);
        }

        /* Read file data */
        gzread(gd, buf, size);

        /* Close file */
        gzclose(gd);

        /* Update file size and return pointer to file data */
        *file_size = size;
        return (buf);
    }
}