Ejemplo n.º 1
0
void SHTokenizeW( 
	const wstring& target, 
	vector<wstring>& tokens, 
	const wstring &delim 
	)
{
	wstring::size_type lastPos = target.find_first_not_of( delim );
	wstring::size_type pos = target.find_first_of( delim, lastPos );

	while( wstring::npos != pos || wstring::npos != lastPos )
	{
		tokens.push_back( target.substr(lastPos, pos - lastPos) );
		lastPos = target.find_first_not_of( delim, pos );
		pos = target.find_first_of( delim, lastPos );
	}
}
    /**
    Gather the Major and Minor version from Product version

    Parameters:  version - Product version, its format like 11.23.32, REV- or 0.4b41

    */
    void InstalledSoftwareInstance::SetDetailedVersion(const wstring& version)
    {
        size_t pos = version.find_first_of('.');
        if( pos != wstring::npos )
        {
            wstring left = version.substr(0, pos);
            wstring right = version.substr(pos+1);
            try
            {
                m_versionMajor = StrToUInt(left);
                // Exclude characters
                for(pos = 0; pos< right.size(); pos++)
                {
                    if( right[pos] < '0' || right[pos] > '9' ) {
                        break;
                    }
                }
                if(pos > 0) {
                    left = right.substr(0, pos);
                    m_versionMinor = StrToUInt(left);
                }
            }
            catch (const SCXException& e)
            {
                SCX_LOGWARNING(m_log, StrAppend(L"parse InstalledSoftwareInstance version fails:", version).append(L" - ").append(e.What()));
            }
        }
    }
Ejemplo n.º 3
0
int CRealTextParser::GetTimecode(const wstring& p_crszTimecode)
{
	int iTimecode(0);
	int iMultiplier(1);

	// Exception: if the timecode doesn't contain any separators, assume the time code is in seconds (and change multiplier to reflect that)
	if (p_crszTimecode.find_first_of('.') == wstring::npos && p_crszTimecode.find_first_of(':') == wstring::npos)
		iMultiplier = 1000;

	wstring szCurrentPart;

	for (int i = p_crszTimecode.length() - 1; i >= 0; --i)
	{
		if (p_crszTimecode.at(i) == '.' || p_crszTimecode.at(i) == ':')
		{
			if (iMultiplier == 1)
			{
				while (szCurrentPart.length() < 3)
					szCurrentPart += L"0";
			}

			iTimecode += iMultiplier * ::_wtoi(szCurrentPart.c_str());

			if (iMultiplier == 1)
			{
				iMultiplier = 1000;
			}
			else
			{
				iMultiplier *= 60;
			}

			szCurrentPart = L"";
		}
		else
		{
			szCurrentPart = p_crszTimecode.substr(i, 1) + szCurrentPart;
		}
	}

	iTimecode += iMultiplier * ::_wtoi(szCurrentPart.c_str());

	return iTimecode;
}
Ejemplo n.º 4
0
HRESULT CDataTuple::GetNextValue(int &iVal, wstring &line, size_t &start)
{
	HRESULT hRet = E_FAIL;
	size_t	 end;
	wstring	sep(TEXT(" \t"), 1);

	if (start >= line.length())
	{
		return hRet;
	}

	end = line.find_first_of (sep, start+1);

	wstring substr;

	if (string::npos != end && end > start)
	{
		substr = line.substr(start, end -start);
	}
	else
	{
		substr = line.substr(start, line.length() -start);
	}

	if (substr.length() > 0)
	{
		float val;
		if (1 == _stscanf_s(substr.c_str(), TEXT("%f"), &val))
		{
			iVal = (int)val;
			hRet = S_OK;
		}
	}
	else
	{
		start = string::npos;
	}

	if (SUCCEEDED(hRet) && end != string::npos)
	{
		start = line.find(sep, end);

		while (start < line.length() && line[start +1] == ' ')
		{
			++start;
		}

	}
	else
	{
		start = string::npos;
	}

	return hRet;
}
Ejemplo n.º 5
0
void EraseChars(wstring& str, const wchar_t chars[]) {
  size_t pos = 0;

  do {
    pos = str.find_first_of(chars, pos);

    if (pos != wstring::npos)
      str.erase(pos, 1);

  } while (pos != wstring::npos);
}
Ejemplo n.º 6
0
void ReplaceChar(wstring& str, const wchar_t c, const wchar_t replace_with) {
  if (c == replace_with)
    return;

  size_t pos = 0;

  do {
    pos = str.find_first_of(c, pos);
    if (pos != wstring::npos)
      str.at(pos) = replace_with;
  } while (pos != wstring::npos);
}
Ejemplo n.º 7
0
void ReplaceChars(wstring& str, const wchar_t chars[],
                  const wstring replace_with) {
  if (chars == replace_with)
    return;

  size_t pos = 0;

  do {
    pos = str.find_first_of(chars, pos);
    if (pos != wstring::npos)
      str.replace(pos, 1, replace_with);
  } while (pos != wstring::npos);
}
Ejemplo n.º 8
0
//The data has the following form in each line.
//"dialog title"    "button text"
//
void parse_line(const wstring& line, wstring& dlg_title, wstring& ctrl_text)
{
    //Retrieve the title
    size_t first_quote = line.find_first_of(QUOTE, 0);
    if(first_quote == wstring::npos)
        return;
    first_quote = first_quote + 1;
    size_t second_quote = line.find_first_of(QUOTE, first_quote);
    if(second_quote == wstring::npos)
        return;
    dlg_title = line.substr(first_quote, second_quote - first_quote);

    //Retrieve the control text.
    first_quote = line.find_first_of(QUOTE, second_quote + 1);
    if(first_quote == wstring::npos)
        return;
    first_quote = first_quote + 1;
    second_quote = line.find_first_of(QUOTE, first_quote);
    if(second_quote == wstring::npos)
        return;
    ctrl_text = line.substr(first_quote, second_quote - first_quote);
}
Ejemplo n.º 9
0
    /**
        Extract a vector of the substrings that are separated by one of the delimter characters

        \param    str          String to tokenize
        \param    tokens       Return a vector of tokens
        \param    delimiters   String containing the delimeter charachters
        \param    trim         true if all tokens should be trimmed (default), otherwise false
        \param    emptyTokens  false if empty tokens should be removed from the result (default), otherwise true.
        \param    keepDelimiters true if delimiters found should be added to the token vector, otherwise (default)
                                 delimiters are removed.

    */
    void StrTokenize(const wstring& str, vector<std::wstring>& tokens,
                     const wstring& delimiters, bool trim, bool emptyTokens, bool keepDelimiters)
    {
        tokens.clear();

        wstring::size_type lastPos = 0;
        wstring::size_type pos = delimiters.empty()?wstring::npos:str.find_first_of(delimiters);

        while (wstring::npos != pos)
        {
            wstring tmp = str.substr(lastPos, pos - lastPos);
            if ( ! tmp.empty() && trim)
            {
                tmp = StrTrim(tmp);
            }
            if ( ! tmp.empty() || emptyTokens)
            {
                tokens.push_back(tmp);
            }
            if ( keepDelimiters )
            {
                tokens.push_back(str.substr(pos, 1));
            }
            lastPos = pos + 1;
            // Find next "non-delimiter"
            pos = str.find_first_of(delimiters, lastPos);
        }

        wstring tmp = str.substr(lastPos, wstring::npos);
        if ( ! tmp.empty() && trim)
        {
            tmp = StrTrim(tmp);
        }
        if ( ! tmp.empty() || emptyTokens)
        {
            tokens.push_back(tmp);
        }
    }
Ejemplo n.º 10
0
// vds: >>
wstring EscapeCommand(wstring cmd) {
	wstring ret;
	size_t cursor = 0;
	while (true) {
		size_t pos = cmd.find_first_of(L"\"", cursor);
		if (pos == wstring::npos) {
			ret += cmd.substr(cursor);
			break;
		}
		ret += cmd.substr(cursor, pos - cursor);
		ret += wstring(L"\\\"");
		cursor = pos + 1;
	}

	return ret;
}
Ejemplo n.º 11
0
size_t Tokenize(const wstring& str, const wstring& delimiters,
                vector<wstring>& tokens) {
  tokens.clear();

  size_t index_begin = str.find_first_not_of(delimiters);

  while (index_begin != wstring::npos) {
    size_t index_end = str.find_first_of(delimiters, index_begin + 1);
    if (index_end == wstring::npos) {
      tokens.push_back(str.substr(index_begin));
      break;
    } else {
      tokens.push_back(str.substr(index_begin, index_end - index_begin));
      index_begin = str.find_first_not_of(delimiters, index_end + 1);
    }
  }

  return tokens.size();
}
Ejemplo n.º 12
0
vector <int> ApplicationVersion::GetComponents(wstring version)
{
	vector <int> components;
	int start = 0, end = 0, pos, num;
	wstring number;

	// Do not use it with strings
	for (unsigned int i = 0; i < version.size(); i++)
		assert(iswdigit(version[i]) || version[i] == L'.');

	do
	{
		pos = version.find_first_of(SEPARATOR, end);
		start = end;
		end = pos;
		number = version.substr(start, end - start);
		num = _wtoi(number.c_str());
		components.push_back(num);
		end = end + SEPARATOR_LEN;
		
	} while (pos != string::npos);

	return components;
}
Ejemplo n.º 13
0
extern vector<wstring> TokenizeWString(const wstring& src, wstring tok, bool trim, wstring null_subst)
{   
	if( src.empty() || tok.empty() ) 
	{
		throw "TokenizeString: empty string\0";   
	}
	
	vector<wstring> v;   
	S_T pre_index = 0, index = 0, len = 0;  
	
	while( (index = src.find_first_of(tok, pre_index)) != npos )   
	{   
		if( (len = index-pre_index)!=0 )   
		{
			v.push_back(src.substr(pre_index, len));   
		}
		else if(trim==false)   
		{
			v.push_back(null_subst);   
		}
		
		pre_index = index+1;   
	}   
	
	wstring endstr = src.substr(pre_index);   
	if( trim==false )
	{
		v.push_back( endstr.empty()?null_subst:endstr );   
	}
	else if( !endstr.empty() )
	{
		v.push_back(endstr);   
	}
	
	return v;   
}   
Ejemplo n.º 14
0
int InStrChars(const wstring& str1, const wstring& str2, int pos) {
  size_t i = str1.find_first_of(str2, pos);
  return (i != wstring::npos) ? i : -1;
}
Ejemplo n.º 15
0
bool CRealTextParser::GetAttributes(wstring& p_rszLine, unsigned int& p_riPos, map<wstring, wstring>& p_rmapAttributes)
{
    if (!SkipSpaces(p_rszLine, p_riPos)) {
        return false;
    }

    while (p_riPos > p_rszLine.length() && p_rszLine.at(p_riPos) != '/' && p_rszLine.at(p_riPos) != '>') {
        wstring szName;
        if (!GetString(p_rszLine, p_riPos, szName, L"\r\n\t =")) {
            return false;
        }

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }

        if (p_rszLine.at(p_riPos) != '=') {
            if (m_bTryToIgnoreErrors) {
                p_riPos = (unsigned int)p_rszLine.find_first_of('=', p_riPos);
                if (p_riPos == wstring::npos) {
                    return false;
                }
            } else {
                return false;
            }
        }

        ++p_riPos;

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }

        bool bUsesQuotes(false);
        if (p_rszLine.at(p_riPos) == '\'' || p_rszLine.at(p_riPos) == '\"') {
            ++p_riPos;
            bUsesQuotes = true;
        }

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }

        wstring szValue;
        if (bUsesQuotes) {
            if (!GetString(p_rszLine, p_riPos, szValue, L"\"\'/>")) {
                return false;
            }
        } else {
            if (!GetString(p_rszLine, p_riPos, szValue, L" \t/>")) {
                return false;
            }
        }

        p_rmapAttributes[StringToLower(szName)] = szValue;

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }

        if (p_rszLine.at(p_riPos) == '\'' || p_rszLine.at(p_riPos) == '\"') {
            ++p_riPos;
        }

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }
    }

    return p_rszLine.length() > p_riPos;
}
Ejemplo n.º 16
0
bool CRealTextParser::ExtractTag(wstring& p_rszLine, Tag& p_rTag)
{
    if (p_rszLine.length() < 2 || p_rszLine.at(0) != '<') {
        if (m_bTryToIgnoreErrors) {
            size_t iTempPos = p_rszLine.find_first_of('<');

            if (iTempPos != wstring::npos) {
                p_rszLine = p_rszLine.substr(iTempPos);

                if (p_rszLine.length() < 2) {
                    return false;
                }
            }

        } else {
            return false;
        }
    }

    unsigned int iPos = 1;

    // skip comments
    if (p_rszLine.at(iPos) == '!') {
        p_rTag.m_bComment = true;

        wstring szComment;
        GetString(p_rszLine, iPos, szComment, L">");
        p_rTag.m_szName = szComment;

        ++iPos; // Skip >
        if (iPos < p_rszLine.length()) {
            p_rszLine = p_rszLine.substr(iPos);
            return true;
        } else {
            return false;
        }
    } else {
        p_rTag.m_bComment = false;
    }

    if (!SkipSpaces(p_rszLine, iPos)) {
        return false;
    }

    if (p_rszLine.at(iPos) == '/') {
        p_rTag.m_bOpen = false;
        p_rTag.m_bClose = true;
        ++iPos;
    } else {
        p_rTag.m_bOpen = true;
        p_rTag.m_bClose = false;
    }

    if (!GetString(p_rszLine, iPos, p_rTag.m_szName, L"\r\n\t />")) {
        return false;
    }

    p_rTag.m_szName = StringToLower(p_rTag.m_szName);

    if (!GetAttributes(p_rszLine, iPos, p_rTag.m_mapAttributes)) {
        return false;
    }

    if (p_rszLine.at(iPos) == '/') {
        ++iPos;
        p_rTag.m_bClose = true;
    }

    if (p_rszLine.at(iPos) == '>') {
        ++iPos;
        p_rszLine = p_rszLine.substr(iPos);
        return true;
    } else {
        if (m_bTryToIgnoreErrors) {
            size_t iTempPos = p_rszLine.find_first_of('>');

            if (iTempPos != wstring::npos) {
                if (iTempPos - 1 >= p_rszLine.length()) {
                    return false;
                }

                p_rszLine = p_rszLine.substr(iTempPos + 1);
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }
}
Ejemplo n.º 17
0
bool ExFriends::OnWhoisRequest(wstring aText)
{
//Nie mozna bylo odnalezc uzytkownika
//Bzik*Bzik is using Diablo II Lord of Destruction and is currently in private game "Emce".
//Uzytkownik ostatni raz byl widziany : Sun Feb 07 19:47:19
//REAL BN:
//testosdas (*tt) is using Diablo II Lord of Destruction in a private game.
#ifdef D2EX_CLOSED_BNET
	if(BNQuene.size() == 0) return true;

	if(aText.find(L"That user is not logged on.")!=wstring::npos ||
	   aText.find(L"That character is not logged on.")!=wstring::npos) { 
		   EnterCriticalSection(&EX_CRITSECT);
		   string aName = BNQuene.front().substr(7);
		   BNQuene.pop_front();
		   ExParty::Update();
		   LeaveCriticalSection(&EX_CRITSECT);
		   return false;
	}
	wstring::size_type Tok = aText.find_first_of(L"*");
	if(Tok == wstring::npos) return false; 
	wstring::size_type Tok2 = aText.find_first_of(L")",Tok);
	if(Tok == wstring::npos) return false; 
	wstring Char = aText.substr(0,Tok-2);
	wstring Acc = aText.substr(Tok+1,Tok2-Tok-1);
	string szChar, szAcc;
	Misc::WideToChar(szAcc, Acc);
	Misc::WideToChar(szChar,Char);
	ExParty::UpdateAccount(szChar, szAcc);
	EnterCriticalSection(&EX_CRITSECT);
	BNQuene.pop_front();
	LeaveCriticalSection(&EX_CRITSECT);
	ExParty::Update();
#else
		if (gBNCSRequests<0)
			gBNCSRequests = 0;

		if (!gBNCSRequests) {
			gBNCSResponseTick = 0;
			return true;
		}

	if(aText.find(L"Nie mozna bylo odnalezc uzytkownika")!=wstring::npos || 
	   aText.find(L"Unknown user.")!=wstring::npos || 
	   aText.find(L"User was last seen on:")!=wstring::npos || 
	   aText.find(L"Uzytkownik ostatni raz byl widziany") != wstring::npos) {
		gBNCSResponseTick = GetTickCount();
		gBNCSRequests--; return false;
	}
	wstring::size_type Tok = aText.find_first_of(L"*");
	if(Tok == wstring::npos) return false; 
	wstring::size_type Tok2 = aText.find_first_of(L" ",Tok);
	if(Tok == wstring::npos) return false; 
	wstring Char = aText.substr(0,Tok);
	wstring Acc = aText.substr(Tok+1,Tok2-Tok-1);
	string szChar, szAcc;
	Misc::WideToChar(szAcc,Acc);
	Misc::WideToChar(szChar,Char);
	ExParty::UpdateAccount(szChar, szAcc);
	gBNCSResponseTick = GetTickCount();
	gBNCSRequests--;
	ExParty::Update();
#endif

	return false;
}
Ejemplo n.º 18
0
void PerfTest::ParseCmdline(int argc, wchar_t* argv[])
{
    for (int i = 1; i < argc; ++i)
    {
        wstring arg(argv[i]);
        vector<wstring> tokens;
        StringUtility::Split<wstring>(arg, tokens, L":");
        if ((tokens.size() != 2) || !StringUtility::StartsWith(tokens.front(), L"-"))
        {
            console.WriteLine("arg[{0}] = '{1}', token count = {2}, 2 expected", i, arg, tokens.size());
            if (!tokens.empty())
            {
                console.WriteLine("tokens: {0}", tokens);
            }
            PrintUsageAndExit();
        }

#ifndef PLATFORM_UNIX
        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), remoteArg))
        {
            remotePath = tokens[1];
            console.WriteLine("remote path = {0}", remotePath);
            if (!StringUtility::StartsWith(remotePath, L"\\\\"))
            {
                console.WriteLine("Invalid UNC path: {0}", remotePath);
                PrintUsageAndExit();
            }

            auto pos = remotePath.find_first_of(L"\\", 2);
            computer = remotePath.substr(0, pos);
            if (computer.empty())
            {
                console.WriteLine("Invalid UNC path: {0}", remotePath);
                PrintUsageAndExit();
            }

            if (pos != wstring::npos)
            {
                remoteWorkDir = remotePath.substr(pos + 1, remotePath.length() - pos - 1);
            }

            if (remoteWorkDir.empty() || (remoteWorkDir[1] != L'$'))
            {
                console.WriteLine("Invalid UNC path: {0}", remotePath);
                PrintUsageAndExit();
            }

            remoteWorkDir[1] = L':';
            console.WriteLine("remote computer = {0}", computer);
            console.WriteLine("remote work directory = {0}", remoteWorkDir);

            continue;
        }
#endif

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), bsizeMinArg))
        {
            if (!StringUtility::TryFromWString(tokens[1], tcpBufferSizeMin_))
            {
                console.WriteLine("Failed to parse '{0}' as buffer size", tokens[1]); 
                PrintUsageAndExit();
            }
            continue;
        }

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), bsizeMaxArg))
        {
            if (!StringUtility::TryFromWString(tokens[1], tcpBufferSizeMax_))
            {
                console.WriteLine("Failed to parse '{0}' as buffer size", tokens[1]); 
                PrintUsageAndExit();
            }
            continue;
        }

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), dataArg))
        {
            if (!StringUtility::TryFromWString(tokens[1], testDataSize_))
            {
                console.WriteLine("Failed to parse '{0}' as data size", tokens[1]); 
                PrintUsageAndExit();
            }
            continue;
        }

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), tminArg))
        {
            if (!StringUtility::TryFromWString(tokens[1], clientThreadMin_))
            {
                console.WriteLine("Failed to parse '{0}' as thread count", tokens[1]); 
                PrintUsageAndExit();
            }
            continue;
        }

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), tmaxArg))
        {
            if (!StringUtility::TryFromWString(tokens[1], clientThreadMax_))
            {
                console.WriteLine("Failed to parse '{0}' as thread count", tokens[1]); 
                PrintUsageAndExit();
            }
            continue;
        }

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), mminArg))
        {
            if (!StringUtility::TryFromWString(tokens[1], messageSizeMin_))
            {
                console.WriteLine("Failed to parse '{0}' as message size", tokens[1]); 
                PrintUsageAndExit();
            }
            continue;
        }

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), mmaxArg))
        {
            if (!StringUtility::TryFromWString(tokens[1], messageSizeMax_))
            {
                console.WriteLine("Failed to parse '{0}' as message size", tokens[1]); 
                PrintUsageAndExit();
            }
            continue;
        }

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), qrArg))
        {
            if (!StringUtility::TryFromWString(tokens[1], shouldQueueReceivedMessage_))
            {
                console.WriteLine("Failed to parse '{0}' as boolean", tokens[1]); 
                PrintUsageAndExit();
            }
            continue;
        }

        if (StringUtility::AreEqualCaseInsensitive(tokens.front(), securityArg))
        {
            if (!SecurityProvider::FromCredentialType(tokens[1], securityProvider).IsSuccess())
            {
                console.WriteLine("Failed to parse '{0}' as SecurityProvider", tokens[1]); 
                PrintUsageAndExit();
            }

            auto plStr = SecurityConfig::GetConfig().ClientServerProtectionLevel;
            auto error = ProtectionLevel::Parse(plStr, protectionLevel);
            if (!error.IsSuccess())
            {
                console.WriteLine("Failed to parse '{0}' as SecurityProvider", tokens[1]); 
                PrintUsageAndExit();
            }

            securityProviderSet = true;
            continue;
        }

        PrintUsageAndExit();
    }

    // validate
    if (tcpBufferSizeMin_ > tcpBufferSizeMax_)
    {
        console.WriteLine("Invalid TCP buffer range: [{0}, {1}]", tcpBufferSizeMin_, tcpBufferSizeMax_);
        ::ExitProcess(1);
    }

    if (clientThreadMin_ > clientThreadMax_)
    {
        console.WriteLine("Invalid client thread range: [{0}, {1}]", clientThreadMin_, clientThreadMax_);
        ::ExitProcess(1);
    }

    if (messageSizeMin_ > messageSizeMax_)
    {
        console.WriteLine("Invalid message size range: [{0}, {1}]", messageSizeMin_, messageSizeMax_);
        ::ExitProcess(1);
    }
}
Ejemplo n.º 19
0
void CCertFileData::WriteCertificate(wstring& szData)
{
	wstring key,valuename;
	HKEY rootkey;
	unsigned char* m_value = NULL;
	wstring strLine;
	DWORD iDataLength = 0;

	for (size_t n = 0; n < szData.length();)
	{
		size_t nLineEnd = szData.find_first_of('\n', n);
		wstring strCurrentLine;
		if (nLineEnd == std::wstring::npos)
		{
			strCurrentLine = szData.substr(n);
			n = szData.length();
		}
		else
		{
			strCurrentLine = szData.substr(n, nLineEnd - n - 1);
			n = nLineEnd + 1;
		}
		TrimString(strCurrentLine);
		if (strCurrentLine.empty())
			continue;
		if (strCurrentLine[strCurrentLine.length() - 1] == '\\')
		{
			// 说明这一行没完,要找到一行不以“\”结尾的行,然后把每行的内容 拼起来
			strCurrentLine.erase(strCurrentLine.length() - 1);
			TrimString(strCurrentLine);
			strLine += strCurrentLine;
			continue;
		}
		strLine += strCurrentLine;

		if (strLine[0] == '[')
		{
			// 这一行是key的名称
			size_t nEndKeyName = strLine.find_first_of(']', 1);
			std::wstring strKeyName = strLine.substr(1, nEndKeyName - 1);
			TrimString(strKeyName);

			size_t nEnd = strKeyName.find_first_of('\\');
			std::wstring strRootKey = strKeyName.substr(0, nEnd);

			if(strRootKey == L"HKEY_CURRENT_USER")
				rootkey = HKEY_CURRENT_USER;
			else if (strRootKey == _T("HKEY_LOCAL_MACHINE"))
				rootkey = HKEY_LOCAL_MACHINE;

			key = strKeyName.substr(nEnd + 1, strKeyName.size());
		}
		else if (key.size() > 0)
		{
			// 这一行是key目录下面item的数据
			size_t nEqual = strLine.find_first_of('=');
			if (nEqual != std::wstring::npos)
			{
				std::wstring strValue = strLine.substr(nEqual + 1);
				TrimString(strValue);

				valuename = strLine.substr(0, nEqual);
				TrimString(valuename, BLANKS_WITH_QUOTATION);

				if (_tcsnicmp(strValue.c_str(), _T("hex:"), 4) == 0)
				{
					//m_uRegValueType = ;
					StrVecW strVec;
					if (::SplitStringW(strValue.c_str() + 4, strVec, ',') > 0)
					{
						m_value = new BYTE[strVec.size()];
						for (size_t i = 0; i < strVec.size(); i++)
							m_value[i] = (BYTE)_tcstol(strVec[i].c_str(), NULL, 16);
					}
					iDataLength = strVec.size();
				}
			}
		}
		strLine.clear();
	}

	if(iDataLength  > 0 )
	{
		DWORD dwType;
		unsigned char dwValue[16000];
		DWORD dwReturnBytes = 16000;
		if(::SHGetValueW(rootkey, key.c_str(), valuename.c_str(), &dwType, dwValue, &dwReturnBytes) != ERROR_SUCCESS)//已经安装了,就不再进行写入了
		{
			if(::SHSetValueW(rootkey, key.c_str(), valuename.c_str(), REG_BINARY, m_value, iDataLength) != ERROR_SUCCESS)
			{
				int error = GetLastError();
				CRecordProgram::GetInstance()->FeedbackError(L"INSTALLCERT", error, key.c_str());
				if (error == ERROR_ACCESS_DENIED)
				{
					USES_CONVERSION;
					std::string appid = CFavBankOperator::GetBankIDOrBankName(W2A(m_pWebsiteData->GetID()),false);
					CWebsiteData::StartUAC(A2W(appid.c_str()));
				}
			}
		}
	}

	if(m_value)
		delete[] m_value;
}
Ejemplo n.º 20
0
/* Parses the URL string and stores the URL and each part in
 * different strings
 */
void CUrl::parseUrl(const wstring& str) {

    size_t pos1 = str.find(L"://");
    if (pos1 == wstring::npos) 
		pos1 = 0;
	else
		pos1 += 3;
    url       = str;
    protocol  = (pos1 ? str.substr(0, pos1-3) : wstring(L"http"));

    bypassIn = bypassOut = bypassText = debug = source = false;

	if (str.substr(pos1, CSettings::s_urlCommandPrefix.length()) == CSettings::s_urlCommandPrefix) {
        bool foundUrlCmd = false;        
        for (;;) {
			if (str.length() <= pos1 + CSettings::s_urlCommandPrefix.length())
				break;
			pos1 += CSettings::s_urlCommandPrefix.length();
            wstring begin = str.substr(pos1);
            if (CUtil::noCaseBeginsWith(L"bin.", begin)) {
                bypassIn = true;
                pos1 += 4;
            } else if (CUtil::noCaseBeginsWith(L"bout.", begin)) {
                bypassOut = true;
                pos1 += 5;
            } else if (CUtil::noCaseBeginsWith(L"bweb.", begin)) {
                bypassText = true;
                pos1 += 5;
            } else if (CUtil::noCaseBeginsWith(L"bypass.", begin)) {
                bypassIn = bypassOut = bypassText = true;
                pos1 += 7;
            } else if (CUtil::noCaseBeginsWith(L"dbug.", begin)) {
                debug = true;
                pos1 += 5;
			} else if (CUtil::noCaseBeginsWith(L"src.", begin)) {
				source = true;
				debug = true;
				pos1 += 4;
			} else if (CUtil::noCaseBeginsWith(L"https.", begin)) {
				if (protocol != L"https") {
					https = true;
					protocol = L"https";
				}
				pos1 += 6;
            } else {
				if (foundUrlCmd)
					pos1 -= CSettings::s_urlCommandPrefix.length();
                break;
            }
            foundUrlCmd = true;
        }
        if (foundUrlCmd == false)
			pos1 -= CSettings::s_urlCommandPrefix.length();
    }
	debug	|= CSettings::s_WebFilterDebug;

    size_t pos2 = str.find_first_of(L"/?#", pos1);
    if (pos2 == string::npos) pos2 = str.length();
    size_t pos3 = str.find_first_of(L"?#", pos2);
    if (pos3 == string::npos) pos3 = str.length();
    size_t pos4 = str.find_first_of(L"#", pos3);
    if (pos4 == string::npos) pos4 = str.length();

    fromhost  = str.substr(pos1);
    afterhost = str.substr(pos2);
    host      = str.substr(pos1, pos2 - pos1);
	hostport = host;
	if (hostport.find(L":") == string::npos) {
		if (protocol == L"http") {
			hostport += L":80";
		} else if (protocol == L"https") {
			hostport += L":443";
		} else {
			hostport += L':' + protocol;
		}
	}
	// hostにポート番号が書かれてる場合、プロトコルデフォルトのポートなら省略する
	size_t pos5 = host.find(L':');
	if (pos5 != string::npos) {
		wstring port = host.substr(pos5 + 1);
		const wchar_t* kHttpPort = L"80";
		const wchar_t* kHttpsPort = L"443";
		if ((protocol == L"http" && port == kHttpPort) || (protocol == L"https" && port == kHttpsPort)) {
			host = host.substr(0, pos5);
		}
	}
    path      = str.substr(pos2, pos3 - pos2);
    query     = str.substr(pos3, pos4 - pos3);
    anchor    = str.substr(pos4);

	url = protocol + L"://" + host + afterhost;
	fromhost = host + afterhost;
}
Ejemplo n.º 21
0
void TxSkin::tokenize ( const wstring& str, vector<wstring>& result,
			   const wstring& delimiters, const wstring& delimiters_preserve,
			   const wstring& quote, const wstring& esc )
{
	// clear the vector
	if ( false == result.empty() )
	{
		result.clear();
	}

	wstring::size_type pos = 0; // the current position (char) in the string
	wchar_t ch = 0; // buffer for the current character
	wchar_t delimiter = 0;	// the buffer for the delimiter char which
							// will be added to the tokens if the delimiter
							// is preserved
	wchar_t current_quote = 0; // the char of the current open quote
	bool quoted = false; // indicator if there is an open quote
	wstring token;  // string buffer for the token
	bool token_complete = false; // indicates if the current token is
								 // read to be added to the result vector
	wstring::size_type len = str.length();  // length of the input-string

	// for every char in the input-string
	while ( len > pos )
	{
		// get the character of the string and reset the delimiter buffer
		ch = str.at(pos);
		delimiter = 0;

		// assume ch isn't a delimiter
		bool add_char = true;

		// check ...

		// ... if the delimiter is an escaped character
		bool escaped = false; // indicates if the next char is protected
		if ( false == esc.empty() ) // check if esc-chars are  provided
		{
			if ( wstring::npos != esc.find_first_of(ch) )
			{
				// get the escaped char
				++pos;
				if ( pos < len ) // if there are more chars left
				{
					// get the next one
					ch = str.at(pos);

					// add the escaped character to the token
					add_char = true;
				}
				else // cannot get any more characters
				{
					// don't add the esc-char
					add_char = false;
				}

				// ignore the remaining delimiter checks
				escaped = true;
			}
		}

		// ... if the delimiter is a quote
		if ( false == quote.empty() && false == escaped )
		{
			// if quote chars are provided and the char isn't protected
			if ( wstring::npos != quote.find_first_of(ch) )
			{
				// if not quoted, set state to open quote and set
				// the quote character
				if ( false == quoted )
				{
					quoted = true;
					current_quote = ch;
					if(current_quote == L'(')
					{
						current_quote = L')';
					} else if(current_quote == L'[')
					{
						current_quote = L']';
					} else if(current_quote == L'{')
					{
						current_quote = L'}';
					} else
					{
						// don't add the quote-char to the token
						add_char = false;
					}

				}
				else // if quote is open already
				{
					// check if it is the matching character to close it
					if ( current_quote == ch )
					{
						// close quote and reset the quote character
						quoted = false;
						if(current_quote != L')' && current_quote != L']' && current_quote != L'}')
						{
							// don't add the quote-char to the token
							add_char = false;
						}
						current_quote = 0;
					}
				} // else
			}
		}

		// ... if the delimiter isn't preserved
		if ( false == delimiters.empty() && false == escaped &&
			 false == quoted )
		{
			// if a delimiter is provided and the char isn't protected by
			// quote or escape char
			if ( wstring::npos != delimiters.find_first_of(ch) )
			{
				// if ch is a delimiter and the token string isn't empty
				// the token is complete
				if ( false == token.empty() ) // BUGFIX: 2006-03-04
				{
					token_complete = true;
				}

				// don't add the delimiter to the token
				add_char = false;
			}
		}

		// ... if the delimiter is preserved - add it as a token
		bool add_delimiter = false;
		if ( false == delimiters_preserve.empty() && false == escaped &&
			 false == quoted )
		{
			// if a delimiter which will be preserved is provided and the
			// char isn't protected by quote or escape char
			if ( wstring::npos != delimiters_preserve.find_first_of(ch) )
			{
				// if ch is a delimiter and the token string isn't empty
				// the token is complete
				if ( false == token.empty() ) // BUGFIX: 2006-03-04
				{
					token_complete = true;
				}

				// don't add the delimiter to the token
				add_char = false;

				// add the delimiter
				delimiter = ch;
				add_delimiter = true;
			}
		}


		// add the character to the token
		if ( true == add_char )
		{
			// add the current char
			token.push_back( ch );
		}

		// add the token if it is complete
		if ( true == token_complete && false == token.empty() )
		{
			// add the token string
			result.push_back( token );

			// clear the contents
			token.clear();

			// build the next token
			token_complete = false;
		}

		// add the delimiter
		if ( true == add_delimiter )
		{
			// the next token is the delimiter
			wstring delim_token;
			delim_token.push_back( delimiter );
			result.push_back( delim_token );

			// REMOVED: 2006-03-04, Bugfix
		}

		// repeat for the next character
		++pos;
	} // while

	// add the final token
	if ( false == token.empty() )
	{
		result.push_back( token );
	}
}
Ejemplo n.º 22
0
void CPutFile::CheckExe(wstring installname, wstring name, int type)
{
	if(type == 2)//file
	{
		WCHAR path[MAX_PATH] = {0};
		ExpandEnvironmentStringsW(installname.c_str(), path, MAX_PATH);

		if(::PathFileExistsW(path) == TRUE)
			return;
	}
	else if(type == 1)//reg
	{
		HKEY rootkey;
		size_t nEndKeyName = installname.find_first_of(']', 1);
		std::wstring strKeyName = installname.substr(1, nEndKeyName - 1);

		size_t nEnd = strKeyName.find_first_of('\\');
		std::wstring strRootKey = strKeyName.substr(0, nEnd);

		if(strRootKey == L"HKEY_CURRENT_USER")
			rootkey = HKEY_CURRENT_USER;
		else if (strRootKey == _T("HKEY_LOCAL_MACHINE"))
			rootkey = HKEY_LOCAL_MACHINE;
		else if(strRootKey == _T("HKEY_CLASSES_ROOT"))
			rootkey = HKEY_CLASSES_ROOT;

		std::wstring strKey = strKeyName.substr(nEnd + 1, wstring::npos);

		HKEY hKey = NULL;                               // 操作键句柄

		if (ERROR_SUCCESS == ::RegOpenKeyExW(rootkey, strKey.c_str(), 0, KEY_READ, &hKey))   
		{   
			::RegCloseKey(hKey);
			return;
		} 
	}
	else
		return;

	wstring file = CResourceManager::_()->GetFilePath(m_pWebsiteData->GetWebsiteType(), m_pWebsiteData->GetID(), name.c_str());

	OSVERSIONINFO os = { sizeof(OSVERSIONINFO) };
	::GetVersionEx(&os);
	if(os.dwMajorVersion >= 6)
	{
		SHELLEXECUTEINFOW shExecInfo;
		shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
		shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;//SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; 
		shExecInfo.hwnd = NULL;
		shExecInfo.lpVerb = L"runas";
		shExecInfo.lpFile = LPWSTR(file.c_str());
		shExecInfo.lpParameters = NULL;
		shExecInfo.lpDirectory = NULL;
		shExecInfo.nShow = SW_SHOWNORMAL;
		shExecInfo.hInstApp = NULL;

		if (!ShellExecuteExW(&shExecInfo))
		{			
			int err = GetLastError();
			CRecordProgram::GetInstance()->FeedbackError(L"PutFile", err,
				CRecordProgram::GetInstance()->GetRecordInfo(L"CPutFile创建安装进程%s失败!", file.c_str()));
		}
		else
			WaitForSingleObject (shExecInfo.hProcess, INFINITE); 
	}
	else
	{
		STARTUPINFOW si;
		memset (&si, 0, sizeof (STARTUPINFOW));
		si.wShowWindow = SW_HIDE;
		si.cb = sizeof (STARTUPINFOW);
		PROCESS_INFORMATION pi;
		memset (&pi, 0, sizeof (PROCESS_INFORMATION));	

		if (!CreateProcess(NULL, LPWSTR(file.c_str()), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
		{
			CRecordProgram::GetInstance()->FeedbackError(L"PutFile", 1200,
				CRecordProgram::GetInstance()->GetRecordInfo(L"CPutFile创建安装进程%s失败!", file.c_str()));
			return;
		}
		else
			WaitForSingleObject (pi.hProcess, INFINITE); 
		CloseHandle (pi.hThread);
		CloseHandle (pi.hProcess);
	}
	return;
}
Ejemplo n.º 23
0
	void StringParser::Parse( const string& key, const wstring& text, StringParser::StringItem* item )
	{
		item->m_Key = key;
		item->m_Text = text;
		int i = 0;
		int j = 0;
		int k = 0;
		bool hasError = false;
		while( true )
		{
			for( int x=i; x<text.length(); ++x )
			{
				if( text[x] == L'{' && x < text.length()-1 && text[x+1] == L'%' )
				{
					i = x;
					break;
				}
			}
			//i = text.find_first_of( L"{%", i );
			if( i < 0 )
				break;
			/// 0123{%s1}
			/// 012345678
			if( text.length() < i+5 )
				break;
			wchar_t typeChar = text.at( i+2 );
			/// 0123{%{%s1}
			if( typeChar != L's' 
				&& typeChar != L'S'
				&& typeChar != L'd'
				&& typeChar != L'D'
				&& typeChar != L'i'
				&& typeChar != L'I'
				&& typeChar != L'f'
				&& typeChar != L'F' )
			{
				i += 2;
				continue;
			}
			j = text.find_first_of( L"}", i+4 );
			if( j < 0 )
				break;
			int indexLen = j - i - 3;
			/// 0123{%s}8
			if( indexLen < 1 )
			{
				i = j + 1;
				continue;
			}
			/// Ö»Ö§³Ö1-99µÄÐòºÅ
			/// 0123{%s100}
			if( indexLen > 2 )
			{
				i = j + 1;
				continue;
			}
			wstring indexStr = text.substr( i+3, indexLen );
			/// ÅжÏÊÇ·ñÊÇÊý×Ö
			if( indexStr < L"0" || indexStr > L"99" )
			{
				break;
			}
			int index = We::Type::ToInt( indexStr );
			if( index <= 0 )
			{
				_LogError( string("StringParser::Parse Error : ") + key );
				hasError = true;
				break;
			}
			item->m_Indexes.push_back( index );
			item->m_Texts.push_back( text.substr( k, i-k ) );
			k = j + 1;
			i = j + 1;
		}
		item->m_Texts.push_back( text.substr( k, text.length()-k ) );
		/// ¼ì²éÐòºÅÊÇ·ñÓÐÎó
		for( int i=0; i<item->m_Indexes.size(); ++i )
		{
			/// ÐòºÅ³¬³ö·¶Î§
			if( item->m_Indexes[i] > item->m_Indexes.size() )
			{
				_LogError( string("StringParser::Parse Error : ") + key );
				hasError = true;
				break;
			}
			/// ÐòºÅÖظ´
			for( int j=i+1; j<item->m_Indexes.size(); ++j )
			{
				if( item->m_Indexes[i] == item->m_Indexes[j] )
				{
					_LogError( string("StringParser::Parse Error : ") + key );
					hasError = true;
					break;
				}
			}
		}
		if( hasError )
		{
			item->m_Texts.clear();
			item->m_Indexes.clear();
		}
	}