Esempio n. 1
0
void CCaHtmlParse::__GetPriceAndRamainTicket(UINT *pPrice, UINT *pRemainTicket, const TidyDoc & tdoc, const TidyNode & tdNode)
{
	CStringA straRet;
	*pPrice = 0;
	*pRemainTicket = 0;

	TidyBuffer text = {0};
	tidyBufInit(&text);
	TidyNodeType type = tidyNodeGetType(tdNode);
	tidyNodeGetText(tdoc, tdNode, &text);
	straRet.Format("%s",text.bp);
	straRet.TrimLeft();

	CStringA straKey("</font>");
	int iPos = straRet.Find(straKey);
	int iEndPos = straRet.Find("</strong>");
	int iStartPos = iPos+straKey.GetLength();
	CStringA straPrice = straRet.Mid(iStartPos, iEndPos-iStartPos);
	straPrice.Remove(0x0d);//去掉回车
	straPrice.Remove(0x0a);//去掉换行
	*pPrice = atoi(straPrice.GetBuffer(0));
	straPrice.ReleaseBuffer();

	//剩余座位
	straKey = ":";
	iPos = straRet.Find(straKey);
	iEndPos = straRet.Find("</td>");
	iStartPos = iPos+straKey.GetLength();
	CStringA straRemainSeat = straRet.Mid(iStartPos, iEndPos-iStartPos);
	*pRemainTicket = atoi(straRemainSeat.GetBuffer(0));
	straRemainSeat.ReleaseBuffer();

	tidyBufFree(&text);
}
bool QueryRegistryValue(const CStringA strRegPath, CStringA& strValue)
{
	HKEY hRootKey = NULL;
	CStringA strSubPath;
	if (!GetRootKeyAndSubPath(strRegPath, hRootKey, strSubPath))
		return false;

	int nVal = strSubPath.ReverseFind('\\');
	CStringA strItem = strSubPath.Mid(nVal + 1);
	strSubPath = strSubPath.Mid(0, nVal);

	if (strItem == ".")
		strItem = "";

	HKEY hSubKey = NULL;
	if (RegOpenKeyExA(hRootKey,	strSubPath, 0, KEY_READ, &hSubKey) == ERROR_SUCCESS)
	{
		CHAR szFile[1024];
		DWORD BufferSize = 1024;
		LONG ret = RegQueryValueExA(hSubKey, strItem, NULL, NULL, (LPBYTE)szFile, &BufferSize);
		RegCloseKey(hSubKey);

		if (ret == ERROR_SUCCESS)
			strValue = szFile;

		return ret == ERROR_SUCCESS;
	}

	return false;
}
void EnumDir(CStringA resToken, int nEnumSubdir, std::vector<CString>& vecFiles)
{
	int nEndSlash = resToken.ReverseFind('\\');
	if (nEndSlash == -1)
		return;

	USES_CONVERSION;

	CStringA path = resToken.Mid(0, nEndSlash);
	CStringA findname = resToken.Mid(nEndSlash + 1);

	// file
	WIN32_FIND_DATAA fd;
	memset(&fd, 0, sizeof(WIN32_FIND_DATAA));
	HANDLE hFind = FindFirstFileA(resToken, &fd);

	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			CStringA subname = fd.cFileName;
			if (subname != "." && subname != "..")
			{
				CStringA fname = path + "\\" + subname;
				if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				{
				}
				else
					vecFiles.push_back(A2CT(fname));
			}
		} while (FindNextFileA(hFind, &fd) != 0);

		FindClose(hFind);
	}

	// directory
	if (nEnumSubdir > 0)
	{
		hFind = FindFirstFileA(path + "\\*.*", &fd);

		if (hFind != INVALID_HANDLE_VALUE)
		{
			do
			{
				CStringA subname = fd.cFileName;
				if (subname != "." && subname != "..")
				{
					CStringA fname = path + "\\" + subname;
					if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
						EnumDir(fname + "\\" + findname, nEnumSubdir, vecFiles);
				}
			} while (FindNextFileA(hFind, &fd) != 0);

			FindClose(hFind);

		}
	}
}
Esempio n. 4
0
void CCaHtmlParse::__GetAirPortCode(CStringA & straDCode, CStringA & straACode, const TidyDoc & tdoc, const TidyNode & tdNode)
{
	CStringA straRet;
	CStringA straSha("上海虹桥");
	CStringA straPvg("上海浦东");
	CStringA straPek("北京首都");
	CStringA straNay("北京南苑");

	straDCode = "";
	straACode = "";

	TidyBuffer text = {0};
	tidyBufInit(&text);
	TidyNodeType type = tidyNodeGetType(tdNode);
	tidyNodeGetText(tdoc, tdNode, &text);
	straRet.Format("%s",text.bp);
	straRet.TrimLeft();

	CStringA straKey("<br />");//<br />后有回车换行符
	int iPos = straRet.Find(straKey);
	CStringA straDCity = straRet.Mid(4, iPos-4);
	if (-1 != straDCity.Find(straSha))
		straDCode = "SHA";
	else if (-1 != straDCity.Find(straPvg))
		straDCode = "PVG";
	else if (-1 != straDCity.Find(straPek))
		straDCode = "PEK";
	else if(-1 != straDCity.Find(straNay))
		straDCode = "NAY";
	else
	{

	}

	//取到达机场,<br />后有回车换行符
	straRet = straRet.Mid(iPos+straKey.GetLength());
	straRet.Remove(0x0d);//去掉回车
	straRet.Remove(0x0a);//去掉换行
	int iEndPos = straRet.Find("</td>");
	CStringA straACity = straRet.Left(iEndPos);
	if (-1 != straACity.Find(straSha))
		straACode = "SHA";
	else if (-1 != straACity.Find(straPvg))
		straACode = "PVG";
	else if (-1 != straACity.Find(straPek))
		straACode = "PEK";
	else if(-1 != straACity.Find(straNay))
		straACode = "NAY";
	else
	{

	}

	tidyBufFree(&text);
}
void EnumRegistry(CStringA strRegPath, std::vector<CStringA>& vecOutRegPaths)
{
	int nStar = strRegPath.Find('*');
	if (nStar != -1)
	{
		// multi-*
		if (nStar != (strRegPath.GetLength() - 1) && strRegPath.Find('*', nStar + 1) != -1)
			return;
	}
	else
	{
		vecOutRegPaths.push_back(strRegPath);
		return;
	}

	CStringA strLeftPart, strRightPart;
	
	strLeftPart = strRegPath.Mid(0, nStar);
	strRightPart = strRegPath.Mid(nStar + 1);

	if (strLeftPart.IsEmpty())
		return;

	if (strLeftPart.GetAt(strLeftPart.GetLength() - 1) != '\\')
		return;

	if (!strRightPart.IsEmpty() && strRightPart.GetAt(0) != '\\')
		return;

	strLeftPart.TrimRight('\\');
	strRightPart.TrimLeft('\\');

	HKEY hRootKey = NULL;
	CStringA strSubKey;
	if (!GetRootKeyAndSubPath(strLeftPart, hRootKey, strSubKey))
		return;

	HKEY hSubKey = NULL;
	if (RegOpenKeyExA(hRootKey,	strSubKey, 0, KEY_READ, &hSubKey) == ERROR_SUCCESS)
	{
		CHAR achKey[255];
		for (DWORD i = 0; ; i++)
		{
			DWORD cbName = 255;
			if (ERROR_SUCCESS == RegEnumKeyExA(hSubKey, i, achKey, &cbName, NULL, NULL, NULL, NULL))
				vecOutRegPaths.push_back(strLeftPart + "\\" + achKey + "\\" + strRightPart);
			else
				break;
		}

		RegCloseKey(hSubKey);
	}
}
Esempio n. 6
0
void DLrtfhtml::openfile(CString filename)
{
	CStdioFile rtf;
	rtf.Open(_T("F:\\\\itbook2.tit"),CStdioFile::modeRead);
	int len=rtf.GetLength();
	rtf.SeekToBegin();
	CStringA content;
	rtf.Read(content.GetBuffer(len),len);
	content.ReleaseBuffer();
	rtf.Close();

	char* str,*strd;
	str=strd=new char[len+1];
	memset(str,'\0',sizeof(str));
	int bg,end;
	bg=end=0;
	char* p;
	while((end=content.Find("\\\'",end))>=0)
	{
		if(end==0 || content.GetAt(end-1)!='\\')
		{//转汉字
			CStringA s;
			if(end!=bg)
			{
				strcpy(str,(LPSTR)(LPCSTR)content.Mid(bg,end-bg));
				str+=(end-bg);
			}
			*str=strtol(content.Mid(end+2,2),&p,16);
			str++;
			bg=end+4;
		}
		else
		{// \\' 去斜杆
			if(end!=bg)
			{
				strcpy(str,(LPSTR)(LPCSTR)content.Mid(bg,end-bg-1)); //   '之前还有两个" \ "
				str+=(end-bg-1);
			}
			strcpy(str,(LPSTR)(LPCSTR)content.Mid(end,2));
			str+=2;
			bg=end+2;
		}
		end++;
	}
	int leng=content.GetLength();
	if((content.GetLength()-bg)>2)//如果再最后两个字符找到\'则会=2  当然根据rtf文档绝对不会这样。
		strcpy(str,(LPSTR)(LPCSTR)content.Mid(bg));
	//}
	int  unicodeLen = ::MultiByteToWideChar( CP_ACP,0,strd,-1,NULL,0);  
	MultiByteToWideChar(CP_ACP,0,strd,-1,(LPWSTR)destcon.GetBuffer(unicodeLen),unicodeLen);
	destcon.ReleaseBuffer();
}
Esempio n. 7
0
BOOL LoadIDs(LPCTSTR szFilename)
{
	BOOL bSuccess = FALSE;

	FILE* pFile = NULL;
	if ( _tfopen_s( &pFile, szFilename, _T("rb") ) == 0 )
	{
		for (;;)
		{
			CStringA sLine;
			CHAR* res = fgets( sLine.GetBuffer( 4096 ), 4096, pFile );
			sLine.ReleaseBuffer();
			if ( ! res )
				break;		// End of file
			sLine.Trim( " \t\r\n" );
			if ( sLine.IsEmpty() || sLine.GetAt( 0 ) != '#' )
				continue;		// Skip empty lines
			int nPos = sLine.FindOneOf( " \t" );
			if ( nPos == -1 || sLine.Left( nPos ) != "#define" )
				continue;		// Skip unknown line
			sLine = sLine.Mid( nPos + 1 ).TrimLeft( " \t" );
			nPos = sLine.FindOneOf( " \t" );
			if ( nPos == -1 )
				continue;		// Skip unknown line
			CStringA sID = sLine.Left( nPos );
			sLine = sLine.Mid( nPos + 1 ).TrimLeft( " \t" );
			UINT nID = 0;
			if ( sLine.Left( 2 ).CompareNoCase( "0x" ) == 0 )
			{
				if ( sscanf_s( sLine, "%x", &nID ) != 1 )
					continue;	// Skip unknown line
			}
			else
			{
				if ( sscanf_s( sLine, "%u", &nID ) != 1 )
					continue;	// Skip unknown line
			}
			if ( g_oIDs.Lookup( sID, nID ) )
			{
				_tprintf( _T("Error: Duplicate ID %hs\n"), sID );
				continue;
			}
			g_oIDs.SetAt( sID, nID );
			bSuccess = TRUE;
		}
		fclose( pFile );
	}

	return bSuccess;
}
Esempio n. 8
0
void CFileTextLines::StripAsciiWhiteSpace(CStringA& sLine,DWORD dwIgnoreWhitespaces, bool blame)
{
	if (blame)
	{
		if (sLine.GetLength() > 66)
			sLine = sLine.Mid(66);
	}
	switch (dwIgnoreWhitespaces)
	{
	case 0: // Compare whitespaces
		// do nothing
		break;
	case 1:
		// Ignore all whitespaces
		StripAsciiWhiteSpace(sLine);
		break;
	case 2:
		// Ignore leading whitespace
		sLine.TrimLeft(" \t");
		break;
	case 3:
		// Ignore leading whitespace
		sLine.TrimRight(" \t");
		break;
	}
}
Esempio n. 9
0
BOOL ProcessString(CStringA sID, CStringA sString)
{
	const int len = sString.GetLength();
	if ( sString.GetAt( 0 ) != '\"' || sString.GetAt( len - 1 ) != '\"' )
	{
		_tprintf( _T("Error: Invalid string format \"%hs\"\n"), sString );
		return FALSE;
	}
	sString = sString.Mid( 1, len - 2 );

	UINT nID = 0;
	if ( ! g_oIDs.Lookup( sID, nID ) )
	{
		_tprintf( _T("Warning: Unknown ID %hs \"%hs\"\n"), sID, sString );
		return TRUE;
	}

	CSSPair sFoo;
	if ( g_oStrings.Lookup( nID, sFoo ) )
	{
		_tprintf( _T("Error: Duplicate ID %hs \"%hs\"\n"), sID, sString );
		return FALSE;
	}

	g_oStrings.SetAt( nID, CSSPair( sString, sID ) );

	return TRUE;
}
Esempio n. 10
0
bool CIPFilter::ParseFilterLine2(const CStringA& sbuffer, uint32& ip1, uint32& ip2, UINT& level, CStringA& desc) const
{
	int iPos = sbuffer.ReverseFind(':');
	if (iPos < 0)
		return false;

	desc = sbuffer.Left(iPos);
	desc.Replace("PGIPDB", "");
	desc.Trim();

	CStringA strIPRange = sbuffer.Mid(iPos + 1, sbuffer.GetLength() - iPos);
	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)
		return false;

	((BYTE*)&ip1)[0] = (BYTE)u4;
	((BYTE*)&ip1)[1] = (BYTE)u3;
	((BYTE*)&ip1)[2] = (BYTE)u2;
	((BYTE*)&ip1)[3] = (BYTE)u1;

	((BYTE*)&ip2)[0] = (BYTE)u8;
	((BYTE*)&ip2)[1] = (BYTE)u7;
	((BYTE*)&ip2)[2] = (BYTE)u6;
	((BYTE*)&ip2)[3] = (BYTE)u5;

	level = DFLT_FILTER_LEVEL;

	return true;
}
Esempio n. 11
0
extern "C" void __declspec(dllexport) detect_httpd(
  HWND hwndParent, 
  int string_size, 
	char *variables, 
  stack_t **stacktop)
{
	EXDLL_INIT();

	TCHAR str[1024];
	ULONG len = 1024;
	char szPath[1024]="";
	bool bDetected = false;

	CRegKey regKey;
	if(ERROR_SUCCESS==regKey.Open(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\services\\Apache2.2")))
	{
		if(ERROR_SUCCESS==regKey.QueryStringValue(_T("ImagePath"), str, &len))
		{
			bDetected = true;
		}
	}

	CStringA sPath = str;
	int nPos = sPath.Find("\\bin\\httpd.exe");
	if(nPos<0)
		bDetected = false;
	sPath = sPath.Mid(0, nPos);
	sPath.Replace("\"", "");
		
	if(bDetected)
		pushstring(sPath.GetBuffer());	
	else
		pushstring("");	
}
void SplitSysListContent(const CStringA& strContent)
{
	USES_CONVERSION;

	int curPos = 0;
	CStringA resToken = strContent.Tokenize("\r\n", curPos);
	while (resToken != "")
	{
		resToken.Trim();

		if (!resToken.IsEmpty() && resToken.GetAt(0) != '#')
		{
			int nPoundKey = resToken.Find('#');
			if (nPoundKey != -1)
				resToken = resToken.Mid(0, nPoundKey);

			resToken.Replace('/', '\\');

			// (1) 注册表
			if (resToken.GetAt(0) == '$')
			{
				if (resToken.GetLength() > 3)
				{
					if (resToken.GetAt(1) == '{')
						DoRegistryPath(resToken);
					else if (resToken.GetAt(1) == '[')
						DoRegistryFile(resToken);
				}
			}
			// (2) 单独文件
			else if (resToken.GetAt(0) == '@')
				DoOnlyFileName(resToken.Mid(1));

			// (3) 其他
			else
				DoFilePathName(resToken);
		}

		resToken = strContent.Tokenize("\r\n", curPos);
	}
}
Esempio n. 13
0
bool CPlayerTaskSocket::ParseHttpReq(CStringA strHtml, CStringA & rHashId, int & rnRange)
{
	rnRange = 0;
	rHashId.Empty();

	//  Not http GET command
	if(strnicmp(strHtml, "GET ", 4)!=0)
		return false;

	strHtml.Delete(0, 4);
	if(strHtml.GetAt(0)=='/')
		strHtml.Delete(0);

	int i;
	i=strHtml.Find("/");
	if(i<0) return false;

	rHashId = strHtml.Mid(0, i);
	strHtml.MakeLower();
	int n=strHtml.Find("range:");
	if(n>0)
	{
		n+=6;
		int iRangeEnd=strHtml.Find("\r\n", n);
		CStringA strRange=strHtml.Mid(n, iRangeEnd-n);
		while(! strRange.IsEmpty())
		{
			if(!isdigit(strRange.GetAt(0)))
				strRange.Delete(0);
			else break;
		}

		if(strRange.GetAt(strRange.GetLength()-1)=='-')
			strRange.Delete(strRange.GetLength()-1);

		strRange.Trim();

		rnRange = atol(strRange);
	}
	return true;
}
Esempio n. 14
0
void CCaHtmlParse::__GetSaleEndDate(CStringA & straEndDate, CStringA & straEndTime, const TidyDoc & tdoc, const TidyNode & tdNode)
{
	CStringA straRet;
	straEndDate = "";
	straEndTime = "";

	TidyBuffer text = {0};
	tidyBufInit(&text);
	TidyNodeType type = tidyNodeGetType(tdNode);
	tidyNodeGetText(tdoc, tdNode, &text);
	straRet.Format("%s",text.bp);
	straRet.TrimLeft();

	int iPos = straRet.Find("<br");
	straRet = straRet.Mid(4, iPos-4);
	straEndDate = straRet.Left(10);
	straEndTime = straRet.Mid(11);
	straEndTime.Trim();

	tidyBufFree(&text);
}
Esempio n. 15
0
void CCaHtmlParse::__GetFlightNoAndFlightStartDate(CStringA & strFlightNo, CStringA & strFlightStartDate, const TidyDoc & tdoc, const TidyNode & tdNode)
{
	CStringA straRet;
	strFlightNo = "";
	strFlightStartDate = "";

	TidyBuffer text = {0};
	tidyBufInit(&text);
	TidyNodeType type = tidyNodeGetType(tdNode);
	tidyNodeGetText(tdoc, tdNode, &text);
	straRet.Format("%s",text.bp);
	straRet.TrimLeft();
	strFlightStartDate = straRet.Mid(4, 10);
	int iStartPos = straRet.Find('C');//匹配CA,ca,Ca,cA,<br />后会插入回车换行符,
	if(-1 == iStartPos)//没找到大写C,匹配小写c
		iStartPos = straRet.Find('c');
	int iEndPos = straRet.Find("</");
	strFlightNo = straRet.Mid(iStartPos, iEndPos-iStartPos);//国航航班号有3位的,还有4位的
	strFlightNo = strFlightNo.MakeUpper();
	strFlightNo = strFlightNo.Mid(2);//去掉CA

	tidyBufFree(&text);
}
Esempio n. 16
0
BOOL CStdioFileEx::ReadAnsiString(CStringA& rString)
{
   _ASSERTE(m_pStream);
   rString = "";      // empty string without deallocating
   
   if(!m_bIsUnicodeText)
   {
      const int nMaxSize = 128;
      LPSTR lpsz = rString.GetBuffer(nMaxSize);
      LPSTR lpszResult;
      int nLen = 0;
      for (;;)
      {
         lpszResult = fgets(lpsz, nMaxSize+1, m_pStream);
         rString.ReleaseBuffer();
         
         // handle error/eof case
         if (lpszResult == NULL && !feof(m_pStream))
         {
            Afx_clearerr_s(m_pStream);
            AfxThrowFileException(CFileException::genericException, _doserrno,
               m_strFileName);
         }
         
         // if string is read completely or EOF
         if (lpszResult == NULL ||
            (nLen = (int)lstrlenA(lpsz)) < nMaxSize ||
            lpsz[nLen-1] == '\n')
            break;
         
         nLen = rString.GetLength();
         lpsz = rString.GetBuffer(nMaxSize + nLen) + nLen;
      }
      //remove crlf if exist.
      nLen = rString.GetLength();
      if (nLen > 1 && rString.Mid(nLen-2) == "\r\n")
      {
         rString.GetBufferSetLength(nLen-2);
      }
      return rString.GetLength() > 0;
   }
   else
   {
      CStringW wideString;
      BOOL bRetval = ReadWideString(wideString);
      //setlocale(LC_ALL, "chs_chn.936");//no need
      rString = wideString;
      return bRetval;
   }
}
bool GetRootKeyAndSubPath(const CStringA& strRegPath, HKEY& hRootKey, CStringA& strSubPath)
{
	bool ret = false;
	if (_strnicmp(strRegPath, "HKLM", 4) == 0)
	{
		hRootKey = HKEY_LOCAL_MACHINE;
		strSubPath = strRegPath.Mid(5);
		ret = true;
	}
	else if (_strnicmp(strRegPath, "HKCU", 4) == 0)
	{
		hRootKey = HKEY_CURRENT_USER;
		strSubPath = strRegPath.Mid(5);
		ret = true;
	}
	else if (_strnicmp(strRegPath, "HKCR", 4) == 0)
	{
		hRootKey = HKEY_CLASSES_ROOT;
		strSubPath = strRegPath.Mid(5);
		ret = true;
	}
	else if (_strnicmp(strRegPath, "HKCC", 4) == 0)
	{
		hRootKey = HKEY_CURRENT_CONFIG;
		strSubPath = strRegPath.Mid(5);
		ret = true;
	}
	else if (_strnicmp(strRegPath, "HKU", 3) == 0)
	{
		hRootKey = HKEY_USERS;
		strSubPath = strRegPath.Mid(4);
		ret = true;
	}

	return ret;
}
void DoFilePathName(CStringA resToken)
{
	CHAR expName[MAX_PATH + 1];
	ExpandEnvironmentStringsA(resToken, expName, MAX_PATH);
	resToken = expName;

	std::vector<CString>* pvecFiles = new std::vector<CString>;

	if (resToken.Find('*') != -1)
	{
		int nEnumSubdir = 0;
		int nLength = resToken.GetLength();
		if (nLength > 2 && resToken.Mid(nLength - 2).MakeLower() == "|s")
		{
			nEnumSubdir = 1;
			resToken = resToken.Mid(0, nLength - 2);
		}
		else if (nLength > 2 && resToken.Mid(nLength - 2).MakeLower() == "|a")
		{
			nEnumSubdir = 2;
			resToken = resToken.Mid(0, nLength - 2);
		}

		//std::vector<CString> vecFiles;
		EnumDir(resToken, nEnumSubdir, *pvecFiles);
	}
	else
	{
		USES_CONVERSION;

		pvecFiles->push_back(A2W(resToken));
	}

	g_sysModuleNameList.insert(g_sysModuleNameList.end(), (*pvecFiles).begin(), (*pvecFiles).end());
	delete pvecFiles;
}
Esempio n. 19
0
void CCookie::ParseFieldKV(const CStringA& strField, CStringA& strKey, CStringA& strVal, char chSep)
{
	int i = strField.Find(chSep);

	if(i < 0)
		strKey = strField;
	else
	{
		strKey = strField.Left(i);
		strVal = strField.Mid(i + 1);

		strVal.Trim();
	}

	strKey.Trim();
}
void DoRegistryFile(CStringA resToken)
{
	int nBrace = -1;
	int nBraceCnt = 1;
	for (int i = 2; i < resToken.GetLength(); i++)
	{
		if (resToken.GetAt(i) == '[')
			nBraceCnt++;
		else if (resToken.GetAt(i) == ']')
		{
			nBraceCnt--;
			if (nBraceCnt == 0)
			{
				nBrace = i;
				break;
			}
		}
	}

	if (nBrace == -1)
		return;

	USES_CONVERSION;

	CStringA strRegPath = resToken.Mid(2, nBrace - 2);

	std::vector<CStringA> vecOutRegPaths;
	EnumRegistry(strRegPath, vecOutRegPaths);

	int cnt = vecOutRegPaths.size();
	for (int i = 0; i < cnt; i++)
	{
		CStringA strFilePath;
		if (QueryRegistryValue(vecOutRegPaths.at(i), strFilePath))
		{
			CHAR expName[MAX_PATH + 1];
			ExpandEnvironmentStringsA(strFilePath, expName, MAX_PATH);
			strFilePath = expName;

			if (strFilePath.Find('\\') != -1)
				DoFilePathName(strFilePath);
			else
				DoOnlyFileName(strFilePath);
		}
	}
}
Esempio n. 21
0
void CCaHtmlParse::__GetFlightStartTime(CStringA & strFlightStartTime, const TidyDoc & tdoc, const TidyNode & tdNode)
{
	CStringA straRet;
	strFlightStartTime = "";

	TidyBuffer text = {0};
	tidyBufInit(&text);
	TidyNodeType type = tidyNodeGetType(tdNode);
	tidyNodeGetText(tdoc, tdNode, &text);
	straRet.Format("%s",text.bp);

	CStringA straKey("\">");
	int iStartPos = straRet.Find(straKey);
	int iEndPos = straRet.Find("</strong>");
	iStartPos = iStartPos+straKey.GetLength();
	strFlightStartTime = straRet.Mid(iStartPos, iEndPos-iStartPos);

	tidyBufFree(&text);
}
Esempio n. 22
0
void CWebSocket::OnRequestReceived(char* pHeader, DWORD dwHeaderLen, char* pData, DWORD dwDataLen, in_addr inad)
{
	CStringA sHeader(pHeader, dwHeaderLen);
	CStringA sData(pData, dwDataLen);
	CStringA sURL;
	bool filereq=false;

	if(sHeader.Left(3) == "GET")
		sURL = sHeader.Trim();

	else if(sHeader.Left(4) == "POST")
		sURL = "?" + sData.Trim();	// '?' to imitate GET syntax for ParseURL

	if(sURL.Find(" ") > -1)
		sURL = sURL.Mid(sURL.Find(" ")+1, sURL.GetLength());
	if(sURL.Find(" ") > -1)
		sURL = sURL.Left(sURL.Find(" "));

	if (sURL.GetLength()>4 &&	// min length (for valid extentions)
		(sURL.Right(4).MakeLower()==".gif" || sURL.Right(4).MakeLower()==".jpg" || sURL.Right(4).MakeLower()==".png" ||
		sURL.Right(4).MakeLower()==".ico" ||sURL.Right(4).MakeLower()==".css" ||sURL.Right(3).MakeLower()==".js" ||
		sURL.Right(4).MakeLower()==".bmp" || sURL.Right(5).MakeLower()==".jpeg"
		)
		&& sURL.Find("..")==-1	// dont allow leaving the emule-webserver-folder for accessing files
		)
			filereq=true;

	ThreadData Data;
	Data.sURL = sURL;
	Data.pThis = m_pParent;
	Data.inadr = inad;
	Data.pSocket = this;

	if (!filereq)
		m_pParent->ProcessURL(Data);
	else
		m_pParent->ProcessFileReq(Data);

	Disconnect();
}
Esempio n. 23
0
    CStringA GetToken(const CStringA& strData, LPCSTR szPrefix, LPCSTR szPostfix, int& nStart)
    {
        CStringA strResult;
        if(nStart < 0)
        {
            AtlThrow(E_INVALIDARG);
            return strResult;
        }

        size_t nPrefixLen = strlen(szPrefix);
        size_t nPostfixLen = strlen(szPostfix);

        int begin = strData.Find(szPrefix, nStart);
        if(begin == -1)
            return strResult;

        nStart = begin + nPrefixLen;
        int end = strData.Find(szPostfix, nStart);
        if(end == -1)
            return strResult;

        strResult = strData.Mid(begin + nPrefixLen, end - begin - nPrefixLen);
        return strResult;
    }
Esempio n. 24
0
void CWebSocket::OnRequestReceived(char *pHeader, DWORD dwHeaderLen, char *pData, DWORD dwDataLen)
{
	EMULE_TRY

	CStringA	sHeader(pHeader, dwHeaderLen);
	CStringA	sURL;
	int			iIdx;
	bool		bFileReq = false;

	if (sHeader.Left(3) == "GET")
	{
		sURL = sHeader.TrimRight();
	}
	else if (sHeader.Left(4) == "POST")
	{
		CStringA		sData(pData, dwDataLen);

		sURL = '?';
		sURL += sData.Trim();	// '?' to imitate GET syntax for ParseURL
	}
	iIdx = sURL.Find(' ');
	if (iIdx >= 0)
		sURL = sURL.Mid(iIdx + 1);
	iIdx = sURL.Find(' ');
	if (iIdx >= 0)
		sURL = sURL.Left(iIdx);

	if (sURL.GetLength() > 4)
	{
		CStringA	strExt4 = sURL.Right(4).MakeLower();

		if (( (strExt4 == ".gif") || (strExt4 == ".jpg") || (strExt4 == ".png") ||
			(strExt4 == ".ico") || (strExt4 == ".css") || (sURL.Right(3).MakeLower() == ".js") ||
			(strExt4 == ".bmp") || (sURL.Right(5).MakeLower() == ".jpeg") || (strExt4 == ".xml") || (strExt4 == ".txt") )
			&& sURL.Find("..") < 0 )	// don't allow leaving the emule-webserver-folder for accessing files
		{
			bFileReq = true;
		}
	}

// HTTP header AcceptEncoding
	CStringA	strAcceptEncoding;
	iIdx = sHeader.Find("Accept-Encoding: ");
	if (iIdx >= 0)
	{
		int	iIdx2 = sHeader.Find("\r\n", iIdx += 17);

		strAcceptEncoding = sHeader.Mid(iIdx, iIdx2 - iIdx);
	}
// End AcceptEncoding

// HTTP header IfModifiedSince
	CStringA	strIfModifiedSince;
	iIdx = sHeader.Find("If-Modified-Since: ");
	if (iIdx >= 0)
	{
		int	iIdx2 = sHeader.Find("\r\n", iIdx += 19);

		strIfModifiedSince = sHeader.Mid(iIdx, iIdx2 - iIdx);
	}
// End IfModifiedSince

	ThreadData Data;

	Data.sURL = sURL;
	Data.pThis = m_pParent;
	Data.pSocket = this;
	Data.strAcceptEncoding = strAcceptEncoding;
	Data.strIfModifiedSince = strIfModifiedSince;

	if (!bFileReq)
		m_pParent->ProcessGeneralReq(Data);
	else
		m_pParent->ProcessFileReq(Data);

	Disconnect();

	EMULE_CATCH2
}
Esempio n. 25
0
bool CWebServer::CallCGI(CWebClientSocket* pClient, CStringA& hdr, CStringA& body, CStringA& mime)
{
    CString path = pClient->m_path, redir = path;
    if (!ToLocalPath(path, redir)) {
        return false;
    }
    CString ext = CPath(path).GetExtension().MakeLower();
    CPath dir(path);
    dir.RemoveFileSpec();

    CString cgi;
    if (!m_cgi.Lookup(ext, cgi) || !CPath(cgi).FileExists()) {
        return false;
    }

    HANDLE hProcess = GetCurrentProcess();
    HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup = NULL;
    HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup = NULL;

    SECURITY_ATTRIBUTES saAttr;
    ZeroMemory(&saAttr, sizeof(saAttr));
    saAttr.nLength = sizeof(saAttr);
    saAttr.bInheritHandle = TRUE;

    if (CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
        BOOL fSuccess = DuplicateHandle(hProcess, hChildStdoutRd, hProcess, &hChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS);
        UNREFERENCED_PARAMETER(fSuccess);
        CloseHandle(hChildStdoutRd);
    }

    if (CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
        BOOL fSuccess = DuplicateHandle(hProcess, hChildStdinWr, hProcess, &hChildStdinWrDup, 0, FALSE, DUPLICATE_SAME_ACCESS);
        UNREFERENCED_PARAMETER(fSuccess);
        CloseHandle(hChildStdinWr);
    }

    STARTUPINFO siStartInfo;
    ZeroMemory(&siStartInfo, sizeof(siStartInfo));
    siStartInfo.cb = sizeof(siStartInfo);
    siStartInfo.hStdError = hChildStdoutWr;
    siStartInfo.hStdOutput = hChildStdoutWr;
    siStartInfo.hStdInput = hChildStdinRd;
    siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    siStartInfo.wShowWindow = SW_HIDE;

    PROCESS_INFORMATION piProcInfo;
    ZeroMemory(&piProcInfo, sizeof(piProcInfo));

    CStringA envstr;

    LPVOID lpvEnv = GetEnvironmentStrings();
    if (lpvEnv) {
        CString str;

        CAtlList<CString> env;
        for (LPTSTR lpszVariable = (LPTSTR)lpvEnv; *lpszVariable; lpszVariable += _tcslen(lpszVariable) + 1)
            if (lpszVariable != (LPTSTR)lpvEnv) {
                env.AddTail(lpszVariable);
            }

        env.AddTail(_T("GATEWAY_INTERFACE=CGI/1.1"));
        env.AddTail(_T("SERVER_SOFTWARE=Media Player Classic - Home Cinema/") MPC_VERSION_STR);
        env.AddTail(_T("SERVER_PROTOCOL=") + pClient->m_ver);
        env.AddTail(_T("REQUEST_METHOD=") + pClient->m_cmd);
        env.AddTail(_T("PATH_INFO=") + redir);
        env.AddTail(_T("PATH_TRANSLATED=") + path);
        env.AddTail(_T("SCRIPT_NAME=") + redir);
        env.AddTail(_T("QUERY_STRING=") + pClient->m_query);

        if (pClient->m_hdrlines.Lookup(_T("content-type"), str)) {
            env.AddTail(_T("CONTENT_TYPE=") + str);
        }
        if (pClient->m_hdrlines.Lookup(_T("content-length"), str)) {
            env.AddTail(_T("CONTENT_LENGTH=") + str);
        }

        POSITION pos = pClient->m_hdrlines.GetStartPosition();
        while (pos) {
            CString key = pClient->m_hdrlines.GetKeyAt(pos);
            CString value = pClient->m_hdrlines.GetNextValue(pos);
            key.Replace(_T("-"), _T("_"));
            key.MakeUpper();
            env.AddTail(_T("HTTP_") + key + _T("=") + value);
        }

        CString name;
        UINT port;

        if (pClient->GetPeerName(name, port)) {
            str.Format(_T("%d"), port);
            env.AddTail(_T("REMOTE_ADDR=") + name);
            env.AddTail(_T("REMOTE_HOST=") + name);
            env.AddTail(_T("REMOTE_PORT=") + str);
        }

        if (pClient->GetSockName(name, port)) {
            str.Format(_T("%d"), port);
            env.AddTail(_T("SERVER_NAME=") + name);
            env.AddTail(_T("SERVER_PORT=") + str);
        }

        env.AddTail(_T("\0"));

        str = Implode(env, '\0');
        envstr = CStringA(str, str.GetLength());

        FreeEnvironmentStrings((LPTSTR)lpvEnv);
    }

    TCHAR* cmdln = DNew TCHAR[32768];
    _sntprintf_s(cmdln, 32768, 32768, _T("\"%s\" \"%s\""), cgi, path);

    if (hChildStdinRd && hChildStdoutWr)
        if (CreateProcess(
                    NULL, cmdln, NULL, NULL, TRUE, 0,
                    envstr.GetLength() ? (LPVOID)(LPCSTR)envstr : NULL,
                    dir, &siStartInfo, &piProcInfo)) {
            DWORD ThreadId;
            CreateThread(NULL, 0, KillCGI, (LPVOID)piProcInfo.hProcess, 0, &ThreadId);

            static const int BUFFSIZE = 1024;
            DWORD dwRead, dwWritten = 0;

            int i = 0, len = pClient->m_data.GetLength();
            for (; i < len; i += dwWritten)
                if (!WriteFile(hChildStdinWrDup, (LPCSTR)pClient->m_data + i, min(len - i, BUFFSIZE), &dwWritten, NULL)) {
                    break;
                }

            CloseHandle(hChildStdinWrDup);
            CloseHandle(hChildStdoutWr);

            body.Empty();

            CStringA buff;
            while (i == len && ReadFile(hChildStdoutRdDup, buff.GetBuffer(BUFFSIZE), BUFFSIZE, &dwRead, NULL) && dwRead) {
                buff.ReleaseBufferSetLength(dwRead);
                body += buff;
            }

            int hdrend = body.Find("\r\n\r\n");
            if (hdrend >= 0) {
                hdr = body.Left(hdrend + 2);
                body = body.Mid(hdrend + 4);
            }

            CloseHandle(hChildStdinRd);
            CloseHandle(hChildStdoutRdDup);

            CloseHandle(piProcInfo.hProcess);
            CloseHandle(piProcInfo.hThread);
        } else {
            body = _T("CGI Error");
        }

    delete [] cmdln;

    return true;
}
Esempio n. 26
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();
}
Esempio n. 27
0
BOOL CCookie::ParseExpires(LPCSTR lpszExpires, __time64_t& tmExpires)
{
	int iLength = (int)strlen(lpszExpires);

	if(iLength == 0 || iLength > 50)
		return FALSE;

	char szMonth[10];
	char szZone[10];

	tm t = {0};

	if(sscanf(	lpszExpires, "%*[^, ]%*[, ]%2d%*[-/ ]%8[^-/ ]%*[-/ ]%4d %2d:%2d:%2d %8c", 
				&t.tm_mday, szMonth, &t.tm_year, &t.tm_hour, &t.tm_min, &t.tm_sec, szZone) != 7)
		return FALSE;

	if(t.tm_year < 70)
		t.tm_year += 100;
	else if (t.tm_year > 100)
		t.tm_year -= 1900;

	int i	 = 0;
	int size = _countof(s_short_month);

	for(; i < size; i++)
	{
		if(strnicmp(szMonth, s_short_month[i], 3) == 0)
			break;
	}

	if(i == size)
		return FALSE;

	t.tm_mon = i;

	CStringA strZone = szZone;

	int iZone	= 0;
	int iMix	= 0;
	int iPos	= strZone.Find('+');

	if(iPos >= 0)
		iMix = 1;
	else
	{
		iPos = strZone.Find('-');

		if(iPos >= 0)
			iMix = -1;
	}

	if(iPos >= 0)
	{
		strZone = strZone.Mid(iPos + 1);
		strZone.Remove(':');

		int val = atoi(strZone);

		if(val > 0)
		{
			int minutes	= val % 100;
			int hours	= val / 100;

			iZone = iMix * (minutes * 60 + hours * 3600);
		}
	}

	tmExpires = GetUTCTime(t, iZone);

	return tmExpires >= 0;
}
Esempio n. 28
0
BOOL LoadResources(LPCTSTR szFilename)
{
	FILE* pFile = NULL;
	if ( _tfopen_s( &pFile, szFilename, _T("rb") ) == 0 )
	{
		CStringA sID;
		for ( States nState = stFile ; nState != stError ; )
		{
			CStringA sLine;
			CHAR* res = fgets( sLine.GetBuffer( 4096 ), 4096, pFile );
			sLine.ReleaseBuffer();
			if ( ! res )
			{
				if ( nState != stFile )
					_tprintf( _T("Error: Unexpected end of file\n") );

				break;		// End of file
			}
			sLine.Trim( ", \t\r\n" );
			if ( sLine.IsEmpty() ||
				 sLine.GetAt( 0 ) == '/' ||
				 sLine.GetAt( 0 ) == '#' )
				continue;	// Skip empty line, comment and pragma

			switch ( nState )
			{
			case stFile:
				if ( sLine == "STRINGTABLE" )
					nState = stStringTable;
				else if ( sLine == "GUIDELINES DESIGNINFO" )
					nState = stGuidelines;
				else
				{
					int nPos = sLine.Find( " DIALOG" );		// DIALOG or DIALOGEX
					if ( nPos != -1 )
					{
						CStringA sID = sLine.SpanExcluding( " " );
						UINT nID;
						if ( ! g_oIDs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Unknown ID \"%hs\" inside DIALOG\n"), sID );
							return 2;
						}
						if ( g_oDialogs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Duplicate ID \"%hs\" inside DIALOG\n"), sID );
							return 2;
						}
						g_oDialogs.SetAt( sID, nID );
					}

					nPos = sLine.Find( " ICON " );
					if ( nPos != -1 )
					{
						CStringA sID = sLine.SpanExcluding( " " );
						UINT nID;
						if ( ! g_oIDs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Unknown ID \"%hs\" of ICON\n"), sID );
							return 2;
						}
						if ( g_oIcons.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Duplicate ID \"%hs\" of ICON\n"), sID );
							return 2;
						}
						g_oIcons.SetAt( sID, nID );
					}

					nPos = sLine.Find( " HTML " );
					if ( nPos == -1 )
						nPos = sLine.Find( " GZIP " );
					if ( nPos != -1 )
					{
						CStringA sID = sLine.SpanExcluding( " " );
						UINT nID;
						if ( ! g_oIDs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Unknown ID \"%hs\" of HTML\n"), sID );
							return 2;
						}
						if ( g_oHtmls.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Duplicate ID \"%hs\" of HTML\n"), sID );
							return 2;
						}
						g_oHtmls.SetAt( sID, nID );
					}

					nPos = sLine.Find( " BITMAP " );
					if ( nPos == -1 )
						nPos = sLine.Find( " JPEG " );
					if ( nPos == -1 )
						nPos = sLine.Find( " PNG " );
					if ( nPos != -1 )
					{
						CStringA sID = sLine.SpanExcluding( " " );
						UINT nID;
						if ( ! g_oIDs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Unknown ID \"%hs\" of BITMAP\n"), sID );
							return 2;
						}
						if ( g_oBitmaps.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Duplicate ID \"%hs\" of BITMAP\n"), sID );
							return 2;
						}
						g_oBitmaps.SetAt( sID, nID );
					}
				}
				break;

			case stGuidelines:
				if ( sLine == "BEGIN" )
					nState = stGuidelinesContent;
				else
				{
					_tprintf( _T("Error: BEGIN not found after GUIDELINES DESIGNINFO\n") );
					return 2;
				}
				break;

			case stGuidelinesContent:
				if ( sLine == "END" )
					nState = stFile;
				else if ( sLine.Right( 6 ) == "DIALOG" )
				{
					nState = stGuidelinesDialog;
					CStringA sID = sLine.SpanExcluding( "," );
					UINT nID;
					if ( ! g_oIDs.Lookup( sID, nID ) )
					{
						_tprintf( _T("Error: Unknown dialog ID \"%hs\" inside GUIDELINES\n"), sID );
						return 2;
					}
					if ( g_oGuidelines.Lookup( sID, nID ) )
					{
						_tprintf( _T("Error: Duplicate dialog ID \"%hs\" inside GUIDELINES\n"), sID );
						return 2;
					}
					if ( ! g_oDialogs.Lookup( sID, nID ) )
					{
						_tprintf( _T("Error: Orphan dialog ID \"%hs\" inside GUIDELINES\n"), sID );
						return 2;
					}
					g_oGuidelines.SetAt( sID, nID );
				}
				else
				{
					_tprintf( _T("Error: Unknown line \"%hs\" inside GUIDELINES\n"), sLine );
					return 2;
				}
				break;

			case stGuidelinesDialog:
				if ( sLine == "END" )
					nState = stGuidelinesContent;
				break;

			case stStringTable:
				if ( sLine == "BEGIN" )
					nState = stContent;
				else
				{
					_tprintf( _T("Error: BEGIN not found after STRINGTABLE\n") );
					return 2;
				}
				break;

			case stContent:
				if ( sLine == "END" )
					nState = stFile;
				else
				{
					int nPos = sLine.FindOneOf( ", \t" );
					if ( nPos != -1 )
					{
						if ( ProcessString( sLine.Left( nPos ),
							sLine.Mid( nPos + 1 ).TrimLeft( ", \t" ) ) )
							nState = stContent;
						else
							nState = stError;
					}
					else
					{
						sID = sLine;
						nState =  stString;
					}
				}
				break;

			case stString:
				if ( ProcessString( sID, sLine ) )
					nState = stContent;
				else
					nState = stError;
				sID.Empty();
				break;
			}
		}

		fclose( pFile );
	}

	return TRUE;
}
Esempio n. 29
0
static bool fixLinks(CStringA& rtf, uidToTitleMap_t *uidToTitleMapPtr)
{
	// quick check, quick exit
	if (rtf.Find("\\lnkd\\protect") == -1)
		return false;

	int clrTableIndex = getColorTableIndex(rtf);
	if (clrTableIndex == -1)
	{
		// something bad happened
		return false;
	}

	// get code page
	unsigned codepage = CP_ACP;
	int cpgPos = rtf.Find("\\ansicpg");
	if (cpgPos != -1)
		codepage = atoi((LPCSTR)rtf + cpgPos + sizeof("\\ansicpg")-1);

	// for each pattern of 
	//		\lnkd\protect[<space>]<text>\protect0\lnkd0
	// replace with "out", where out is:
	//      sprintf(out, _linkRTF, <nodeurl>, clrTableIndex, <text>)
	// where <nodeurl> is:
	//		lookupNode(stripRTF(<text>))

	int pos, ofs = 0;
	while ( (pos = rtf.Find("\\lnkd\\protect", ofs)) != -1 )
	{
		// ofs2 points to start of text
		int ofs2 = pos + sizeof("\\lnkd\\protect")-1;

		// check if the \protect had a ' ' delimiter, eat it if so
		if (rtf[ofs2] == ' ')
			ofs2++;

		// locate the end tag
		int pos2 = rtf.Find("\\protect0\\lnkd0", ofs2);
		ASSERT(pos2 != -1);
		if (pos2 == -1)
			return false;

		// get the text inbetween
		// here is the link (title of page)..
		CStringA rtfLink = rtf.Mid(ofs2, pos2-ofs2);
		CString link = stripRTF(rtfLink, codepage);

		// look it up
		CStringA url;
		if (isURL(link))
		{
			// points to a URL itself (http://, https://, ftp:// etc..)
			url = escapeRTF(link);

			// There appears to be a strange bug with the rich edit control, in that if
			// the hyperlink and the text are exacly the same, the hyperlink effect goes
			// off. As a workaround, add a space after the URL (this is ignore in our
			// EN_LINK handler).
			url += " ";
		}
		else
		{
			uint32 nodeUid = 0;
			if (uidToTitleMapPtr->Lookup(link, nodeUid))
				// matched a node
				url.Format("node://./%u", nodeUid);
			else
				// unmatched node, we'll handle this later
				url.Format("oldlink://./%s", escapeRTF(link));
		}

		// make the replacement
		CStringA replacement;
		replacement.Format(_linkRTF, url, clrTableIndex, escapeRTF(link));

		// delete [pos, pos2+15]
		rtf.Delete(pos, pos2+15-pos);
		rtf.Insert(pos, replacement);

		// repositon to just after the replacement
		ofs = pos + replacement.GetLength();
	}

	return true;
}
void CFtpClientReqSocket::DataReceived(const BYTE* pucData, UINT uSize)
{	
	if( !IsEntireResponse((const char*)pucData,uSize) ) //先检查是否有一个完整HeaderLine回来了..
		return ;

	CStringA strLine;
	CStringA strNumber;
	CStringA strMultiNumber;
	CStringA strMultiReply;

	LPCSTR pData=(LPCSTR)pucData;
	bool bMultiLine = false;

	while ( uSize>0 )
	{
		LPCSTR pszNl = (LPCSTR)memchr(pData, '\n', uSize);

		if(!pszNl)
			return;
		
		int iLineLen = pszNl - pData;
		ASSERT( iLineLen >= 0 );
		if (iLineLen > 0)
			strLine = CStringA(pData, iLineLen - 1); 

		pData += (strLine.GetLength() + 2);
		uSize -= (strLine.GetLength() + 2);

		if( GetClient() )
		{
			GetClient()->AddPeerLog(new CTraceServerMessage(CString(strLine)));
		}

		BOOL bNumber = ( strLine.GetLength() >= 3 ) &&
			_istdigit( strLine[0] ) && _istdigit( strLine[1] ) && _istdigit( strLine[2] );

		if ( bNumber )
			strNumber = strLine.Left( 3 );

		if ( !bMultiLine && bNumber && strLine[3] == _T('-') )
		{
			// Got first line of multi-line reply
			bMultiLine = TRUE;
			strMultiNumber = strNumber;
			strMultiReply = strLine.Mid( 4 );
		}
		else if ( !bMultiLine && bNumber )
		{
			// Got single-line reply
			if ( !OnHeaderLine( strNumber, strLine.Mid( 4 ).Trim( " \t\r\n" ) ) ) 
				return ;
		}
		else if ( bMultiLine && bNumber && strLine[3] == ' ' &&
			strMultiNumber == strNumber )
		{
			// Got last line of multi-line reply
			bMultiLine = FALSE;
			strMultiReply += "\n";
			strMultiReply += strLine.Mid( 4 );
			if ( ! OnHeaderLine( strNumber, strMultiReply.Trim( " \t\r\n" ) ) )
				return ;
		}
		else if ( bMultiLine )
		{			
			strMultiReply += "\n";
			strMultiReply += strLine;
		}
	}
}