Example #1
0
void CMsregPacket::WriteToFile(CFile& cfFile)
{
	// Save the current position so we can return and write out
	// the correct checksum.

	DWORD dwPosition = cfFile.GetPosition();

	// Call the top level object in the derivation chain to actually
	// write the data to the file. A checksum will be accumulated as
	// the writing progresses. Note that the header will not be included
	// in the checksum. The size of the block is determined after the
	// block data has been written. The block size is used to skip
	// unknown blocks.

	m_Header.dwSize = 0;
	m_Header.dwChecksum = 0;

	WriteDataToFile(cfFile, m_Header.dwChecksum);

	// All the data has been written. Rewrite the header with the real values.
	// Note that the checksum value has already been filled in. The block size
	// is difference between the current file position and the starting position.

	DWORD dwNewPosition = cfFile.GetPosition();
	m_Header.dwSize = dwNewPosition-dwPosition;

	cfFile.Seek(dwPosition, CFile::begin);

	CMsregPacket::WriteDataToFile(cfFile, m_Header.dwChecksum);

	// Move back to the end of the block.

	cfFile.Seek(dwNewPosition, CFile::begin);
}
Example #2
0
void CBlokRtf::Control(CFile &f, int iBlk)
{
	CString m,n,lnS;
	int iR=0,iLn=0;
	int iDel=0;
	int curPos = f.GetPosition();
	m.Format("Тек поз curPos = %i",curPos);
AfxMessageBox(m);

	char* b = new char[iBlk];

	iR = f.Read(b,iBlk);	// Долбанная функция

	curPos = f.GetPosition();
	m.Format("Поз после Read curPos = %i прочитано iR = %i",curPos,iR);
AfxMessageBox(m);
	CString s=_T("");
	for(int i=0;i<iBlk;i++){
		if(_T(' ')==*(b+i) ){
			s+=_T("_");
		}
		else if( _T('\n')==*(b+i)){
			s+=_T("~");
			iDel++;
		}
		else if(_T('\r')==*(b+i)){
			s+=_T("#");
			iDel++;
		}
		else{
			s+=*(b+i);
		}

//		s+=*(b+i);
	}
//	iLn = s.GetLength();
	lnS.Format(" iDel= %i",iDel);
AfxMessageBox(s+'\n'+lnS);
/*	int ln;
	ln=s.GetLength();
	n.Format("Длина строки s = %i k = %i",ln);
AfxMessageBox(s+'\n'+n);
*/
	curPos-=(iBlk+iDel);
//	curPos-=iBlk;

	m.Format("Поз для возврата curPos = %i",curPos);
AfxMessageBox(m);

	f.Seek(curPos,CFile::begin);

	curPos = f.GetPosition();
	m.Format("Тек поз после Seek назад на исх curPos = %i",curPos);
AfxMessageBox(m);
	delete [] b;

}
Example #3
0
void CHistoryDlg::OnButtonHistCompact() 
{
	// Compact History File
	CWaitCursor wc;

	CFile theHistoryFile;
	CFileException cfe;

	if(theHistoryFile.Open("HISTORY.DAT", CFile::modeReadWrite, &cfe) == FALSE)
	{
		TRACE("CHistoryDlg::BuildHistoryFileStats() - File Not Opened\n");
		return;
	}

	CTaskObject oneTask;

	DWORD dwReadPos = 0;
	DWORD dwWritePos = 0;

	while(oneTask.ReadFromFile(theHistoryFile) == TRUE)
	{
		if(oneTask.m_bHistoryDeleted == TRUE)
			continue;

		dwReadPos = theHistoryFile.GetPosition();

		theHistoryFile.Seek(dwWritePos, CFile::begin);

		oneTask.WriteToFile(theHistoryFile, FALSE);

		dwWritePos = theHistoryFile.GetPosition();

		theHistoryFile.Seek(dwReadPos, CFile::begin);
	}

	theHistoryFile.SetLength(dwWritePos);

	theHistoryFile.Close();

	CListCtrl* pListCtrl = (CListCtrl*) GetDlgItem(IDC_LIST_HISTORY);

	pListCtrl->DeleteAllItems();

	BuildHistoryFileStats(pListCtrl);

	UpdateButtons();

}
bool    External::Write_Chunks_Header(   CFile&  file,    short  chunkCode,   unsigned char version,   long&  retSizeFilePos,   CString&  retErrorMesg  )
{


	retErrorMesg.Empty();
	retSizeFilePos =  -1;


	long   sizeBytesAfterChkHdr =  0;    //  will write in later



	CString   retTagString;


	if(    ! Get_Chunks_TagString(   chunkCode,    retTagString,   retErrorMesg  )     )
		return  false;




	file.Write(   retTagString.GetBuffer( 8 ),    8   );

	file.Write(   &version,    1  );     //	unsigned char   version =   10;    ....   1.0



	retSizeFilePos  =      file.GetPosition();     //  return filePos 'just before' we write the 4 bytes for chunk's size

	file.Write(   &sizeBytesAfterChkHdr,    4  );


	return  true;
}
Example #5
0
mpc_int32_t Mpc_Callback_GetPosition(void *data)
{
  CFile *file = (CFile *)data;
  if (!file) return 0;
  int position = (int)file->GetPosition();
  if (position >= 0)
    return position;
  return -1;
}
Example #6
0
long CAPEv2Tag::ftell_callback(void *fp)
{
  CFile *file = (CFile *)fp;
  int64_t pos = file->GetPosition();
  if(pos > LONG_MAX)
    return -1;
  else
    return (long)pos;
}
Example #7
0
void CHistoryDlg::BuildHistoryFileStats(CListCtrl* pListCtrl)
{
	m_nEntries = 0;
	m_nDeleted = 0;

	CFile theHistoryFile;
	CFileException cfe;

	if(theHistoryFile.Open("HISTORY.DAT", CFile::modeRead, &cfe) == FALSE)
	{
		TRACE("CHistoryDlg::BuildHistoryFileStats() - File Not Opened\n");
		return;
	}

	TRACE("CHistoryDlg::BuildHistoryFileStats() - Getting Status ...\n");

	CTaskObject oneTask;

	DWORD dwFilePos = 0;
	
	int nPartsTotal;
	TCHAR szParts[32];

	while(oneTask.ReadFromFile(theHistoryFile) == TRUE)
	{
		++m_nEntries;
		if (oneTask.m_nState == CTaskObject::PM_POSTING)
			oneTask.m_nState = CTaskObject::PM_QUEUED;
		else if (oneTask.m_nState == CTaskObject::PM_ENCODING)
			oneTask.m_nState = CTaskObject::PM_ENC_QUEUED;


		TRACE2("  Task %4d at Offset %u\n", m_nEntries, dwFilePos);
		
		if(oneTask.m_bHistoryDeleted)
			++m_nDeleted;
		else
		{
			if(pListCtrl != NULL)
			{
				nPartsTotal = oneTask.getNbParts();
				sprintf(szParts, "%d/%d", nPartsTotal - oneTask.m_dwaPartsToPost.GetSize(), nPartsTotal);
				pListCtrl->InsertItem(0, oneTask.m_szSubject);
				pListCtrl->SetItemText(0, 1, szParts);
				pListCtrl->SetItemText(0, 2, oneTask.m_szHistoryDateTime);
				pListCtrl->SetItemData(0, dwFilePos);
			}
		}

		dwFilePos = theHistoryFile.GetPosition();
	}

	theHistoryFile.Close();
}
Example #8
0
int CWebServer::ContentReaderCallback(void *cls, size_t pos, char *buf, int max)
#endif
{
  CFile *file = (CFile *)cls;
  if((unsigned int)pos != file->GetPosition())
    file->Seek(pos);
  unsigned res = file->Read(buf, max);
  if(res == 0)
    return -1;
  return res;
}
//--------------------------------------------------------------------------------
bool CFileIndexObjMap::Write(CFile& file)
	{
	DWORD nPos;
	bool bPosOk = false;
	bool bRv = true;
	POSITION pos = GetStartPosition();

	TRY
		{
		nPos = file.GetPosition();
		bPosOk = true;
		DWORD nNum = 'CMAP';
		file.Write(&nNum, sizeof(nNum));
		nNum = GetCount();
		file.Write(&nNum, sizeof(nNum));
		}
	CATCH_ALL(e)
		{
		bRv = false;
		pos = NULL;
		}
	END_CATCH_ALL;

	while(pos != NULL)
		TRY
			{
			LPCTSTR pKey;
			CFileIndexObject* pObj;
			GetNextAssoc(pos, pKey, pObj);
			if(pObj == NULL)
				THROW(new CException);

			pObj->Write(file, false);
			}
		CATCH_ALL(e)
			{
			bRv = false;
			break;
			}
		END_CATCH_ALL;

	if(bPosOk && ! bRv)
		TRY
			{
			file.Seek(nPos, CFile::begin);
			}
		CATCH_ALL(e)
			{
			}
		END_CATCH_ALL;

	return bRv;
	}
Example #10
0
int CPatch::Parser(CString &pathfile)
{
	CString str;

	CFile PatchFile;

	m_PathFile=pathfile;
	if( ! PatchFile.Open(pathfile,CFile::modeRead) )
		return -1;

#if 0
	int i=0;
	while(i<4)
	{
		PatchFile.ReadString(str);
		if(i==1)
			this->m_Author=str.Right( str.GetLength() - 6 );
		if(i==2)
			this->m_Date = str.Right( str.GetLength() - 6 );
		if(i==3)
			this->m_Subject = str.Right( str.GetLength() - 8 );

		++i;
	}

	LONGLONG offset=PatchFile.GetPosition();
#endif
	PatchFile.Read(m_Body.GetBuffer((UINT)PatchFile.GetLength()), (UINT)PatchFile.GetLength());
	m_Body.ReleaseBuffer();
	PatchFile.Close();

	int start=0;
	CStringA one;
	one=m_Body.Tokenize("\n",start);

	one=m_Body.Tokenize("\n",start);
	if(one.GetLength()>6)
		g_Git.StringAppend(&m_Author, (BYTE*)one.GetBuffer() + 6, CP_UTF8, one.GetLength() - 6);

	one=m_Body.Tokenize("\n",start);
	if(one.GetLength()>6)
		g_Git.StringAppend(&m_Date, (BYTE*)one.GetBuffer() + 6, CP_UTF8, one.GetLength() - 6);

	one=m_Body.Tokenize("\n",start);
	if(one.GetLength()>9)
		g_Git.StringAppend(&m_Subject, (BYTE*)one.GetBuffer() + 9, CP_UTF8, one.GetLength() - 9);

	//one=m_Body.Tokenize("\n",start);

	g_Git.StringAppend(&m_strBody, (BYTE*)m_Body.GetBuffer() + start + 1, CP_UTF8, m_Body.GetLength() - start - 1);

	return 0;
}
Example #11
0
int64_t CAddonCallbacksAddon::GetFilePosition(const void* addonData, void* file)
{
  CAddonInterfaces* helper = (CAddonInterfaces*) addonData;
  if (!helper)
    return 0;

  CFile* cfile = (CFile*)file;
  if (!cfile)
    return 0;

  return cfile->GetPosition();
}
//--------------------------------------------------------------------------------
bool CFileIndexObject::Read(CFile& file, bool bResetPosOnError)
	{
	DWORD nPos;
	bool bPosOk = false;
	DWORD nNum;
	char* pBuf = NULL;
	bool bRv = true;

	TRY
		{
		if(bResetPosOnError)
			{
			nPos = file.GetPosition();
			bPosOk = true;
			}

		// read the object id
		if(file.Read(&nNum, sizeof(nNum)) == sizeof(nNum))
			// be sure we're reading the object we want
			if(nNum == GetObjectId())
				// read the name length
				if(file.Read(&nNum, sizeof(nNum)) == sizeof(nNum))
					{
					pBuf = m_sName.GetBuffer(nNum);
					bRv = (file.Read(pBuf, nNum) == nNum);
					}
	char temp[1024];
	file.Read(temp, 1024);
		}
	CATCH_ALL(e)
		{
		bRv = false;
		}
	END_CATCH_ALL;

	if(pBuf != NULL)
		m_sName.ReleaseBuffer();

	if(bResetPosOnError && bPosOk && ! bRv)
		TRY
			{
			file.Seek(nPos, CFile::begin);
			}
		CATCH_ALL(e)
			{
			}
		END_CATCH_ALL;

	return bRv;
	}
//--------------------------------------------------------------------------------
bool CFileIndexObjMap::Read(CFile& file)
	{
	DWORD nPos;
	bool bPosOk = false;
	bool bRv = true;
	POSITION pos = GetStartPosition();
	int nCount;

	TRY
		{
		nPos = file.GetPosition();
		bPosOk = true;
		DWORD nNum;
		if(file.Read(&nNum, sizeof(nNum)) != sizeof(nNum) || nNum != 'CMAP')
			bRv = false;
		if(file.Read(&nNum, sizeof(nNum)) != sizeof(nNum))
			bRv = false;
		nCount = nNum;
		}
	CATCH_ALL(e)
		{
		bRv = false;
		}
	END_CATCH_ALL;

	for(int i = 0; i < nCount; i++)
		{
		CFileIndexObject* pObj = CreateNewIndexObject();
		bRv = pObj->Read(file, false);
		if(! bRv)
			{
			delete pObj;
			break;
			}
		SetAt(pObj->GetName(), pObj);
		}

	if(bPosOk && ! bRv)
		TRY
			{
			file.Seek(nPos, CFile::begin);
			}
		CATCH_ALL(e)
			{
			}
		END_CATCH_ALL;

	return bRv;
	}
Example #14
0
int CCDDARipJob::RipChunk(CFile& reader, CEncoder* encoder, int& percent)
{
  percent = 0;

  uint8_t stream[1024];

  // get data
  int result = reader.Read(stream, 1024);

  // return if rip is done or on some kind of error
  if (result <= 0)
    return 1;

  // encode data
  int encres=encoder->Encode(result, stream);

  // Get progress indication
  percent = static_cast<int>(reader.GetPosition()*100/reader.GetLength());

  if (reader.GetPosition() == reader.GetLength())
    return 2;

  return -(1-encres);
}
Example #15
0
void CBlokRtf::GetRStrWrt(int iBlk, CString strFnd, CFile &inF, CFile &oF, int &curPos, CString &strOut)
{
//Указатель устанавливает за строкой поиска
//пишет в файл со строкой поиска
//возвращает считанный весь буфер в виде строки strOut
	CString strBuf,strTg,s;
	CString strWrt=_T("");
	strTg = _T("");
	int tPos;//=0;				// Позиция в strBuf
	int iCnt = 0;
	bool bEnd=true;
	strBuf = GetStrBuf(iBlk,inF,curPos,bEnd);
	if(!bEnd){
//		AfxMessageBox("False");
		return;
	}
//AfxMessageBox("Исх строка\n"+strBuf);
//AfxMessageBox("Подстрока\n"+strFnd);
//-------------------------------Ищу вхождение  подстроки
	if((tPos = strBuf.Find(strFnd))!=-1){
		strTg = strBuf.Left(tPos+strFnd.GetLength());
		iCnt = strTg.GetLength();
		strOut+=strTg;
		oF.Write(strTg,iCnt);			// Записал
//		s.Format(" Нашёл GetRStr curPos = %i",curPos);
//AfxMessageBox("Нашёл в GetRStrWrtStr \n"+s+'\n'+strTg);
		curPos+= iCnt;
		inF.Seek(curPos,CFile::begin); // поставил указатель ЗА
//			s.Format(" после нашёл Seek curPos = %i",curPos);
//		AfxMessageBox(s);
		return;
	}
	else{						// Не нашёл, можно читать дальше
		AfxMessageBox("Не нашёл GetRStrWrt\n"+strBuf);
//		AfxMessageBox("накопление\n"+strOut);
		oF.Write(strBuf,iBlk);			// Записал
		curPos+=iBlk;
		inF.Seek(curPos,CFile::begin);	// Переместил
//		inF.Seek(iBlk,CFile::current);	// Переместил
		curPos = inF.GetPosition();
		GetRStrWrt(iBlk,strFnd,inF,oF,curPos,strOut);
		return;
	}

}
void    External::Write_Chunks_Length(    CFile&  file,   long  tagsLengthFilePos    )
{


	long   curFilePos  =     file.GetPosition();    //  Go back to the TAG and now write the length to the previous tag

	file.Seek(   tagsLengthFilePos,    CFile::begin    );



	long   dataLength  =   curFilePos  -  (  tagsLengthFilePos  + 4  );   //  +4 bytes:  for the version field in the ChunkTag to the end of tag.


	file.Write(   &dataLength,   4   );


	file.Seek(   curFilePos,    CFile::begin    );   // and return to current position
}
Example #17
0
void CBlokRtf::GetRStr(int iBlk, CString strFnd, CFile &inF, int &curPos, CString& strOut)
{
//Считывает строку по подстроке
//указатель устанавливается за стракой
//ничего НЕ пишет

	CString strBuf,strTg,s;
	strTg = _T("");
	int tPos;//=0;				// Позиция в strBuf
	int iCnt = 0;
	bool bEnd=true;
	strBuf = GetStrBuf(iBlk,inF,curPos,bEnd);
	if(!bEnd){
//		AfxMessageBox("False");
		return;
	}
//AfxMessageBox("Исх строка\n"+strBuf+'\n'+"Подстрока\n"+strFnd);
//-------------------------------Ищу вхождение  подстроки
	if((tPos = strBuf.Find(strFnd))!=-1){
		strTg = strBuf.Left(tPos+strFnd.GetLength());
//AfxMessageBox("Нашёл в GetR \n"+strTg);
		iCnt = strTg.GetLength();
		strOut+=strTg;
		s.Format(" Нашёл GetRStr curPos = %i",curPos);
AfxMessageBox("Нашёл в GetRStr \n"+s+'\n'+"strTg = "+strTg);
		curPos+= iCnt;
		inF.Seek(curPos,CFile::begin); // поставил указатель ЗА
//			s.Format(" после нашёл Seek curPos = %i",curPos);
//		AfxMessageBox(s);
		return;
	}
	else{						// Не нашёл, можно читать дальше
//		AfxMessageBox("Не нашёл GetRStr\n"+strBuf);
//		AfxMessageBox("накопление\n"+strOut);
		strOut+=strBuf;
		curPos+=iBlk;
		inF.Seek(curPos,CFile::begin);	// Переместил
//		inF.Seek(iBlk,CFile::current);	// Переместил
		curPos = inF.GetPosition();
		GetRStr(iBlk,strFnd,inF,curPos,strOut);
		return;
	}

}
Example #18
0
void  CBlokRtf::GetStrWrtStr(int iBlk, CFile &inF, CFile& oF, CString strFnd, int& curPos)
{
// получение строки от тек. поз. до искомой строки
// включая саму строку поиска
// установка указателя за последним символом искомой строки
// пишет !!!

	CString strBuf=_T(""),s;

//	s.Format("до считки curPos = %i",curPos);
//	AfxMessageBox(s);
	bool bEnd=true;
	strBuf = GetStrBuf(iBlk,inF,curPos,bEnd);
//	s.Format("после считки curPos = %i",curPos);
//	AfxMessageBox(s);

	int tPos,iCnt;
	CString strTg=_T("");

	if((tPos=strBuf.Find(strFnd))!=-1){ // Нашёл
		strTg = strBuf.Left(tPos+strFnd.GetLength());
//AfxMessageBox("Нашёл в GetStrWrtStr \n"+strTg);
		iCnt = strTg.GetLength();
		oF.Write(strTg,iCnt);			// Записал
		curPos+= iCnt;
		s.Format(" Нашёл GetStrWrtStr curPos = %i",curPos);
AfxMessageBox(s+'\n'+strTg);
		inF.Seek(curPos,CFile::begin); // поставил указатель ЗА
									   // искомую строку
		return; // curPos;
	}
	else{
		oF.Write(strBuf,iBlk);					// Записал 
//		AfxMessageBox("Не нашёл GetStrWrtStr\n"+strBuf);
		curPos+=iBlk;
		inF.Seek(curPos,CFile::begin);			// Переместил
//		inF.Seek(iBlk,CFile::current);			// Переместил
		curPos = inF.GetPosition();
		GetStrWrtStr(iBlk,inF,oF,strFnd,curPos);
		return;
	}

}
//--------------------------------------------------------------------------------
bool CFileIndexObject::Write(CFile& file, bool bResetPosOnError)
	{
	DWORD nPos;
	bool bPosOk = false;
	bool bRv = true;
	TRY
		{
		if(bResetPosOnError)
			{
			nPos = file.GetPosition();
			bPosOk = true;
			}

		DWORD nNum = GetObjectId();
		file.Write(&nNum, sizeof(nNum));
		nNum = m_sName.GetLength();
		file.Write(&nNum, sizeof(nNum));
		file.Write((LPCTSTR) m_sName, nNum);
	char temp[1024];
	file.Write(temp, 1024);
		}
	CATCH_ALL(e)
		{
		bRv = false;		
		}
	END_CATCH_ALL;

	if(bPosOk && bResetPosOnError && ! bRv)
		TRY
			{
			file.Seek(nPos, CFile::begin);
			}
		CATCH_ALL(e)
			{
			}
		END_CATCH_ALL;

	return bRv;
	}
Example #20
0
void CEditView::SerializeRaw(CArchive& ar)
	// Read/Write object as stand-alone file.
{
	ASSERT_VALID(this);
	if (ar.IsStoring())
	{
		WriteToArchive(ar);
	}
	else
	{
		CFile* pFile = ar.GetFile();
		ASSERT(pFile->GetPosition() == 0);
		DWORD nFileSize = pFile->GetLength();
		if (nFileSize/sizeof(TCHAR) > nMaxSize)
		{
			AfxMessageBox(AFX_IDP_FILE_TOO_LARGE);
			AfxThrowUserException();
		}
		// ReadFromArchive takes the number of characters as argument
		ReadFromArchive(ar, (UINT)nFileSize/sizeof(TCHAR));
	}
	ASSERT_VALID(this);
}
Example #21
0
BOOL CWindowsMetaFile::GetMetaFile(LPCSTR pszFileName, ALDUS_WMF_HEADER* pAldusHeader, METAHEADER* pHeader, HMETAFILE* phMetaFile)
{
	BOOL fSuccess = FALSE;
	
	ASSERT(pszFileName != NULL);
	
	// Create the file we will be using.

	CFile File;

	// Attempt to open the file.

	if (File.Open(pszFileName, CFile::modeRead | CFile::shareDenyWrite))
	{
		ALDUS_WMF_HEADER AldusHeader;

		// Read the Aldus header.

		if (File.Read(&AldusHeader, sizeof(AldusHeader)) == sizeof(AldusHeader))
		{
			// Save the Aldus header if the user has requested it.
					
			if (pAldusHeader != NULL)
			{
				*pAldusHeader = AldusHeader;
			}
						
			// Validate the header.

			if (AldusHeader.key == ALDUS_WMF_KEY)
			{
				// If the user has only requested the Aldus header, stop and return TRUE.
				
				fSuccess = (pHeader == NULL) && (phMetaFile == NULL);
				
				if (!fSuccess)
				{
					// Read the metafile header.
	
					METAHEADER Header;
	
					DWORD dwPosition = File.GetPosition();
	
					if (File.Read(&Header, sizeof(Header)) == sizeof(Header))
					{
						// Save the metafile header if the user has requested it.
							
						if (pHeader != NULL)
						{
							*pHeader = Header;
						}
						
						// If the user does not want a metafile handle, stop and return TRUE.
						
						fSuccess = phMetaFile == NULL;
								
						if (!fSuccess)
						{
							*phMetaFile = NULL;
								
							// Get the size from the metafile header.
							
							DWORD dwSize = Header.mtSize*2;
							
							if (dwSize != 0)
							{
								// Allocate the memory to hold the metafile data.
									
								HGLOBAL hMetaFileData;
									
								hMetaFileData = GlobalAlloc(GMEM_MOVEABLE|GMEM_SHARE, dwSize);
									
								if (hMetaFileData != NULL)
								{
									LPVOID pMetaFileData;
										
									pMetaFileData = GlobalLock(hMetaFileData);
										
									if (pMetaFileData != NULL)
									{
										// Seek back to the start of the metafile header.
										
										File.Seek(dwPosition, CFile::begin);

										// Read the metafile data.
										
										if (File.ReadHuge(pMetaFileData, dwSize) == dwSize)
										{
											// We have now read the data, make a metafile from it.
	
#ifdef WIN32
											*phMetaFile = ::SetMetaFileBitsEx(dwSize, (LPBYTE)pMetaFileData);
#else
											*phMetaFile = ::SetMetaFileBits(hMetaFileData);
#endif
											fSuccess = *phMetaFile != NULL;
										}

#ifdef WIN32
										GlobalUnlock(hMetaFileData);
										pMetaFileData = NULL;
#else
										if (*phMetaFile == NULL)
										{
											GlobalUnlock(hMetaFileData);
											pMetaFileData = NULL;
										}
#endif
									}
#ifdef WIN32
									GlobalFree(hMetaFileData);
									hMetaFileData = NULL;
#else
									if (*phMetaFile == NULL)
									{
										GlobalFree(hMetaFileData);
										hMetaFileData = NULL;
									}
#endif
								}
							}
						}
					}
				}
			}
		}
	}

	return fSuccess;
}
Example #22
0
BOOL CPreviewThread::Run()
{
	ASSERT (m_pPartfile) ;
	CFile destFile;
	CFile srcFile;
	if (!srcFile.Open(m_pPartfile->GetFilePath(), CFile::modeRead | CFile::shareDenyNone))
		return FALSE;
	try{
		uint32 nSize = m_pPartfile->GetFileSize();
		CString strExtension = CString(_tcsrchr(m_pPartfile->GetFileName(), _T('.')));
		CString strPreviewName = m_pPartfile->GetTempPath() + _T("\\") + m_pPartfile->GetFileName().Mid(0, 5) + _T("_preview") + strExtension;
		bool bFullSized = true;
		if (!strExtension.CompareNoCase(_T(".mpg")) || !strExtension.CompareNoCase(_T(".mpeg")))
			bFullSized = false;
		if (!destFile.Open(strPreviewName, CFile::modeWrite | CFile::shareDenyWrite | CFile::modeCreate))
			return FALSE;
		srcFile.SeekToBegin();
		if (bFullSized)
			destFile.SetLength(nSize);
		destFile.SeekToBegin();
		BYTE abyBuffer[4096];
		uint32 nRead;
		while (destFile.GetPosition()+4096 < PARTSIZE*2){
			nRead = srcFile.Read(abyBuffer,4096);
			destFile.Write(abyBuffer,nRead);
		}
		srcFile.Seek(-(PARTSIZE*2),CFile::end);
		uint32 nToGo =PARTSIZE*2;
		if (bFullSized)
			destFile.Seek(-(PARTSIZE*2),CFile::end);
		do{
			nRead = (nToGo - 4096 < 1)? nToGo:4096;
			nToGo -= nRead;
			nRead = srcFile.Read(abyBuffer,4096);
			destFile.Write(abyBuffer,nRead);
		}
		while (nToGo);
		destFile.Close();
		srcFile.Close();
		m_pPartfile->m_bPreviewing = false;

		SHELLEXECUTEINFO SE;
		MEMSET(&SE,0,sizeof(SE));
		SE.fMask = SEE_MASK_NOCLOSEPROCESS ;
		SE.lpVerb = _T("open");
		
		CString path;
		if (!m_player.IsEmpty())
		{
			TCHAR shortPath[512]; //Cax2 short path for vlc
			GetShortPathName(strPreviewName, shortPath, ARRSIZE(shortPath));

			path=thePrefs.GetVideoPlayer();
			int pos = path.ReverseFind(_T('\\'));
			if (pos == -1)
				path.Empty();
			else
				path = path.Left(pos + 1);
			SE.lpFile = m_player.GetBuffer();
			SE.lpParameters=shortPath;
			SE.lpDirectory=path.GetBuffer();
		}
		else
			SE.lpFile = strPreviewName.GetBuffer();
		SE.nShow = SW_SHOW;
		SE.cbSize = sizeof(SE);
		ShellExecuteEx(&SE);
		if (SE.hProcess){
			WaitForSingleObject(SE.hProcess, INFINITE);
			CloseHandle(SE.hProcess);
		}
		CFile::Remove(strPreviewName);
	}	
	catch(CFileException* error){
		m_pPartfile->m_bPreviewing = false;
		error->Delete();
	}
	return TRUE;
}
Example #23
0
RET_VAL ConnectionLimit::IsVistaPatched(LPCTSTR path)
{
	UnlockFile("c:\\windows\\system32\\drivers\\vga.sys");
	CFile file;
	DWORD dwOffset = 0;
	bool isWow = IsWow64();
	PVOID oldValue = NULL;
	if(isWow)
	{
		MyWow64DisableWow64FsRedirection(&oldValue);
	}

	if(file.Open(path,CFile::modeRead))
	{
		TCHAR patchedChar = 0x90;
		if(isWow)
		{
			MyWow64RevertWow64FsRedirection(oldValue);
		}
		unsigned int bytesRead = 0;
		TCHAR buffer[1024];
		bytesRead = file.Read(buffer, 1024);
		while(bytesRead != 0)
		{
			for (int i = 0; i<bytesRead; ++i)
			{
				if(!isWow)
				{

					if(buffer[i] == VISTA_MAGIC_32[0])
					{
						if(i>= (bytesRead - 8))
						{
							int pos = file.GetPosition();
							file.Seek(-8, CFile::current);
							bytesRead-=8;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 9; ++c)
						{
							if(buffer[i+c] != VISTA_MAGIC_32[c])
							{
								break;
							}
							else
							{
								if(c == 8)
								{
									dwOffset += i + 9;
									bool patched = true;
									for(int p = 0; p < 6; ++p)
									{
										if(buffer[i+9+p] != patchedChar)
											patched = false;
									}
									file.Close();
									if(patched)
										return RET_YES;
									else
										return RET_NO;
									//return dwOffset;
								}
							}
						}
					}
				}
				else
				{
					if(buffer[i] == MAGIC_64[0])
					{
						if(i>= (bytesRead - 24))
						{
							int pos = file.GetPosition();
							file.Seek(-24, CFile::current);
							bytesRead-=24;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 24; ++c)
						{
							if(buffer[i+c] != MAGIC_64[c])
							{
								break;
							}
							else
							{
								if(c == 23)
								{
									dwOffset += i + 50;
									file.Close();
									//return dwOffset;
								}
							}
						}
					}

				}
			}
			dwOffset += bytesRead;
			bytesRead = file.Read(buffer, 1024);
		}
		file.Close();
	}
	return RET_ERROR;

}
Example #24
0
DWORD ConnectionLimit::GetOffset(LPCTSTR path)
{
	CFile file;
	DWORD dwOffset = 0;
	bool isWow = IsWow64();
	PVOID oldValue = NULL;
	if(isWow)
	{
		MyWow64DisableWow64FsRedirection(&oldValue);
	}

	if(file.Open(path,CFile::modeRead|CFile::typeBinary))
	{
		if(isWow)
		{
			MyWow64RevertWow64FsRedirection(oldValue);
		}
		unsigned int bytesRead = 0;
		char buffer[1024];
		bytesRead = file.Read(buffer, 1024);
		while(bytesRead != 0)
		{
			for (int i = 0; i<bytesRead; ++i)
			{
				if(!isWow && (CAntiSpySettings::GetSuiteType() != CAntiSpySettings::SUITE_TYPE::WINDOWS_VISTA))
				{

					if(buffer[i] == MAGIC_32[0])
					{
						if(i>= (bytesRead - 5))
						{
							int pos = file.GetPosition();
							file.Seek(-5, CFile::current);
							bytesRead-=5;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 6; ++c)
						{
							if(buffer[i+c] != MAGIC_32[c])
							{
								break;
							}
							else
							{
								if(c == 5)
								{
									dwOffset += i + 10;
									file.Close();
									return dwOffset;
								}
							}
						}
					}
				}
				else if(!isWow && (CAntiSpySettings::GetSuiteType() == CAntiSpySettings::SUITE_TYPE::WINDOWS_VISTA))
				{
					if(buffer[i] == VISTA_MAGIC_32[0])
					{
						if(i>= (bytesRead - 8))
						{
							int pos = file.GetPosition();
							file.Seek(-8, CFile::current);
							bytesRead-=8;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 9; ++c)
						{
							if(buffer[i+c] != VISTA_MAGIC_32[c])
							{
								break;
							}
							else
							{
								if(c == 8)
								{
									dwOffset += i + 9;
									file.Close();
									return dwOffset;
								}
							}
						}
					}
				}
				else if(isWow && (CAntiSpySettings::GetSuiteType() != CAntiSpySettings::SUITE_TYPE::WINDOWS_VISTA))
				{
					if(buffer[i] == MAGIC_64[0])
					{
						if(i>= (bytesRead - 24))
						{
							int pos = file.GetPosition();
							file.Seek(-24, CFile::current);
							bytesRead-=24;
							pos = file.GetPosition();
							break;
						}

						for (int c = 1; c < 24; ++c)
						{
							if(buffer[i+c] != MAGIC_64[c])
							{
								break;
							}
							else
							{
								if(c == 23)
								{
									dwOffset += i + 50;
									file.Close();
									return dwOffset;
								}
							}
						}
					}

				}
			}
			dwOffset += bytesRead;
			bytesRead = file.Read(buffer, 1024);
		}
		file.Close();
	}
	return 0;
}
Example #25
0
void Scheme::Load(CScintilla& sc, bool allSettings, LPCTSTR filename)
{
	CFile cfile;
	SchemeHdrRec hdr;
	MsgRec Msg;
	TextRec Txt;
	PropRec Prp;
	char Next2;

	memset(&m_CommentSpec, 0, sizeof(CommentSpecRec));

	if( filename )
	{
		SetFileName(filename);
	}

	if( cfile.Open(m_SchemeFile) )
	{
		// Check the file is OK and read the header.
		if(!InitialLoad(cfile, hdr))
		{
			UNEXPECTED(_T("Tried to load invalid binary scheme file at run-time"));
			cfile.Close();
			return;
		}

		// Set the defaults - these may be changed by the load.
		SetupScintilla(sc, allSettings);

		std::vector<char> buf;

		while (cfile.GetPosition() < cfile.GetLength())
		{
			cfile.Read(&Next2, sizeof(char));
			switch(Next2)
			{
				case nrMsgRec:
					cfile.Read(&Msg, sizeof(MsgRec));
					sc.SPerform(Msg.MsgNum, Msg.wParam, Msg.lParam);
					break;
				case nrTextRec:
					{
						cfile.Read(&Txt, sizeof(TextRec));
						buf.resize(Txt.TextLength + 1);
						cfile.Read(&buf[0], Txt.TextLength*sizeof(char));
						buf[Txt.TextLength] = '\0';
						switch(Txt.TextType)
						{
							case ttFontName : 
								sc.SPerform(SCI_STYLESETFONT, Txt.wParam, (long)&buf[0]);
								break;
							case ttKeywords : 
								sc.SetKeyWords(Txt.wParam, &buf[0]);
								break;
							case ttLexerLanguage : 
								{
									sc.SPerform(SCI_SETLEXERLANGUAGE, 0, (long)&buf[0]);
									m_Lexer = &buf[0];
								}
								break;
							case ttWordChars :
								{
									sc.SPerform(SCI_SETWORDCHARS, 0, (long)&buf[0]);
								}
								break;
						}
					}
					break;
				case nrPropRec:
				{
					cfile.Read(&Prp, sizeof(PropRec));
					buf.resize(Prp.NameLength + 1);
					cfile.Read(&buf[0], Prp.NameLength * sizeof(char));
					buf[Prp.NameLength] = '\0';

					std::vector<char> buf2(Prp.ValueLength + 1);
					cfile.Read(&buf2[0], Prp.ValueLength * sizeof(char));
					buf2[Prp.ValueLength] = '\0';
					sc.SPerform(SCI_SETPROPERTY, (long)&buf[0], (long)&buf2[0]);
				}
				break;
				case nrCommentRec:
				{
					// skip here...
					cfile.Read(&m_CommentSpec, sizeof(CommentSpecRec));
				}
				break;
			}
		}

		cfile.Close();

		if((hdr.Flags & fldEnabled) && OPTIONS->GetCached(Options::OFoldingEnabled))
		{
			///@todo obviously these details need to come from settings somewhere...
			sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold", (LPARAM)"1");
			sc.SPerform(SCI_SETMARGINTYPEN, 2, SC_MARGIN_SYMBOL);
			sc.SPerform(SCI_SETMARGINMASKN, 2, SC_MASK_FOLDERS);
			sc.SPerform(SCI_SETMARGINSENSITIVEN, 2, true);
			sc.SPerform(SCI_SETMARGINWIDTHN, 2, 14);
			sc.SPerform(SCI_SETFOLDFLAGS, 16, 0);
			sc.SetFoldingMargins(efsVSNet);

			sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold.compact", (LPARAM)((hdr.Flags & fldCompact) ? "1" : "0"));
			
			if(hdr.Flags & fldComments)
				sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold.comment", (LPARAM)"1");

			if(hdr.Flags & fldPreProc)
				sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold.preprocessor", (LPARAM)"1");

			if(hdr.Flags & fldElse) 
				sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold.at.else", (LPARAM)"1");
		}

		if(hdr.Flags & schOverrideTabs)
		{
			if(hdr.Flags & schUseTabs)
				sc.SPerform(SCI_SETUSETABS, 1, 0);
			else
				sc.SPerform(SCI_SETUSETABS, 0, 0);
		}

		if(hdr.Flags & schOverrideTabSize)
		{
			sc.SPerform(SCI_SETTABWIDTH, hdr.TabWidth, 0);
		}

	}
	else
	{
		// Show an error or something...
	}
}
Example #26
0
BOOL CInfCreature::Read(CFile &file)
{
	UINT nCount;
	int i;

	UINT nStartPos = file.GetPosition();

	nCount = file.Read(&m_infCre,sizeof(INF_CRE));
	if (nCount != sizeof(INF_CRE))
	{
		m_nError = ERR_CRE_READHEADER;
		return(FALSE);
	}

	if (memcmp(m_infCre.chSignature,"CRE ",4))
	{
		m_nError = ERR_CRE_MISSINGSIG;
		return(FALSE);
	}

	if (!_bIgnoreDataVersions && memcmp(m_infCre.chVersion,"V1.0",4))
	{
		m_nError = ERR_CRE_BADVERSION;
		return(FALSE);
	}

	// Known spells should follow the header.
	if (m_infCre.dwKnownSpellsOffset)
	{
		try { file.Seek(m_infCre.dwKnownSpellsOffset+nStartPos,CFile::begin); }
		catch(CFileException *pe)
		{
			pe->Delete();
			m_nError = ERR_CRE_READBADKNOWN;
			return(FALSE);
		}

		m_pKnownSpells = new INF_CRE_KNOWNSPELL[m_infCre.dwKnownSpellsCount];
		if (!m_pKnownSpells)
		{
			m_nError = ERR_CRE_OOM_KNOWNSPELLS;
			return(FALSE);
		}

		nCount = file.Read(m_pKnownSpells,sizeof(INF_CRE_KNOWNSPELL)*m_infCre.dwKnownSpellsCount);
		if (nCount != sizeof(INF_CRE_KNOWNSPELL)*m_infCre.dwKnownSpellsCount)
		{
			m_nError = ERR_CRE_READKNOWN;
			return(FALSE);
		}
	}

	// Spell memorization information should follow the known spells listing.
	if (m_infCre.dwSpellMemorizationInfoOffset)
	{
		try { file.Seek(m_infCre.dwSpellMemorizationInfoOffset+nStartPos,CFile::begin); }
		catch(CFileException *pe)
		{
			pe->Delete();
			m_nError = ERR_CRE_READBADMEMINFO;
			return(FALSE);
		}

		m_pMemInfo = new INF_CRE_MEMINFO[m_infCre.dwSpellMemorizationInfoCount];
		if (!m_pMemInfo)
		{
			m_nError = ERR_CRE_OOM_MEMINFO;
			return(FALSE);
		}

		nCount = file.Read(m_pMemInfo,sizeof(INF_CRE_MEMINFO)*m_infCre.dwSpellMemorizationInfoCount);
		if (nCount != sizeof(INF_CRE_MEMINFO)*m_infCre.dwSpellMemorizationInfoCount)
		{
			m_nError = ERR_CRE_READMEMINFO;
			return(FALSE);
		}
	}

	// Memorized spells should be next.
	if (m_infCre.dwMemorizedSpellsOffset)
	{
		try { file.Seek(m_infCre.dwMemorizedSpellsOffset+nStartPos,CFile::begin); }
		catch(CFileException *pe)
		{
			pe->Delete();
			m_nError = ERR_CRE_READBADMEM;
			return(FALSE);
		}

		m_pMemSpells = new INF_CRE_MEMSPELL[m_infCre.dwMemorizedSpellsCount];
		if (!m_pMemSpells)
		{
			m_nError = ERR_CRE_OOM_MEMSPELL;
			return(FALSE);
		}

		nCount = file.Read(m_pMemSpells,sizeof(INF_CRE_MEMSPELL)*m_infCre.dwMemorizedSpellsCount);
		if (nCount != sizeof(INF_CRE_MEMSPELL)*m_infCre.dwMemorizedSpellsCount)
		{
			m_nError = ERR_CRE_READMEM;
			return(FALSE);
		}
	}

	///////////////////////////////////////////////////////////////////
	// Convert the CRE data into the SPELLDATA format.
	//

	// Need to first know how many of each type there are so the memory
	// can be allocated.
	// 10/7/2000 - I was assuming that there would be a single entry in
	//		the Known Spells section for each spell known. This is probably 
	//		a safe assumption, as that would mean the same spell in your
	//		book more than once. I hit a problem with a player who had
	//		the same innate spell listed more than once. This caused grief
	//		with the below conversion. The spell counts we get off and the
	//		offsets in the written file would be incorrect. I'm now making	
	//		sure a Known Spell isn't counted more than one time. I suspect
	//		the character that had the duplicates was edited by hand.
	CStringList slKnown[INF_CRE_SPELLTYPES];
	CString strSpell;
	char szSpell[10];
	memset(szSpell,0,10);

	for (i=0;i<(int)m_infCre.dwKnownSpellsCount;i++)
	{
		if (m_pKnownSpells[i].wSpellType >= INF_CRE_SPELLTYPES)
		{
			m_nError = ERR_CRE_UNKNOWNSPELLTYPE;
			return(FALSE);
		}

		// Make sure this spell has not already been counted.
		memcpy(szSpell,m_pKnownSpells[i].chSpellName,8);
		strSpell = szSpell;
		strSpell.MakeUpper();
		if (slKnown[m_pKnownSpells[i].wSpellType].Find(strSpell))
			continue;
		
		slKnown[m_pKnownSpells[i].wSpellType].AddTail((const char *)strSpell);
		m_nSpellCount[m_pKnownSpells[i].wSpellType]++;
	}

	for (i=0;i<INF_CRE_SPELLTYPES;i++)
	{
		if (m_nSpellCount[i])
		{
			m_pSpellData[i] = new SPELLDATA[m_nSpellCount[i]];
			if (!m_pSpellData[i])
			{
				m_nError = ERR_CRE_OOM_SPELLDATA;
				return(FALSE);
			}
			memset(m_pSpellData[i],0,sizeof(SPELLDATA)*m_nSpellCount[i]);
		}
		else
			m_pSpellData[i] = NULL;
	}

	SPELLDATA *pSpellData;
	int nSpellIndex[INF_CRE_SPELLTYPES];
	memset(&nSpellIndex[0],0,sizeof(int)*INF_CRE_SPELLTYPES);
	memset(szSpell,0,10);

	// Fill up the internal structures with all the known spells.
	int j;
	for (i=0;i<(int)m_infCre.dwKnownSpellsCount;i++)
	{
		if (m_pSpellData[m_pKnownSpells[i].wSpellType])
		{
			// See if the spell is already in our list. This is another fix for the
			// multiple copies of the same known spell.
			for (j=0;j<nSpellIndex[m_pKnownSpells[i].wSpellType];j++)
				if (!strnicmp(m_pKnownSpells[i].chSpellName,(m_pSpellData[m_pKnownSpells[i].wSpellType]+j)->szResName,8))
					break;
			// If not at the end of the list, we found a dupliate.
			if (j<nSpellIndex[m_pKnownSpells[i].wSpellType])
				continue;

			pSpellData = m_pSpellData[m_pKnownSpells[i].wSpellType] + nSpellIndex[m_pKnownSpells[i].wSpellType];

			pSpellData->nTimesMemorized = 0;
			pSpellData->nTimesCanCast = 0;
			memcpy(szSpell,m_pKnownSpells[i].chSpellName,8);
			strcpy(pSpellData->szResName,szSpell);
			pSpellData->wLevel = m_pKnownSpells[i].wSpellLevel;
			pSpellData->wType = m_pKnownSpells[i].wSpellType;

			nSpellIndex[m_pKnownSpells[i].wSpellType]++;
		}
	}

	// If there were any duplicates in the number of known spells the count needs to
	// be changed. The editor will trim out those duplicates when it saves.
	m_infCre.dwKnownSpellsCount = 0;
	for (i=0;i<INF_CRE_SPELLTYPES;i++)
		m_infCre.dwKnownSpellsCount += m_nSpellCount[i];

	// Find all the memorized spells and count up the times memorized.
	int k;
	BOOL bFoundSpell;
	for (i=0;i<(int)m_infCre.dwMemorizedSpellsCount;i++)
	{
		// Find it in the new lists.
		bFoundSpell = FALSE;
		for (j=0;j<INF_CRE_SPELLTYPES;j++)
			for (k=0;k<m_nSpellCount[j];k++)
				if (m_pSpellData[j] && !strnicmp((m_pMemSpells+i)->chSpellName,(m_pSpellData[j]+k)->szResName,8))
				{
					(m_pSpellData[j]+k)->nTimesMemorized++;
					if (m_pMemSpells[i].dwMemorized)
						(m_pSpellData[j]+k)->nTimesCanCast++;
					bFoundSpell = TRUE;
				}

		// If we didn't find the spell in the list then the spell is a memorized
		// but known spell, which is how the sequencers seem to work. To keep it 
		// simple, since we are not editing this list, each of the spells has its
		// own entry in the list. If there are 2 of the same spell, there are two
		// entries in the list (the other spells have 1 entry with a count of the
		// number of times memorized).
		if (!bFoundSpell)
		{
			pSpellData = new SPELLDATA;
			memset(pSpellData,0,sizeof(SPELLDATA));
			memset(szSpell,0,10);

			// The data members are not important other than the spell name. I'm going
			// to assume that if it is mem'd but not known, that it is currently
			// castable. I'm staying with the SPELLDATA structure just for consistency
			// and to have it set up to track data for possible future changes (rather
			// than just keeping a string list of all the spell names).
			memcpy(szSpell,m_pMemSpells[i].chSpellName,8);
			strcpy(pSpellData->szResName,szSpell);

			m_plMemButNotKnown.AddTail(pSpellData);
		}
	}

	delete [] m_pKnownSpells;
	m_pKnownSpells = NULL;
	delete [] m_pMemSpells;
	m_pMemSpells = NULL;

	// This needs to be called to refresh all the counts and indices. The values
	// here will be wrong if the above found any duplicate known spells or mem'd
	// but not known spells.
	UpdateSpellInfo();

	// Item slots next.
	try { file.Seek(m_infCre.dwItemSlotsOffset+nStartPos,CFile::begin); }
	catch(CFileException *pe)
	{
		pe->Delete();
		m_nError = ERR_CRE_READBADITEMSLOTS;
		return(FALSE);
	}

	nCount = file.Read(&m_infItemSlots,sizeof(INF_CRE_ITEMSLOTS));
	if (nCount != sizeof(INF_CRE_ITEMSLOTS))
	{
		m_nError = ERR_CRE_READITEMSLOTS;
		return(FALSE);
	}

	// Item listing next.
	if (m_infCre.dwItemsCount)
	{
		try { file.Seek(m_infCre.dwItemsOffset+nStartPos,CFile::begin); }
		catch(CFileException *pe)
		{
			pe->Delete();
			m_nError = ERR_CRE_READBADITEMLIST;
			return(FALSE);
		}

		if (m_infCre.dwItemsCount > INF_NUM_ITEMSLOTS)
		{
			m_nError = ERR_CRE_READTOOMANYITEMS;
			return(FALSE);
		}

		for (i=0;i<(int)m_infCre.dwItemsCount;i++)
		{
			nCount = file.Read(&m_infItems[i],sizeof(INF_CRE_ITEM));
			if (nCount != sizeof(INF_CRE_ITEM))
			{
				m_nError = ERR_CRE_READITEM;
				return(FALSE);
			}
		}
	}

	if (m_infCre.dwAffectCount)
	{
		try { file.Seek(m_infCre.dwAffectOffset+nStartPos,CFile::begin); }
		catch(CFileException *pe)
		{
			pe->Delete();
			m_nError = ERR_CRE_READBADAFFECTS;
			return(FALSE);
		}

		INF_AFF *pAff;
		for (i=0;i<(int)m_infCre.dwAffectCount;i++)
		{
			pAff = new INF_AFF;
			if (!pAff)
			{
				m_nError = ERR_CRE_OOM_AFFECTS;
				return(FALSE);
			}

			nCount = file.Read(pAff,sizeof(INF_AFF));
			if (nCount != sizeof(INF_AFF))
			{
				m_nError = ERR_CRE_READAFFECTS;
				return(FALSE);
			}

			m_plAffects.AddTail(pAff);
		}
	}

	m_bHasChanged = FALSE;
	return(TRUE);
}
Example #27
0
bool CZipManager::GetZipList(const CURL& url, vector<SZipEntry>& items)
{
  CLog::Log(LOGDEBUG, "%s - Processing %s", __FUNCTION__, url.GetRedacted().c_str());

  struct __stat64 m_StatData = {};

  std::string strFile = url.GetHostName();

  if (CFile::Stat(strFile,&m_StatData))
  {
    CLog::Log(LOGDEBUG,"CZipManager::GetZipList: failed to stat file %s", url.GetRedacted().c_str());
    return false;
  }

  map<std::string,vector<SZipEntry> >::iterator it = mZipMap.find(strFile);
  if (it != mZipMap.end()) // already listed, just return it if not changed, else release and reread
  {
    map<std::string,int64_t>::iterator it2=mZipDate.find(strFile);
    CLog::Log(LOGDEBUG,"statdata: %" PRId64" new: %" PRIu64, it2->second, (uint64_t)m_StatData.st_mtime);

      if (m_StatData.st_mtime == it2->second)
      {
        items = it->second;
        return true;
      }
      mZipMap.erase(it);
      mZipDate.erase(it2);
  }

  CFile mFile;
  if (!mFile.Open(strFile))
  {
    CLog::Log(LOGDEBUG,"ZipManager: unable to open file %s!",strFile.c_str());
    return false;
  }

  unsigned int hdr;
  if (mFile.Read(&hdr, 4)!=4 || (Endian_SwapLE32(hdr) != ZIP_LOCAL_HEADER &&
                                 Endian_SwapLE32(hdr) != ZIP_DATA_RECORD_HEADER &&
                                 Endian_SwapLE32(hdr) != ZIP_SPLIT_ARCHIVE_HEADER))
  {
    CLog::Log(LOGDEBUG,"ZipManager: not a zip file!");
    mFile.Close();
    return false;
  }

  if (Endian_SwapLE32(hdr) == ZIP_SPLIT_ARCHIVE_HEADER)
    CLog::LogF(LOGWARNING, "ZIP split archive header found. Trying to process as a single archive..");

  // push date for update detection
  mZipDate.insert(make_pair(strFile,m_StatData.st_mtime));


  // Look for end of central directory record
  // Zipfile comment may be up to 65535 bytes
  // End of central directory record is 22 bytes (ECDREC_SIZE)
  // -> need to check the last 65557 bytes
  int64_t fileSize = mFile.GetLength();
  // Don't need to look in the last 18 bytes (ECDREC_SIZE-4)
  // But as we need to do overlapping between blocks (3 bytes),
  // we start the search at ECDREC_SIZE-1 from the end of file
  int searchSize = (int) min(65557, fileSize-ECDREC_SIZE+1);
  int blockSize = (int) min(1024, searchSize);
  int nbBlock = searchSize / blockSize;
  int extraBlockSize = searchSize % blockSize;
  // Signature is on 4 bytes
  // It could be between 2 blocks, so we need to read 3 extra bytes
  auto_buffer buffer(blockSize + 3);
  bool found = false;

  // Loop through blocks starting at the end of the file (minus ECDREC_SIZE-1)
  for (int nb=1; !found && (nb <= nbBlock); nb++)
  {
    mFile.Seek(fileSize-ECDREC_SIZE+1-(blockSize*nb),SEEK_SET);
    if (mFile.Read(buffer.get(), blockSize + 3) != blockSize + 3)
      return false;
    for (int i=blockSize-1; !found && (i >= 0); i--)
    {
      if ( Endian_SwapLE32(*((unsigned int*)(buffer.get()+i))) == ZIP_END_CENTRAL_HEADER )
      {
        // Set current position to start of end of central directory
        mFile.Seek(fileSize-ECDREC_SIZE+1-(blockSize*nb)+i,SEEK_SET);
        found = true;
      }
    }
  }

  // If not found, look in the last block left...
  if ( !found && (extraBlockSize > 0) )
  {
    mFile.Seek(fileSize-ECDREC_SIZE+1-searchSize,SEEK_SET);
    if (mFile.Read(buffer.get(), extraBlockSize + 3) != extraBlockSize + 3)
      return false;
    for (int i=extraBlockSize-1; !found && (i >= 0); i--)
    {
      if ( Endian_SwapLE32(*((unsigned int*)(buffer.get()+i))) == ZIP_END_CENTRAL_HEADER )
      {
        // Set current position to start of end of central directory
        mFile.Seek(fileSize-ECDREC_SIZE+1-searchSize+i,SEEK_SET);
        found = true;
      }
    }
  }

  buffer.clear();

  if ( !found )
  {
    CLog::Log(LOGDEBUG,"ZipManager: broken file %s!",strFile.c_str());
    mFile.Close();
    return false;
  }

  unsigned int cdirOffset, cdirSize;
  // Get size of the central directory
  mFile.Seek(12,SEEK_CUR);
  if (mFile.Read(&cdirSize, 4) != 4)
    return false;
  cdirSize = Endian_SwapLE32(cdirSize);
  // Get Offset of start of central directory with respect to the starting disk number
  if (mFile.Read(&cdirOffset, 4) != 4)
    return false;
  cdirOffset = Endian_SwapLE32(cdirOffset);

  // Go to the start of central directory
  mFile.Seek(cdirOffset,SEEK_SET);

  char temp[CHDR_SIZE];
  while (mFile.GetPosition() < cdirOffset + cdirSize)
  {
    SZipEntry ze;
    if (mFile.Read(temp, CHDR_SIZE) != CHDR_SIZE)
      return false;
    readCHeader(temp, ze);
    if (ze.header != ZIP_CENTRAL_HEADER)
    {
      CLog::Log(LOGDEBUG,"ZipManager: broken file %s!",strFile.c_str());
      mFile.Close();
      return false;
    }

    // Get the filename just after the central file header
    auto_buffer bufName(ze.flength);
    if (mFile.Read(bufName.get(), ze.flength) != ze.flength)
      return false;
    std::string strName(bufName.get(), bufName.size());
    bufName.clear();
    g_charsetConverter.unknownToUTF8(strName);
    ZeroMemory(ze.name, 255);
    strncpy(ze.name, strName.c_str(), strName.size()>254 ? 254 : strName.size());

    // Jump after central file header extra field and file comment
    mFile.Seek(ze.eclength + ze.clength,SEEK_CUR);

    items.push_back(ze);
  }

  /* go through list and figure out file header lengths */
  for(vector<SZipEntry>::iterator it = items.begin(); it != items.end(); ++it)
  {
    SZipEntry& ze = *it;
    // Go to the local file header to get the extra field length
    // !! local header extra field length != central file header extra field length !!
    mFile.Seek(ze.lhdrOffset+28,SEEK_SET);
    if (mFile.Read(&(ze.elength), 2) != 2)
      return false;
    ze.elength = Endian_SwapLE16(ze.elength);

    // Compressed data offset = local header offset + size of local header + filename length + local file header extra field length
    ze.offset = ze.lhdrOffset + LHDR_SIZE + ze.flength + ze.elength;

  }

  mZipMap.insert(make_pair(strFile,items));
  mFile.Close();
  return true;
}
Example #28
0
bool CZipManager::GetZipList(const CStdString& strPath, std::vector<SZipEntry>& items)
{
  CURL url(strPath);
  __stat64 m_StatData;

  CStdString strFile = url.GetHostName();
 
  std::map<CStdString,std::vector<SZipEntry> >::iterator it = mZipMap.find(strFile);
  if (it != mZipMap.end()) // already listed, just return it if not changed, else release and reread
  {
    std::map<CStdString,__int64>::iterator it2=mZipDate.find(strFile);
    if (CFile::Stat(strFile,&m_StatData))
#ifndef _LINUX
      CLog::Log(LOGDEBUG,"statdata: %i, new: %i",it2->second,m_StatData.st_mtime);
#else
      CLog::Log(LOGDEBUG,"statdata: %llu new: %llu",it2->second,m_StatData._st_mtime);
#endif
#ifndef _LINUX
      if (m_StatData.st_mtime == it2->second)
#else
      if (m_StatData._st_mtime == it2->second)
#endif
      {
        items = it->second;
        return true;
      }
      mZipMap.erase(it);
      mZipDate.erase(it2);
  }

  CFile mFile;
  if (!mFile.Open(strFile))
  {
    CLog::Log(LOGDEBUG,"ZipManager: unable to open file %s!",strFile.c_str());
    return false;
  }

  SZipEntry ze;
  char temp[30];
  mFile.Read(temp,30);
  readHeader(temp, ze);
  if( ze.header != ZIP_LOCAL_HEADER ) 
  {      
    CLog::Log(LOGDEBUG,"ZipManager: not a zip file!");
    mFile.Close();
    return false;
  }
  // push date for update detection
  CFile::Stat(strFile,&m_StatData);
#ifndef _LINUX
  mZipDate.insert(std::make_pair<CStdString,__int64>(strFile,m_StatData.st_mtime));
#else
  mZipDate.insert(std::make_pair<CStdString,__int64>(strFile,m_StatData._st_mtime));
#endif
  
  // now list'em
  mFile.Seek(0,SEEK_SET);
  CStdString strSkip;

  while (mFile.GetPosition() != mFile.GetLength())
  {
    mFile.Read(temp,30);
    readHeader(temp, ze);
    if (ze.header != ZIP_LOCAL_HEADER)
    {
      if (ze.header != ZIP_CENTRAL_HEADER)
      {
        CLog::Log(LOGDEBUG,"ZipManager: broken file %s!",strFile.c_str());
        return false;
      }
      else // no handling of zip central header, we are done
      {        
        mZipMap.insert(std::make_pair<CStdString,std::vector<SZipEntry> >(strFile,items));
        mFile.Close();
        return true;
      }
    }
    CStdString strName;
    mFile.Read(strName.GetBuffer(ze.flength), ze.flength);
    strName.ReleaseBuffer();
    g_charsetConverter.stringCharsetToUtf8(strName);
    ZeroMemory(ze.name, 255);
    strncpy(ze.name, strName.c_str(), strName.size()>254 ? 254 : strName.size());
    mFile.Seek(ze.elength,SEEK_CUR);
    ze.offset = mFile.GetPosition();
    mFile.Seek(ze.csize,SEEK_CUR);
    if (ze.flags & 8)
    {
      mFile.Read(&ze.crc32,4);
      mFile.Read(&ze.csize,4);
      mFile.Read(&ze.usize,4);
    }
    items.push_back(ze);
  }
  mFile.Close();
  return false; // should never get here with healthy .zips until central header is dealt with
}
BOOL CPreviewThread::Run()
{
	//Xman
	// BEGINSLUGFILLER: SafeHash
	CReadWriteLock lock(&theApp.m_threadlock);
	if (!lock.ReadLock(0))
		return 0;
	// END SLUGFILLER: SafeHash

	ASSERT (m_pPartfile) ;
	CFile destFile;
	CFile srcFile;
	if (!srcFile.Open(m_pPartfile->GetFilePath(), CFile::modeRead | CFile::shareDenyNone))
		return FALSE;
	try{
		uint64 nSize = m_pPartfile->GetFileSize();
		CString strExtension = CString(_tcsrchr(m_pPartfile->GetFileName(), _T('.')));
		CString strPreviewName = m_pPartfile->GetTempPath() + m_pPartfile->GetFileName().Mid(0, 5) + _T("_preview") + strExtension;
		bool bFullSized = true;
		if (!strExtension.CompareNoCase(_T(".mpg")) || !strExtension.CompareNoCase(_T(".mpeg")))
			bFullSized = false;
		if (!destFile.Open(strPreviewName, CFile::modeWrite | CFile::shareDenyWrite | CFile::modeCreate))
			return FALSE;
		srcFile.SeekToBegin();
		if (bFullSized)
			destFile.SetLength(nSize);
		destFile.SeekToBegin();
		BYTE abyBuffer[4096];
		uint32 nRead;
		while (destFile.GetPosition()+4096 < PARTSIZE*2){
			nRead = srcFile.Read(abyBuffer,4096);
			destFile.Write(abyBuffer,nRead);
		}
		srcFile.Seek(-(LONGLONG)(PARTSIZE*2), CFile::end);
		uint32 nToGo = PARTSIZE*2;
		if (bFullSized)
			destFile.Seek(-(LONGLONG)(PARTSIZE*2), CFile::end);
		do{
			nRead = (nToGo - 4096 < 1)? nToGo:4096;
			nToGo -= nRead;
			nRead = srcFile.Read(abyBuffer,4096);
			destFile.Write(abyBuffer,nRead);
		}
		while (nToGo);
		destFile.Close();
		srcFile.Close();
		m_pPartfile->m_bPreviewing = false;

		SHELLEXECUTEINFO SE = {0};
		SE.fMask = SEE_MASK_NOCLOSEPROCESS;

		CString strCommand;
		CString strArgs;
		CString strCommandDir;
		if (!m_strCommand.IsEmpty())
		{
			SE.lpVerb = _T("open");	// "open" the specified video player

			// get directory of video player application
			strCommandDir = m_strCommand;
			int iPos = strCommandDir.ReverseFind(_T('\\'));
			if (iPos == -1)
				strCommandDir.Empty();
			else
				strCommandDir = strCommandDir.Left(iPos + 1);
			PathRemoveBackslash(strCommandDir.GetBuffer());
			strCommandDir.ReleaseBuffer();

			strArgs = m_strCommandArgs;
			if (!strArgs.IsEmpty())
				strArgs += _T(' ');
			if (strPreviewName.Find(_T(' ')) != -1)
				strArgs += _T('\"') + strPreviewName + _T('\"');
			else
				strArgs += strPreviewName;

			strCommand = m_strCommand;
			ExpandEnvironmentStrings(strCommand);
			ExpandEnvironmentStrings(strArgs);
			ExpandEnvironmentStrings(strCommandDir);
			SE.lpFile = strCommand;
			SE.lpParameters = strArgs;
			SE.lpDirectory = strCommandDir;
		}
		else
		{
			SE.lpVerb = NULL;	// use the default verb or the open verb for the document
			SE.lpFile = strPreviewName;
		}
		SE.nShow = SW_SHOW;
		SE.cbSize = sizeof(SE);
		ShellExecuteEx(&SE);
		if (SE.hProcess){
			WaitForSingleObject(SE.hProcess, INFINITE);
			CloseHandle(SE.hProcess);
		}
		CFile::Remove(strPreviewName);
	}
	catch(CFileException* error){
		m_pPartfile->m_bPreviewing = false;
		error->Delete();
	}
	return TRUE;
}
Example #30
0
 CFile cfile;
 cfile.Open(_T("Seek_File.dat"), CFile::modeCreate |
    CFile::modeReadWrite);
 LONGLONG lOffset = 1000;
 ULONGLONG lActual;
 lActual = cfile.Seek(lOffset, CFile::begin);
 ASSERT(cfile.GetPosition() == lActual);