Ejemplo n.º 1
0
BOOL CCustomAutoComplete::SaveList(LPCTSTR pcFileName)
{
#ifdef _UNICODE
	FILE	*fp = _tfsopen(pcFileName, _T("wb"), _SH_DENYWR);
#else
	FILE	*fp = _tfsopen(pcFileName, _T("w"), _SH_DENYWR);
#endif

	if (fp == NULL)
		return FALSE;

#ifdef _UNICODE
//	Write Unicode byte-order mark 0xFEFF
	fputwc(0xFEFF, fp);

#endif
	for (int i = 0; i < m_asList.GetCount(); i++)
#ifdef _UNICODE
		_ftprintf(fp, _T("%s\r\n"), m_asList[i]);
#else
		_ftprintf(fp, _T("%s\n"), m_asList[i]);
#endif
	fclose(fp);

	return (ferror(fp) == 0);
}
Ejemplo n.º 2
0
FILE * __cdecl _tfopen (
	const _TSCHAR *file,
	const _TSCHAR *mode
	)
{
#ifdef _POSIX_
	return( _tfsopen(file, mode) );
#else
	return( _tfsopen(file, mode, _SH_DENYNO) );
#endif
}
Ejemplo n.º 3
0
HRESULT CPixelShaderCompiler::CompileShaderFromFile(
    LPCTSTR pSrcFile,
    LPCSTR pEntrypoint,
    LPCSTR pProfile,
    DWORD Flags,
    IDirect3DPixelShader9** ppPixelShader,
    CString* pDisasm,
    CString* pErrMsg)
{
    HRESULT ret = E_FAIL;
    if (FILE* fp = _tfsopen(pSrcFile, _T("rb"), _SH_SECURE)) {
        VERIFY(fseek(fp, 0, SEEK_END) == 0);
        long size = ftell(fp);
        rewind(fp);
        if (size > 0) {
            auto data = new(std::nothrow) char[(size_t)size];
            if (data) {
                if (fread(data, size, 1, fp) == 1) {
                    ret = InternalCompile(data, (size_t)size, CT2A(pSrcFile), pEntrypoint,
                                          pProfile, Flags, ppPixelShader, pDisasm, pErrMsg);
                } else {
                    ASSERT(FALSE);
                }
                delete[] data;
            } else {
                ASSERT(FALSE);
            }
        }
        VERIFY(fclose(fp) == 0);
    }
    return ret;
}
Ejemplo n.º 4
0
CString GitAdminDir::ReadGitLink(const CString& topDir, const CString& dotGitPath)
{
	CAutoFILE pFile = _tfsopen(dotGitPath, _T("r"), SH_DENYWR);

	if (!pFile)
		return _T("");

	int size = 65536;
	auto buffer = std::make_unique<char[]>(size);
	int length = (int)fread(buffer.get(), sizeof(char), size, pFile);
	CStringA gitPathA(buffer.get(), length);
	if (length < 8 || gitPathA.Left(8) != "gitdir: ")
		return _T("");
	CString gitPath = CUnicodeUtils::GetUnicode(gitPathA);
	// trim after converting to UTF-16, because CStringA trim does not work when having UTF-8 chars
	gitPath = gitPath.Trim().Mid(8); // 8 = len("gitdir: ")
	gitPath.Replace('/', '\\');
	gitPath.TrimRight('\\');
	if (!gitPath.IsEmpty() && gitPath[0] == _T('.'))
	{
		gitPath = topDir + _T("\\") + gitPath;
		CString adminDir;
		PathCanonicalize(CStrBuf(adminDir, MAX_PATH), gitPath);
		return adminDir;
	}
	return gitPath;
}
Ejemplo n.º 5
0
bool CServerList::SaveStaticServers()
{
	bool bResult = false;

	FILE* fpStaticServers = _tfsopen(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("staticservers.dat"), _T("wb"), _SH_DENYWR);
	if (fpStaticServers == NULL) {
		LogError(LOG_STATUSBAR, GetResString(IDS_ERROR_SSF));
		return bResult;
	}

	// write Unicode byte-order mark 0xFEFF
	if (fputwc(0xFEFF, fpStaticServers) != _TEOF)
	{
		bResult = true;
		POSITION pos = list.GetHeadPosition();
		while (pos)
		{
			const CServer* pServer = list.GetNext(pos);
			if (pServer->IsStaticMember())
			{
				if (_ftprintf(fpStaticServers, _T("%s:%i,%i,%s\r\n"), pServer->GetAddress(), pServer->GetPort(), pServer->GetPreference(), pServer->GetListName()) == EOF) {
					bResult = false;
					break;
				}
			}
		}
	}

	fclose(fpStaticServers);
	return bResult;
}
Ejemplo n.º 6
0
void CIPFilter::SaveToDefaultFile()
{
	CString strFilePath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + DFLT_IPFILTER_FILENAME;
	FILE* fp = _tfsopen(strFilePath, _T("wt"), _SH_DENYWR);
	if (fp != NULL)
	{
		for (int i = 0; i < m_iplist.GetCount(); i++)
		{
			const SIPFilter* flt = m_iplist[i];

			CHAR szStart[16];
			ipstrA(szStart, _countof(szStart), htonl(flt->start));

			CHAR szEnd[16];
			ipstrA(szEnd, _countof(szEnd), htonl(flt->end));

			if (fprintf(fp, "%-15s - %-15s , %3u , %s\n", szStart, szEnd, flt->level, flt->desc) == 0 || ferror(fp))
			{
				CString strError;
				strError.Format(_T("Failed to save IP filter to file \"%s\" - %s"), strFilePath, _tcserror(errno));
				throw strError;
			}
		}
		fclose(fp);
		m_bModified = false;
	}
	else
	{
		CString strError;
		strError.Format(_T("Failed to save IP filter to file \"%s\" - %s"), strFilePath, _tcserror(errno));
		throw strError;
	}
}
Ejemplo n.º 7
0
bool CHTRichEditCtrl::SaveLog(LPCTSTR pszDefName)
{
	bool bResult = false;
	CFileDialog dlg(FALSE, _T("log"), pszDefName ? pszDefName : (LPCTSTR)m_strTitle, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("Log Files (*.log)|*.log||"), this, 0);
	if (dlg.DoModal() == IDOK)
	{
		FILE* fp = _tfsopen(dlg.GetPathName(), _T("wb"), _SH_DENYWR);
		if (fp)
		{
			// write Unicode byte-order mark 0xFEFF
			fputwc(0xFEFF, fp);

			CString strText;
			GetWindowText(strText);
			fwrite(strText, sizeof(TCHAR), strText.GetLength(), fp);
			if (ferror(fp)){
				CString strError;
				strError.Format(_T("Failed to write log file \"%s\" - %s"), dlg.GetPathName(), _tcserror(errno));
				AfxMessageBox(strError, MB_ICONERROR);
			}
			else
				bResult = true;
			fclose(fp);
		}
		else{
			CString strError;
			strError.Format(_T("Failed to create log file \"%s\" - %s"), dlg.GetPathName(), _tcserror(errno));
			AfxMessageBox(strError, MB_ICONERROR);
		}
	}
	return bResult;
}
Ejemplo n.º 8
0
bool CServerListCtrl::StaticServerFileAppend(CServer *server)
{
	try
	{
		// Remove any entry before writing to avoid duplicates
		StaticServerFileRemove(server);

		FILE* staticservers = _tfsopen(thePrefs.GetConfigDir() + _T("staticservers.dat"), _T("a"), _SH_DENYWR);
		if (staticservers==NULL) 
		{
			LogError(LOG_STATUSBAR, GetResString(IDS_ERROR_SSF));
			return false;
		}
		
		if (_ftprintf(staticservers,
					_T("%s:%i,%i,%s\n"),
					server->GetAddress(),
					server->GetPort(), 
					server->GetPreferences(),
					server->GetListName()) != EOF) 
		{
			AddLogLine(false, _T("'%s:%i,%s' %s"), server->GetAddress(), server->GetPort(), server->GetListName(), GetResString(IDS_ADDED2SSF));
			server->SetIsStaticMember(true);
			theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(server);
		}

		fclose(staticservers);
	}
	catch (...)
	{
		ASSERT(0);
		return false;
	}
	return true;
}
Ejemplo n.º 9
0
void CPerfLog::WriteSamples(UINT nCurDn, UINT nCurUp, UINT nCurDnOH, UINT nCurUpOH)
{
	ASSERT( m_bInitialized );

	if (m_eFileFormat == CSV)
	{
		time_t tNow = time(NULL);
		char szTime[40];
		// do not localize this date/time string!
		strftime(szTime, ARRSIZE(szTime), "%m/%d/%Y %H:%M:%S", localtime(&tNow));

		FILE* fp = _tfsopen(m_strFilePath, (m_eMode == OneSample) ? _T("wt") : _T("at"), _SH_DENYWR);
		if (fp == NULL){
			LogError(false, _T("Failed to open performance log file \"%s\" - %s"), m_strFilePath, _tcserror(errno));
			return;
		}
		setvbuf(fp, NULL, _IOFBF, 16384); // ensure that all lines are written to file with one call
		if (m_eMode == OneSample || _filelength(_fileno(fp)) == 0)
			fprintf(fp, "\"(PDH-CSV 4.0)\",\"DatDown\",\"DatUp\",\"OvrDown\",\"OvrUp\"\n");
		fprintf(fp, "\"%s\",\"%u\",\"%u\",\"%u\",\"%u\"\n", szTime, nCurDn, nCurUp, nCurDnOH, nCurUpOH);
		fclose(fp);
	}
	else
	{
		ASSERT( m_eFileFormat == MRTG );

		FILE* fp = _tfsopen(m_strMRTGDataFilePath, (m_eMode == OneSample) ? _T("wt") : _T("at"), _SH_DENYWR);
		if (fp != NULL) {
			fprintf(fp, "%u\n%u\n\n\n", nCurDn, nCurUp);
			fclose(fp);
		}
		else {
			LogError(false, _T("Failed to open performance log file \"%s\" - %s"), m_strMRTGDataFilePath, _tcserror(errno));
		}

		fp = _tfsopen(m_strMRTGOverheadFilePath, (m_eMode == OneSample) ? _T("wt") : _T("at"), _SH_DENYWR);
		if (fp != NULL) {
			fprintf(fp, "%u\n%u\n\n\n", nCurDnOH, nCurUpOH);
			fclose(fp);
		}
		else {
			LogError(false, _T("Failed to open performance log file \"%s\" - %s"), m_strMRTGOverheadFilePath, _tcserror(errno));
		}
	}
}
Ejemplo n.º 10
0
bool CLogFile::Open()
{
	if (m_fp != NULL)
		return true;

	m_fp = _tfsopen(m_strFilePath, _T("a+b"), _SH_DENYWR);
	if (m_fp != NULL)
	{
		m_tStarted = time(NULL);
		m_uBytesWritten = _filelength(_fileno(m_fp));
		if (m_uBytesWritten == 0)
		{
			if (m_eFileFormat == Unicode)
			{
				// write Unicode byte-order mark 0xFEFF
				fputwc(0xFEFF, m_fp);
			}
			else
			{
				ASSERT( m_eFileFormat == Utf8 );
				; // could write UTF-8 header..
			}
		}
		else if (m_uBytesWritten >= sizeof(WORD))
		{
			// check for Unicode byte-order mark 0xFEFF
			WORD wBOM;
			if (fread(&wBOM, sizeof(wBOM), 1, m_fp) == 1)
			{
				if (wBOM == 0xFEFF && m_eFileFormat == Unicode)
				{
					// log file already in Unicode format
					(void)fseek(m_fp, 0, SEEK_END); // actually not needed because file is opened in 'Append' mode..
				}
				else if (wBOM != 0xFEFF && m_eFileFormat != Unicode)
				{
					// log file already in UTF-8 format
					(void)fseek(m_fp, 0, SEEK_END); // actually not needed because file is opened in 'Append' mode..
				}
				else
				{
					// log file does not have the required format, create a new one (with the req. format)
					ASSERT( (m_eFileFormat==Unicode && wBOM!=0xFEFF) || (m_eFileFormat==Utf8 && wBOM==0xFEFF) );

					ASSERT( !m_bInOpenCall );
					if (!m_bInOpenCall) // just for safety
					{
						m_bInOpenCall = true;
						StartNewLogFile();
						m_bInOpenCall = false;
					}
				}
			}
		}
	}
	return m_fp != NULL;
}
Ejemplo n.º 11
0
static int LoadSignature(const CString &signatureFilename, signature_packet_t *p_sig)
{
	FILE * pFile = _tfsopen(signatureFilename, _T("rb"), SH_DENYWR);
	if (pFile)
	{
		int size = 65536;
		std::unique_ptr<unsigned char[]> buffer(new unsigned char[size]);
		int length = 0;
		if ((length = (int)fread(buffer.get(), sizeof(char), size, pFile)) >= 8)
		{
			fclose(pFile);
			// is unpacking needed?
			if ((uint8_t)buffer[0] < 0x80)
			{
				std::unique_ptr<unsigned char[]> unpacked(new unsigned char[size]);
				size = pgp_unarmor((char *)buffer.get(), length, unpacked.get(), length);

				if (size < 2)
					return -1;

				buffer.swap(unpacked);
			}
			else
				size = length;

			if (packet_type(buffer[0]) != SIGNATURE_PACKET)
				return -1;

			DWORD i_header_len = packet_header_len(buffer[0]);
			if ((i_header_len != 1 && i_header_len != 2 && i_header_len != 4) || i_header_len + 1 > (DWORD)size)
				return -1;

			DWORD i_len = scalar_number((uint8_t *)(buffer.get() + 1), i_header_len);
			if (i_len + i_header_len + 1 != (DWORD)size)
				return -1;

			if (parse_signature_packet(p_sig, (uint8_t *)(buffer.get() + 1 + i_header_len), i_len))
				return -1;

			if (p_sig->type != BINARY_SIGNATURE && p_sig->type != TEXT_SIGNATURE)
			{
				if (p_sig->version == 4)
				{
					free(p_sig->specific.v4.hashed_data);
					free(p_sig->specific.v4.unhashed_data);
				}
				return -1;
			}

			return 0;
		}
		else
			fclose(pFile);
	}
	return -1;
}
Ejemplo n.º 12
0
	BOOL CDuiAutoComplete::SaveList(LPCTSTR pszFileName)
	{
		FILE* fp = _tfsopen(pszFileName, _T("wb"), _SH_DENYWR);
		if (fp == NULL)
			return FALSE;

		// д Unicode ±àÂë×Ö½ÚÐò mark 0xFEFF
		fputwc(0xFEFF, fp);

		for (int i = 0; i < m_sStringArrayMap.GetSize(); i++)
			_ftprintf(fp, _T("%s\r\n"), m_sStringArrayMap[i]);
		fclose(fp);
		return !ferror(fp);
	}
Ejemplo n.º 13
0
BOOL CCustomAutoComplete::SaveList(LPCTSTR pszFileName)
{
	FILE* fp = _tfsopen(pszFileName, _T("wb"), _SH_DENYWR);
	if (fp == NULL)
		return FALSE;

	// write Unicode byte-order mark 0xFEFF
	fputwc(0xFEFF, fp);

	for (int i = 0; i < m_asList.GetCount(); i++)
		_ftprintf(fp, _T("%s\r\n"), m_asList[i]);
	fclose(fp);
	return !ferror(fp);
}
Ejemplo n.º 14
0
BOOL CCustomAutoComplete::LoadList(LPCTSTR pcFileName)
{
#ifdef _UNICODE
	FILE	*fp = _tfsopen(pcFileName, _T("rb"), _SH_DENYWR);
#else
	FILE	*fp = _tfsopen(pcFileName, _T("r"), _SH_DENYWR);
#endif

	if (fp == NULL)
		return FALSE;

#ifdef _UNICODE
//	Verify Unicode byte-order mark 0xFEFF
	WORD	wBOM = fgetwc(fp);

//	If not UNICODE file, set reading to ASCII mode
	if (wBOM != 0xFEFF)
	{
		_setmode(_fileno(fp), _O_TEXT);
		fseek(fp, 0, SEEK_SET);
	}

#endif
	CString strItem;

	while (_fgetts(strItem.GetBufferSetLength(256), 256, fp) != NULL)
	{
		strItem.ReleaseBuffer();
		strItem.Trim(_T(" \r\n"));
		AddItem(strItem, -1);
	}

	fclose(fp);

	return TRUE;
}
Ejemplo n.º 15
0
Archivo: Log.cpp Proyecto: zyy329/Tools
const CLog::SOpenFile* CLog::GetLogFile( EErrorMsg_Type eType )
{
    static SOpenFile* pOpenFile;
    pOpenFile = NULL;

    // 日志文件对象获得
    if ( eType > eERROR_MSG_TYPE_START && eType < eERROR_MSG_TYPE_NUMBERS )
    {
        MapLogFileItr itr = m_mapLogFile.find( eType );

        if ( itr != m_mapLogFile.end() )
        {
            // 获得已打开的日志文件对象
            pOpenFile = &(itr->second);
        }
        else
        {
            // 创建新日志文件对象
            pair<MapLogFileItr, bool> ret = m_mapLogFile.insert( make_pair(eType, SOpenFile()) );
            if ( ret.second == true )
            {
                pOpenFile = &(ret.first->second);
            }
        }
    }

    // 日志文件指针维护
    CTime tempTime = CTime::GetCurrentTime();
    if( pOpenFile != NULL )
    {
        // 日志文件维护
        if ( pOpenFile->pFile == NULL || (pOpenFile->cTime.GetDay() != tempTime.GetDay()) )
        {
            if(pOpenFile->pFile != NULL) fclose(pOpenFile->pFile);

            TString strFliePath;
            GetLogFilePath( eType, strFliePath );
            pOpenFile->pFile = _tfsopen(strFliePath.c_str(), _T("a+t"), _SH_DENYNO);

            if (pOpenFile->pFile != NULL)
            {
                pOpenFile->cTime = tempTime;
            }
        }
    }

    return pOpenFile;
}
Ejemplo n.º 16
0
void
RedirectDebugOutput()
{
#ifdef _WIN32
	WString logfile = MakePath(gDataDir, "stdout.txt");
	nfp = _tfsopen(logfile, _T("w"), _SH_DENYWR);
#else // _WIN32
	nfp = fopen("stdout.txt", "w");
#endif
	if (nfp)
#if __STDC_WANT_SECURE_LIB__
		setvbuf(nfp, NULL, _IOLBF, 1024);
#else
		setbuf(nfp, NULL);
#endif
}
Ejemplo n.º 17
0
bool CLog::Open()
{
	if (m_fp != NULL)
		return true;

	m_fp = _tfsopen(m_strFilePath, _T("a+b"), _SH_DENYWR);
	if (m_fp != NULL)
	{
		m_tStarted = time(NULL);
		m_uBytesWritten = _filelength(fileno(m_fp));
#ifdef _UNICODE
		if (m_uBytesWritten == 0)
		{
			// write Unicode byte-order mark 0xFEFF
			fputwc(0xFEFF, m_fp);
		}
		else if (m_uBytesWritten >= sizeof(WORD))
		{
			// check for Unicode byte-order mark 0xFEFF
			WORD wBOM;
			if (fread(&wBOM, sizeof(wBOM), 1, m_fp) == 1)
			{
				if (wBOM == 0xFEFF)
				{
					// log file already in Unicode format
					fseek(m_fp, 0, SEEK_END); // actually not needed because file is opened in 'Append' mode..
				}
				else
				{
					ASSERT( !m_bInOpenCall );
					if (!m_bInOpenCall) // just for safety
					{
						m_bInOpenCall = true;
						StartNewLogFile();
						m_bInOpenCall = false;
					}
				}
			}
		}
#endif
	}
	return m_fp != NULL;
}
Ejemplo n.º 18
0
BOOL CCustomAutoComplete::LoadList(LPCTSTR pszFileName)
{
	FILE* fp = _tfsopen(pszFileName, _T("rb"), _SH_DENYWR);
	if (fp == NULL)
		return FALSE;

	// verify Unicode byte-order mark 0xFEFF
	WORD wBOM = fgetwc(fp);
	if (wBOM != 0xFEFF){
		fclose(fp);
		return FALSE;
	}

	TCHAR szItem[256];
	while (_fgetts(szItem, ARRSIZE(szItem), fp) != NULL){
		CString strItem(szItem);
		strItem.Trim(_T(" \r\n"));
		AddItem(strItem, -1);
	}
	fclose(fp);
	return TRUE;
}
Ejemplo n.º 19
0
	BOOL CDuiAutoComplete::LoadList(LPCTSTR pszFileName)
	{
		FILE* fp = _tfsopen(pszFileName, _T("rb"), _SH_DENYWR);
		if (fp == NULL)
			return FALSE;

		// УÑé Unicode ±àÂë×Ö½ÚÐò mark 0xFEFF
		WORD wBOM = fgetwc(fp);
		if (wBOM != 0xFEFF){
			fclose(fp);
			return FALSE;
		}

		TCHAR szItem[256];
		while (_fgetts(szItem, ARRSIZE(szItem), fp) != NULL){
			CDuiString strItem(szItem);
			strItem.Replace(_T("\r"),_T(""));
			strItem.Replace(_T("\n"),_T(""));
			AddItem(strItem, -1);
		}
		fclose(fp);
		return TRUE;
	}
Ejemplo n.º 20
0
int CIPFilter::AddFromFile(LPCTSTR pszFilePath, bool bShowResponse)
{
	DWORD dwStart = GetTickCount();
	FILE* readFile = _tfsopen(pszFilePath, _T("r"), _SH_DENYWR);
	if (readFile != NULL)
	{
		enum EIPFilterFileType
		{
			Unknown = 0,
			FilterDat = 1,		// ipfilter.dat/ip.prefix format
			PeerGuardian = 2,	// PeerGuardian text format
			PeerGuardian2 = 3	// PeerGuardian binary format
		} eFileType = Unknown;

		setvbuf(readFile, NULL, _IOFBF, 32768);

		TCHAR szNam[_MAX_FNAME];
		TCHAR szExt[_MAX_EXT];
		_tsplitpath(pszFilePath, NULL, NULL, szNam, szExt);
		if (_tcsicmp(szExt, _T(".p2p")) == 0 || (_tcsicmp(szNam, _T("guarding.p2p")) == 0 && _tcsicmp(szExt, _T(".txt")) == 0))
			eFileType = PeerGuardian;
		else if (_tcsicmp(szExt, _T(".prefix")) == 0)
			eFileType = FilterDat;
		else
		{
			VERIFY( _setmode(fileno(readFile), _O_BINARY) != -1 );
			static const BYTE _aucP2Bheader[] = "\xFF\xFF\xFF\xFFP2B";
			BYTE aucHeader[sizeof _aucP2Bheader - 1];
			if (fread(aucHeader, sizeof aucHeader, 1, readFile) == 1)
			{
				if (memcmp(aucHeader, _aucP2Bheader, sizeof _aucP2Bheader - 1)==0)
					eFileType = PeerGuardian2;
				else
				{
					(void)fseek(readFile, 0, SEEK_SET);
					VERIFY( _setmode(fileno(readFile), _O_TEXT) != -1 ); // ugly!
				}
			}
		}

		int iFoundRanges = 0;
		int iLine = 0;
		if (eFileType == PeerGuardian2)
		{
			// Version 1: strings are ISO-8859-1 encoded
			// Version 2: strings are UTF-8 encoded
			uint8 nVersion;
			if (fread(&nVersion, sizeof nVersion, 1, readFile)==1 && (nVersion==1 || nVersion==2))
			{
				while (!feof(readFile))
				{
					CHAR szName[256];
					int iLen = 0;
					for (;;) // read until NUL or EOF
					{
						int iChar = getc(readFile);
						if (iChar == EOF)
							break;
						if (iLen < sizeof szName - 1)
							szName[iLen++] = (CHAR)iChar;
						if (iChar == '\0')
							break;
					}
					szName[iLen] = '\0';
					
					uint32 uStart;
					if (fread(&uStart, sizeof uStart, 1, readFile) != 1)
						break;
					uStart = ntohl(uStart);

					uint32 uEnd;
					if (fread(&uEnd, sizeof uEnd, 1, readFile) != 1)
						break;
					uEnd = ntohl(uEnd);

					iLine++;
					// (nVersion == 2) ? OptUtf8ToStr(szName, iLen) : 
					AddIPRange(uStart, uEnd, DFLT_FILTER_LEVEL, CStringA(szName, iLen));
					iFoundRanges++;
				}
			}
		}
		else
		{
			CStringA sbuffer;
			CHAR szBuffer[1024];
			while (fgets(szBuffer, _countof(szBuffer), readFile) != NULL)
			{
				iLine++;
				sbuffer = szBuffer;
				
				// ignore comments & too short lines
				if (sbuffer.GetAt(0) == '#' || sbuffer.GetAt(0) == '/' || sbuffer.GetLength() < 5) {
					sbuffer.Trim(" \t\r\n");
					DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter: ignored line %u\n", iLine) : 0 );
					continue;
				}

				if (eFileType == Unknown)
				{
					// looks like html
					if (sbuffer.Find('>') > -1 && sbuffer.Find('<') > -1)
						sbuffer.Delete(0, sbuffer.ReverseFind('>') + 1);

					// check for <IP> - <IP> at start of line
					UINT u1, u2, u3, u4, u5, u6, u7, u8;
					if (sscanf(sbuffer, "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8) == 8)
					{
						eFileType = FilterDat;
					}
					else
					{
						// check for <description> ':' <IP> '-' <IP>
						int iColon = sbuffer.Find(':');
						if (iColon > -1)
						{
							CStringA strIPRange = sbuffer.Mid(iColon + 1);
							UINT u1, u2, u3, u4, u5, u6, u7, u8;
							if (sscanf(strIPRange, "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8) == 8)
							{
								eFileType = PeerGuardian;
							}
						}
					}
				}

				bool bValid = false;
				uint32 start = 0;
				uint32 end = 0;
				UINT level = 0;
				CStringA desc;
				if (eFileType == FilterDat)
					bValid = ParseFilterLine1(sbuffer, start, end, level, desc);
				else if (eFileType == PeerGuardian)
					bValid = ParseFilterLine2(sbuffer, start, end, level, desc);

				// add a filter
				if (bValid)
				{
					AddIPRange(start, end, level, desc);
					iFoundRanges++;
				}
				else
				{
					sbuffer.Trim(" \t\r\n");
					DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter: ignored line %u\n", iLine) : 0 );
				}
			}
		}
		fclose(readFile);

		// sort the IP filter list by IP range start addresses
		qsort(m_iplist.GetData(), m_iplist.GetCount(), sizeof(m_iplist[0]), CmpSIPFilterByStartAddr);

		// merge overlapping and adjacent filter ranges
		int iDuplicate = 0;
		int iMerged = 0;
		if (m_iplist.GetCount() >= 2)
		{
			// On large IP-filter lists there is a noticeable performance problem when merging the list.
			// The 'CIPFilterArray::RemoveAt' call is way too expensive to get called during the merging,
			// thus we use temporary helper arrays to copy only the entries into the final list which
			// are not get deleted.

			// Reserve a byte array (its used as a boolean array actually) as large as the current 
			// IP-filter list, so we can set a 'to delete' flag for each entry in the current IP-filter list.
			char* pcToDelete = new char[m_iplist.GetCount()];
			memset(pcToDelete, 0, m_iplist.GetCount());
			int iNumToDelete = 0;

			SIPFilter* pPrv = m_iplist[0];
			int i = 1;
			while (i < m_iplist.GetCount())
			{
				SIPFilter* pCur = m_iplist[i];
				if (   pCur->start >= pPrv->start && pCur->start <= pPrv->end	 // overlapping
					|| pCur->start == pPrv->end+1 && pCur->level == pPrv->level) // adjacent
				{
					if (pCur->start != pPrv->start || pCur->end != pPrv->end) // don't merge identical entries
					{
						//TODO: not yet handled, overlapping entries with different 'level'
						if (pCur->end > pPrv->end)
							pPrv->end = pCur->end;
						//pPrv->desc += _T("; ") + pCur->desc; // this may create a very very long description string...
						iMerged++;
					}
					else
					{
						// if we have identical entries, use the lowest 'level'
						if (pCur->level < pPrv->level)
							pPrv->level = pCur->level;
						iDuplicate++;
					}
					delete pCur;
					//m_iplist.RemoveAt(i);	// way too expensive (read above)
					pcToDelete[i] = 1;		// mark this entry as 'to delete'
					iNumToDelete++;
					i++;
					continue;
				}
				pPrv = pCur;
				i++;
			}

			// Create new IP-filter list which contains only the entries from the original IP-filter list
			// which are not to be deleted.
			if (iNumToDelete > 0)
			{
				CIPFilterArray newList;
				newList.SetSize(m_iplist.GetCount() - iNumToDelete);
				int iNewListIndex = 0;
				for (int i = 0; i < m_iplist.GetCount(); i++) {
					if (!pcToDelete[i])
						newList[iNewListIndex++] = m_iplist[i];
				}
				ASSERT( iNewListIndex == newList.GetSize() );

				// Replace current list with new list. Dump, but still fast enough (only 1 memcpy)
				m_iplist.RemoveAll();
				m_iplist.Append(newList);
				newList.RemoveAll();
				m_bModified = true;
			}
			delete[] pcToDelete;
		}

		if (thePrefs.GetVerbose())
		{
			DWORD dwEnd = GetTickCount();
			AddDebugLogLine(false, _T("Loaded IP filters from \"%s\""), pszFilePath);
			AddDebugLogLine(false, _T("Parsed lines/entries:%u  Found IP ranges:%u  Duplicate:%u  Merged:%u  Time:%s"), iLine, iFoundRanges, iDuplicate, iMerged, CastSecondsToHM((dwEnd-dwStart+500)/1000));
		}
		AddLogLine(bShowResponse, GetResString(IDS_IPFILTERLOADED), m_iplist.GetCount());
	}
	return m_iplist.GetCount();
}
Ejemplo n.º 21
0
// ==> IP Filter White List [Stulle] - Stulle
void CIPFilter::AddFromFileWhite(LPCTSTR pszFilePath)
{
	FILE* readFile = _tfsopen(pszFilePath, _T("r"), _SH_DENYWR);
	if (readFile != NULL)
	{
		_setmode(fileno(readFile), _O_TEXT);

		int iLine = 0;
		CStringA sbuffer;
		CHAR szBuffer[1024];
		while (fgets(szBuffer, _countof(szBuffer), readFile) != NULL)
		{
			iLine++;
			sbuffer = szBuffer;
			
			// ignore comments & too short lines
			if (sbuffer.GetAt(0) == '#' || sbuffer.GetAt(0) == '/' || sbuffer.GetLength() < 5) {
				sbuffer.Trim(" \t\r\n");
				DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter (white): ignored line %u\n", iLine) : 0 );
				continue;
			}

			bool bValid = false;
			uint32 start = 0;
			uint32 end = 0;
			UINT level = 0;
			CStringA desc;
			bValid = ParseFilterLine1(sbuffer, start, end, level, desc);

			// add a filter
			if (bValid)
			{
				AddIPRangeWhite(start, end, level, desc);
				DEBUG_ONLY( TRACE("Added White Entry - start: %u end: %u level: %u desc: %s\n", start, end, level, desc));
			}
			else
			{
				sbuffer.Trim(" \t\r\n");
				DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter (white list): ignored line %u\n", iLine) : 0 );
			}
		}
		fclose(readFile);

		// sort the IP filter list by IP range start addresses
		qsort(m_iplist_White.GetData(), m_iplist_White.GetCount(), sizeof(m_iplist_White[0]), CmpSIPFilterByStartAddr);

		// merge overlapping and adjacent filter ranges
		if (m_iplist_White.GetCount() >= 2)
		{
			// On large IP-filter lists there is a noticeable performance problem when merging the list.
			// The 'CIPFilterArray::RemoveAt' call is way too expensive to get called during the merging,
			// thus we use temporary helper arrays to copy only the entries into the final list which
			// are not get deleted.

			// Reserve a byte array (its used as a boolean array actually) as large as the current 
			// IP-filter list, so we can set a 'to delete' flag for each entry in the current IP-filter list.
			char* pcToDelete = new char[m_iplist_White.GetCount()];
			memset(pcToDelete, 0, m_iplist_White.GetCount());
			int iNumToDelete = 0;

			SIPFilter* pPrv = m_iplist_White[0];
			int i = 1;
			while (i < m_iplist_White.GetCount())
			{
				SIPFilter* pCur = m_iplist_White[i];
				if (   pCur->start >= pPrv->start && pCur->start <= pPrv->end	 // overlapping
					|| pCur->start == pPrv->end+1 && pCur->level == pPrv->level) // adjacent
				{
					if (pCur->start != pPrv->start || pCur->end != pPrv->end) // don't merge identical entries
					{
						//TODO: not yet handled, overlapping entries with different 'level'
						if (pCur->end > pPrv->end)
							pPrv->end = pCur->end;
						//pPrv->desc += _T("; ") + pCur->desc; // this may create a very very long description string...
					}
					else
					{
						// if we have identical entries, use the lowest 'level'
						if (pCur->level < pPrv->level)
							pPrv->level = pCur->level;
					}
					delete pCur;
					//m_iplist_White.RemoveAt(i);	// way too expensive (read above)
					pcToDelete[i] = 1;		// mark this entry as 'to delete'
					iNumToDelete++;
					i++;
					continue;
				}
				pPrv = pCur;
				i++;
			}

			// Create new IP-filter list which contains only the entries from the original IP-filter list
			// which are not to be deleted.
			if (iNumToDelete > 0)
			{
				CIPFilterArray newList;
				newList.SetSize(m_iplist_White.GetCount() - iNumToDelete);
				int iNewListIndex = 0;
				for (int i = 0; i < m_iplist_White.GetCount(); i++) {
					if (!pcToDelete[i])
						newList[iNewListIndex++] = m_iplist_White[i];
				}
				ASSERT( iNewListIndex == newList.GetSize() );

				// Replace current list with new list. Dump, but still fast enough (only 1 memcpy)
				m_iplist_White.RemoveAll();
				m_iplist_White.Append(newList);
				newList.RemoveAll();
				m_bModified = true;
			}
			delete[] pcToDelete;
		}
	}
	if(m_iplist_White.GetCount()>0)
		AddLogLine(false, GetResString(IDS_IPFILTERWHITELOADED), m_iplist_White.GetCount());
	return;
}
Ejemplo n.º 22
0
int CPreviewApps::ReadAllApps()
{
	RemoveAllApps();

	CString strFilePath = GetDefaultAppsFile();
	FILE* readFile = _tfsopen(strFilePath, _T("r"), _SH_DENYWR);
	if (readFile != NULL)
	{
		CString name, url, sbuffer;
		while (!feof(readFile))
		{
			TCHAR buffer[1024];
			if (_fgetts(buffer, ARRSIZE(buffer), readFile) == NULL)
				break;
			sbuffer = buffer;

			// ignore comments & too short lines
			if (sbuffer.GetAt(0) == _T('#') || sbuffer.GetAt(0) == _T('/') || sbuffer.GetLength() < 5)
				continue;

			int iPos = 0;
			CString strTitle = sbuffer.Tokenize(_T("="), iPos);
			strTitle.Trim();
			if (!strTitle.IsEmpty())
			{
				CString strCommandLine = sbuffer.Tokenize(_T(";"), iPos);
				strCommandLine.Trim();
				if (!strCommandLine.IsEmpty())
				{
					LPCTSTR pszCommandLine = strCommandLine;
					LPTSTR pszCommandArgs = PathGetArgs(pszCommandLine);
					CString strCommand, strCommandArgs;
					if (pszCommandArgs)
						strCommand = strCommandLine.Left(pszCommandArgs - pszCommandLine);
					else
						strCommand = strCommandLine;
					strCommand.Trim(_T(" \t\""));
					if (!strCommand.IsEmpty())
					{
						UINT uMinCompletedSize = 0;
						UINT uMinStartOfFile = 0;
						CStringArray astrExtensions;
						CString strParams = sbuffer.Tokenize(_T(";"), iPos);
						while (!strParams.IsEmpty())
						{
							int iPosParam = 0;
							CString strId = strParams.Tokenize(_T("="), iPosParam);
							if (!strId.IsEmpty())
							{
								CString strValue = strParams.Tokenize(_T("="), iPosParam);
								if (strId.CompareNoCase(_T("Ext")) == 0)
								{
									if (!strValue.IsEmpty())
									{
										if (strValue[0] != _T('.'))
											strValue = _T('.') + strValue;
										astrExtensions.Add(strValue);
									}
								}
								else if (strId.CompareNoCase(_T("MinSize")) == 0)
								{
									if (!strValue.IsEmpty())
										_stscanf(strValue, _T("%u"), &uMinCompletedSize);
								}
								else if (strId.CompareNoCase(_T("MinStart")) == 0)
								{
									if (!strValue.IsEmpty())
										_stscanf(strValue, _T("%u"), &uMinStartOfFile);
								}
							}
							strParams = sbuffer.Tokenize(_T(";"), iPos);
						}

						SPreviewApp svc;
						svc.strTitle = strTitle;
						svc.strCommand = strCommand;
						svc.strCommandArgs = pszCommandArgs;
						svc.strCommandArgs.Trim();
						svc.astrExtensions.Append(astrExtensions);
						svc.uMinCompletedSize = uMinCompletedSize;
						svc.uMinStartOfFile = uMinStartOfFile;
						m_aApps.Add(svc);
					}
				}
			}
		}
		fclose(readFile);

		struct _stat st;
		if (_tstat(strFilePath, &st) == 0)
			m_tDefAppsFileLastModified = st.st_mtime;
	}

	return m_aApps.GetCount();
}
Ejemplo n.º 23
0
void CGitStatusCache::Create()
{
    ATLASSERT(m_pInstance == NULL);
    m_pInstance = new CGitStatusCache;

    m_pInstance->watcher.SetFolderCrawler(&m_pInstance->m_folderCrawler);
#define LOADVALUEFROMFILE(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto exit;
#define LOADVALUEFROMFILE2(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto error;
    unsigned int value = (unsigned int)-1;
    FILE * pFile = NULL;
    // find the location of the cache
    TCHAR path[MAX_PATH];		//MAX_PATH ok here.
    TCHAR path2[MAX_PATH];
    if (SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path)==S_OK)
    {
        _tcscat_s(path, MAX_PATH, _T("\\TGitCache"));
        if (!PathIsDirectory(path))
        {
            if (CreateDirectory(path, NULL)==0)
                goto error;
        }
        _tcscat_s(path, MAX_PATH, _T("\\cache"));
        // in case the cache file is corrupt, we could crash while
        // reading it! To prevent crashing every time once that happens,
        // we make a copy of the cache file and use that copy to read from.
        // if that copy is corrupt, the original file won't exist anymore
        // and the second time we start up and try to read the file,
        // it's not there anymore and we start from scratch without a crash.
        _tcscpy_s(path2, MAX_PATH, path);
        _tcscat_s(path2, MAX_PATH, _T("2"));
        DeleteFile(path2);
        CopyFile(path, path2, FALSE);
        DeleteFile(path);
        pFile = _tfsopen(path2, _T("rb"), _SH_DENYNO);
        if (pFile)
        {
            try
            {
                LOADVALUEFROMFILE(value);
                if (value != 2)
                {
                    goto error;
                }
                int mapsize = 0;
                LOADVALUEFROMFILE(mapsize);
                for (int i=0; i<mapsize; ++i)
                {
                    LOADVALUEFROMFILE2(value);
                    if (value > MAX_PATH)
                        goto error;
                    if (value)
                    {
                        CString sKey;
                        if (fread(sKey.GetBuffer(value+1), sizeof(TCHAR), value, pFile)!=value)
                        {
                            sKey.ReleaseBuffer(0);
                            goto error;
                        }
                        sKey.ReleaseBuffer(value);
                        CCachedDirectory * cacheddir = new CCachedDirectory();
                        if (cacheddir == NULL)
                            goto error;
                        if (!cacheddir->LoadFromDisk(pFile))
                            goto error;
                        CTGitPath KeyPath = CTGitPath(sKey);
                        if (m_pInstance->IsPathAllowed(KeyPath))
                        {
                            m_pInstance->m_directoryCache[KeyPath] = cacheddir;
                            // only add the path to the watch list if it is versioned
                            if ((cacheddir->GetCurrentFullStatus() != git_wc_status_unversioned)&&(cacheddir->GetCurrentFullStatus() != git_wc_status_none))
                                m_pInstance->watcher.AddPath(KeyPath, false);
                            // do *not* add the paths for crawling!
                            // because crawled paths will trigger a shell
                            // notification, which makes the desktop flash constantly
                            // until the whole first time crawling is over
                            // m_pInstance->AddFolderForCrawling(KeyPath);
                        }
                    }
                }
            }
            catch (CAtlException)
            {
                goto error;
            }
        }
    }
exit:
    if (pFile)
        fclose(pFile);
    DeleteFile(path2);
    m_pInstance->watcher.ClearInfoMap();
    ATLTRACE("cache loaded from disk successfully!\n");
    return;
error:
    if (pFile)
        fclose(pFile);
    DeleteFile(path2);
    m_pInstance->watcher.ClearInfoMap();
    Destroy();
    m_pInstance = new CGitStatusCache;
    ATLTRACE("cache not loaded from disk\n");
}
Ejemplo n.º 24
0
/*
void CIPFilter::UpdateIPFilterURL()
*/
void CIPFilter::UpdateIPFilterURL(uint32 uNewVersion)
// <== Advanced Updates [MorphXT/Stulle] - Stulle
{
	bool bHaveNewFilterFile = false;
	CString url = thePrefs.GetAutoUpdateIPFilter_URL();
	SYSTEMTIME SysTime;
	if (!url.IsEmpty())
	{
		CString strTempFilePath;
		_tmakepathlimit(strTempFilePath.GetBuffer(MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T("tmp"));
		strTempFilePath.ReleaseBuffer();

		CHttpDownloadDlg dlgDownload;
		dlgDownload.m_strTitle = GetResString(IDS_DWL_IPFILTERFILE);
		dlgDownload.m_sURLToDownload = url;
		dlgDownload.m_sFileToDownloadInto = strTempFilePath;

		if (PathFileExists(GetDefaultFilePath()))
			memcpy(&SysTime, &thePrefs.m_IPfilterVersion, sizeof(SYSTEMTIME));
		else
			memset(&SysTime, 0, sizeof(SYSTEMTIME));
		// ==> Advanced Updates [MorphXT/Stulle] - Stulle
		if(thePrefs.IsIPFilterViaDynDNS())
			dlgDownload.m_pLastModifiedTime = NULL;
		else
		// <== Advanced Updates [MorphXT/Stulle] - Stulle
			dlgDownload.m_pLastModifiedTime = &SysTime; //Xman remark: m_pLastModifiedTime is a pointer which points to the SysTime-struct

		if (dlgDownload.DoModal() != IDOK)
		{
			(void)_tremove(strTempFilePath);
			CString strError = GetResString(IDS_DWLIPFILTERFAILED);
			if (!dlgDownload.GetError().IsEmpty())
				strError += _T("\r\n\r\n") + dlgDownload.GetError();
			AfxMessageBox(strError, MB_ICONERROR);
			return;
		}
		// ==> Advanced Updates [MorphXT/Stulle] - Stulle
		/*
		if (dlgDownload.m_pLastModifiedTime == NULL)
		*/
		if (thePrefs.IsIPFilterViaDynDNS() == false && dlgDownload.m_pLastModifiedTime == NULL)
		// <== Advanced Updates [MorphXT/Stulle] - Stulle
			return;

		CString strMimeType;
		GetMimeType(strTempFilePath, strMimeType);

		bool bIsArchiveFile = false;
		bool bUncompressed = false;
		CZIPFile zip;
		if (zip.Open(strTempFilePath))
		{
			bIsArchiveFile = true;

			CZIPFile::File* zfile = zip.GetFile(_T("guarding.p2p"));
			if (zfile == NULL)
				zfile = zip.GetFile(_T("ipfilter.dat"));
			if (zfile)
			{
				CString strTempUnzipFilePath;
				_tmakepathlimit(strTempUnzipFilePath.GetBuffer(_MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
				strTempUnzipFilePath.ReleaseBuffer();

				if (zfile->Extract(strTempUnzipFilePath))
				{
					zip.Close();
					zfile = NULL;

					if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %hs\n"), theApp.ipfilter->GetDefaultFilePath(), strerror(errno));
					if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %hs\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), strerror(errno));
					if (_tremove(strTempFilePath) != 0)
						TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %hs\n"), strTempFilePath, strerror(errno));
					bUncompressed = true;
					bHaveNewFilterFile = true;
				}
				else {
					CString strError;
					strError.Format(GetResString(IDS_ERR_IPFILTERZIPEXTR), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
			}
			else {
				CString strError;
				strError.Format(GetResString(IDS_ERR_IPFILTERCONTENTERR), strTempFilePath);
				AfxMessageBox(strError, MB_ICONERROR);
			}

			zip.Close();
		}
		else if (strMimeType.CompareNoCase(_T("application/x-rar-compressed")) == 0)
		{
			bIsArchiveFile = true;

			CRARFile rar;
			if (rar.Open(strTempFilePath))
			{
				CString strFile;
				if (rar.GetNextFile(strFile)
					&& (strFile.CompareNoCase(_T("ipfilter.dat")) == 0 || strFile.CompareNoCase(_T("guarding.p2p")) == 0))
				{
					CString strTempUnzipFilePath;
					_tmakepathlimit(strTempUnzipFilePath.GetBuffer(MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
					strTempUnzipFilePath.ReleaseBuffer();
					if (rar.Extract(strTempUnzipFilePath))
					{
						rar.Close();

						if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
							TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %hs\n"), theApp.ipfilter->GetDefaultFilePath(), strerror(errno));
						if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
							TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %hs\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), strerror(errno));
						if (_tremove(strTempFilePath) != 0)
							TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %hs\n"), strTempFilePath, strerror(errno));
						bUncompressed = true;
						bHaveNewFilterFile = true;
					}
					else
					{
						CString strError;
						strError.Format(_T("Failed to extract IP filter file from RAR file \"%s\"."), strTempFilePath);
						AfxMessageBox(strError, MB_ICONERROR);
					}
				}
				else
				{
					CString strError;
					strError.Format(_T("Failed to find IP filter file \"guarding.p2p\" or \"ipfilter.dat\" in RAR file \"%s\"."), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
				rar.Close();
			}
			else
			{
				CString strError;
				strError.Format(_T("Failed to open file \"%s\".\r\n\r\nInvalid file format?\r\n\r\nDownload latest version of UNRAR.DLL from http://www.rarlab.com and copy UNRAR.DLL into eMule installation folder."), url);
				AfxMessageBox(strError, MB_ICONERROR);
			}
		}
		else
		{
			CGZIPFile gz;
			if (gz.Open(strTempFilePath))
			{
				bIsArchiveFile = true;

				CString strTempUnzipFilePath;
				_tmakepathlimit(strTempUnzipFilePath.GetBuffer(_MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
				strTempUnzipFilePath.ReleaseBuffer();

				// add filename and extension of uncompressed file to temporary file
				CString strUncompressedFileName = gz.GetUncompressedFileName();
				if (!strUncompressedFileName.IsEmpty())
				{
					strTempUnzipFilePath += _T('.');
					strTempUnzipFilePath += strUncompressedFileName;
				}

				if (gz.Extract(strTempUnzipFilePath))
				{
					gz.Close();

					if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %hs\n"), theApp.ipfilter->GetDefaultFilePath(), strerror(errno));
					if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %hs\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), strerror(errno));
					if (_tremove(strTempFilePath) != 0)
						TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %hs\n"), strTempFilePath, strerror(errno));
					bUncompressed = true;
					bHaveNewFilterFile = true;
				}
				else {
					CString strError;
					strError.Format(GetResString(IDS_ERR_IPFILTERZIPEXTR), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
			}
			gz.Close();
		}

		if (!bIsArchiveFile && !bUncompressed)
		{
			// Check first lines of downloaded file for potential HTML content (e.g. 404 error pages)
			bool bValidIPFilterFile = true;
			FILE* fp = _tfsopen(strTempFilePath, _T("rb"), _SH_DENYWR);
			if (fp)
			{
				char szBuff[16384];
				int iRead = fread(szBuff, 1, _countof(szBuff)-1, fp);
				if (iRead <= 0)
					bValidIPFilterFile = false;
				else
				{
					szBuff[iRead-1] = '\0';

					const char* pc = szBuff;
					while (*pc == ' ' || *pc == '\t' || *pc == '\r' || *pc == '\n')
						pc++;
					if (strnicmp(pc, "<html", 5) == 0
						|| strnicmp(pc, "<xml", 4) == 0
						|| strnicmp(pc, "<!doc", 5) == 0)
					{
						bValidIPFilterFile = false;
					}
				}
				fclose(fp);
			}

			if (bValidIPFilterFile)
			{
				(void)_tremove(theApp.ipfilter->GetDefaultFilePath());
				VERIFY( _trename(strTempFilePath, theApp.ipfilter->GetDefaultFilePath()) == 0 );
				bHaveNewFilterFile = true;
			}
			else
			{
				AfxMessageBox(GetResString(IDS_DWLIPFILTERFAILED), MB_ICONERROR);
			}
		}
	}
	else
	{
		AfxMessageBox(_T("Failed to auto-update IPFilter. No URL given"), MB_ICONERROR);
		return;
	}

	// ==> Advanced Updates [MorphXT/Stulle] - Stulle
	/*
	struct tm tmTemp;
	thePrefs.m_last_ipfilter_check = safe_mktime(CTime::GetCurrentTime().GetLocalTm(&tmTemp));
	*/
	// <== Advanced Updates [MorphXT/Stulle] - Stulle

	if (bHaveNewFilterFile)
	{
		LoadFromDefaultFile();
		if (thePrefs.GetFilterServerByIP())
			theApp.emuledlg->serverwnd->serverlistctrl.RemoveAllFilteredServers();
	}

	// In case we received an invalid IP-filter file (e.g. an 404 HTML page with HTTP status "OK"),
	// warn the user that there are no IP-filters available any longer.
	if (bHaveNewFilterFile && theApp.ipfilter->GetIPFilter().GetCount() == 0)
	{
		CString strLoaded;
		strLoaded.Format(GetResString(IDS_IPFILTERLOADED), theApp.ipfilter->GetIPFilter().GetCount());
		CString strError;
		strError.Format(_T("%s\r\n\r\n%s"), GetResString(IDS_DWLIPFILTERFAILED), strLoaded);
		AfxMessageBox(strError, MB_ICONERROR);
		return;
	}

	//everything fine. update the stored version
	if (bHaveNewFilterFile)
	// ==> Advanced Updates [MorphXT/Stulle] - Stulle
	/*
		memcpy(&thePrefs.m_IPfilterVersion, &SysTime, sizeof SysTime); 
	*/
	{
		thePrefs.m_uIPFilterVersionNum = uNewVersion;
		if(thePrefs.IsIPFilterViaDynDNS())
		{
			memset(&SysTime, 0, sizeof(SYSTEMTIME));
			if(theApp.emuledlg->preferenceswnd &&
				theApp.emuledlg->preferenceswnd->m_wndScar &&
				theApp.emuledlg->preferenceswnd->m_wndScar.m_IpFilterTime)
			{
				CString strBuffer = NULL;
				strBuffer.Format(_T("v%u"), thePrefs.GetIPFilterVersionNum());
				theApp.emuledlg->preferenceswnd->m_wndScar.m_IpFilterTime.SetWindowText(strBuffer);
			}
		}
		else
			memcpy(&thePrefs.m_IPfilterVersion, &SysTime, sizeof SysTime);
	}
	else
	{
		thePrefs.m_uIPFilterVersionNum = 0;
		memset(&SysTime, 0, sizeof(SYSTEMTIME));
		if(thePrefs.IsIPFilterViaDynDNS())
		{
			if(theApp.emuledlg->preferenceswnd &&
				theApp.emuledlg->preferenceswnd->m_wndScar &&
				theApp.emuledlg->preferenceswnd->m_wndScar.m_IpFilterTime)
				theApp.emuledlg->preferenceswnd->m_wndScar.m_IpFilterTime.SetWindowText(GetResString(IDS_DL_NONE));
		}
	}
	if(thePrefs.IsIPFilterViaDynDNS() == false &&
		theApp.emuledlg->preferenceswnd &&
		theApp.emuledlg->preferenceswnd->m_wndScar &&
		theApp.emuledlg->preferenceswnd->m_wndScar.m_IpFilterTime)
	{
		TCHAR sTime[30];
		sTime[0] = _T('\0');
		SysTimeToStr(thePrefs.GetIPfilterVersion(), sTime);
		theApp.emuledlg->preferenceswnd->m_wndScar.m_IpFilterTime.SetWindowText(sTime);
	}
	// <== Advanced Updates [MorphXT/Stulle] - Stulle
}
Ejemplo n.º 25
0
//---------------------------------------------------------------------------
void CSendImageShack::Send() {
	// check Netlib
	if( !hNetlibUser ) {
		//PrintError(1,TRUE);
		return;
	}
	if (!m_pszFileName) {
		m_pszFileName = (LPSTR)GetFileName(m_pszFile, DBVT_ASCIIZ);
	}
	if (!m_pszContentType) GetContentType();

	// create new boundary
	MFDR_Reset();

	// initialize the netlib request
	ZeroMemory(&m_nlhr, sizeof(m_nlhr));
	m_nlhr.cbSize					= sizeof(m_nlhr);
	m_nlhr.requestType				= REQUEST_POST;
	m_nlhr.flags					= NLHRF_HTTP11;			//NLHRF_DUMPASTEXT;
	m_nlhr.szUrl					= "http://www.imageshack.us/upload_api.php";
	m_nlhr.headersCount				= 6;
	{	//NETLIBHTTPHEADER start
		m_nlhr.headers=(NETLIBHTTPHEADER*)mir_alloc(sizeof(NETLIBHTTPHEADER)*m_nlhr.headersCount);
		m_nlhr.headers[0].szName		= "Referer";
		m_nlhr.headers[0].szValue		= "http://www.imageshack.us/upload_api.php";
		m_nlhr.headers[1].szName		= "Connection";
		m_nlhr.headers[1].szValue		= "Keep-alive";
		m_nlhr.headers[2].szName		= "AcceptLanguage";
		m_nlhr.headers[2].szValue		= "en-us, pt-br";
		m_nlhr.headers[3].szName		= "Host";
		m_nlhr.headers[3].szValue		= "imageshack.us";
		m_nlhr.headers[4].szName		= "User-Agent";
		m_nlhr.headers[4].szValue		= __USER_AGENT_STRING;	//szAgent;	/;
		//nlhr.headers[x].szName		= "Authorization";
		//nlhr.headers[x].szValue		= auth;		//Basic base-64-authorization

		//$header .= "Content-type: multipart/form-data; boundary=" . part::getBoundary() . "\r\n";
		mir_snprintf(m_nlheader_ContentType, SIZEOF(m_nlheader_ContentType), "multipart/form-data; boundary=%s", m_MFDRboundary);
		m_nlhr.headers[m_nlhr.headersCount-1].szName		= "Content-Type";
		m_nlhr.headers[m_nlhr.headersCount-1].szValue		= m_nlheader_ContentType;
	}	//NETLIBHTTPHEADER end

//POST DATA file-header, init DATA with MultipartFormDataRequest
	//$params[] = new filepart('fileupload', $file, basename($file), $contentType, 'iso-8859-1');
	//($this->sendStart($h);)
	AppendToData("--");
	AppendToData(m_MFDRboundary);
	AppendToData("\r\n");
	//($this->sendDispositionHeader($h);)
	AppendToData("Content-Disposition: form-data; name=\"");
	AppendToData("fileupload");
	AppendToData("\"; filename=\"");
	AppendToData(m_pszFileName);
	AppendToData("\"");
	AppendToData("\r\n");
	//($this->sendContentTypeHeader($h);)
	AppendToData("Content-Type: ");
	AppendToData(m_pszContentType);
	AppendToData("; charset=");
	AppendToData("iso-8859-1");
	//($this->sendEndOfHeader($h);)
	AppendToData("\r\n");
	AppendToData("\r\n");
	//Now we add the file binary ($this->sendData($h))
	FILE * fileId = _tfsopen(m_pszFile, _T("rb"), _SH_DENYWR );
	if( !fileId) {
		//PrintError(1,TRUE);
		return;
	}
	fseek(fileId, NULL, SEEK_END);
	size_t lenFile  = ftell(fileId);
	size_t sizeDest = sizeof(char)*(m_nlhr.dataLength + lenFile + 1);
	m_nlhr.pData    = (char *) mir_realloc(m_nlhr.pData, sizeDest);
	fseek(fileId, NULL, SEEK_SET );
	int i;
	int ch = fgetc( fileId );
	for( i=0; (i < (int)lenFile ) && ( feof( fileId ) == 0 ); i++ ) {
		m_nlhr.pData[m_nlhr.dataLength+i] = (char)ch;
		ch = fgetc( fileId );
	}
	m_nlhr.pData[sizeDest-1] = 0;						//NULL Termination for binary data
	m_nlhr.dataLength = (int)sizeDest - 1;
	fclose(fileId);
	//($this->sendEnd($h);)
	AppendToData("\r\n");

//POST DATA footer (for "optimage", 1)
//POST DATA footer (for "optsize", optsize)

//POST DATA footer (for "tags", tags)
//POST DATA footer (for "rembar", "yes" : "no")
//POST DATA footer (for "public", "yes" : "no")
//POST DATA footer (for "cookie", cookie)

//POST DATA footer (for "key", DEVKEY_IMAGESHACK)
	//($this->sendStart($h);)
	AppendToData("--");
	AppendToData(m_MFDRboundary);
	AppendToData("\r\n");
	//($this->sendDispositionHeader($h);)
	AppendToData("Content-Disposition: form-data; name=\"");
	AppendToData("key");
	AppendToData("\"");
	//($this->sendTransferEncodingHeader($h); )
	AppendToData("\r\n");
	AppendToData("Content-Transfer-Encoding: ");
	AppendToData("8bit");				//??"binary"
	//($this->sendEndOfHeader($h);)
	AppendToData("\r\n");
	AppendToData("\r\n");
	//($this->sendData($h);)
	AppendToData(DEVKEY_IMAGESHACK);
	//($this->sendEnd($h);)
	AppendToData("\r\n");

//POST DATA Exit
	//$postdata = "--" . part::getBoundary() . "--\r\n";
	AppendToData("--");
	AppendToData(m_MFDRboundary);
	AppendToData("--\r\n");

//start upload thread
	if (m_SendSync) {
		m_bFreeOnExit = FALSE;
		SendThread();
		return;
	}
	m_bFreeOnExit = TRUE;
	mir_forkthread(&CSendImageShack::SendThreadWrapper, this);
}
Ejemplo n.º 26
0
void CPPgSecurity::OnLoadIPFFromURL()
{
	bool bHaveNewFilterFile = false;
	CString url;
	GetDlgItemText(IDC_UPDATEURL,url);
	if (!url.IsEmpty())
	{
		// add entered URL to LRU list even if it's not yet known whether we can download from this URL (it's just more convenient this way)
		if (m_pacIPFilterURL && m_pacIPFilterURL->IsBound())
			m_pacIPFilterURL->AddItem(url, 0);

		CString strTempFilePath;
		_tmakepathlimit(strTempFilePath.GetBuffer(MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T("tmp"));
		strTempFilePath.ReleaseBuffer();

		CHttpDownloadDlg dlgDownload;
		dlgDownload.m_strTitle = GetResString(IDS_DWL_IPFILTERFILE);
		dlgDownload.m_sURLToDownload = url;
		dlgDownload.m_sFileToDownloadInto = strTempFilePath;
		if (dlgDownload.DoModal() != IDOK)
		{
			(void)_tremove(strTempFilePath);
			CString strError = GetResString(IDS_DWLIPFILTERFAILED);
			if (!dlgDownload.GetError().IsEmpty())
				strError += _T("\r\n\r\n") + dlgDownload.GetError();
			AfxMessageBox(strError, MB_ICONERROR);
			return;
		}

		CString strMimeType;
		GetMimeType(strTempFilePath, strMimeType);

		bool bIsArchiveFile = false;
		bool bUncompressed = false;
		CZIPFile zip;
		if (zip.Open(strTempFilePath))
		{
			bIsArchiveFile = true;

			CZIPFile::File* zfile = zip.GetFile(_T("guarding.p2p"));
			if (zfile == NULL)
				zfile = zip.GetFile(_T("ipfilter.dat"));
			if (zfile)
			{
				CString strTempUnzipFilePath;
				_tmakepathlimit(strTempUnzipFilePath.GetBuffer(_MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
				strTempUnzipFilePath.ReleaseBuffer();

				if (zfile->Extract(strTempUnzipFilePath))
				{
					zip.Close();
					zfile = NULL;

					if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %s\n"), theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
					if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %s\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
					if (_tremove(strTempFilePath) != 0)
						TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %s\n"), strTempFilePath, _tcserror(errno));
					bUncompressed = true;
					bHaveNewFilterFile = true;
				}
				else {
					CString strError;
					strError.Format(GetResString(IDS_ERR_IPFILTERZIPEXTR), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
			}
			else {
				CString strError;
				strError.Format(GetResString(IDS_ERR_IPFILTERCONTENTERR), strTempFilePath);
				AfxMessageBox(strError, MB_ICONERROR);
			}

			zip.Close();
		}
		else if (strMimeType.CompareNoCase(_T("application/x-rar-compressed")) == 0)
		{
			bIsArchiveFile = true;

			CRARFile rar;
			if (rar.Open(strTempFilePath))
			{
				CString strFile;
				if (rar.GetNextFile(strFile)
					&& (strFile.CompareNoCase(_T("ipfilter.dat")) == 0 || strFile.CompareNoCase(_T("guarding.p2p")) == 0))
				{
					CString strTempUnzipFilePath;
					_tmakepathlimit(strTempUnzipFilePath.GetBuffer(MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
					strTempUnzipFilePath.ReleaseBuffer();
					if (rar.Extract(strTempUnzipFilePath))
					{
						rar.Close();

						if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
							TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %s\n"), theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
						if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
							TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %s\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
						if (_tremove(strTempFilePath) != 0)
							TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %s\n"), strTempFilePath, _tcserror(errno));
						bUncompressed = true;
						bHaveNewFilterFile = true;
					}
					else
					{
						CString strError;
						strError.Format(_T("Failed to extract IP filter file from RAR file \"%s\"."), strTempFilePath);
						AfxMessageBox(strError, MB_ICONERROR);
					}
				}
				else
				{
					CString strError;
					strError.Format(_T("Failed to find IP filter file \"guarding.p2p\" or \"ipfilter.dat\" in RAR file \"%s\"."), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
				rar.Close();
			}
			else
			{
				CString strError;
				strError.Format(_T("Failed to open file \"%s\".\r\n\r\nInvalid file format?\r\n\r\nDownload latest version of UNRAR.DLL from http://www.rarlab.com and copy UNRAR.DLL into eMule installation folder."), url);
				AfxMessageBox(strError, MB_ICONERROR);
			}
		}
		else
		{
			CGZIPFile gz;
			if (gz.Open(strTempFilePath))
			{
				bIsArchiveFile = true;

				CString strTempUnzipFilePath;
				_tmakepathlimit(strTempUnzipFilePath.GetBuffer(_MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
				strTempUnzipFilePath.ReleaseBuffer();

				// add filename and extension of uncompressed file to temporary file
				CString strUncompressedFileName = gz.GetUncompressedFileName();
				if (!strUncompressedFileName.IsEmpty())
				{
					strTempUnzipFilePath += _T('.');
					strTempUnzipFilePath += strUncompressedFileName;
				}

				if (gz.Extract(strTempUnzipFilePath))
				{
					gz.Close();

					if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %s\n"), theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
					if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %s\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
					if (_tremove(strTempFilePath) != 0)
						TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %s\n"), strTempFilePath, _tcserror(errno));
					bUncompressed = true;
					bHaveNewFilterFile = true;
				}
				else {
					CString strError;
					strError.Format(GetResString(IDS_ERR_IPFILTERZIPEXTR), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
			}
			gz.Close();
		}

		if (!bIsArchiveFile && !bUncompressed)
		{
			// Check first lines of downloaded file for potential HTML content (e.g. 404 error pages)
			bool bValidIPFilterFile = true;
			FILE* fp = _tfsopen(strTempFilePath, _T("rb"), _SH_DENYWR);
			if (fp)
			{
				char szBuff[16384];
				int iRead = fread(szBuff, 1, _countof(szBuff)-1, fp);
				if (iRead <= 0)
					bValidIPFilterFile = false;
				else
				{
					szBuff[iRead-1] = '\0';

					const char* pc = szBuff;
					while (*pc == ' ' || *pc == '\t' || *pc == '\r' || *pc == '\n')
						pc++;
					if (strnicmp(pc, "<html", 5) == 0
						|| strnicmp(pc, "<xml", 4) == 0
						|| strnicmp(pc, "<!doc", 5) == 0)
					{
						bValidIPFilterFile = false;
					}
				}
				fclose(fp);
			}

			if (bValidIPFilterFile)
			{
				(void)_tremove(theApp.ipfilter->GetDefaultFilePath());
				VERIFY( _trename(strTempFilePath, theApp.ipfilter->GetDefaultFilePath()) == 0 );
				bHaveNewFilterFile = true;
			}
			else
			{
				AfxMessageBox(GetResString(IDS_DWLIPFILTERFAILED), MB_ICONERROR);
			}
		}
	}

	if (url.IsEmpty() || bHaveNewFilterFile)
		OnReloadIPFilter();

	// In case we received an invalid IP-filter file (e.g. an 404 HTML page with HTTP status "OK"),
	// warn the user that there are no IP-filters available any longer.
	if (bHaveNewFilterFile && theApp.ipfilter->GetIPFilter().GetCount() == 0)
	{
		CString strLoaded;
		strLoaded.Format(GetResString(IDS_IPFILTERLOADED), theApp.ipfilter->GetIPFilter().GetCount());
		CString strError;
		strError.Format(_T("%s\r\n\r\n%s"), GetResString(IDS_DWLIPFILTERFAILED), strLoaded);
		AfxMessageBox(strError, MB_ICONERROR);
	}
}
Ejemplo n.º 27
0
void CSVNStatusCache::Create()
{
    ATLASSERT(m_pInstance == NULL);
    if (m_pInstance != NULL)
        return;

    m_pInstance = new CSVNStatusCache;

    m_pInstance->watcher.SetFolderCrawler(&m_pInstance->m_folderCrawler);
#define LOADVALUEFROMFILE(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto exit;
#define LOADVALUEFROMFILE2(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto error;
    unsigned int value = (unsigned int)-1;
    FILE * pFile = NULL;
    // find the location of the cache
    CString path = GetSpecialFolder(FOLDERID_LocalAppData);
    CString path2;
    if (!path.IsEmpty())
    {
        path += L"\\TSVNCache";
        if (!PathIsDirectory(path))
        {
            DeleteFile(path);
            if (CreateDirectory(path, NULL)==0)
                goto error;
        }
        path += STATUSCACHEFILENAME;
        // in case the cache file is corrupt, we could crash while
        // reading it! To prevent crashing every time once that happens,
        // we make a copy of the cache file and use that copy to read from.
        // if that copy is corrupt, the original file won't exist anymore
        // and the second time we start up and try to read the file,
        // it's not there anymore and we start from scratch without a crash.
        path2 = path;
        path2 += L"2";
        DeleteFile(path2);
        CopyFile(path, path2, FALSE);
        DeleteFile(path);
        pFile = _tfsopen(path2, L"rb", _SH_DENYNO);
        if (pFile)
        {
            try
            {
                LOADVALUEFROMFILE(value);
                if (value != CACHEDISKVERSION)
                {
                    goto error;
                }
                int mapsize = 0;
                LOADVALUEFROMFILE(mapsize);
                for (int i=0; i<mapsize; ++i)
                {
                    LOADVALUEFROMFILE2(value);
                    if (value > MAX_PATH)
                        goto error;
                    if (value)
                    {
                        CString sKey;
                        if (fread(sKey.GetBuffer(value+1), sizeof(TCHAR), value, pFile)!=value)
                        {
                            sKey.ReleaseBuffer(0);
                            goto error;
                        }
                        sKey.ReleaseBuffer(value);
                        std::unique_ptr<CCachedDirectory> cacheddir (new CCachedDirectory());
                        if (!cacheddir.get() || !cacheddir->LoadFromDisk(pFile))
                        {
                            cacheddir.reset();
                            goto error;
                        }
                        CTSVNPath KeyPath = CTSVNPath(sKey);
                        if (m_pInstance->IsPathAllowed(KeyPath))
                        {
                            // only add the path to the watch list if it is versioned
                            if ((cacheddir->GetCurrentFullStatus() != svn_wc_status_unversioned)&&(cacheddir->GetCurrentFullStatus() != svn_wc_status_none))
                                m_pInstance->watcher.AddPath(KeyPath, false);

                            m_pInstance->m_directoryCache[KeyPath] = cacheddir.release();

                            // do *not* add the paths for crawling!
                            // because crawled paths will trigger a shell
                            // notification, which makes the desktop flash constantly
                            // until the whole first time crawling is over
                            // m_pInstance->AddFolderForCrawling(KeyPath);
                        }
                    }
                }
            }
            catch (CAtlException)
            {
                goto error;
            }
        }
    }
exit:
    if (pFile)
        fclose(pFile);
    if (!path2.IsEmpty())
        DeleteFile(path2);
    m_pInstance->watcher.ClearInfoMap();
    CTraceToOutputDebugString::Instance()(__FUNCTION__ ": cache loaded from disk successfully!\n");
    return;
error:
    if (pFile)
        fclose(pFile);
    if (!path2.IsEmpty())
        DeleteFile(path2);
    m_pInstance->watcher.ClearInfoMap();
    Destroy();
    m_pInstance = new CSVNStatusCache;
    CTraceToOutputDebugString::Instance()(__FUNCTION__ ": cache not loaded from disk\n");
}
Ejemplo n.º 28
0
// load the station data from a file
// pszFile = the file name + path for the ini file to be loaded
// pszShortFile = the file name of the ini file, but not including the path
// Data = the struct to load the ini content to, and return to previous function
static void LoadStationData(TCHAR *pszFile, TCHAR *pszShortFile, WIDATA *Data)
{
	WIDATAITEM DataItem;
	char *Group, *Temp;
	char *ValName, *Value;

	static const char *statusStr[10] =
	{
		"LIGHTNING",
		"FOG",
		"SNOW SHOWER",
		"SNOW",
		"RAIN SHOWER",
		"RAIN",
		"PARTLY CLOUDY",
		"CLOUDY",
		"SUNNY",
		"N/A"
	};

	// clean up old stuff
	memset(Data, 0, sizeof(*Data));
	Data->Enabled = FALSE;

	// open the ini file
	FILE *pfile = _tfsopen(pszFile, _T("rt"), _SH_DENYWR);
	if (pfile != NULL) {
		char Line[4096];
		fgets(Line, _countof(Line), pfile);
		TrimString(Line);

		// make sure it is a valid weather protocol ini file
		if (!mir_strcmp(Line, "[Weather 0.3.x Update Data]"))
			Data->InternalVer = 1;
		else if (!mir_strcmp(Line, "[Weather 0.3.x Update Data 1.1]"))
			Data->InternalVer = 2;
		else if (!mir_strcmp(Line, "[Weather 0.3.x Update Data 1.1a]"))
			Data->InternalVer = 3;
		else if (!mir_strcmp(Line, "[Weather 0.3.x Update Data 1.2]"))
			Data->InternalVer = 4;
		else if (!mir_strcmp(Line, "[Weather 0.3.x Update Data 1.3]"))
			Data->InternalVer = 5;
		else if (!mir_strcmp(Line, "[Weather 0.3.x Update Data 1.4]"))
			Data->InternalVer = 6;
		else if (!mir_strcmp(Line, "[Weather 0.3.x Update Data 1.5]"))
			Data->InternalVer = 7;
		else {
			TCHAR str[4096];
			mir_sntprintf(str, TranslateT("Invalid ini format for: %s"), pszFile);
			MessageBox(NULL, str, TranslateT("Weather Protocol"), MB_OK | MB_ICONERROR);
			fclose(pfile);
			return;
		}

		// initialize all data fields
		Group = "";

		Data->DisplayName = _T("");
		Data->InternalName = _T("");
		Data->Description = _T("");
		Data->Author = _T("");
		Data->Version = _T("");
		Data->DefaultURL = "";
		Data->DefaultMap = _T("");
		Data->UpdateURL = "";
		Data->UpdateURL2 = "";
		Data->UpdateURL3 = "";
		Data->UpdateURL4 = "";
		Data->Cookie = "";
		Data->UserAgent = "";
		Data->IDSearch.SearchURL = "";
		Data->IDSearch.NotFoundStr = _T("");
		Data->NameSearch.SearchURL = "";
		Data->NameSearch.NotFoundStr = _T("");
		Data->NameSearch.SingleStr = _T("");
		Data->NameSearch.Single.First = _T("");
		Data->NameSearch.Multiple.First = _T("");
		Data->IDSearch.Available = FALSE;
		Data->NameSearch.Single.Available = FALSE;
		Data->NameSearch.Multiple.Available = FALSE;
		wSetData(&Data->FileName, pszFile);
		wSetData(&Data->ShortFileName, pszShortFile);

		ResetDataItem(&Data->IDSearch.Name, _T("ID Search - Station Name"));
		ResetDataItem(&Data->NameSearch.Single.Name, _T("Name Search Single Result - Station Name"));
		ResetDataItem(&Data->NameSearch.Single.ID, _T("Name Search Single Result - Station ID"));
		ResetDataItem(&Data->NameSearch.Multiple.Name, _T("Name Search Multiple Result - Station Name"));
		ResetDataItem(&Data->NameSearch.Multiple.ID, _T("Name Search Multiple Result - Station ID"));

		DataItem.Name = _T("");
		DataItem.Start = _T("");
		DataItem.End = _T("");
		DataItem.Unit = _T("");
		DataItem.Url = "";
		DataItem.Break = _T("");
		DataItem.Type = 0;

		Temp = "";

		// initialize the linked list for update items
		Data->UpdateDataCount = 0;
		Data->MemUsed = sizeof(WIDATA) + sizeof(WIDATALIST) + (mir_tstrlen(pszShortFile) + mir_tstrlen(pszFile) + 20)*sizeof(TCHAR);
		Data->UpdateData = NULL;
		Data->UpdateDataTail = NULL;

		// initialize the icon assignment list
		for (int i = 0; i < 10; i++)
			WICondListInit(&Data->CondList[i]);

		while (!feof(pfile)) {
			// determine current tag

			if (fgets(Line, _countof(Line), pfile) == NULL)
				break;
			TrimString(Line);

			// if the line is a group header/footer
			if (Line[0] == '[') {
				char *chop = strchr(Line + 1, ']');
				if (chop == NULL)
					continue;

				if (Line[1] != '/') {	// if it is not a footer (for old ini)
					// save the group name
					Temp = (char *)mir_alloc(mir_strlen(Line) + 10);
					strncpy(Temp, Line + 1, chop - Line - 1);
					Temp[chop - Line - 1] = 0;
					wfree(&Group);
					wSetData(&Group, Temp);
					// see if it is a update item, if it is, add a new item to the linked list
					//					if (_stricmp(Group, "HEADER") && _stricmp(Group, "DEFAULT") && _stricmp(Group, "ID SEARCH") && 
					//					strcmpi(Group, "NAME SEARCH"))
					//						wSetData(&DataItem.Name, Group);
					if (_stricmp(Group, "HEADER") && _stricmp(Group, "DEFAULT") && _stricmp(Group, "ID SEARCH") &&
						_stricmp(Group, "NAME SEARCH") && _stricmp(Group, "ICONS")) {
						wSetData(&DataItem.Name, Temp);
						DataItem.Type = WID_NORMAL;
						WIItemListAdd(&DataItem, Data);
						Data->UpdateDataCount++;
					}
					mir_free(Temp);
				}
				else {
					wfree(&Group);
					wSetData(&Group, "");
				}
			}
			// ignore comments and all lines without an '='
			Value = strstr(Line, "=");
			if (Value == NULL)	continue;

			// get the string before '=' (ValName) and after '=' (Value)
			ValName = (char *)mir_alloc(mir_strlen(Line) + 1);
			strncpy(ValName, Line, Value - Line);
			ValName[Value - Line] = 0;
			Value++;
			ConvertBackslashes(Value);
			// store the value for each string
			if (!_stricmp(Group, "HEADER")) {
				if (!_stricmp(ValName, "NAME"))						wSetData(&Data->DisplayName, Value);
				else if (!_stricmp(ValName, "INTERNAL NAME"))	wSetData(&Data->InternalName, Value);
				else if (!_stricmp(ValName, "DESCRIPTION"))		wSetData(&Data->Description, Value);
				else if (!_stricmp(ValName, "AUTHOR")) 			wSetData(&Data->Author, Value);
				else if (!_stricmp(ValName, "VERSION")) 			wSetData(&Data->Version, Value);
			}
			else if (!_stricmp(Group, "DEFAULT")) {
				if (!_stricmp(ValName, "DEFAULT URL"))				wSetData(&Data->DefaultURL, Value);
				else if (!_stricmp(ValName, "DEFAULT MAP"))		wSetData(&Data->DefaultMap, Value);
				else if (!_stricmp(ValName, "UPDATE URL"))		wSetData(&Data->UpdateURL, Value);
				else if (!_stricmp(ValName, "UPDATE URL2"))		wSetData(&Data->UpdateURL2, Value);
				else if (!_stricmp(ValName, "UPDATE URL3"))		wSetData(&Data->UpdateURL3, Value);
				else if (!_stricmp(ValName, "UPDATE URL4"))		wSetData(&Data->UpdateURL4, Value);
				else if (!_stricmp(ValName, "COOKIE"))				wSetData(&Data->Cookie, Value);
				else if (!_stricmp(ValName, "USERAGENT"))			wSetData(&Data->UserAgent, Value);
			}
			else if (!_stricmp(Group, "ID SEARCH")) {
				if (!_stricmp(ValName, "AVAILABLE")) {
					if (!_stricmp(Value, "TRUE"))				Data->IDSearch.Available = TRUE;
					else										Data->IDSearch.Available = FALSE;
				}
				else if (!_stricmp(ValName, "SEARCH URL"))		wSetData(&Data->IDSearch.SearchURL, Value);
				else if (!_stricmp(ValName, "NOT FOUND STR"))	wSetData(&Data->IDSearch.NotFoundStr, Value);
				else if (!_stricmp(ValName, "NAME START")) 		wSetData(&Data->IDSearch.Name.Start, Value);
				else if (!_stricmp(ValName, "NAME END")) 		wSetData(&Data->IDSearch.Name.End, Value);
			}
			else if (!_stricmp(Group, "NAME SEARCH")) {
				if (!_stricmp(ValName, "SINGLE RESULT")) {
					if (!_stricmp(Value, "TRUE"))				Data->NameSearch.Single.Available = TRUE;
					else										Data->NameSearch.Single.Available = FALSE;
				}
				else if (!_stricmp(ValName, "MULTIPLE RESULT")) {
					if (!_stricmp(Value, "TRUE"))				Data->NameSearch.Multiple.Available = TRUE;
					else										Data->NameSearch.Multiple.Available = FALSE;
				}
				else if (!_stricmp(ValName, "SEARCH URL"))		wSetData(&Data->NameSearch.SearchURL, Value);
				else if (!_stricmp(ValName, "NOT FOUND STR"))	wSetData(&Data->NameSearch.NotFoundStr, Value);
				else if (!_stricmp(ValName, "SINGLE RESULT STR")) wSetData(&Data->NameSearch.SingleStr, Value);
				else if (!_stricmp(ValName, "SINGLE FIRST"))	wSetData(&Data->NameSearch.Single.First, Value);
				else if (!_stricmp(ValName, "SINGLE NAME START"))wSetData(&Data->NameSearch.Single.Name.Start, Value);
				else if (!_stricmp(ValName, "SINGLE NAME END")) wSetData(&Data->NameSearch.Single.Name.End, Value);
				else if (!_stricmp(ValName, "SINGLE ID START"))	wSetData(&Data->NameSearch.Single.ID.Start, Value);
				else if (!_stricmp(ValName, "SINGLE ID END")) 	wSetData(&Data->NameSearch.Single.ID.End, Value);
				else if (!_stricmp(ValName, "MULT FIRST"))		wSetData(&Data->NameSearch.Multiple.First, Value);
				else if (!_stricmp(ValName, "MULT NAME START"))	wSetData(&Data->NameSearch.Multiple.Name.Start, Value);
				else if (!_stricmp(ValName, "MULT NAME END")) 	wSetData(&Data->NameSearch.Multiple.Name.End, Value);
				else if (!_stricmp(ValName, "MULT ID START"))	wSetData(&Data->NameSearch.Multiple.ID.Start, Value);
				else if (!_stricmp(ValName, "MULT ID END")) 	wSetData(&Data->NameSearch.Multiple.ID.End, Value);
			}
			else if (!_stricmp(Group, "ICONS")) {
				for (int i = 0; i < 10; i++) {
					if (!_stricmp(ValName, statusStr[i])) {
						WICondListAdd(Value, &Data->CondList[i]);
						break;
					}
				}
			}
			else if (Data->UpdateDataCount != 0) {
				if (!_stricmp(ValName, "START")) 			wSetData(&Data->UpdateDataTail->Item.Start, Value);
				else if (!_stricmp(ValName, "SOURCE"))		wSetData(&Data->UpdateDataTail->Item.Start, Value);
				else if (!_stricmp(ValName, "END")) 		wSetData(&Data->UpdateDataTail->Item.End, Value);
				else if (!_stricmp(ValName, "UNIT")) 		wSetData(&Data->UpdateDataTail->Item.Unit, Value);
				else if (!_stricmp(ValName, "URL")) 		wSetData(&Data->UpdateDataTail->Item.Url, Value);
				else if (!_stricmp(ValName, "HIDDEN")) {
					if (!_stricmp(Value, "TRUE")) {
						TCHAR *nm = Data->UpdateDataTail->Item.Name;
						size_t len = mir_tstrlen(nm) + 1;

						Data->UpdateDataTail->Item.Name = nm = (TCHAR*)mir_realloc(nm, sizeof(TCHAR)*(len + 3));
						memmove(nm + 1, nm, len*sizeof(TCHAR));
						*nm = '#';
					}
				}
				else if (!_stricmp(ValName, "SET DATA")) {
					Data->UpdateDataTail->Item.Type = WID_SET;
					wSetData(&Data->UpdateDataTail->Item.End, Value);
				}
				else if (!_stricmp(ValName, "BREAK DATA")) {
					Data->UpdateDataTail->Item.Type = WID_BREAK;
					wSetData(&Data->UpdateDataTail->Item.Break, Value);
				}
			}
			// recalculate memory used
			Data->MemUsed += (mir_strlen(Value) + 10);
			wfree(&ValName);
		}
		// calcualate memory used for the ini and close the file
		Data->MemUsed += sizeof(WIDATAITEMLIST)*Data->UpdateDataCount;
		Data->Enabled = TRUE;	// enable the service
		fclose(pfile);
		wfree(&Group);
	}
}
Ejemplo n.º 29
0
bool CServerListCtrl::StaticServerFileRemove(const CServer *server)
{
	try
	{
		if (!server->IsStaticMember())
			return true;

		CString strLine;
		CString strTest;
		TCHAR buffer[1024];
		int lenBuf = 1024;
		int pos;
		CString StaticFilePath = thePrefs.GetConfigDir() + _T("staticservers.dat");
		CString StaticTempPath = thePrefs.GetConfigDir() + _T("statictemp.dat");
		FILE* staticservers = _tfsopen(StaticFilePath , _T("r"), _SH_DENYWR);
		FILE* statictemp = _tfsopen(StaticTempPath , _T("w"), _SH_DENYWR);

		if ((staticservers == NULL) || (statictemp == NULL))
		{
			if (staticservers)
				fclose(staticservers);
			if (statictemp)
				fclose(statictemp);
			LogError(LOG_STATUSBAR, GetResString(IDS_ERROR_SSF));
			return false;
		}

		while (!feof(staticservers))
		{
			if (_fgetts(buffer, lenBuf, staticservers) == 0)
				break;

			strLine = buffer;

			// ignore comments or invalid lines
			if (strLine.GetAt(0) == _T('#') || strLine.GetAt(0) == _T('/'))
				continue;
			if (strLine.GetLength() < 5)
				continue;

			// Only interested in "host:port"
			pos = strLine.Find(_T(','));
			if (pos == -1)
				continue;
			strLine = strLine.Left(pos);

			// Get host and port from given server
			strTest.Format(_T("%s:%i"), server->GetAddress(), server->GetPort());

			// Compare, if not the same server write original line to temp file
			if (strLine.Compare(strTest) != 0)
				_ftprintf(statictemp, buffer);
		}

		fclose(staticservers);
		fclose(statictemp);

		// All ok, remove the existing file and replace with the new one
		CFile::Remove( StaticFilePath );
		CFile::Rename( StaticTempPath, StaticFilePath );
	}
	catch (...)
	{
		ASSERT(0);
		return false;
	}
	return true;
}