Example #1
0
bool
CKeyMap::parseModifiers(CString& x, KeyModifierMask& mask)
{
	// initialize tables
	initKeyNameMaps();

	mask = 0;
	CString::size_type tb = x.find_first_not_of(" \t", 0);
	while (tb != CString::npos) {
		// get next component
		CString::size_type te = x.find_first_of(" \t+)", tb);
		if (te == CString::npos) {
			te = x.size();
		}
		CString c = x.substr(tb, te - tb);
		if (c.empty()) {
			// missing component
			return false;
		}

		if (s_nameToModifierMap->count(c) > 0) {
			KeyModifierMask mod = s_nameToModifierMap->find(c)->second;
			if ((mask & mod) != 0) {
				// modifier appears twice
				return false;
			}
			mask |= mod;
		}
		else {
			// unknown string
			x.erase(0, tb);
			CString::size_type tb = x.find_first_not_of(" \t");
			CString::size_type te = x.find_last_not_of(" \t");
			if (tb == CString::npos) {
				x = "";
			}
			else {
				x = x.substr(tb, te - tb + 1);
			}
			return true;
		}

		// check for '+' or end of string
		tb = x.find_first_not_of(" \t", te);
		if (tb != CString::npos) {
			if (x[tb] != '+') {
				// expected '+'
				return false;
			}
			tb = x.find_first_not_of(" \t", tb + 1);
		}
	}

	// parsed the whole thing
	x = "";
	return true;
}
Example #2
0
void StepManiaLanServer::AnalizeChat(PacketFunctions &Packet, const unsigned int clientNum)
{
	CString message = Packet.ReadNT();
	if (message.at(0) == '/')
	{
		CString command = message.substr(1, message.find(" ")-1);
		if ((command.compare("list") == 0)||(command.compare("have") == 0))
		{
			if (command.compare("list") == 0)
			{
				Reply.ClearPacket();
				Reply.Write1(NSCCM + NSServerOffset);
				Reply.WriteNT(ListPlayers());
				SendNetPacket(clientNum, Reply);
			}
			else
			{
				message = "";
				message += Client[clientNum]->Player[0].name;
				if (Client[clientNum]->twoPlayers)
					message += "&";
				message += Client[clientNum]->Player[1].name;
				message += " forces has song.";
				Client[clientNum]->forceHas = true;
				ServerChat(message);
			}
		}
		else
		{
			if (clientNum == 0)
			{
				if (command.compare("force_start") == 0)
					ForceStart();
				if (command.compare("kick") == 0)
				{
					CString name = message.substr(message.find(" ")+1);
					Kick(name);
				}
				if (command.compare("ban") == 0)
				{
					CString name = message.substr(message.find(" ")+1);
					Ban(name);
				}
			}
			else
			{
				Reply.ClearPacket();
				Reply.Write1(NSCCM + NSServerOffset);
				Reply.WriteNT("You do not have permission to use server commands.");
				SendNetPacket(clientNum, Reply);
			}
		}
	}
	else
		RelayChat(message, clientNum);
}
Example #3
0
void CClient::ParsePass(const CString& sAuthLine) {
    // [user[@identifier][/network]:]password

    const size_t uColon = sAuthLine.find(":");
    if (uColon != CString::npos) {
        m_sPass = sAuthLine.substr(uColon + 1);

        ParseUser(sAuthLine.substr(0, uColon));
    } else {
        m_sPass = sAuthLine;
    }
}
Example #4
0
void CClient::ParseUser(const CString& sAuthLine) {
    // user[@identifier][/network]

    const size_t uSlash = sAuthLine.rfind("/");
    if (uSlash != CString::npos) {
        m_sNetwork = sAuthLine.substr(uSlash + 1);

        ParseIdentifier(sAuthLine.substr(0, uSlash));
    } else {
        ParseIdentifier(sAuthLine);
    }
}
Example #5
0
void CIniFile::Path(const CString& newPath){
//альтернатива basename, dirname
  int lastSlashPos = newPath.rfind('/');

  CString fname = newPath.substr(lastSlashPos+1, CString::npos);

  archive_path = backup_path = newPath.substr(0, lastSlashPos);

  backup_path += "/backup/" + fname;
  archive_path += "/archive/" + fname;
  path = newPath;
};
 CString Directory::GetFolderPath(const CString& strFolderPath)
 {
     int n1 = strFolderPath.rfind(FILE_SEPARATOR_STR);
     if (n1 < 0 )
         return _T("");
     return strFolderPath.substr(0,n1);
 }
Example #7
0
bool getline(CString &_str, CString &line){
  if(_str.size()==0)  return false;
  CString::size_type pLeft=0, pRight = _str.find('\n');
  line = _str.substr( pLeft, pRight );
  _str = _str.erase(0,pRight+1);
  return true;
};
Example #8
0
void CClient::ParseIdentifier(const CString& sAuthLine) {
    // user[@identifier]

    const size_t uAt = sAuthLine.rfind("@");
    if (uAt != CString::npos) {
        const CString sId = sAuthLine.substr(uAt + 1);

        if (IsValidIdentifier(sId)) {
            m_sIdentifier = sId;
            m_sUser = sAuthLine.substr(0, uAt);
        } else {
            m_sUser = sAuthLine;
        }
    } else {
        m_sUser = sAuthLine;
    }
}
Example #9
0
	virtual EModRet OnRaw(CString& sLine) {
		if (sLine.Equals("ERROR ", false, 6)) {
			//ERROR :Closing Link: nick[24.24.24.24] (Excess Flood)
			//ERROR :Closing Link: nick[24.24.24.24] Killer (Local kill by Killer (reason))
			CString sError(sLine.substr(6));
			if (sError.Left(1) == ":")
				sError.LeftChomp();
			Log("[" + m_pUser->GetUserName() + "/" + m_pNetwork->GetName() + "] disconnected from IRC: " +
			    m_pNetwork->GetCurrentServer()->GetName() + " [" + sError + "]", LOG_NOTICE);
		}
		return CONTINUE;
        }
Example #10
0
    bool IsOnlineModNick(const CString& sNick) {
        const CString& sPrefix = m_pUser->GetStatusPrefix();
        if (!sNick.Equals(sPrefix, false, sPrefix.length()))
            return false;

        CString sModNick = sNick.substr(sPrefix.length());
        if (!sModNick.Equals("status") &&
                !m_pUser->GetModules().FindModule(sModNick) &&
                !CZNC::Get().GetModules().FindModule(sModNick))
            return false;
        return true;
    }
Example #11
0
void CFile::SetFileName(const CString& sLongName) {
	if (sLongName.StartsWith("~/")) {
		m_sLongName = CFile::GetHomePath() + sLongName.substr(1);
	} else
		m_sLongName = sLongName;

	m_sShortName = sLongName;
	m_sShortName.TrimRight("/");

	CString::size_type uPos = m_sShortName.rfind('/');
	if (uPos != CString::npos) {
		m_sShortName = m_sShortName.substr(uPos +1);
	}
}
Example #12
0
File: schat.cpp Project: clem16/znc
	virtual EModRet OnUserRaw(CString & sLine) override
	{
		if (sLine.Equals("schat ", false, 6)) {
			OnModCommand("chat " + sLine.substr(6));
			return(HALT);

		} else if (sLine.Equals("schat")) {
			PutModule("SChat User Area ...");
			OnModCommand("help");
			return(HALT);
		}

		return(CONTINUE);
	}
Example #13
0
CString Font::GetPageNameFromFileName( const CString &sFilename )
{
	size_t begin = sFilename.find_first_of( '[' );
	if( begin == string::npos )
		return "main";

	size_t end = sFilename.find_first_of( ']', begin );
	if( end == string::npos )
		return "main";

	begin++;
	end--;
	if( end == begin )
		return "main";
	return sFilename.substr( begin, end-begin+1 );
}
Example #14
0
	bool Add(const CString& sChan) {
		if (sChan.empty() || sChan == "!") {
			return false;
		}

		if (sChan.Left(1) == "!") {
			m_vsNegChans.push_back(sChan.substr(1));
		} else {
			m_vsChans.push_back(sChan);
		}

		// Also save it for next module load
		SetNV(sChan, "");

		return true;
	}
Example #15
0
	bool AlreadyAdded(const CString& sInput) {
		vector<CString>::iterator it;

		if (sInput.Left(1) == "!") {
			CString sChan = sInput.substr(1);
			for (it = m_vsNegChans.begin(); it != m_vsNegChans.end();
					++it) {
				if (*it == sChan)
					return true;
			}
		} else {
			for (it = m_vsChans.begin(); it != m_vsChans.end(); ++it) {
				if (*it == sInput)
					return true;
			}
		}
		return false;
	}
Example #16
0
CString CDir::ChangeDir(const CString& sPath, const CString& sAdd, const CString& sHome) {
	CString sHomeDir(sHome);

	if (sHomeDir.empty()) {
		sHomeDir = CFile::GetHomePath();
	}

	if (sAdd == "~") {
		return sHomeDir;
	}

	CString sAddDir(sAdd);

	if (sAddDir.StartsWith("~/")) {
		sAddDir.LeftChomp();
		sAddDir = sHomeDir + sAddDir;
	}

	CString sRet = ((sAddDir.size()) && (sAddDir[0] == '/')) ? "" : sPath;
	sAddDir += "/";
	CString sCurDir;

	sRet.TrimSuffix("/");

	for (unsigned int a = 0; a < sAddDir.size(); a++) {
		switch (sAddDir[a]) {
			case '/':
				if (sCurDir == "..") {
					sRet = sRet.substr(0, sRet.rfind('/'));
				} else if ((sCurDir != "") && (sCurDir != ".")) {
					sRet += "/" + sCurDir;
				}

				sCurDir = "";
				break;
			default:
				sCurDir += sAddDir[a];
				break;
		}
	}

	return (sRet.empty()) ? "/" : sRet;
}
Example #17
0
	bool Del(const CString& sChan) {
		vector<CString>::iterator it, end;

		if (sChan.empty() || sChan == "!")
			return false;

		if (sChan.Left(1) == "!") {
			CString sTmp = sChan.substr(1);
			it = m_vsNegChans.begin();
			end = m_vsNegChans.end();

			for (; it != end; ++it)
				if (*it == sTmp)
					break;

			if (it == end)
				return false;

			m_vsNegChans.erase(it);
		} else {
			it = m_vsChans.begin();
			end = m_vsChans.end();

			for (; it != end; ++it)
				if (*it == sChan)
					break;

			if (it == end)
				return false;

			m_vsChans.erase(it);
		}

		DelNV(sChan);

		return true;
	}
Example #18
0
bool CIniFile::ReadString(const char* ini_str)
{
  CString   line;
  CString   keyname, valuename, value;
  CString::size_type pLeft, pRight;

  Clear();
  CString _str = ini_str;
  while( getline( _str, line)) {
    // To be compatible with Win32, check for existence of '\r'.
    // Win32 files have the '\r' and Unix files don't at the end of a line.
    // Note that the '\r' will be written to INI files from
    // Unix so that the created INI file can be read under Win32
    // without change.
    //printf("str=%s \n line=%s\n",_str.c_str(),line.c_str());
    if ( line[line.length() - 1] == '\r')
      line = line.substr( 0, line.length() - 1);

    if ( line.length()) {
      // Check that the user hasn't openned a binary file by checking the first
      // character of each line!
      if ( !isprint( line.at(0))) {
//       printf( "Failing on char %d\n", line[0]);
//       f.close();
//        return false;
      };
      if (( pLeft = line.find_first_of(";#[=:")) != CString::npos) {
       switch ( line[pLeft]) {
       case '[':
         if ((pRight = line.find_last_of("]")) != CString::npos &&
              pRight > pLeft) {
           keyname = line.substr( pLeft + 1, pRight - pLeft - 1);
           AddKeyName( keyname);
//           printf("Section: %s\n",keyname.c_str());
         }
       break;

       case '=':
//       case ':':
         valuename = line.substr( 0, pLeft);
         value = line.substr( pLeft + 1);
         AddValue( keyname, valuename, value);
//         printf("%s=%s\n",valuename.c_str(),value.c_str());
       break;

       case ';':
       case '#':
         if ( !names.size())
            HeaderComment( line.substr( pLeft + 1));
          else
            KeyComment( keyname, line.substr( pLeft + 1));
       break;
       };//switch()
      }//if(( pLeft = line.find_first_of(";#[=")) != CString::npos)
    };//if ( line.length())
  };//while( getline( ini_str, line))

  if(minSize <= 0)
    return true;

  if ( names.size())
    return true;

  return false;
};
Example #19
0
void Font::LoadFontPageSettings( FontPageSettings &cfg, IniFile &ini, const CString &sTexturePath, const CString &sPageName, CString sChars )
{
	cfg.m_sTexturePath = sTexturePath;

	/* If we have any characters to map, add them. */
	for( unsigned n=0; n<sChars.size(); n++ )
	{
		char c = sChars[n];
		cfg.CharToGlyphNo[c] = n;
	}
	int iNumFramesWide, iNumFramesHigh;
	RageTexture::GetFrameDimensionsFromFileName( sTexturePath, &iNumFramesWide, &iNumFramesHigh );
	int iNumFrames = iNumFramesWide * iNumFramesHigh;
	
	ini.RenameKey("Char Widths", "main");

//	LOG->Trace("Loading font page '%s' settings from page name '%s'",
//		TexturePath.c_str(), sPageName.c_str());
	
	ini.GetValue( sPageName, "DrawExtraPixelsLeft", cfg.m_iDrawExtraPixelsLeft );
	ini.GetValue( sPageName, "DrawExtraPixelsRight", cfg.m_iDrawExtraPixelsRight );
	ini.GetValue( sPageName, "AddToAllWidths", cfg.m_iAddToAllWidths );
	ini.GetValue( sPageName, "ScaleAllWidthsBy", cfg.m_fScaleAllWidthsBy );
	ini.GetValue( sPageName, "LineSpacing", cfg.m_iLineSpacing );
	ini.GetValue( sPageName, "Top", cfg.m_iTop );
	ini.GetValue( sPageName, "Baseline", cfg.m_iBaseline );
	ini.GetValue( sPageName, "DefaultWidth", cfg.m_iDefaultWidth );
	ini.GetValue( sPageName, "AdvanceExtraPixels", cfg.m_iAdvanceExtraPixels );
	ini.GetValue( sPageName, "TextureHints", cfg.m_sTextureHints );

	/* Iterate over all keys. */
	const XNode* pNode = ini.GetChild( sPageName );
	if( pNode )
	{
		FOREACH_CONST_Attr( pNode, pAttr )
		{
			CString sName = pAttr->m_sName;
			const CString &sValue = pAttr->m_sValue;

			sName.MakeUpper();

			/* If val is an integer, it's a width, eg. "10=27". */
			if( IsAnInt(sName) )
			{
				cfg.m_mapGlyphWidths[atoi(sName)] = atoi( sValue );
				continue;
			}

			/* "map codepoint=frame" maps a char to a frame. */
			if( sName.substr(0, 4) == "MAP " )
			{
				/*
				 * map CODEPOINT=frame. CODEPOINT can be
				 * 1. U+hexval
				 * 2. an alias ("oq")
				 * 3. a game type followed by a game alias, eg "pump menuleft"
				 * 4. a character in quotes ("X")
				 *
				 * map 1=2 is the same as
				 * range unicode #1-1=2
				 */
				CString sCodepoint = sName.substr(4); /* "CODEPOINT" */
			
				const Game* pGame = NULL;

				if( sCodepoint.find_first_of(' ') != sCodepoint.npos )
				{
					/* There's a space; the first word should be a game type. Split it. */
					unsigned pos = sCodepoint.find_first_of( ' ' );
					CString gamename = sCodepoint.substr( 0, pos );
					sCodepoint = sCodepoint.substr( pos+1 );

					pGame = GameManager::StringToGameType(gamename);

					if( pGame == NULL )
					{
						LOG->Warn( "Font definition '%s' uses unknown game type '%s'",
							ini.GetPath().c_str(), gamename.c_str() );
						continue;
					}
				}

				wchar_t c;
				if( sCodepoint.substr(0, 2) == "U+" && IsHexVal(sCodepoint.substr(2)) )
					sscanf( sCodepoint.substr(2).c_str(), "%x", &c );
				else if( sCodepoint.size() > 0 &&
						utf8_get_char_len(sCodepoint[0]) == int(sCodepoint.size()) )
				{
					c = utf8_get_char( sCodepoint.c_str() );
					if(c == wchar_t(-1))
						LOG->Warn("Font definition '%s' has an invalid value '%s'.",
							ini.GetPath().c_str(), sName.c_str() );
				}
				else if( !FontCharAliases::GetChar(sCodepoint, c) )
				{
					LOG->Warn("Font definition '%s' has an invalid value '%s'.",
						ini.GetPath().c_str(), sName.c_str() );
					continue;
				}

				cfg.CharToGlyphNo[c] = atoi( sValue );

				continue;
			}

			if( sName.substr(0, 6) == "RANGE " )
			{
				/*
				 * range CODESET=first_frame or
				 * range CODESET #start-end=first_frame
				 * eg
				 * range CP1252=0       (default for 256-frame fonts)
				 * range ASCII=0        (default for 128-frame fonts)
				 *
				 * (Start and end are in hex.)
				 *
				 * Map two high-bit portions of ISO-8859- to one font:
				 * range ISO-8859-2 #80-FF=0
				 * range ISO-8859-3 #80-FF=128
				 *
				 * Map hiragana to 0-84:
				 * range Unicode #3041-3094=0
				 */
				vector<CString> asMatches;
				static Regex parse("^RANGE ([A-Z\\-]+)( ?#([0-9A-F]+)-([0-9A-F]+))?$");
				bool bMatch = parse.Compare( sName, asMatches );
				
				ASSERT( asMatches.size() == 4 ); /* 4 parens */

				if( !bMatch || asMatches[0].empty() )
					RageException::Throw("Font definition '%s' has an invalid range '%s': parse error",
						ini.GetPath().c_str(), sName.c_str() );
				
				/* We must have either 1 match (just the codeset) or 4 (the whole thing). */

				int iCount = -1;
				int iFirst = 0;
				if( !asMatches[2].empty() )
				{
					sscanf( asMatches[2].c_str(), "%x", &iFirst );
					int iLast;
					sscanf( asMatches[3].c_str(), "%x", &iLast );
					if( iLast < iFirst )
						RageException::Throw("Font definition '%s' has an invalid range '%s': %i < %i.",
							ini.GetPath().c_str(), sName.c_str(), iLast < iFirst );

					iCount = iLast - iFirst + 1;
				}

				CString sRet = cfg.MapRange( asMatches[0], iFirst, atoi(sValue), iCount );
				if( !sRet.empty() )
					RageException::Throw( "Font definition '%s' has an invalid range '%s': %s.",
						ini.GetPath().c_str(), sName.c_str(), sRet.c_str() );

				continue;
			}

			if( sName.substr(0, 5) == "LINE " )
			{
				/* line ROW=CHAR1CHAR2CHAR3CHAR4
				 * eg.
				 * line 0=ABCDEFGH
				 *
				 * This lets us assign characters very compactly and readably. */

				CString sRowStr = sName.substr(5);
				ASSERT( IsAnInt(sRowStr) );
				const int iRow = atoi( sRowStr.c_str() );
				const int iFirstFrame = iRow * iNumFramesWide;

				if( iRow > iNumFramesHigh )
					RageException::Throw( "The font definition \"%s\" tries to assign line %i, but the font is only %i characters high",
						ini.GetPath().c_str(), iFirstFrame, iNumFramesHigh );

				/* Decode the string. */
				const wstring wdata( CStringToWstring(sValue) );

				if( int(wdata.size()) > iNumFramesWide )
					RageException::Throw( "The font definition \"%s\" assigns %i characters to row %i (\"%ls\"), but the font only has %i characters wide",
						ini.GetPath().c_str(), wdata.size(), iRow, wdata.c_str(), iNumFramesWide );

				for( unsigned i = 0; i < wdata.size(); ++i )
					cfg.CharToGlyphNo[wdata[i]] = iFirstFrame+i;
			}
		}
	}
Example #20
0
CString CDir::ChangeDir(const CString& sPathIn, const CString& sAddIn, const CString& sHomeIn) {
	/* this function is pretty crappy but needed to fix ZNC's strange way of handling file paths */
	CString sResult;
	CString sPath(sPathIn);
	CString sAdd(sAddIn);
	CString sHomeDir(sHomeIn);

	if (sHomeDir.empty())
	{
		// use the default home dir, if no custom home dir has been passed in.
		sHomeDir = CZNC::Get().GetHomePath();
	}

	// we want to use backslashes for this function's inner workings.
	sHomeDir.Replace("/", "\\");
	sPath.Replace("/", "\\");
	sAdd.Replace("/", "\\");

	if (sAdd == "~")
	{
		// if the add dir is the home dir (why?!), use that as result...
		sResult = sHomeDir;
	}
	else
	{
		if(!PathIsRelative(sAdd.c_str()))
		{
			// if add already is an absolute path, use it for the result...
			// ... however, it can still contain ./ or ../ stuff,
			// which will be resolved later.
			sResult = sAdd;
		}
		else
		{
			// if the first part of the path (sPath) is relative,
			// make it absolute, starting from the znc.exe directory:
			if(PathIsRelative(sPath.c_str()))
			{
				char szLocalPath[1024] = {0};

				// get the full path to znc.exe and strip off "znc.exe" from the end:
				if(GetModuleFileName(NULL, szLocalPath, 1023) != 0 && szLocalPath[0])
				{
					PathRemoveFileSpec(szLocalPath);

					if(PathIsDirectory(szLocalPath))
					{
						// append the relative sPath to our znc.exe dir,
						// thereby making it absolute.
						char szAbsolutePathBuffer[1024] = {0};
						PathCombine(szAbsolutePathBuffer, szLocalPath, sPath.c_str());

						// PathCombine will also resolve any ./ or ../ parts in the path.

						// use the now-absolute path:
						sPath = szAbsolutePathBuffer;
					}
				}
			}

			// append the (relative) sAdd path to the (absolute) sPath path:
			char szAbsoluteResultBuffer[1024] = {0};
			PathCombine(szAbsoluteResultBuffer, sPath.c_str(), sAdd.c_str());

			sResult = szAbsoluteResultBuffer;
		}
	}

	char szResultBuffer[1024] = {0};
	
	// make sure no ./ or ../ stuff survives this function. never.
	if(!sResult.empty() && PathCanonicalize(szResultBuffer, sResult.c_str()))
	{
		if(sAdd.empty() || sAdd[sAdd.length() - 1] != '\\')
		{
			PathRemoveBackslash(szResultBuffer);
		}
		else
		{
			PathAddBackslash(szResultBuffer);
		}

		sResult = szResultBuffer;
		sResult.Replace("\\", "/");

		return sResult;
	}
	else
	{
		abort();
		return ""; // to shut up compiler warning
	}
#else
CString CDir::ChangeDir(const CString& sPath, const CString& sAdd, const CString& sHome) {
	CString sHomeDir(sHome);

	if (sHomeDir.empty()) {
		sHomeDir = CZNC::Get().GetHomePath();
	}

	if (sAdd == "~") {
		return sHomeDir;
	}

	CString sAddDir(sAdd);

	if (sAddDir.Left(2) == "~/") {
		sAddDir.LeftChomp();
		sAddDir = sHomeDir + sAddDir;
	}

	CString sRet = ((sAddDir.size()) && (sAddDir[0] == '/')) ? "" : sPath;
	sAddDir += "/";
	CString sCurDir;

	if (sRet.Right(1) == "/") {
		sRet.RightChomp();
	}

	for (unsigned int a = 0; a < sAddDir.size(); a++) {
		switch (sAddDir[a]) {
			case '/':
				if (sCurDir == "..") {
					sRet = sRet.substr(0, sRet.rfind('/'));
				} else if ((sCurDir != "") && (sCurDir != ".")) {
					sRet += "/" + sCurDir;
				}

				sCurDir = "";
				break;
			default:
				sCurDir += sAddDir[a];
				break;
		}
	}

	return (sRet.empty()) ? "/" : sRet;
#endif
}
Example #21
0
bool CClient::PutClient(const CMessage& Message) {
    if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) {
        return false;
    } else if (!m_bAccountNotify &&
               Message.GetType() == CMessage::Type::Account) {
        return false;
    }

    CMessage Msg(Message);

    const CIRCSock* pIRCSock = GetIRCSock();
    if (pIRCSock) {
        if (Msg.GetType() == CMessage::Type::Numeric) {
            unsigned int uCode = Msg.As<CNumericMessage>().GetCode();

            if (uCode == 352) {  // RPL_WHOREPLY
                if (!m_bNamesx && pIRCSock->HasNamesx()) {
                    // The server has NAMESX, but the client doesn't, so we need
                    // to remove extra prefixes
                    CString sNick = Msg.GetParam(6);
                    if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) {
                        CString sNewNick = sNick;
                        size_t pos =
                            sNick.find_first_not_of(pIRCSock->GetPerms());
                        if (pos >= 2 && pos != CString::npos) {
                            sNewNick = sNick[0] + sNick.substr(pos);
                        }
                        Msg.SetParam(6, sNewNick);
                    }
                }
            } else if (uCode == 353) {  // RPL_NAMES
                if ((!m_bNamesx && pIRCSock->HasNamesx()) ||
                    (!m_bUHNames && pIRCSock->HasUHNames())) {
                    // The server has either UHNAMES or NAMESX, but the client
                    // is missing either or both
                    CString sNicks = Msg.GetParam(3);
                    VCString vsNicks;
                    sNicks.Split(" ", vsNicks, false);

                    for (CString& sNick : vsNicks) {
                        if (sNick.empty()) break;

                        if (!m_bNamesx && pIRCSock->HasNamesx() &&
                            pIRCSock->IsPermChar(sNick[0])) {
                            // The server has NAMESX, but the client doesn't, so
                            // we just use the first perm char
                            size_t pos =
                                sNick.find_first_not_of(pIRCSock->GetPerms());
                            if (pos >= 2 && pos != CString::npos) {
                                sNick = sNick[0] + sNick.substr(pos);
                            }
                        }

                        if (!m_bUHNames && pIRCSock->HasUHNames()) {
                            // The server has UHNAMES, but the client doesn't,
                            // so we strip away ident and host
                            sNick = sNick.Token(0, false, "!");
                        }
                    }

                    Msg.SetParam(
                        3, CString(" ").Join(vsNicks.begin(), vsNicks.end()));
                }
            }
        } else if (Msg.GetType() == CMessage::Type::Join) {
            if (!m_bExtendedJoin && pIRCSock->HasExtendedJoin()) {
                Msg.SetParams({Msg.As<CJoinMessage>().GetTarget()});
            }
        }
    }

    MCString mssTags;

    for (const auto& it : Msg.GetTags()) {
        if (IsTagEnabled(it.first)) {
            mssTags[it.first] = it.second;
        }
    }

    if (HasServerTime()) {
        // If the server didn't set the time tag, manually set it
        mssTags.emplace("time", CUtils::FormatServerTime(Msg.GetTime()));
    }

    Msg.SetTags(mssTags);
    Msg.SetClient(this);
    Msg.SetNetwork(m_pNetwork);

    bool bReturn = false;
    NETWORKMODULECALL(OnSendToClientMessage(Msg), m_pUser, m_pNetwork, this,
                      &bReturn);
    if (bReturn) return false;

    CString sCopy = Msg.ToString();
    NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this,
                      &bReturn);
    if (bReturn) return false;

    DEBUG("(" << GetFullName() << ") ZNC -> CLI ["
        << CDebug::Filter(sCopy) << "]");
    Write(sCopy + "\r\n");
    return true;
}
Example #22
0
bool CIniFile::ReadFile(const CString&  _path)
{
  // Normally you would use ifstream, but the SGI CC compiler has
  // a few bugs with ifstream. So ... fstream used.
  ifstream f;
  CString   line;
  CString   keyname, valuename, value;
  CString::size_type pLeft, pRight;

  //если файл испортили из-вне.
  //проверка испорченности файла: открытие
  f.open( _path.c_str());
  if ( f.fail()){
    printf("Warning: ini file:'%s' is NOT OPENED\n", _path.c_str());
    f.close();
    return false;
  };

  //проверка испорченности файла: проверяем размер
  if((minSize > 0) && (size_of_stream(f) < minSize)){
    printf("Warning: ini file:'%s' is suspiciously SMALL\n", _path.c_str());
    f.close();
    return false;
  };

  try{
  Clear();
  while( getline( f, line)) {
    // To be compatible with Win32, check for existence of '\r'.
    // Win32 files have the '\r' and Unix files don't at the end of a line.
    // Note that the '\r' will be written to INI files from
    // Unix so that the created INI file can be read under Win32
    // without change.
    //printf("str=%s \n line=%s\n",_str.c_str(),line.c_str());
    if ( line[line.length() - 1] == '\r')
      line = line.substr( 0, line.length() - 1);

    if ( line.length()) {
      // Check that the user hasn't openned a binary file by checking the first
      // character of each line!
//      if ( !isprint( line[0])) {
//       printf( "Failing on char %d\n", line[0]);
//       f.close();
//        return false;
//      };
      if (( pLeft = line.find_first_of(";#[=:")) != CString::npos) {
       switch ( line[pLeft]) {
       case '[':
         if ((pRight = line.find_last_of("]")) != CString::npos &&
              pRight > pLeft) {
           keyname = trim(line.substr( pLeft + 1, pRight - pLeft - 1));

           AddKeyName(keyname);
           //printf("Section: %s\n",keyname.c_str());
         }
       break;

       case '=':
         valuename = trim(line.substr( 0, pLeft));
         value = trim(line.substr( pLeft + 1));
         SetValue( keyname, valuename, value);
       break;
//
//       case ':':
//         valuename = line.substr( 0, pLeft);
//         value = line.substr( pLeft + 1);
//         AddValue( keyname, valuename, value);
//       break;

       case ';':
       case '#':
         if ( !names.size())
            HeaderComment( line.substr( pLeft + 1));
          else
            KeyComment( keyname, line.substr( pLeft + 1));
       break;
       };//switch()
      }//if(( pLeft = line.find_first_of(";#[=")) != CString::npos)
    };//if ( line.length())
  };//while( getline( ini_str, line))
  }catch(...){

  };
  f.close();

  //проверка испорченности файла: проверяем размер
  if(minSize<=0)
    return true;

  if(0 == names.size()){
    printf("Warning: ini file:'%s' is NOT contain any names\n", _path.c_str());
    return false;
  };

  return (CheckFile());
}
Example #23
0
CString CChan::GetModeArg(CString& sArgs) const {
	CString sRet = sArgs.substr(0, sArgs.find(' '));
	sArgs = (sRet.size() < sArgs.size()) ? sArgs.substr(sRet.size() +1) : "";
	return sRet;
}
Example #24
0
bool CClient::PutClient(const CMessage& Message) {
    if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) {
        return false;
    } else if (!m_bAccountNotify &&
               Message.GetType() == CMessage::Type::Account) {
        return false;
    }

    CMessage Msg(Message);

    const CIRCSock* pIRCSock = GetIRCSock();
    if (pIRCSock) {
        if (Msg.GetType() == CMessage::Type::Numeric) {
            unsigned int uCode = Msg.As<CNumericMessage>().GetCode();

            if (uCode == 352) {  // RPL_WHOREPLY
                if (!m_bNamesx && pIRCSock->HasNamesx()) {
                    // The server has NAMESX, but the client doesn't, so we need
                    // to remove extra prefixes
                    CString sNick = Msg.GetParam(6);
                    if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) {
                        CString sNewNick = sNick;
                        size_t pos =
                            sNick.find_first_not_of(pIRCSock->GetPerms());
                        if (pos >= 2 && pos != CString::npos) {
                            sNewNick = sNick[0] + sNick.substr(pos);
                        }
                        Msg.SetParam(6, sNewNick);
                    }
                }
            } else if (uCode == 353) {  // RPL_NAMES
                if ((!m_bNamesx && pIRCSock->HasNamesx()) ||
                    (!m_bUHNames && pIRCSock->HasUHNames())) {
                    // The server has either UHNAMES or NAMESX, but the client
                    // is missing either or both
                    CString sNicks = Msg.GetParam(3);
                    VCString vsNicks;
                    sNicks.Split(" ", vsNicks, false);

                    for (CString& sNick : vsNicks) {
                        if (sNick.empty()) break;

                        if (!m_bNamesx && pIRCSock->HasNamesx() &&
                            pIRCSock->IsPermChar(sNick[0])) {
                            // The server has NAMESX, but the client doesn't, so
                            // we just use the first perm char
                            size_t pos =
                                sNick.find_first_not_of(pIRCSock->GetPerms());
                            if (pos >= 2 && pos != CString::npos) {
                                sNick = sNick[0] + sNick.substr(pos);
                            }
                        }

                        if (!m_bUHNames && pIRCSock->HasUHNames()) {
                            // The server has UHNAMES, but the client doesn't,
                            // so we strip away ident and host
                            sNick = sNick.Token(0, false, "!");
                        }
                    }

                    Msg.SetParam(
                        3, CString(" ").Join(vsNicks.begin(), vsNicks.end()));
                }
            }
        } else if (Msg.GetType() == CMessage::Type::Join) {
            if (!m_bExtendedJoin && pIRCSock->HasExtendedJoin()) {
                Msg.SetParams({Msg.As<CJoinMessage>().GetTarget()});
            }
        }
    }

    CString sLine = Msg.ToString(CMessage::ExcludeTags);

    // TODO: introduce a module hook that gives control over the tags that are
    // sent
    MCString mssTags;

    if (HasServerTime()) {
        CString sServerTime = Msg.GetTag("time");
        if (!sServerTime.empty()) {
            mssTags["time"] = sServerTime;
        } else {
            mssTags["time"] = CUtils::FormatServerTime(Msg.GetTime());
        }
    }

    if (HasBatch()) {
        CString sBatch = Msg.GetTag("batch");
        if (!sBatch.empty()) {
            mssTags["batch"] = sBatch;
        }
    }

    if (!mssTags.empty()) {
        CUtils::SetMessageTags(sLine, mssTags);
    }

    PutClient(sLine);
    return true;
}