Пример #1
0
  void ZipWriter::Open()
  {
    if (IsOpen())
    {
      return;
    }

    if (path_.size() == 0)
    {
      throw OrthancException("Please call SetOutputPath() before creating the file");
    }

    hasFileInZip_ = false;

    if (isZip64_)
    {
      pimpl_->file_ = zipOpen64(path_.c_str(), APPEND_STATUS_CREATE);
    }
    else
    {
      pimpl_->file_ = zipOpen(path_.c_str(), APPEND_STATUS_CREATE);
    }

    if (!pimpl_->file_)
    {
      throw OrthancException(ErrorCode_CannotWriteFile);
    }
  }
/*
Trying to write offset and vertices data to file.
*/
void CPathEstimator::WriteFile(string name) {
	// We need this directory to exist
	boost::filesystem::path f("./maps/paths");
	if (!boost::filesystem::exists(f))
		boost::filesystem::create_directories(f);

	unsigned int hash = Hash();
	char hashString[50];
	sprintf(hashString,"%u",hash);

	string filename = string("maps/paths/") + stupidGlobalMapname.substr(0, stupidGlobalMapname.find('.') + 1) + hashString + "." + name + ".zip";
	zipFile file = zipOpen(filename.c_str(), APPEND_STATUS_CREATE);

	if (file) {
		zipOpenNewFileInZip(file, "pathinfo", NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_BEST_COMPRESSION);
		
		//Write hash.
		unsigned int hash = Hash();
		zipWriteInFileInZip(file, (void*)&hash, 4);

		//Write block-center-offsets.
		int blocknr;
		for(blocknr = 0; blocknr < nbrOfBlocks; blocknr++) {
			zipWriteInFileInZip(file, (void*)blockState[blocknr].sqrCenter, moveinfo->moveData.size() * sizeof(int2));
			//file.write((char*)blockState[blocknr].sqrCenter, moveinfo->moveData.size() * sizeof(int2));
		}

		//Write vertices.
		zipWriteInFileInZip(file, (void*)vertex, nbrOfVertices * sizeof(float));
		//file.write((char*)vertex, nbrOfVertices * sizeof(float));

		zipCloseFileInZip(file);
		zipClose(file, NULL);
	}
}
Пример #3
0
 ZipFile::ZipFile(const openstudio::path &t_filename, bool t_add)
   : m_zipFile(zipOpen(openstudio::toString(t_filename).c_str(), t_add?APPEND_STATUS_ADDINZIP:APPEND_STATUS_CREATE))
 {
   if (!m_zipFile) {
     throw std::runtime_error("ZipFile " + openstudio::toString(t_filename) + " could not be opened");
   }
 }
Пример #4
0
void FileUtils::addToZip(const char* archivePath, const char* path, const char* content, int length) throw (IOException)
{
	int result = ZIP_OK;

	int appendMode = fileExists(archivePath) ? APPEND_STATUS_ADDINZIP : APPEND_STATUS_CREATE;

	zipFile archive = zipOpen(archivePath, appendMode);
	result = zipOpenNewFileInZip(archive, path, 0 /* file attributes */, 0 /* extra field */, 0 /* extra field size */,
						0/* global extra field */, 0 /* global extra field size */, 0 /* comment */, Z_DEFLATED /* method */,
						Z_DEFAULT_COMPRESSION /* level */);
	if (result != ZIP_OK)
	{
		throw IOException("Unable to add new file to zip archive");
	}
	result = zipWriteInFileInZip(archive, content, static_cast<unsigned int>(length));
	if (result != ZIP_OK)
	{
		throw IOException("Unable to write file data to zip archive");
	}
	result = zipCloseFileInZip(archive);
	if (result != ZIP_OK)
	{
		throw IOException("Unable to close file in zip archive");
	}
	result = zipClose(archive, 0 /* global comment */);
	if (result != ZIP_OK)
	{
		throw IOException("Unable to close zip archive");
	}
}
Пример #5
0
int zip_open(const char *path, const char *mode)
{
	if (zipfile) zip_close();

	if (!strcmp(mode, "rb"))
	{
		zip_mode = ZIP_READOPEN;

		if ((zipfile = unzOpen(path)) != NULL)
			return (int)zipfile;

		strcpy(basedir, path);

		basedirend = basedir + strlen(basedir);
		*basedirend++ = '/';
	}
	else if (!strcmp(mode, "wb"))
	{
		if ((zipfile = zipOpen(path, 0)) != NULL)
		{
			zip_mode = ZIP_WRITEOPEN;
			return (int)zipfile;
		}
	}

	return -1;
}
Пример #6
0
bool ZipFile::SwitchMode(short mode)
{
    if(mode == ZipFile::OPEN)
    {
        if(zFile)
        {
            zipClose(zFile, NULL);
            zFile = 0;
        }

        if(!uzFile)
            uzFile = unzOpen(ZipFilePath.c_str());

        return (uzFile != 0);
    }
    else if(mode == ZipFile::CREATE || mode == ZipFile::APPEND)
    {
        if(uzFile)
        {
            unzClose(uzFile);
            uzFile = 0;
        }

        if(!zFile)
            zFile = zipOpen(ZipFilePath.c_str(), mode);

        return (zFile != 0);
    }

    return false;
}
bool MkInterfaceForZipFileWriting::SetUp(const MkPathName& filePath, bool overwrite, bool makeDirectoryPath)
{
	Clear();

	m_CurrentFilePath.ConvertToRootBasisAbsolutePath(filePath);

	if (makeDirectoryPath)
	{
		MkPathName dirPath = m_CurrentFilePath.GetPath();
		bool ok = dirPath.MakeDirectoryPath();
		MK_CHECK(ok, m_CurrentFilePath.GetFileName() + L" 파일을 위한 " + dirPath + L" 경로 생성 실패")
			return false;
	}

	int append = APPEND_STATUS_CREATE;
	if (m_CurrentFilePath.CheckAvailable())
	{
		if (overwrite)
		{
			append = APPEND_STATUS_ADDINZIP;
		}
		else
		{
			m_CurrentFilePath.DeleteCurrentFile();
		}
	}

	std::string charPath;
	m_CurrentFilePath.ExportMultiByteString(charPath);
	m_ZipFile = zipOpen(charPath.c_str(), append);
	return (m_ZipFile != NULL);
}
Пример #8
0
bool
create_ZIP_archive(char *file_path)
{
	if ((zip_handle = zipOpen(file_path, 0)) == NULL)
		return(false);
	unzipping = false;
	return(true);
}
Пример #9
0
BOOL fsUploadMgr::ZipFiles ()
{
	if (m_bZipFileCreated)
		return TRUE;

	Event (UMGRE_ZIP_FILES_START);

	char szTmpFile [MAX_PATH];
	char szTmpPath [MAX_PATH];
	GetTempPath (MAX_PATH, szTmpPath);
	GetTempFileName (szTmpPath, "tmp", 0, szTmpFile);
	m_strUploadFile = szTmpFile;
	
	zipFile zip = zipOpen (m_strUploadFile, 0);
	BOOL bOk = TRUE;

	m_strZipContentsDescHtml = "<ul>";

	for (size_t i = 0; i < m_pkg.m_vPathes.size () && bOk && m_bNeedStop == false; i++)
	{
		LPCSTR psz = m_pkg.m_vPathes [i];

		char szName [1000] = "";
		fsGetFileName (psz, szName);

		if (GetFileAttributes (psz) & FILE_ATTRIBUTE_DIRECTORY)
		{
			AddItemToZipContentsDescHtml (szName, _UI64_MAX);
			m_strZipContentsDescHtml += "<ul>";
			bOk = bOk && Zip_AddFolder (zip, psz, NULL, 1);
			m_strZipContentsDescHtml += "</ul>";
		}
		else
		{
			bOk = bOk && Zip_AddFile (zip, psz, NULL);
			if (bOk)
			{
				WIN32_FILE_ATTRIBUTE_DATA wfad;
				GetFileAttributesEx (psz, GetFileExInfoStandard, &wfad);
				AddItemToZipContentsDescHtml (szName, ((UINT64)wfad.nFileSizeHigh << 32) + wfad.nFileSizeLow);
			}
		}
	}

	m_strZipContentsDescHtml += "</ul>";

	zipClose (zip, NULL);

	if (m_bNeedStop || bOk == FALSE)
		DeleteFile (m_strUploadFile);
	else
		m_bZipFileCreated = TRUE;

	if (m_bNeedStop == false)
		Event (bOk ? UMGRE_ZIP_FILES_DONE : UMGRE_ZIP_FILES_FAILED);

	return m_bZipFileCreated;
}
Пример #10
0
int hts_extract_meta(const char* path) {
    char catbuff[CATBUFF_SIZE];
    unzFile zFile = unzOpen(fconcat(catbuff,path,"hts-cache/new.zip"));
    zipFile zFileOut = zipOpen(fconcat(catbuff,path,"hts-cache/meta.zip"), 0);
    if (zFile != NULL && zFileOut != NULL) {
        if (unzGoToFirstFile(zFile) == Z_OK) {
            zip_fileinfo fi;
            unz_file_info ufi;
            char BIGSTK filename[HTS_URLMAXSIZE * 4];
            char BIGSTK comment[8192];
            memset(comment, 0, sizeof(comment));       // for truncated reads
            memset(&fi, 0, sizeof(fi));
            memset(&ufi, 0, sizeof(ufi));
            do  {
                int readSizeHeader;
                filename[0] = '\0';
                comment[0] = '\0';

                if (unzOpenCurrentFile(zFile) == Z_OK) {
                    if (
                        (readSizeHeader = unzGetLocalExtrafield(zFile, comment, sizeof(comment) - 2)) > 0
                        &&
                        unzGetCurrentFileInfo(zFile, &ufi, filename, sizeof(filename) - 2, NULL, 0, NULL, 0) == Z_OK
                    )
                    {
                        comment[readSizeHeader] = '\0';
                        fi.dosDate = ufi.dosDate;
                        fi.internal_fa = ufi.internal_fa;
                        fi.external_fa = ufi.external_fa;
                        if (zipOpenNewFileInZip(zFileOut,
                                                filename,
                                                &fi,
                                                NULL,
                                                0,
                                                NULL,
                                                0,
                                                NULL, /* comment */
                                                Z_DEFLATED,
                                                Z_DEFAULT_COMPRESSION) == Z_OK)
                        {
                            if (zipWriteInFileInZip(zFileOut, comment, (int) strlen(comment)) != Z_OK) {
                            }
                            if (zipCloseFileInZip(zFileOut) != Z_OK) {
                            }
                        }
                    }
                    unzCloseCurrentFile(zFile);
                }
            } while( unzGoToNextFile(zFile) == Z_OK );
        }
        zipClose(zFileOut, "Meta-data extracted by HTTrack/"HTTRACK_VERSION);
        unzClose(zFile);
        return 1;
    }
    return 0;
}
Пример #11
0
static int writezip_cb(lua_State* L)
{
	const char* zipname = luaL_checkstring(L, 1);
	luaL_checktype(L, 2, LUA_TTABLE);
	int result = 0;

	zipFile zf = zipOpen(zipname, APPEND_STATUS_CREATE);
	if (zf)
	{
		result = 1;

		lua_pushnil(L);
		while (lua_next(L, 2) != 0)
		{
			const char* key = lua_tostring(L, -2);
			size_t valuelen;
			const char* value = lua_tolstring(L, -1, &valuelen);

			int i = zipOpenNewFileInZip(zf, key, NULL,
					NULL, 0,
					NULL, 0,
					NULL,
					Z_DEFLATED,
					Z_DEFAULT_COMPRESSION);
			if (i != ZIP_OK)
			{
				result = 0;
				break;
			}

			i = zipWriteInFileInZip(zf, value, valuelen);
			if (i != ZIP_OK)
			{
				result = 0;
				break;
			}

			i = zipCloseFileInZip(zf);
			if (i != ZIP_OK)
			{
				result = 0;
				break;
			}

			lua_pop(L, 1); /* leave key on stack */
		}

		zipClose(zf, NULL);
	}

	if (!result)
		return 0;
	lua_pushboolean(L, true);
	return 1;
}
Пример #12
0
bool ZipFile::Open(QString fileName) // TODO: Change this to a class.
{
	Close();

	// Open the jar (it's really a zip) file:
	zf = zipOpen(fileName.toAscii().constData(), APPEND_STATUS_ADDINZIP);
	if (!zf)
		return false;

	return true;
}
Пример #13
0
static int save_archive(char *filename, char *buffer, int size)
{	
    zipFile fd = NULL;
    int ret = 0;
    fd=zipOpen(filename,0);
    if(!fd)
    {
       printf("Failed to create zip\r\n");
       return (0);
    }

    ret=zipOpenNewFileInZip(fd,"SNAPSHOT",
			    NULL,
				NULL,0,
			    NULL,0,
			    NULL,
			    Z_DEFLATED,
			    Z_BEST_COMPRESSION);
			    
    if(ret != ZIP_OK)
    {
       zipClose(fd,NULL);
       printf("Failed to create file in zip\r\n");
       return (0);    
    }

    ret=zipWriteInFileInZip(fd,buffer,size);
    if(ret != ZIP_OK)
    {
      zipCloseFileInZip(fd);
      zipClose(fd,NULL);
      printf("Failed to write file in zip\r\n");
      return (0);
    }

    ret=zipCloseFileInZip(fd);
    if(ret != ZIP_OK)
    {
      zipClose(fd,NULL);
      printf("Failed to close file in zip\r\n");
      return (0);
    }

    ret=zipClose(fd,NULL);
    if(ret != ZIP_OK)
    {
      printf("Failed to close zip\r\n");
      return (0);
    }
	
    return(1);
}
Пример #14
0
int FILE_compress_dir(const string& src_path, const string& dst_path, const string& prefix)
{
	zipFile archive = zipOpen(dst_path.c_str(), 0);
	if(archive == NULL)
		return -1;

	int r = compress_recursive(archive, src_path,prefix);
	
	zipClose(archive, NULL);
	
	return r;
	
}
Пример #15
0
/**
 * Try to write offset and vertex data to file.
 */
void CPathEstimator::WriteFile(const std::string& cacheFileName, const std::string& map)
{
	// We need this directory to exist
	if (!filesystem.CreateDirectory(pathDir))
		return;

	const unsigned int hash = Hash();
	char hashString[64] = {0};

	sprintf(hashString, "%u", hash);

	const std::string filename = std::string(pathDir) + map + hashString + "." + cacheFileName + ".zip";
	zipFile file;

	// open file for writing in a suitable location
	file = zipOpen(filesystem.LocateFile(filename, FileSystem::WRITE).c_str(), APPEND_STATUS_CREATE);

	if (file) {
		zipOpenNewFileInZip(file, "pathinfo", NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_BEST_COMPRESSION);

		// Write hash.
		zipWriteInFileInZip(file, (void*) &hash, 4);

		// Write block-center-offsets.
		for (int blocknr = 0; blocknr < blockStates.GetSize(); blocknr++)
			zipWriteInFileInZip(file, (void*) &blockStates[blocknr].nodeOffsets[0], moveinfo->moveData.size() * sizeof(int2));

		// Write vertices.
		zipWriteInFileInZip(file, &vertices[0], vertices.size() * sizeof(float));

		zipCloseFileInZip(file);
		zipClose(file, NULL);


		// get the CRC over the written path data
		CArchiveZip* pfile = new CArchiveZip(filesystem.LocateFile(filename));

		if (!pfile || !pfile->IsOpen()) {
			delete pfile;
			return;
		}

		std::auto_ptr<CArchiveZip> auto_pfile(pfile);
		CArchiveZip& file(*pfile);
		
		const unsigned fid = file.FindFile("pathinfo");
		assert(fid < file.NumFiles());
		pathChecksum = file.GetCrc32(fid);
	}
}
Пример #16
0
static bool CreateZip(const std::string &path, const std::vector<std::string> &files, const std::string &pb2BasePath)
{
	std::ifstream input;
	std::vector<char> buffer;
	bool ok = true;

	zipFile zf = zipOpen(path.c_str(), APPEND_STATUS_CREATE);

	if (zf == NULL)
        return false;

	for (size_t i = 0; i < files.size(); i++)
	{
		input.open(pb2BasePath + files[i], std::ios::binary | std::ios::ate);
		if (!input.is_open())
		{
			ok = false;
			input.close();
			break;
		}
		std::streamoff size = input.tellg();
		buffer.resize(static_cast<unsigned int>(size));
		input.seekg(0, std::ios::beg);
		input.read((char*)&buffer[0], size);
		input.close();

		zip_fileinfo zfi = { 0 };
		if (S_OK == zipOpenNewFileInZip(zf, files[i].c_str(), &zfi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION))
		{
			if (0 != zipWriteInFileInZip(zf, &buffer[0], buffer.size()))
				ok = false;

            if (0 != zipCloseFileInZip(zf))
                ok = false;
		}
		else
		{
			ok = false;
		}
	}

	if (0 != zipClose(zf, NULL))
	{
		return false;
	}
	else
	{
		return ok;
	}
}
Пример #17
0
/*
 * try to write offset and vertex data to file
 */
void CPathEstimator::WriteFile(std::string name) {
	// We need this directory to exist
	if (!filesystem.CreateDirectory("maps/paths"))
		return;

	unsigned int hash = Hash();
	char hashString[50];
	sprintf(hashString,"%u",hash);

	std::string filename = std::string("maps/paths/") + stupidGlobalMapname.substr(0, stupidGlobalMapname.find_last_of('.') + 1) + hashString + "." + name + ".zip";
	zipFile file;

	// open file for writing in a suitable location
	file = zipOpen(filesystem.LocateFile(filename, FileSystem::WRITE).c_str(), APPEND_STATUS_CREATE);

	if (file) {
		zipOpenNewFileInZip(file, "pathinfo", NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_BEST_COMPRESSION);

		// Write hash.
		unsigned int hash = Hash();
		zipWriteInFileInZip(file, (void*) &hash, 4);

		// Write block-center-offsets.
		for (int blocknr = 0; blocknr < nbrOfBlocks; blocknr++) {
			zipWriteInFileInZip(file, (void*) blockState[blocknr].sqrCenter, moveinfo->moveData.size() * sizeof(int2));
		}

		// Write vertices.
		zipWriteInFileInZip(file, (void*) vertex, nbrOfVertices * sizeof(float));

		zipCloseFileInZip(file);
		zipClose(file, NULL);


		// get the CRC over the written path data
		CArchiveZip* pfile = SAFE_NEW CArchiveZip(filesystem.LocateFile(filename));

		if (!pfile || !pfile->IsOpen()) {
			delete pfile;
			return;
		}

		std::auto_ptr<CArchiveZip> auto_pfile(pfile);
		CArchiveZip& file(*pfile);
		pathChecksum = file.GetCrc32("pathinfo");
	}
}
/*!

\brief Creates zip archive for writing.
\details Will close any open zip archive before opening a new archive. If a zip archive
already exists with the same name, it will be overwritten.
\param[in] FileName String containing the name of the new zip archive.
\param[in] Mode Parameter for future functionality.
\return Returns dmz::True if the archive was successfully created.

*/
dmz::Boolean
dmz::WriterZip::open_zip_file (const String &FileName, const UInt32 Mode) {

   Boolean result (False);

   close_zip_file ();

   _state.zf = zipOpen (FileName.get_buffer (), APPEND_STATUS_CREATE);

   if (_state.zf) {

      _state.zipFileName = FileName;
      result = True;
   }

   return result;
}
Пример #19
0
// ----------------------------------------------------------------------------
// Compress
// ----------------------------------------------------------------------------
bool archive_Compress(std::string zipFilename, std::string filename, const byte* data, uint size) {
  if(zipFilename.empty( ) || zipFilename.size( ) == 0) {
    logger_LogError("Zip filename is invalid.", ARCHIVE_SOURCE);
    return false;
  }  
  if(filename.empty( ) || filename.size( ) == 0) {
    logger_LogError("Filename is invalid.", ARCHIVE_SOURCE);
    return false;
  }
  if(data == NULL) {
    logger_LogError("Data parameter is invalid.", ARCHIVE_SOURCE);
    return false;  
  }
  
  zipFile file = zipOpen(zipFilename.c_str( ), APPEND_STATUS_CREATE);
  if(file == NULL) {
    logger_LogInfo("Failed to create the zip file " + zipFilename + ".", ARCHIVE_SOURCE);
    return false;
  }
  
  zip_fileinfo fileInfo = {0};
  fileInfo.dosDate = 1;
  
  int result = zipOpenNewFileInZip(file, filename.c_str( ), &fileInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_BEST_COMPRESSION);
  if(result != ZIP_OK) {
    logger_LogInfo("Failed to open a new file within the zip file " + filename + ".", ARCHIVE_SOURCE);
    logger_LogInfo("Result: " + result, ARCHIVE_SOURCE);
    zipClose(file, "Failed to compress.");
    return false;  
  }
  
  result = zipWriteInFileInZip(file, data, size);
  if(result != ZIP_OK) {
    logger_LogInfo("Failed to write data to the zip file " + filename + ".", ARCHIVE_SOURCE);
    zipCloseFileInZip(file);
    zipClose(file, "Failed to compress.");
    return false;
  }
 
  zipCloseFileInZip(file);
  zipClose(file, "Comment");
  return true;
}
Пример #20
0
/*
========================
idZipBuilder::CleanSourceFolder

this folder is assumed to be a path under FSPATH_BASE
========================
*/
zipFile idZipBuilder::CreateZipFile( const char* name )
{
	idLib::Printf( "Creating zip file: '%s'\n", name );
	
	// do not allow overwrite as this should be a tempfile attempt to check the file out
	if( !Sys_IsFileWritable( name ) )
	{
		idLib::PrintfIf( zip_verbosity.GetBool(), "File %s not writable, cannot proceed.\n", name );
		return NULL;
	}
	
	// open the zip file
	zipFile zf = zipOpen( name, 0 );
	if( zf == NULL )
	{
		idLib::Warning( "[%s] - error opening file '%s'!", __FUNCTION__, name );
	}
	return zf;
}
Пример #21
0
/********************************************************************
 ** Main thread
 * Takes a table, serialiaze it to memory and register it in the save thread
 ********************************************************************/
static int serial_new(lua_State *L)
{
	const char *zfname = lua_tostring(L, 1);
	luaL_checktype(L, 2, LUA_TFUNCTION);
	luaL_checktype(L, 3, LUA_TFUNCTION);
	if (!lua_isnil(L, 4) && !lua_istable(L, 4)) { lua_pushstring(L, "argument 4 is not nil or table"); lua_error(L); }
	if (!lua_isnil(L, 5) && !lua_istable(L, 5)) { lua_pushstring(L, "argument 5 is not nil or table"); lua_error(L); }
	if (!lua_isnil(L, 6) && !lua_istable(L, 6)) { lua_pushstring(L, "argument 6 is not nil or table"); lua_error(L); }

	int d2_ref = luaL_ref(L, LUA_REGISTRYINDEX);
	int d_ref = luaL_ref(L, LUA_REGISTRYINDEX);
	int a_ref = luaL_ref(L, LUA_REGISTRYINDEX);
	int fadd_ref = luaL_ref(L, LUA_REGISTRYINDEX);
	int fname_ref = luaL_ref(L, LUA_REGISTRYINDEX);

	serial_type *s = (serial_type*)lua_newuserdata(L, sizeof(serial_type));
	auxiliar_setclass(L, "core{serial}", -1);

	zipFile *zf = NULL;
	if (!last_zipname || strcmp(last_zipname, zfname)) {
		zf = zipOpen(zfname, APPEND_STATUS_CREATE);
		last_zf = zf;
		if (last_zipname) free(last_zipname);
		last_zipname = strdup(zfname);
	} else {
		zf = last_zf;
	}

	s->zf = zf;
	s->zfname = zfname;
	s->fname = fname_ref;
	s->fadd = fadd_ref;
	s->allow = a_ref;
	s->disallow = d_ref;
	s->disallow2 = d2_ref;

	return 1;
}
Пример #22
0
zipFile zipopen (const char* path, const char* filenameinzip, int append)
{
  zipFile zf = NULL;
  int err=ZIP_OK;

#ifdef USEWIN32IOAPI
    zlib_filefunc_def ffunc;
    fill_win32_filefunc(&ffunc);
    zf = zipOpen2(path,append,NULL,&ffunc);
#else
    zf = zipOpen(path, append);
#endif

    if (zf == NULL) return NULL;

    zip_fileinfo zi;

    zi.tmz_date.tm_sec  = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
    zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
    zi.dosDate     = 0;
    zi.internal_fa = 0;
    zi.external_fa = 0;
    filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);

    err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
                     NULL,0,NULL,0,NULL,
                     Z_DEFLATED,
                     Z_DEFAULT_COMPRESSION);
  
    if (err != ZIP_OK)
    {
       zipClose(zf, NULL);
       return NULL;
    }

    return zf;
}
Пример #23
0
// extended interface
bool CZipper::OpenZip(LPCTSTR szFilePath, LPCTSTR szRootFolder, bool bAppend)
{
	CloseZip();

	if (!szFilePath || !lstrlen(szFilePath))
		return false;

	// convert szFilePath to fully qualified path 
	char szFullPath[MAX_PATH];

	if (!GetFullPathName(szFilePath, MAX_PATH, szFullPath, NULL))
		return false;

	// zipOpen will fail if bAppend is TRUE and zip does not exist
	if (bAppend && ::GetFileAttributes(szFullPath) == 0xffffffff)
		bAppend = false;

	m_uzFile = zipOpen(szFullPath, bAppend ? 1 : 0);

	if (m_uzFile)
	{
		if (!szRootFolder)
		{
			char szDrive[_MAX_DRIVE], szFolder[MAX_PATH];
			_splitpath(szFullPath, szDrive, szFolder, NULL, NULL);

			_makepath(m_szRootFolder, szDrive, szFolder, NULL, NULL);
		}
		else if (lstrlen(szRootFolder))
		{
			_makepath(m_szRootFolder, NULL, szRootFolder, "", NULL);
		}
	}

	return (m_uzFile != NULL);
}
Пример #24
0
		/* \brief
		* creates the on demand one-time crash dump of the process.
		*
		* creates the crash dump and tries to start an crash handler
		* external process for further processing and user information.
		*
		* \author
		* Florian Schaper <*****@*****.**>
		*/
		void wait_for_crash() {
			// wait for the method generate_crash_dump to be called.
			boost::unique_lock<boost::mutex> lock( m_mutex_creating_mutex );
			while (! m_generate_crash_dump) {
				m_create_crash_dump_condition.wait(lock);
			}

			if (m_is_armed && m_writedump_callback) {
				// create file at the path dictated
				HANDLE file_handle = CreateFileA((m_crash_dump_file + ".dmp").c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

				// if we could not open the file there is nothing we can do
				if ((file_handle != NULL) && (file_handle != INVALID_HANDLE_VALUE)) {

					// create the minidump by calling the DbgHelp library
					MINIDUMP_EXCEPTION_INFORMATION minidump_information;
					minidump_information.ThreadId = m_thread_id;
					minidump_information.ExceptionPointers = m_exception_pointers;
					minidump_information.ClientPointers = FALSE;

					MINIDUMP_TYPE minidump_type = MiniDumpWithProcessThreadData;

					int successful = (*m_writedump_callback)(GetCurrentProcess(), GetCurrentProcessId(), file_handle, minidump_type, (m_exception_pointers != 0) ? &minidump_information : 0, 0, 0);

					// close the minidump file
					CloseHandle(file_handle);

					try {
						PaloSession::requestRecord(m_crash_dump_file, "txt");
					} catch (...) {
						Logger::error << "Can't create crashed requests file." << endl;
					}

					zipFile z = zipOpen((m_crash_dump_file + ".zip").c_str(), APPEND_STATUS_CREATE);
					if (z) {
						ZipUtils::addToZip(z, m_crash_dump_file + ".dmp");
						ZipUtils::addToZip(z, m_crash_dump_file + ".txt");
						ZipUtils::addToZip(z, m_palo_ini);

						int errclose = zipClose(z, NULL);
						if (errclose == ZIP_OK) {
							FileName fnDMP("", m_crash_dump_file, "dmp");
							FileUtils::remove(fnDMP);
							FileName fnTXT("", m_crash_dump_file, "txt");
							FileUtils::remove(fnTXT);
						} else {
							Logger::error << "Can't close ZIP file." << endl;
						}

					} else {
						Logger::error << "Can't open ZIP file." << endl;
					}

					Logger::error << "Server has encountered a problem and needs to close. Crash dump with detailed information saved to Data directory: " << m_crash_dump_file << endl;
				}

				// try to call the user defined crash report handler
				if (m_execute_crash_reporting && !m_crash_report_call_format.empty() && !m_paloBinaryFolder.empty()) {
					// commented, crash_report.exe not used (no sense to start it from win service)
					//chdir(m_paloBinaryFolder.c_str());
					//std::system((boost::format(m_crash_report_call_format) % m_crash_dump_file).str().c_str());
				}

				// signal the end of minidump creation
				{
					boost::lock_guard<boost::mutex> lock(m_mutex_finished_creating);
					m_finished_crash_dump = true;
				}
			}
			m_finish_crash_dump_condition.notify_all();
		}
Пример #25
0
int RSAZCryptor::zipToFile(unsigned contentLength, void const *content, const char* fileToBeZipped, const char* fileOut)
{
    unsigned len=(int)strlen(fileOut);
    char* filename_try = (char*)malloc(len+16);
   if (filename_try==NULL)
   {
        return ZIP_INTERNALERROR;
   }

    strcpy(filename_try, fileOut);

    bool dot_found = false;
    for (unsigned i=0; i<len; i++)
    {
        if (filename_try[i]=='.')
        {
             dot_found=true;
             break;
        }
    }

    if (!dot_found)
        strcat(filename_try,".zip");

    zipFile zf;
    int opt_overwrite=0; //?1

#ifdef USEWIN32IOAPI
    zlib_filefunc_def ffunc;
    fill_win32_filefunc(&ffunc);
    zf = zipOpen2(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
#else
    zf = zipOpen(filename_try,(opt_overwrite==2) ? 2 : 0);
#endif

    int err=0;
    if (zf == NULL)
    {
        printf("error opening %s\n",filename_try);
        err= ZIP_ERRNO;
    }

    zip_fileinfo zi;
    zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
    zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
    zi.dosDate = 0;
    zi.internal_fa = 0;
    zi.external_fa = 0;

    err = zipOpenNewFileInZip3(zf,fileToBeZipped,&zi,
                            NULL,0,NULL,0,NULL /* comment*/,
                            Z_DEFLATED,
                            Z_DEFAULT_COMPRESSION,0,
                            /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
                            -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                            NULL, 0);

    if (err != ZIP_OK)
        printf("error in opening %s in zipfile\n",fileToBeZipped);

    if (contentLength>0)
    {
        err = zipWriteInFileInZip (zf,content,contentLength);
        if (err<0)
        {
            printf("error in writing %s in the zipfile\n", fileToBeZipped);
        }
    }

    if (err<0)
        err=ZIP_ERRNO;
    else
    {
        err = zipCloseFileInZip(zf);
        if (err!=ZIP_OK)
            printf("error in closing %s in the zipfile\n", fileToBeZipped);
    }

    if (zipClose(zf,NULL) != ZIP_OK)
        printf("error in closing %s\n",filename_try);

    free(filename_try);
    return 0;
}
Пример #26
0
int RSAZCryptor::zipToFile(const char* zipFileName, bool cleanFileListAfterUsed)
{
    unsigned len=(int)strlen(zipFileName);
    char* filename_try = (char*)malloc(len+16);
   if (filename_try==NULL)
   {
        return ZIP_INTERNALERROR;
   }

    strcpy(filename_try, zipFileName);

    bool dot_found = false;
    for (unsigned i=0; i<len; i++)
    {
        if (filename_try[i]=='.')
        {
             dot_found=true;
             break;
        }
    }

    if (!dot_found)
        strcat(filename_try,".zip");

    zipFile zf;
    int opt_overwrite=0; //?1

#ifdef USEWIN32IOAPI
    zlib_filefunc_def ffunc;
    fill_win32_filefunc(&ffunc);
    zf = zipOpen2(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
#else
    zf = zipOpen(filename_try,(opt_overwrite==2) ? 2 : 0);
#endif

    int err=0;
    if (zf == NULL)
    {
        printf("error opening %s\n",filename_try);
        err= ZIP_ERRNO;
    }

    unsigned count = 0;
    linkedlist_filetozip* pFileList = m_filesToBeZIP;
    while (pFileList && (err==ZIP_OK))
    {
        count++;

        unsigned contentLength = pFileList->content_length;
        void const *content = pFileList->file_content;
        char* fileName = NULL;
        char fileName0[16];

        if (pFileList->file_name)
            fileName = pFileList->file_name;
        else
        {
            sprintf(fileName0, "file%d", count);
            fileName = fileName0;
        }
        struct tm * ts = gmtime(&pFileList->file_time);

        zip_fileinfo zi;
        zi.tmz_date.tm_sec = ts->tm_sec;
        zi.tmz_date.tm_min = ts->tm_min;   
        zi.tmz_date.tm_hour = ts->tm_hour; 
        zi.tmz_date.tm_mday = ts->tm_mday;  
        zi.tmz_date.tm_mon = ts->tm_mon;
        zi.tmz_date.tm_year = ts->tm_year;  

        zi.dosDate = 0;
        zi.internal_fa = 0;
        zi.external_fa = 0;

        err = zipOpenNewFileInZip3(zf,fileName,&zi,
                                NULL,0,NULL,0,NULL /* comment*/,
                                Z_DEFLATED,
                                Z_DEFAULT_COMPRESSION,0,
                                /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
                                -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
                                NULL, 0);

        if (err != ZIP_OK)
            printf("error in opening %s in zipfile\n",fileName);

        if (contentLength>0)
        {
            err = zipWriteInFileInZip (zf,content,contentLength);
            if (err<0)
            {
                printf("error in writing %s in the zipfile\n", fileName);
            }
        }

        if (err<0)
            err=ZIP_ERRNO;
        else
        {
            err = zipCloseFileInZip(zf);
            if (err!=ZIP_OK)
                printf("error in closing %s in the zipfile\n", fileName);
        }

        pFileList = pFileList->next_filetozip;
    }

    if (zipClose(zf,NULL) != ZIP_OK)
        printf("error in closing %s\n",filename_try);

    free(filename_try);

    if (cleanFileListAfterUsed)
    {
        cleanFileList(m_filesToBeZIP);
        m_filesToBeZIP = NULL;
    }
    return 0;
}
Пример #27
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;
}
Пример #28
0
int main(int argc, char **argv) {
		
#if defined(__APPLE__) && defined(__MACH__)
	char path[2049];
	_NSGetExecutablePath(path, 2048);

	String basePath = path;
	vector<String> cpts = basePath.split("/");
	String installPath = "";
	for(int i=0; i < cpts.size() - 2; i++) {
		installPath = installPath + cpts[i];
		installPath += String("/");
	}
#else
	char path[2049];
	TCHAR tpath[2049];
	GetModuleFileName(NULL, (LPWSTR)tpath, 2048);
	wtoc(path, tpath, 2048);
	
	String basePath = path;
	vector<String> cpts = basePath.split("\\");
	String installPath = "";
	for(int i=0; i < cpts.size() - 2; i++) {
		installPath = installPath + cpts[i];
		installPath += String("\\");
	}

#endif

	printf("Polycode build tool v0.1.1\n");

	for(int i=0; i < argc; i++) {
		String argString = String(argv[i]);
		vector<String> bits = argString.split("=");
		if(bits.size() == 2) {
			BuildArg arg;
			arg.name = bits[0];
			arg.value = bits[1];
			args.push_back(arg);
		}
		
	}
	
	if(getArg("--config") == "") {
		printf("\n\nInput config XML missing. Use --config=path to specify.\n\n");
		return 1;
	}

	
	if(getArg("--out") == "") {
		printf("\n\nOutput file not specified. Use --out=outfile.polyapp to specify.\n\n");
		return 1;		
	}

	char dirPath[4099];
#if defined(__APPLE__) && defined(__MACH__)
	_getcwd(dirPath, sizeof(dirPath));
#else	
	TCHAR tdirpath[4099];
	GetCurrentDirectory(4098, (LPWSTR)tdirpath);
	wtoc(dirPath, tdirpath, 4098);

#endif
	String currentPath = String(dirPath);

	String configPath = getArg("--config");

	String finalPath = configPath;
	if(configPath[0] != '/') {

#ifdef _WINDOWS
		finalPath = currentPath+"\\"+configPath;
#else
		finalPath = currentPath+"/"+configPath;
#endif
	}

	finalPath = finalPath.replace(":", "");
	finalPath = finalPath.replace("\\", "/");
	finalPath = finalPath.substr(1, finalPath.length() - 1);

	printf("Reading config file from %s\n", finalPath.c_str());

	Object configFile;
	if(!configFile.loadFromXML(finalPath)) {
		printf("Specified config file doesn't exist!\n");
		return 1;
	}
	printf("OK!\n");
	// start required params

	String entryPoint;
	int defaultWidth;
	int defaultHeight;
	int frameRate = 60;
	int antiAliasingLevel = 0;
	bool fullScreen = false;
	float backgroundColorR = 0.2;
	float backgroundColorG = 0.2;
	float backgroundColorB = 0.2;

	if(configFile.root["entryPoint"]) {
		printf("Entry point: %s\n", configFile.root["entryPoint"]->stringVal.c_str());
		entryPoint = configFile.root["entryPoint"]->stringVal;
	} else {
		printf("Required parameter: \"entryPoint\" is missing from config file!\n");
		return 1;		
	}

	if(configFile.root["defaultWidth"]) {
		printf("Width: %d\n", configFile.root["defaultWidth"]->intVal);
		defaultWidth = configFile.root["defaultWidth"]->intVal;
	} else {
		printf("Required parameter: \"defaultWidth\" is missing from config file!\n");
		return 1;		
	}

	if(configFile.root["defaultHeight"]) {
		printf("Height: %d\n", configFile.root["defaultHeight"]->intVal);
		defaultHeight = configFile.root["defaultHeight"]->intVal;
	} else {
		printf("Required parameter: \"defaultHeight\" is missing from config file!\n");
		return 1;		
	}

	// start optional params

	if(configFile.root["frameRate"]) {
		printf("Frame rate: %d\n", configFile.root["frameRate"]->intVal);
		frameRate = configFile.root["frameRate"]->intVal;
	}

	if(configFile.root["antiAliasingLevel"]) {
		printf("Anti-aliasing level: %d\n", configFile.root["antiAliasingLevel"]->intVal);
		antiAliasingLevel = configFile.root["antiAliasingLevel"]->intVal;
	}

	if(configFile.root["fullScreen"]) {
		fullScreen = configFile.root["fullScreen"]->boolVal;
		if(fullScreen) {
			printf("Full-screen: true\n");
		} else {
			printf("Full-screen: false\n");
		}
	}

	if(configFile.root["backgroundColor"]) {
		ObjectEntry *color = configFile.root["backgroundColor"];
		if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
			backgroundColorR = (*color)["red"]->NumberVal;
			backgroundColorG = (*color)["green"]->NumberVal;
			backgroundColorB = (*color)["blue"]->NumberVal;
			printf("Background color: %f %f %f\n", backgroundColorR, backgroundColorG, backgroundColorB);

		} else {
			printf("backgroundColor node specified, but missing all three color attributes (red,green,blue). Ignoring.\n");
		}
	}

	zipFile z = zipOpen(getArg("--out").c_str(), 0);
	

	Object runInfo;
	runInfo.root.name = "PolycodeApp";
	runInfo.root.addChild("entryPoint", entryPoint);
	runInfo.root.addChild("defaultHeight", defaultHeight);
	runInfo.root.addChild("defaultWidth", defaultWidth);
	runInfo.root.addChild("frameRate", frameRate);
	runInfo.root.addChild("antiAliasingLevel", antiAliasingLevel);
	runInfo.root.addChild("fullScreen", fullScreen);
	
	ObjectEntry *color = runInfo.root.addChild("backgroundColor");
	color->addChild("red", backgroundColorR);
	color->addChild("green", backgroundColorG);
	color->addChild("blue", backgroundColorB);

	addFileToZip(z, entryPoint, entryPoint, false);

	if(configFile.root["modules"]) {
#ifdef _WINDOWS
		String modulesPath = installPath + "Modules\\";
#else
		String modulesPath = installPath + "Modules/";
#endif

		ObjectEntry *modules = configFile.root["modules"];
		if(modules) {		
			for(int i=0; i < modules->length; i++) {
				printf("Adding module: %s\n", (*modules)[i]->stringVal.c_str());
				String modulePath = modulesPath + (*modules)[i]->stringVal;
#ifdef _WINDOWS
				String moduleAPIPath = modulePath + "\\API";
				String moduleLibPath = modulePath + "\\Lib";
				moduleAPIPath = moduleAPIPath.replace("\\", "/");
				moduleAPIPath = moduleAPIPath.substr(2, moduleAPIPath.length() - 2);	
				moduleLibPath = moduleLibPath.replace("\\", "/");
				moduleLibPath = moduleLibPath.substr(2, moduleLibPath.length() - 2);	

#else
				String moduleAPIPath = modulePath + "/API";
				String moduleLibPath = modulePath + "/Lib";
#endif
				printf("Path:%s\n", moduleAPIPath.c_str());		


				addFolderToZip(z, moduleAPIPath, "", false);
				addFolderToZip(z, moduleLibPath, "__lib", false);

				//String module = configFile.root["entryPoint"]->stringVal;
			}
			runInfo.root.addChild(configFile.root["modules"]);
		}
	}

	if(configFile.root["packedItems"]) {
		ObjectEntry *packed = configFile.root["packedItems"];
		if(packed) {
			for(int i=0; i < packed->length; i++) {
				ObjectEntry *entryPath = (*(*packed)[i])["path"];
				ObjectEntry *entryType = (*(*packed)[i])["type"];
				if(entryPath && entryType) {
					if(entryType->stringVal == "folder") {
						addFolderToZip(z, entryPath->stringVal, entryPath->stringVal, false);
					} else {
						addFileToZip(z, entryPath->stringVal, entryPath->stringVal, false);
					}
				}
			}
			runInfo.root.addChild(configFile.root["packedItems"]);
		}
	}


	runInfo.saveToXML("runinfo_tmp_zzzz.polyrun");
	addFileToZip(z, "runinfo_tmp_zzzz.polyrun", "runinfo.polyrun", true);

	//addFolderToZip(z, getArg("--project"), "");
	
	zipClose(z, "");	

	OSBasics::removeItem("runinfo_tmp_zzzz.polyrun");

	return 0;
}
Пример #29
0
bool CDialogPackage::CreatePackage()
{
    // Create options file
    WCHAR tempFile[MAX_PATH];
    GetTempPath(MAX_PATH, tempFile);
    GetTempFileName(tempFile, L"ini", 0, tempFile);

    WritePrivateProfileString(L"rmskin", L"Name", m_Name.c_str(), tempFile);
    WritePrivateProfileString(L"rmskin", L"Author", m_Author.c_str(), tempFile);
    WritePrivateProfileString(L"rmskin", L"Version", m_Version.c_str(), tempFile);

    if (!c_Dialog->m_Load.empty())
    {
        WritePrivateProfileString(L"rmskin", L"LoadType", c_Dialog->m_LoadLayout ? L"Layout" : L"Skin", tempFile);
        WritePrivateProfileString(L"rmskin", L"Load", c_Dialog->m_Load.c_str(), tempFile);
    }

    if (!c_Dialog->m_VariableFiles.empty())
    {
        WritePrivateProfileString(L"rmskin", L"VariableFiles", m_VariableFiles.c_str(), tempFile);
    }

    if (c_Dialog->m_MergeSkins)
    {
        WritePrivateProfileString(L"rmskin", L"MergeSkins", L"1", tempFile);
    }

    WritePrivateProfileString(L"rmskin", L"MinimumRainmeter", m_MinimumRainmeter.c_str(), tempFile);
    WritePrivateProfileString(L"rmskin", L"MinimumWindows", m_MinimumWindows.c_str(), tempFile);

    // Create archive and add options file and header bitmap
    m_ZipFile = zipOpen(StringUtil::NarrowUTF8(m_TargetFile).c_str(), APPEND_STATUS_CREATE);

    auto cleanup = [&]()->bool
    {
        zipClose(m_ZipFile, NULL);
        return false;
    };

    if (!m_ZipFile ||
            (!c_Dialog->m_HeaderFile.empty() && !AddFileToPackage(c_Dialog->m_HeaderFile.c_str(), L"RMSKIN.bmp")) ||
            !AddFileToPackage(tempFile, L"RMSKIN.ini"))
    {
        std::wstring error = L"Unable to create package.";
        error += L"\n\nClick OK to close Packager.";
        MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR);
        DeleteFile(tempFile);
        return cleanup();
    }

    // Add skin
    {
        std::wstring zipPrefix = L"Skins\\" + m_SkinFolder.first;
        zipPrefix += L'\\';
        if (!AddFolderToPackage(m_SkinFolder.second, L"", zipPrefix.c_str()))
        {
            return cleanup();
        }
    }

    // Add layouts
    for (auto iter = m_LayoutFolders.cbegin(); iter != m_LayoutFolders.cend(); ++iter)
    {
        std::wstring realPath = (*iter).second + L"Rainmeter.ini";
        std::wstring zipPath = L"Layouts\\" + (*iter).first;
        zipPath += L"\\Rainmeter.ini";
        if (!AddFileToPackage(realPath.c_str(), zipPath.c_str()))
        {
            std::wstring error = L"Error adding layout '";
            error += (*iter).first;
            error += L"'.";
            error += L"\n\nClick OK to close Packager.";
            MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR);
            return cleanup();
        }
    }

    // Add plugins
    for (auto iter = m_PluginFolders.cbegin(); iter != m_PluginFolders.cend(); ++iter)
    {
        // Add 32bit and 64bit versions
        for (int i = 0; i < 2; ++i)
        {
            const std::wstring& realPath = (i == 0) ? (*iter).second.first : (*iter).second.second;
            std::wstring zipPath = ((i == 0) ? L"Plugins\\32bit\\" : L"Plugins\\64bit\\") + (*iter).first;
            if (!AddFileToPackage(realPath.c_str(), zipPath.c_str()))
            {
                std::wstring error = L"Error adding plugin '";
                error += (*iter).first;
                error += L"'.";
                error += L"\n\nClick OK to close Packager.";
                MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR);
                return cleanup();
            }
        }
    }

    // Add footer
    FILE* file;
    if (zipClose(m_ZipFile, NULL) == ZIP_OK &&
            (file = _wfopen(m_TargetFile.c_str(), L"r+b")) != NULL)
    {
        fseek(file, 0, SEEK_END);
        CDialogInstall::PackageFooter footer = { _ftelli64(file), 0, "RMSKIN" };
        fwrite(&footer, sizeof(footer), 1, file);
        fclose(file);
    }
    else
    {
        std::wstring error = L"Unable to create package.";
        error += L"\n\nClick OK to close Packager.";
        MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR);
        return false;
    }

    return true;
}
Пример #30
0
void ReleaseDialog::release()
{
    QString pwd = lineedit_pwd->text();
    QString name = lineedit_name->text();
    if(pwd.isEmpty() || name.isEmpty() || name.size() > 16)
    {
        QString prompt;
        prompt = QString("必须设置加密密码\n填写版本信息。");
        if(name.size() > 16)
            prompt = QString("版本信息不能超过16个字符。");
        QMessageBox box(QMessageBox::Information, "提示", prompt);
        box.setStandardButtons(QMessageBox::Ok);
        box.setButtonText(QMessageBox::Ok, "确定");
        box.exec();
        return;
    }

    ////name 最大16个字符



    if(!setFilePath())
        return;

    QDateTime start,end;
    getDateTime(start, end);
    QString jsonfilePath = getReadFilePath(start, end);

    ///读JSON下载资源
    readJsonFile(jsonfilePath);

    ///打包
    QStringList fileNames = getCurrentDirFiles(releasePath);
    QString destPath  = QCoreApplication::applicationDirPath();
    destPath.append("/ZIP/");
    QDir dir(destPath);
    if(!dir.exists())
        dir.mkpath(destPath);
    QString destName = currentDate.toString("yyyy-MM-dd_hh_mm_ss");
    destName.append(".zip");
    destPath.append(destName);

    QFile destFile(destPath);
    if(destFile.exists())
    {
    }

    zipFile zf;
    QByteArray dest = destPath.toLocal8Bit();
    zf = zipOpen(dest.data(), APPEND_STATUS_CREATE);


    if (zf == NULL)
    {
        return;
    }

//   LOKI_ON_BLOCK_EXIT(zipClose, zf, (const char *)NULL);
   for (int i=0; i<fileNames.size(); i++)
   {
       QString tempStr = fileNames.at(i);
       QString path = releasePath;
       path.remove("music");
       QString temprel = path;
       QString deststr = tempStr.remove(temprel);
       if (!ZipAddFile(zf, deststr, fileNames.at(i),  pwd,  true)) //"default_yqc"
       {
           continue;
       }
   }

   int errclose = zipClose(zf, NULL);
   if (errclose != ZIP_OK)
       qDebug() << " zipClose ret : " << errclose;

   ///上传打包文件
   QString url;
   CurlUpload *curlUpload = new CurlUpload();
   bool ok = curlUpload->uploadYQDyun(destName, destPath, url);

   qDebug() << " upload yun : ok : " << ok;
   qDebug() << " zip name " << destName;
   qDebug() << " url " << url;
   /// post 表格数据
   QDateTime time = QDateTime::currentDateTime();
   QString timeStr = time.toString("yyyy-MM-dd-hh-mm-ss");
   int version = time.toTime_t();
   QString postStr = QString("name=%1&url=%2&time=%3&remark=%4&version=%5")
                            .arg(name)
                            .arg(url)
                            .arg(timeStr)
                            .arg(pwd)
                            .arg(version);


   CurlUpload *curlDownlaod = new CurlUpload();
   curlDownlaod->postJson(postStr);

   return;
}