Example #1
0
bool CIRCNetwork::AddServer(const CString& sName) {
	if (sName.empty()) {
		return false;
	}

	bool bSSL = false;
	CString sLine = sName;
	sLine.Trim();

	CString sHost = sLine.Token(0);
	CString sPort = sLine.Token(1);

	if (sPort.Left(1) == "+") {
		bSSL = true;
		sPort.LeftChomp();
	}

	unsigned short uPort = sPort.ToUShort();
	CString sPass = sLine.Token(2, true);

	return AddServer(sHost, uPort, sPass, bSSL);
}
Example #2
0
void
CMSWindowsClientTaskBarReceiver::copyLog() const
{
	if (m_logBuffer != NULL) {
		// collect log buffer
		CString data;
		for (CBufferedLogOutputter::const_iterator index = m_logBuffer->begin();
								index != m_logBuffer->end(); ++index) {
			data += *index;
			data += "\n";
		}

		// copy log to clipboard
		if (!data.empty()) {
			CMSWindowsClipboard clipboard(m_window);
			clipboard.open(0);
			clipboard.emptyUnowned();
			clipboard.add(IClipboard::kText, data);
			clipboard.close();
		}
	}
}
Example #3
0
	void HandleIgnoreCommand(const CString& sLine) {
		CString sHostmask = sLine.Token(1);
		CString sType = sLine.Token(2);

		if (sType.empty()) {
			sType = "all";
		} else if (sType.Equals("*")) {
			sType = "all";
		}

		if (!(sType.Equals("all") || sType.Equals("privmsg") || sType.Equals("notice") || sType.Equals("ctcp"))) {
			PutModule("Unknown type");
			return;
		}

		CIgnore Ignore(sHostmask, sType);
		m_vIgnores.push_back(Ignore);

		Save();

		PutModule("Ignore added (" + Ignore.GetHostmask() + ")");
	}
Example #4
0
	void Skype_GotMessageProperty(uint64_t a_msgID, const CString& a_property, const CString& a_value)
	{
		EnterCriticalSection(&m_rcvdMsgLock);

		try
		{
			if(m_rcvdMsgs.find(a_msgID) != m_rcvdMsgs.end())
			{
				CReceivedSkypeMsg *l_msg = m_rcvdMsgs[a_msgID];

				if(a_property.Equals("BODY"))
				{
					l_msg->body = (l_msg->edited && a_value.empty() ? "[deleted]" : a_value);
				}
				else if(a_property.Equals("TIMESTAMP"))
					l_msg->timestamp = a_value.ToULong();
				if(a_property.Equals("CHATNAME"))
					l_msg->chatName = a_value;
				else if(a_property.Equals("FROM_DISPNAME"))
					l_msg->fromDispname = a_value;
				else if(a_property.Equals("TYPE"))
					l_msg->type = a_value;

				if(l_msg->isComplete())
				{
					if(l_msg->type == "SAID" || l_msg->type == "EMOTED" || l_msg->edited)
					{
						SendSkypeMsgToIRC(l_msg);
					}
					m_rcvdMsgs.erase(m_rcvdMsgs.find(a_msgID));
					delete l_msg;
				}
			}
		}
		catch(...) {}

		LeaveCriticalSection(&m_rcvdMsgLock);
	}
Example #5
0
	virtual void OnModCommand(const CString& sLine) {
		CString sCommand = sLine.Token(0);
		if (sCommand.Equals("TIMERS")) {
			ListTimers();
		}
		else if (sCommand.Equals("SET")) {
			CString sFormat = sLine.Token(1);

			if (!sFormat.empty()) {
				m_sFormat = sFormat;
				SetNV("nick", m_sFormat);
			}

			if (m_pUser) {
				CString sExpanded = GetAwayNick();
				CString sMsg = "AwayNick is set to [" + m_sFormat + "]";

				if (m_sFormat != sExpanded) {
					sMsg += " (" + sExpanded + ")";
				}

				PutModule(sMsg);
			}
		} else if (sCommand.Equals("SHOW")) {
			if (m_pUser) {
				CString sExpanded = GetAwayNick();
				CString sMsg = "AwayNick is set to [" + m_sFormat + "]";

				if (m_sFormat != sExpanded) {
					sMsg += " (" + sExpanded + ")";
				}

				PutModule(sMsg);
			}
		} else if (sCommand.Equals("HELP")) {
			PutModule("Commands are: show, timers, set [awaynick]");
		}
	}
Example #6
0
	void OnTargetCommand(const CString& sCommand) {
		CString sArg = sCommand.Token(1, false);
		CString sTarget;
		CString sMessage;
		LogMode mode;

		if (sArg.Equals("file")) {
			sTarget = "file";
			sMessage = "Now logging to file";
			mode = LOG_TO_FILE;
		} else if (sArg.Equals("syslog")) {
			sTarget = "syslog";
			sMessage = "Now only logging to syslog";
			mode = LOG_TO_SYSLOG;
		} else if (sArg.Equals("both")) {
			sTarget = "both";
			sMessage = "Now logging to syslog and file";
			mode = LOG_TO_BOTH;
		} else {
			if (sArg.empty()) {
				PutModule("Usage: Target <file|syslog|both> [path]");
			} else {
				PutModule("Unknown target");
			}
			return;
		}

		if (mode != LOG_TO_SYSLOG) {
			CString sPath = sCommand.Token(2, true);
			SetLogFilePath(sPath);
			sMessage += " [" + sPath + "]";
		}

		Log(sMessage);
		SetNV("target", sTarget);
		m_eLogMode = mode;
		PutModule(sMessage);
	}
Example #7
0
File: shell.cpp Project: aszrul/znc
    void OnModCommand(const CString& sLine) override {
        CString sCommand = sLine.Token(0);
        if (sCommand.Equals("cd")) {
            CString sArg = sLine.Token(1, true);
            CString sPath = CDir::ChangeDir(
                m_sPath,
                (sArg.empty() ? CString(CZNC::Get().GetHomePath()) : sArg),
                CZNC::Get().GetHomePath());
            CFile Dir(sPath);

            if (Dir.IsDir()) {
                m_sPath = sPath;
            } else if (Dir.Exists()) {
                PutShell("cd: not a directory [" + sPath + "]");
            } else {
                PutShell("cd: no such directory [" + sPath + "]");
            }

            PutShell("znc$");
        } else {
            RunCommand(sLine);
        }
    }
Example #8
0
	virtual void Away(bool bForce = false, const CString & sReason = "")
	{
		if ((!m_bIsAway) || (bForce))
		{
			if (!bForce)
				m_sReason = sReason;
			else if (!sReason.empty())
				m_sReason = sReason;

			time_t iTime = time(NULL);
			char *pTime = ctime(&iTime);
			CString sTime;
			if (pTime)
			{
				sTime = pTime;
				sTime.Trim();
			}
			if (m_sReason.empty())
				m_sReason = "Auto Away at " + sTime;
			PutIRC("AWAY :" + m_sReason);
			m_bIsAway = true;
		}
	}
Example #9
0
	void SaveBufferToDisk()
	{
		if (!m_sPassword.empty())
		{
			CString sFile = CRYPT_VERIFICATION_TOKEN;

			for (u_int b = 0; b < m_vMessages.size(); b++)
				sFile += m_vMessages[b] + "\n";

			CBlowfish c(m_sPassword, BF_ENCRYPT);
			sFile = c.Crypt(sFile);
			CString sPath = GetPath();
			if (!sPath.empty())
			{
				CFile File(sPath);
				if (File.Open(O_WRONLY | O_CREAT | O_TRUNC, 0600)) {
					File.Chmod(0600);
					File.Write(sFile);
				}
				File.Close();
			}
		}
	}
Example #10
0
CString
IKeyState::CKeyInfo::join(const std::set<CString>& destinations)
{
	// collect destinations into a string.  names are surrounded by ':'
	// which makes searching easy.  the string is empty if there are no
	// destinations and "*" means all destinations.
	CString screens;
	for (std::set<CString>::const_iterator i = destinations.begin();
								i != destinations.end(); ++i) {
		if (*i == "*") {
			screens = "*";
			break;
		}
		else {
			if (screens.empty()) {
				screens = ":";
			}
			screens += *i;
			screens += ":";
		}
	}
	return screens;
}
Example #11
0
const std::locale& CTranslation::LoadTranslation(const CString& sDomain) {
    CString sLanguage = m_sLanguageStack.empty() ? "" : m_sLanguageStack.back();
    sLanguage.Replace("-", "_");
    if (sLanguage.empty()) sLanguage = "C";
#ifdef HAVE_I18N
    // Not using built-in support for multiple domains in single std::locale
    // via overloaded call to .str() because we need to be able to reload
    // translations from disk independently when a module gets updated
    auto& domain = m_Translations[sDomain];
    auto lang_it = domain.find(sLanguage);
    if (lang_it == domain.end()) {
        boost::locale::generator gen;
        gen.add_messages_path(LOCALE_DIR);
        gen.add_messages_domain(sDomain);
        std::tie(lang_it, std::ignore) =
            domain.emplace(sLanguage, gen(sLanguage + ".UTF-8"));
    }
    return lang_it->second;
#else
    // dummy, it's not used anyway
    return std::locale::classic();
#endif
}
Example #12
0
CString CUser::AddTimestamp(time_t tm, const CString& sStr) const {
	CString sRet = sStr;

	if (!GetTimestampFormat().empty() && (m_bAppendTimestamp || m_bPrependTimestamp)) {
		CString sTimestamp = CUtils::FormatTime(tm, GetTimestampFormat(), m_sTimezone);
		if (sTimestamp.empty()) {
			return sRet;
		}

		if (m_bPrependTimestamp) {
			sRet = sTimestamp;
			sRet += " " + sStr;
		}
		if (m_bAppendTimestamp) {
			// From http://www.mirc.com/colors.html
			// The Control+O key combination in mIRC inserts ascii character 15,
			// which turns off all previous attributes, including color, bold, underline, and italics.
			//
			// \x02 bold
			// \x03 mIRC-compatible color
			// \x04 RRGGBB color
			// \x0F normal/reset (turn off bold, colors, etc.)
			// \x12 reverse (weechat)
			// \x16 reverse (mirc, kvirc)
			// \x1D italic
			// \x1F underline
			// Also see http://www.visualirc.net/tech-attrs.php
			if (CString::npos != sRet.find_first_of("\x02\x03\x04\x0F\x12\x16\x1D\x1F")) {
				sRet += "\x0F";
			}

			sRet += " " + sTimestamp;
		}
	}

	return sRet;
}
Example #13
0
bool CTemplate::ValidIf(const CString& sArgs) {
	CString sArgStr = sArgs;
	//sArgStr.Replace(" ", "", "\"", "\"", true);
	sArgStr.Replace(" &&", "&&", "\"", "\"", false);
	sArgStr.Replace("&& ", "&&", "\"", "\"", false);
	sArgStr.Replace(" ||", "||", "\"", "\"", false);
	sArgStr.Replace("|| ", "||", "\"", "\"", false);

	CString::size_type uOrPos = sArgStr.find("||");
	CString::size_type uAndPos = sArgStr.find("&&");

	while (uOrPos != CString::npos || uAndPos != CString::npos || !sArgStr.empty()) {
		bool bAnd = false;

		if (uAndPos < uOrPos) {
			bAnd = true;
		}

		CString sExpr = sArgStr.Token(0, false, ((bAnd) ? "&&" : "||"));
		sArgStr = sArgStr.Token(1, true, ((bAnd) ? "&&" : "||"));

		if (ValidExpr(sExpr)) {
			if (!bAnd) {
				return true;
			}
		} else {
			if (bAnd) {
				return false;
			}
		}

		uOrPos = sArgStr.find("||");
		uAndPos = sArgStr.find("&&");
	}

	return false;
}
Example #14
0
bool CIRCNetwork::AddServer(const CString& sName, unsigned short uPort,
                            const CString& sPass, bool bSSL) {
#ifndef HAVE_LIBSSL
    if (bSSL) {
        return false;
    }
#endif

    if (sName.empty()) {
        return false;
    }

    if (!uPort) {
        uPort = 6667;
    }

    // Check if server is already added
    for (CServer* pServer : m_vServers) {
        if (!sName.Equals(pServer->GetName())) continue;

        if (uPort != pServer->GetPort()) continue;

        if (sPass != pServer->GetPass()) continue;

        if (bSSL != pServer->IsSSL()) continue;

        // Server is already added
        return false;
    }

    CServer* pServer = new CServer(sName, uPort, sPass, bSSL);
    m_vServers.push_back(pServer);

    CheckIRCConnect();

    return true;
}
Example #15
0
bool CDir::MakeDir(const CString& sPath, mode_t iMode) {
	CString sDir;
	VCString dirs;
	VCString::iterator it;

	// Just in case someone tries this...
	if (sPath.empty())
		return false;

	// If this is an absolute path, we need to handle this now!
	if (sPath.Left(1) == "/")
		sDir = "/";

	// For every single subpath, do...
	sPath.Split("/", dirs, false);
	for (it = dirs.begin(); it != dirs.end(); ++it) {
		// Add this to the path we already created
		sDir += *it;

		int i = mkdir(sDir.c_str(), iMode);

		if (i != 0) {
			// All errors except EEXIST are fatal
			if (errno != EEXIST)
				return false;

			// If it's EEXIST we have to make sure it's a dir
			if (!CFile::IsDir(sDir))
				return false;
		}

		sDir += "/";
	}

	// All went well
	return true;
}
Example #16
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 #17
0
static CString GetDataMountPath()
{
#ifdef ITG_ARCADE
// XXX: not currently used
	return "/stats/";
#endif // ITG_ARCADE

	static CString sMountPath;

	// optimization
	if( !sMountPath.empty() )
		return sMountPath;

	/* We need to get the fully qualified path. This is not pleasant... */
	vector<RageFileManager::DriverLocation> mountpoints;
	FILEMAN->GetLoadedDrivers( mountpoints );

	// the first direct driver mounted to / should be our root.
	for( unsigned i = 0; i < mountpoints.size(); i++ )
	{
		RageFileManager::DriverLocation *l = &mountpoints[i];

		if( l->Type != "dir" )
			continue;

		if( l->MountPoint != "/" )
			continue;

		sMountPath = l->Root;
		break;
	}

	CollapsePath( sMountPath );
	LOG->Trace( "DataMountPath resolved to \"%s\".", sMountPath.c_str() );

	return sMountPath;
}
Example #18
0
/* Given a file in a font, find all of the files for the font.
 * 
 * Possibilities:
 *
 * Normal 16x16.png
 * Normal [other] 16x16.png
 * Normal [more] 8x8.png
 * Normal 16x16.ini
 * Normal.ini
 *
 * Any of the above should find all of the above.  Allow the
 * extension to be omitted. */
void Font::GetFontPaths( const CString &sFontOrTextureFilePath,
							   CStringArray &asTexturePathsOut, CString &sIniPath )
{
	CString sDir, sFName, sExt;
	splitpath( sFontOrTextureFilePath, sDir, sFName, sExt );

	/* Don't give us a redir; resolve those before sending them here. */
	ASSERT( sExt.CompareNoCase("redir") );

	/* sFName can't be empty, or we don't know what to search for. */
	ASSERT( !sFName.empty() );

	CString sFontName = GetFontName( sFName );

	CStringArray asFiles;
	GetDirListing( sDir+sFontName + "*", asFiles, false, false );

	for( unsigned i = 0; i < asFiles.size(); ++i )
	{
		/* We now have a list of possibilities, but it may include false positives,
		 * such as "Normal2" when the font name is "Normal".  Weed them. */
		if( GetFontName(asFiles[i]).CompareNoCase(sFontName) )
			continue;

		/* If it's an INI, and we don't already have an INI, use it. */
		if( !asFiles[i].Right(4).CompareNoCase(".ini"))  
		{
			if( !sIniPath.empty() )
				RageException::Throw( "More than one INI found\n%s\n%s", sIniPath.c_str(), asFiles[i].c_str() );
			
			sIniPath = sDir+asFiles[i];
			continue;
		}

		asTexturePathsOut.push_back( sDir+asFiles[i] );
	}
}
Example #19
0
void CIRCSock::Connected() {
    DEBUG(GetSockName() << " == Connected()");

    CString sPass = m_sPass;
    CString sNick = m_pNetwork->GetNick();
    CString sIdent = m_pNetwork->GetIdent();
    CString sRealName = m_pNetwork->GetRealName();

    bool bReturn = false;
    IRCSOCKMODULECALL(OnIRCRegistration(sPass, sNick, sIdent, sRealName), &bReturn);
    if (bReturn) return;

    PutIRC("CAP LS");

    if (!sPass.empty()) {
        PutIRC("PASS " + sPass);
    }

    PutIRC("NICK " + sNick);
    PutIRC("USER " + sIdent + " \"" + sIdent + "\" \"" + sIdent + "\" :" + sRealName);

    // SendAltNick() needs this
    m_Nick.SetNick(sNick);
}
Example #20
0
bool CryptManager::VerifyFileWithFile( CString sPath, CString sSignatureFile, CString sPublicKeyFile )
{
	ASSERT( PREFSMAN->m_bSignProfileData );

	CString sMessageFilename = sPath;
	if( sSignatureFile.empty() )
		sSignatureFile = sPath + SIGNATURE_APPEND;

	CString sPublicKey;
	if( !GetFileContents(sPublicKeyFile, sPublicKey) )
		return false;

	int iBytes = FILEMAN->GetFileSizeInBytes( sSignatureFile );
	if( iBytes > MAX_SIGNATURE_SIZE_BYTES )
		return false;

	CString sSignature;
	if( !GetFileContents(sSignatureFile, sSignature) )
		return false;

	RageFile file;
	if( !file.Open(sPath) )
	{
		LOG->Warn( "VerifyFileWithFile: open(%s) failed: %s", sPath.c_str(), file.GetError().c_str() );
		return false;
	}

	CString sError;
	if( !CryptHelpers::VerifyFile(file, sSignature, sPublicKey, sError) )
	{
		LOG->Warn( "VerifyFile(%s) failed: %s", sPath.c_str(), sError.c_str() );
		return false;
	}

	return true;
}
Example #21
0
bool CClient::OnModeMessage(CModeMessage& Message) {
    CString sTarget = Message.GetTarget();
    CString sModes = Message.GetModes();

    if (m_pNetwork && m_pNetwork->IsChan(sTarget) && sModes.empty()) {
        // If we are on that channel and already received a
        // /mode reply from the server, we can answer this
        // request ourself.

        CChan* pChan = m_pNetwork->FindChan(sTarget);
        if (pChan && pChan->IsOn() && !pChan->GetModeString().empty()) {
            PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() +
                      " " + sTarget + " " + pChan->GetModeString());
            if (pChan->GetCreationDate() > 0) {
                PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " +
                          GetNick() + " " + sTarget + " " +
                          CString(pChan->GetCreationDate()));
            }
            return true;
        }
    }

    return false;
}
Example #22
0
void CryptManager::SignFileToFile( CString sPath, CString sSignatureFile )
{
	ASSERT( PREFSMAN->m_bSignProfileData );

	CString sPrivFilename = PRIVATE_KEY_PATH;
	CString sMessageFilename = sPath;
	if( sSignatureFile.empty() )
		sSignatureFile = sPath + SIGNATURE_APPEND;

	CString sPrivKey;
	if( !GetFileContents(sPrivFilename, sPrivKey) )
		return;

	if( !IsAFile(sMessageFilename) )
	{
		LOG->Trace( "SignFileToFile: \"%s\" doesn't exist", sMessageFilename.c_str() );
		return;
	}

	RageFile file;
	if( !file.Open(sMessageFilename) )
	{
		LOG->Warn( "VerifyFileWithFile: open(%s) failed: %s", sPath.c_str(), file.GetError().c_str() );
		return;
	}

	CString sSignature;
	CString sError;
	if( !CryptHelpers::SignFile(file, sPrivKey, sSignature, sError) )
	{
		LOG->Warn( "SignFileToFile failed: %s", sError.c_str() );
		return;
	}

	WriteFile( sSignatureFile, sSignature );
}
Example #23
0
CString Alsa9Buf::GetHardwareID( CString name )
{
	InitializeErrorHandler();

	if( name.empty() )
		name = DeviceName();
	
	snd_ctl_t *handle;
	int err;
	err = dsnd_ctl_open( &handle, name, 0 );
	if ( err < 0 )
	{
		LOG->Info( "Couldn't open card \"%s\" to get ID: %s", name.c_str(), dsnd_strerror(err) );
		return "???";
	}

	snd_ctl_card_info_t *info;
	dsnd_ctl_card_info_alloca(&info);
	err = dsnd_ctl_card_info( handle, info );
	CString ret = dsnd_ctl_card_info_get_id( info );
	dsnd_ctl_close(handle);

	return ret;
}
Example #24
0
	void OnModCommand(const CString& sLine) {
		CString sCommand = sLine.Token(0).AsUpper();

		if(sCommand == "RELAY")
		{
			if(SendIRCMsgToSkype(sLine.Token(1), sLine.Token(2), sLine.Token(3, true)))
			{
				PutModule("RELAY: message sent!");
				return;
			}
			PutModule("RELAY: message failed!");
		}
		else if(sCommand == "SET")
		{
			const CString& sChan = sLine.Token(1), sChatName = sLine.Token(2);

			if(!sChan.empty() && !sChatName.empty())
			{
				m_chanNameMap[sChan.AsLower()] = sChatName;
				SetNV(sChan, sChatName);
				PutModule("MAPPED: chatname " + sChatName + " to " + sChan + "!");
			}
		}
	}
Example #25
0
bool CLogMod::OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) {
	CFile LogFile(m_sLogPath);
  CDir  LogDir (LogFile.GetDir());
  for(std::vector<CFile*>::iterator it = LogDir.begin(); it != LogDir.end(); ++it) {
    CTemplate& Row = Tmpl.AddRow("LogsLoop");
    Row["File"] = (**it).GetShortName();
  }
  if (WebSock.HasParam("file", false)) {
    CString path = CDir::CheckPathPrefix(GetSavePath(), LogFile.GetDir() + WebSock.GetParam("file", false));
    if (path.empty()) {
      WebSock.PrintErrorPage("Invalid Path");
      return true;
    }

    CFile DisplayFile(path);
    CString content;

    DisplayFile.Open();

    int PageSize = 1024 * 1024;
    int Page = 0;
    if (WebSock.HasParam("page", false)) {
      Page = WebSock.GetParam("page", false).ToInt();
      DisplayFile.Seek(Page * PageSize);
    }
    Tmpl["Prev"] = CString(Page - 1);
    Tmpl["Next"] = CString(Page + 1);
    Tmpl["Curr"] = WebSock.GetParam("file", false);

    DisplayFile.ReadFile(content, PageSize);
    DisplayFile.Close();
    
    Tmpl["Log"] = content;
  }
  return true;
}
Example #26
0
File: nickserv.cpp Project: KTE/znc
	virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
		if (!sArgs.empty()) {
			SetNV("Password", sArgs);
			SetArgs("");
		}

		if (GetNV("IdentifyCmd").empty()) {
			SetNV("IdentifyCmd", "PRIVMSG NickServ :IDENTIFY {password}");
		}
		if (GetNV("GhostCmd").empty()) {
			SetNV("GhostCmd", "PRIVMSG NickServ :GHOST {nickname} {password}");
		}
		if (GetNV("RecoverCmd").empty()) {
			SetNV("RecoverCmd", "PRIVMSG NickServ :RECOVER {nickname} {password}");
		}
		if (GetNV("ReleaseCmd").empty()) {
			SetNV("ReleaseCmd", "PRIVMSG NickServ :RELEASE {nickname} {password}");
		}
		if (GetNV("GroupCmd").empty()) {
			SetNV("GroupCmd", "PRIVMSG NickServ :GROUP {nickname} {password}");
		}

		return true;
	}
Example #27
0
/* sText is UTF-8.  If not all of the characters in sText are available in the
 * font, sAlternateText will be used instead.  If there are unavailable characters
 * in sAlternateText, too, just use sText. */
void BitmapText::SetText( const CString& _sText, const CString& _sAlternateText, int iWrapWidthPixels )
{
	ASSERT( m_pFont );

	CString sNewText = StringWillUseAlternate(_sText,_sAlternateText) ? _sAlternateText : _sText;

	if( iWrapWidthPixels == -1 )	// wrap not specified
		iWrapWidthPixels = m_iWrapWidthPixels;

	if( m_sText == sNewText && iWrapWidthPixels==m_iWrapWidthPixels )
		return;
	m_sText = sNewText;
	m_iWrapWidthPixels = iWrapWidthPixels;

	// Break the string into lines.
	//

	m_wTextLines.clear();

	if( iWrapWidthPixels == -1 )
	{
		split( CStringToWstring(m_sText), L"\n", m_wTextLines, false );
	}
	else
	{
		//
		// Break sText into lines that don't exceed iWrapWidthPixels
		// (if only one word fits on the line, it may be larger than iWrapWidthPixels).
		//
		// TODO: Investigate whether this works in all languages
		/* It doesn't.  I can add Japanese wrapping, at least.  We could handle hyphens
		 * and soft hyphens and pretty easily, too. -glenn */
		// TODO: Move this wrapping logic into Font
		CStringArray asLines;
		split( m_sText, "\n", asLines, false );

		for( unsigned line = 0; line < asLines.size(); ++line )
		{
			CStringArray asWords;
			split( asLines[line], " ", asWords );

			CString sCurLine;
			int iCurLineWidth = 0;

			for( unsigned i=0; i<asWords.size(); i++ )
			{
				const CString &sWord = asWords[i];
				int iWidthWord = m_pFont->GetLineWidthInSourcePixels( CStringToWstring(sWord) );

				if( sCurLine.empty() )
				{
					sCurLine = sWord;
					iCurLineWidth = iWidthWord;
					continue;
				}

				CString sToAdd = " " + sWord;
				int iWidthToAdd = m_pFont->GetLineWidthInSourcePixels(L" ") + iWidthWord;
				if( iCurLineWidth + iWidthToAdd <= iWrapWidthPixels )	// will fit on current line
				{
					sCurLine += sToAdd;
					iCurLineWidth += iWidthToAdd;
				}
				else
				{
					m_wTextLines.push_back( CStringToWstring(sCurLine) );
					sCurLine = sWord;
					iCurLineWidth = iWidthWord;
				}
			}
			m_wTextLines.push_back( CStringToWstring(sCurLine) );
		}
	}

	BuildChars();
	UpdateBaseZoom();
}
Example #28
0
CConfig CIRCNetwork::ToConfig() const {
	CConfig config;

	if (!m_sNick.empty()) {
		config.AddKeyValuePair("Nick", m_sNick);
	}

	if (!m_sAltNick.empty()) {
		config.AddKeyValuePair("AltNick", m_sAltNick);
	}

	if (!m_sIdent.empty()) {
		config.AddKeyValuePair("Ident", m_sIdent);
	}

	if (!m_sRealName.empty()) {
		config.AddKeyValuePair("RealName", m_sRealName);
	}
	if (!m_sBindHost.empty()) {
		config.AddKeyValuePair("BindHost", m_sBindHost);
	}

	config.AddKeyValuePair("IRCConnectEnabled", CString(GetIRCConnectEnabled()));
	config.AddKeyValuePair("FloodRate", CString(GetFloodRate()));
	config.AddKeyValuePair("FloodBurst", CString(GetFloodBurst()));
	config.AddKeyValuePair("JoinDelay", CString(GetJoinDelay()));
	config.AddKeyValuePair("Encoding", m_sEncoding);

	if (!m_sQuitMsg.empty()) {
		config.AddKeyValuePair("QuitMsg", m_sQuitMsg);
	}

	// Modules
	const CModules& Mods = GetModules();

	if (!Mods.empty()) {
		for (CModule* pMod : Mods) {
			CString sArgs = pMod->GetArgs();

			if (!sArgs.empty()) {
				sArgs = " " + sArgs;
			}

			config.AddKeyValuePair("LoadModule", pMod->GetModName() + sArgs);
		}
	}

	// Servers
	for (CServer* pServer : m_vServers) {
		config.AddKeyValuePair("Server", pServer->GetString());
	}

	for (const CString& sFP : m_ssTrustedFingerprints) {
		config.AddKeyValuePair("TrustedServerFingerprint", sFP);
	}

	// Chans
	for (CChan* pChan : m_vChans) {
		if (pChan->InConfig()) {
			config.AddSubConfig("Chan", pChan->GetName(), pChan->ToConfig());
		}
	}

	return config;
}
Example #29
0
void CUtils::GenerateCert(FILE *pOut, const CString& sHost) {
    EVP_PKEY *pKey = nullptr;
    X509 *pCert = nullptr;
    X509_NAME *pName = nullptr;
    const int days = 365;
    const int years = 10;

    unsigned int uSeed = (unsigned int)time(nullptr);
    int serial = (rand_r(&uSeed) % 9999);

    RSA *pRSA = RSA_generate_key(2048, 0x10001, nullptr, nullptr);
    if ((pKey = EVP_PKEY_new())) {
        if (!EVP_PKEY_assign_RSA(pKey, pRSA)) {
            EVP_PKEY_free(pKey);
            return;
        }

        PEM_write_RSAPrivateKey(pOut, pRSA, nullptr, nullptr, 0, nullptr, nullptr);

        if (!(pCert = X509_new())) {
            EVP_PKEY_free(pKey);
            return;
        }

        X509_set_version(pCert, 2);
        ASN1_INTEGER_set(X509_get_serialNumber(pCert), serial);
        X509_gmtime_adj(X509_get_notBefore(pCert), 0);
        X509_gmtime_adj(X509_get_notAfter(pCert), (long)60*60*24*days*years);
        X509_set_pubkey(pCert, pKey);

        pName = X509_get_subject_name(pCert);

        const char *pLogName = getenv("LOGNAME");
        const char *pHostName = nullptr;

        if (!sHost.empty()) {
            pHostName = sHost.c_str();
        }

        if (!pHostName) {
            pHostName = getenv("HOSTNAME");
        }

        if (!pLogName) {
            pLogName = "Unknown";
        }

        if (!pHostName) {
            pHostName = "host.unknown";
        }

        CString sEmailAddr = pLogName;
        sEmailAddr += "@";
        sEmailAddr += pHostName;

        X509_NAME_add_entry_by_txt(pName, "OU", MBSTRING_ASC, (unsigned char *)pLogName, -1, -1, 0);
        X509_NAME_add_entry_by_txt(pName, "CN", MBSTRING_ASC, (unsigned char *)pHostName, -1, -1, 0);
        X509_NAME_add_entry_by_txt(pName, "emailAddress", MBSTRING_ASC, (unsigned char *)sEmailAddr.c_str(), -1, -1, 0);

        X509_set_subject_name(pCert, pName);
        X509_set_issuer_name(pCert, pName);

        if (!X509_sign(pCert, pKey, EVP_sha256())) {
            X509_free(pCert);
            EVP_PKEY_free(pKey);
            return;
        }

        PEM_write_X509(pOut, pCert);
        X509_free(pCert);
        EVP_PKEY_free(pKey);

        fprintf(pOut, "%s", szDefaultDH2048);
    }
}
Example #30
0
bool CModules::LoadModule(const CString& sModule, const CString& sArgs, CUser* pUser, CString& sRetMsg) {
	sRetMsg = "";

	if (FindModule(sModule) != NULL) {
		sRetMsg = "Module [" + sModule + "] already loaded.";
		return false;
	}

	bool bSuccess;
	GLOBALMODULECALL(OnModuleLoading(sModule, sArgs, bSuccess, sRetMsg), pUser, NULL, return bSuccess);

	CString sModPath, sDataPath;
	CString sDesc;
	bool bVersionMismatch;
	bool bIsGlobal;

	if (!FindModPath(sModule, sModPath, sDataPath)) {
		sRetMsg = "Unable to find module [" + sModule + "]";
		return false;
	}

	ModHandle p = OpenModule(sModule, sModPath, bVersionMismatch, bIsGlobal, sDesc, sRetMsg);

	if (!p)
		return false;

	if (bVersionMismatch) {
		dlclose(p);
		sRetMsg = "Version mismatch, recompile this module.";
		return false;
	}

	if ((pUser == NULL) != bIsGlobal) {
		dlclose(p);
		sRetMsg = "Module [" + sModule + "] is ";
		sRetMsg += (bIsGlobal) ? "" : "not ";
		sRetMsg += "a global module.";
		return false;
	}

	CModule* pModule = NULL;

	if (pUser) {
		typedef CModule* (*fp)(ModHandle, CUser* pUser,
				const CString& sModName, const CString& sDataPath);
		fp Load = (fp) dlsym(p, "ZNCModLoad");

		if (!Load) {
			dlclose(p);
			sRetMsg = "Could not find ZNCModLoad() in module [" + sModule + "]";
			return false;
		}

		pModule = Load(p, pUser, sModule, sDataPath);
	} else {
		typedef CModule* (*fp)(ModHandle, const CString& sModName,
				const CString& sDataPath);
		fp Load = (fp) dlsym(p, "ZNCModLoad");

		if (!Load) {
			dlclose(p);
			sRetMsg = "Could not find ZNCModLoad() in module [" + sModule + "]";
			return false;
		}

		pModule = Load(p, sModule, sDataPath);
	}

	pModule->SetDescription(sDesc);
	pModule->SetGlobal(bIsGlobal);
	pModule->SetArgs(sArgs);
	pModule->SetModPath(CDir::ChangeDir(CZNC::Get().GetCurPath(), sModPath));
	push_back(pModule);

	bool bLoaded;
	try {
		bLoaded = pModule->OnLoad(sArgs, sRetMsg);
	} catch (CModule::EModException) {
		bLoaded = false;
		sRetMsg = "Caught an exception";
	}

	if (!bLoaded) {
		UnloadModule(sModule, sModPath);
		if (!sRetMsg.empty())
			sRetMsg = "Module [" + sModule + "] aborted: " + sRetMsg;
		else
			sRetMsg = "Module [" + sModule + "] aborted.";
		return false;
	}

	if (!sRetMsg.empty()) {
		sRetMsg = "Loaded module [" + sModule + "] [" + sRetMsg + "] [" + sModPath + "]";
	} else {
		sRetMsg = "Loaded module [" + sModule + "] [" + sModPath + "]";
	}
	return true;
}