Пример #1
0
int LoadConfig(HTTPCSTR UserFile, HTTPCSTR PasswordFile, PCONFIG config) {

	char line[100];
	HTTPCSTR filename = UserFile;
	if (!filename)
		filename = PasswordFile;

	FILE *dataFile = _tfopen(filename, _T("r"));

	if (dataFile) {
		if (dataFile) {
			while (!feof(dataFile)) {
				memset(line, '\0', sizeof(line));
				if (ReadAndSanitizeInput(dataFile, line, sizeof(line) - 1) &&
					(strlen(line) > 1)) {

#ifdef _UNICODE
					HTTPCHAR* lpoutputW = (HTTPCHAR*)malloc(strlen(line) + 1);
					MultiByteToWideChar(CP_UTF8, 0, line, strlen(line),
						lpoutputW, strlen(line) + 1);
					lpoutputW[strlen(line) - 1] = 0;
					if (UserFile)
						AddUser(lpoutputW, config);
					else
						AddPassword(lpoutputW, config);
					free(lpoutputW);
#else
					if ((UserFile) && (PasswordFile)) {
						HTTPCHAR *p = _tcstok(line, _T(":"));
						if (p) {
							AddUser(p, config);
							p = _tcstok(NULL, _T(":"));
							if (p) {
								AddPassword(p, config);
							}
							else {
								AddPassword(_T(""), config);
							}
						}
					}
					else {
						if (UserFile)
							AddUser(line, config);
						else
							AddPassword(line, config);
					}

#endif

				}
			}
			fclose(dataFile);
		}
	}
	return (1);

}
Пример #2
0
	virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
		// Load the chans from the command line
		unsigned int a = 0;
		VCString vsChans;
		sArgs.Split(" ", vsChans, false);

		for (VCString::const_iterator it = vsChans.begin(); it != vsChans.end(); ++it) {
			CString sName = "Args";
			sName += CString(a);
			AddUser(sName, "*", *it);
		}

		// Load the saved users
		for (MCString::iterator it = BeginNV(); it != EndNV(); it++) {
			const CString& sLine = it->second;
			CAutoVoiceUser* pUser = new CAutoVoiceUser;

			if (!pUser->FromString(sLine) || FindUser(pUser->GetUsername().AsLower())) {
				delete pUser;
			} else {
				m_msUsers[pUser->GetUsername().AsLower()] = pUser;
			}
		}

		return true;
	}
Пример #3
0
void SessionImpl::OnJoinSessionReply(const JoinSessionReply& reply, const NetworkConnectionPtr&)
{
	XTASSERT(m_curState == MachineSessionState::JOINING);

	if (reply.GetResult())
	{
		LogInfo("Session Join Succeeded");

		SetState(MachineSessionState::JOINED);

		// Add the connection to the session to the Sync manager
		m_context->GetSyncManager()->AddConnection(m_sessionConnection);
		m_context->GetInternalSyncManager()->AddConnection(m_sessionConnection);

		// Connect the tunnel between the secondary client and the session
		m_tunnelBridge = new TunnelBridge(m_sessionConnection, m_context->GetPairedConnection());

        AddUser(m_context->GetLocalUser());

        m_sessionMgr->NotifyOnUserJoinedSessionListeners(this, m_context->GetLocalUser());

		// Tell all listeners that we've successfully created the session.
		m_listenerList->NotifyListeners(&SessionListener::OnJoinSucceeded);
	}
	else
	{
		LogInfo("Session Join Failed!");

		Leave();
	}
}
void ConnectionManager(ServerGame& aGame, Ogre::String aAddress, int32 aPort)
{
    LOG(INFO) << "Init SRP";

    boost::asio::ssl::context sslCtx(boost::asio::ssl::context::tlsv1_server);
    SSL_CTX* ctx = sslCtx.native_handle();

    SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
    SSL_CTX_SRP_CTX_init(ctx);
    if (SSL_CTX_set_cipher_list(ctx, "SRP") != 1)
    {
        LOG(ERROR) << "Can not set SRP ciphers";
        return;
    }

    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
    SSL_CTX_set_srp_username_callback(ctx, SSLSRPServerParamCallback);

    AddUser("test", "test");

    LOG(INFO) << "Listening to " << aAddress << ":" << aPort;
    boost::asio::io_service IOService;
    boost::asio::ip::tcp::acceptor gate(IOService,
        boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), aPort));

    while (true)
    {
        SSLStreamPtr sslStream(new SSLStream(IOService, sslCtx));
        gate.accept(sslStream->lowest_layer());
        boost::thread thrd(boost::bind(ClientConnection, boost::ref(aGame), sslStream));
    }
}
Пример #5
0
// 유저가 로비에 입장
ERROR_CODE Lobby::EnterUser(User* pUser)
{
	// 로비 최대 수용인원을 넘으면 에러
	if (m_UserIndexDic.size() >= m_MaxUserCount) {
		return ERROR_CODE::LOBBY_ENTER_MAX_USER_COUNT;
	}

	// 이미 이 로비에 있는 유저가 또 로비에 들어오려고 하면 에러
	if (FindUser(pUser->GetIndex()) != nullptr) {
		return ERROR_CODE::LOBBY_ENTER_USER_DUPLICATION;
	}

	// 로비에 접속한 유저 리스트에 유저 추가
	auto addRet = AddUser(pUser);
	if (addRet != ERROR_CODE::NONE) {
		return addRet;
	}

	pUser->EnterLobby(m_LobbyIndex);

	m_UserIndexDic.insert({ pUser->GetIndex(), pUser });
	m_UserIDDic.insert({ pUser->GetID().c_str(), pUser });

	return ERROR_CODE::NONE;
}
Пример #6
0
void C4Network2IRCChannel::OnUsers(const char *szUsers, const char *szPrefixes)
	{
	// Find actual prefixes
	szPrefixes = SSearch(szPrefixes, ")");
	// Reconstructs the list
	if(!fReceivingUsers)
		ClearUsers();
	while(szUsers && *szUsers)
		{
		// Get user name
		StdStrBuf PrefixedName = ircExtractPar(&szUsers);
		// Remove prefix(es)
		const char *szName = PrefixedName.getData();
		if(szPrefixes)
			while(strchr(szPrefixes, *szName))
				szName++;
		// Copy prefix
		StdStrBuf Prefix;
		Prefix.Copy(PrefixedName.getData(), szName - PrefixedName.getData());
		// Add user
		AddUser(szName)->SetPrefix(Prefix.getData());
		}
	// Set flag the user list won't get cleared again until OnUsersEnd is called
	fReceivingUsers = true;
	}
Пример #7
0
UserManageDlg::UserManageDlg()
{
    SET_FONT

    setWindowTitle(tr("用户管理"));
    m_pUserCenter = USERCENTER::instance();
    CreateToolBar();

	userTable_ = new QTableWidget(this);
    userTable_->setRowCount(0);
    userTable_->setColumnCount(2);
    userTable_->setColumnWidth(0, 130);
    userTable_->setColumnWidth(1, 200);
    userTable_->setFrameStyle(QFrame::Plain);
    userTable_->setEditTriggers(QAbstractItemView::NoEditTriggers);
    userTable_->setSelectionBehavior(QAbstractItemView::SelectRows);
    userTable_->setSelectionMode(QAbstractItemView::SingleSelection);

	QStringList headList;
	headList << "用户名" << "用户角色";
	userTable_->setHorizontalHeaderLabels(headList);

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(toolBar_);
    layout->addWidget(userTable_);
    setLayout(layout);

    connect(addUserAct_, SIGNAL(triggered()), this, SLOT(AddUser()));
    connect(delUserAct_, SIGNAL(triggered()), this, SLOT(DelUser()));
    connect(editUserAct_, SIGNAL(triggered()), this, SLOT(EditUser()));

    DisplayUsers();
}
Пример #8
0
void CUsers::Hearing(const CCallsign &my, const CCallsign &rpt1, const CCallsign &xlx)
{
    CUser heard(my, rpt1, xlx);
    
    // first check if we have this user listed yet
    bool found = false;
    for ( int i = 0; (i < m_Users.size()) && !found; i++ )
    {
        found = (m_Users[i] == heard);
        if ( found )
        {
            m_Users[i].HeardNow();
        }
    }
    
    // if not found, add user to list
    // otherwise just re-sort the list
    if ( !found )
    {
        AddUser(heard);
    }
    else
    {
        std::sort(m_Users.begin(), m_Users.end());
    }
}
Пример #9
0
void Channel::Joined( User& who )
{
	AddUser( who );
	if ( uidata.panel == 0 ) {
		wxLogError( _T("OnUserJoinedChannel: ud->panel NULL") );
		return;
	}
	uidata.panel->Joined(who);
}
Пример #10
0
void Channel::OnChannelJoin( User& who )
{
	AddUser( who );
	//wxLogDebugFunc( wxEmptyString );
	if ( uidata.panel == 0 ) {
		wxLogError( _T("OnChannelJoin: ud->panel NULL") );
		return;
	}
	uidata.panel->OnChannelJoin( who );
}
Пример #11
0
bool CKnights::AddUser(CUser *pUser)
{
	if (pUser == NULL
		|| !AddUser(pUser->m_pUserData->m_id))
		return false;

	pUser->m_pUserData->m_bKnights = m_sIndex;
	pUser->m_pUserData->m_bFame = TRAINEE;
	return true;
}
Пример #12
0
Файл: db.c Проект: Ethylix/child
void loaduserdb()
{
    char accname[50];
    int acclevel;
    int seen,options,timeout;
    char md5_pass[35];
    User *uptr;
    MYSQL_RES *result;
    MYSQL_ROW row;

    if (!reconnect_to_db()) {
        fprintf(stderr,"Cannot connect to db\n");
        operlog("Cannot connect to db");
        return;
    }

    mysql_query(&mysql,"SELECT * FROM child_users");
    if ((result = mysql_use_result(&mysql)) == NULL) {
        printf("CRITICAL: Cannot load user table: mysql_use_result returned NULL\n");
        return;
    }
    while ((row = mysql_fetch_row(result))) {
        strncpy(accname,row[0],50);
        acclevel = strtol(row[1],NULL,10);
        seen = strtol(row[2],NULL,10);
        strncpy(md5_pass,row[4],35);
        options = strtol(row[5],NULL,10);
        timeout = strtol(row[6],NULL,10);

        if (!timeout) timeout = TIMEOUT_DFLT;

        if (vv) printf("Adding user %s with level %d and pass %s and vhost %s\n",accname,acclevel,md5_pass,row[3]);

        if (find_user(accname))
            continue;

        uptr = AddUser(accname,acclevel);

        if (seen) uptr->lastseen = seen; else uptr->lastseen = time(NULL);
        uptr->options = options;
        uptr->timeout = timeout;

        if (vv) printf("User %s added (%p)\n",accname,uptr);

        strncpy(uptr->vhost,row[3],HOSTLEN);
        strncpy(uptr->email,row[7],EMAILLEN);
        uptr->regtime = strtol(row[8], NULL, 10);

        memset(uptr->md5_pass,'\0',34);
        strncpy(uptr->md5_pass,md5_pass,32);
    }

    mysql_close(&mysql);
}
Пример #13
0
bool 
UserManager::AddObject( ValueSet &objectValues, SsapiResponder *pResponder ){
	
	bool rc = true;		
	User *pUser = new User( GetListenManager() );

	*pUser = objectValues;
	if( !pUser->AreThereAnyTooLongStrings( pResponder ) )
		rc= AddUser( pUser, pResponder );

	delete pUser;
	return rc;
}
Пример #14
0
// подключение клиента
void MyServer::incomingConnection(int handle)
{
    //передаем дескрпитор сокета, указатель на сервер (для вызова его методов),
    // и стандартный параметр - parent
    MyClient *client = new MyClient(handle, this, this);
    //подключаем сигналы напрямую к виджету, если его передали в конструктор сервера
    if (widget != 0)
    {
        connect(client, SIGNAL(ConnectUser(QString)), widget, SLOT(AddUser(QString)));
        connect(client, SIGNAL(DisconnectUser(QString)), widget, SLOT(DelitUser(QString)));
        connect(client, SIGNAL(messageUser(QString,QString,QStringList)), widget, SLOT(MessagesUser(QString,QString,QStringList)));
    }
    connect(client, SIGNAL(DisconUser(MyClient*)), this, SLOT(RemoveUser(MyClient*)));
    clients.append(client);
}
Пример #15
0
    void IRCChannel::HandleIRCLine(IRCLine line) {
        // Lets assume that IRCClient are only sending us stuff for this channel!
        if (line.cmd == "JOIN") {
            AddUser(new User(line.prefix));
            
        } else if (line.cmd == "353") {
            vector<string> names;
            boost::split(names, line.tail, boost::is_any_of(" "));
            for (vector<string>::iterator itr = names.begin();
                 itr != names.end();
                 itr++) {
                
                string n = *itr;
                
                if (n[0] == '@' ||
                    n[0] == '+')
                    n = n.substr(1,n.length()-1);

                AddUser(new User(n));
                

            }
        } else if (line.cmd == "PRIVMSG") {
            string nick = line.prefix.Nick();
            User* user = FindUser(nick);
            if (!user)
                throw "user not found on channel";

            MessageEventArg arg;
            arg.user = user;
            arg.channel = this;
            arg.message = line.tail;

            msgEvent.Notify(arg);
        }
    }
Пример #16
0
CatanRoom::CatanRoom(LobbyManager *manager, RoomID ID, CatanUser *creator, QString displayName,
                       CatanGameConfiguration *config ) :
    QObject(manager), manager(manager), ID(ID), displayname(displayName), config(config)
{
    playerCount = 0;
    host = 0;
    for( int i = 0; i < CATAN_MAX_PLAYERS; i++ )
    {
       players[i] = 0;
       readyPlayers[i] = false;
    }
    AddUser( creator );

    connect( &startTimer, SIGNAL(timeout()),
             this, SLOT(startGame()));
}
Пример #17
0
// New user registered.
void OnUserRegistered(BYTE *InBuffer) {
	String name, ip;
	DWORD sex;

	try {
		//name
		GetStreamString(&InBuffer, &name);
		//ip
		GetStreamString(&InBuffer, &ip);
		//sex
		GetStreamDword(&InBuffer, &sex);

		AddUser(name, NULL, ip, sex, false);
	} catch (Exception *E) {
		throw(Format(__("OnUserRegisteredError"), ARRAYOFCONST((E->Message))));
	}
}
Пример #18
0
int UserManageInterface(char* command[2]){
	FILE* uFile = NULL;
	int hasUserList = 0;
	char userid[255];
	if (strcmp(command[0], "Reg") == 0 || strcmp(command[0], "Del") == 0){
		uFile = fopen(Userdata, "r");
		if (uFile == NULL){
			sprintf(now_display.message, "%s is unknown.", Userdata);
			return 0;
		}
		else{
			while (!feof(uFile)){
				fscanf(uFile, "%s\n", userid);
				if (strcmp(userid, command[1]) == 0){
					hasUserList = 1;
					break;
				}
			}
		}
		fclose(uFile);
	}
	if (strcmp(command[0], "Reg") == 0){
		if (hasUserList == 1){
			sprintf(now_display.message, "%s is already registered.\n", command[1]);
			RejectUser();
			return 0;
		}
		AddUser(command[1]);
	}
	else if (strcmp(command[0], "Del") == 0){
		if (hasUserList == 0){
			sprintf(now_display.message, "%s is not exist in User database.\n", command[1]);
			RejectUser();
			return 0;
		}
		DelUser(command[1]);
	}
	else if (strcmp(command[0], "Show") == 0 && strcmp(command[1], "UserList") == 0){
		ShowUserList();
	}
	else{
		sprintf(now_display.message, "Wrong Command.Try Again.\n(ex.\"Admin Reg UserA\" or \"Admin Del UserA\"");
	}
}
Пример #19
0
void AXHackTrigger::OnUse(AXPlayerController* User)
{
	//ServerOnUse(User);

	if (AllowedToHack(User) && bHackable)
	{
		AddUser(User);
		CurrentAmbientSound = HackAmbientSound;
		SetActorTickEnabled(true);
		AmbientSoundUpdated();
		UUTGameplayStatics::UTPlaySound(GetWorld(), StartHackSound, this, SRT_None);


	}
	else
	{
		UUTGameplayStatics::UTPlaySound(GetWorld(), DeniedSound, this, SRT_None);
	}
}
Пример #20
0
void CNrpLaborMarket::_LoadUsers( const NrpText& fileName )
{
	IniFile sv( fileName );
	int maxUser = _self[ USERNUMBER ];
	for( int i=0; i < maxUser; i++ )
	{
		NrpText name = sv.Get( SECTION_USERS, CreateKeyUser(i), NrpText("") );
		NrpText className = sv.Get( SECTION_USERS, CreateKeyType(i), NrpText("") );

		NrpText fileName = (NrpText)_nrpApp[ SAVEDIR_USERS ] + name + ".user";

		if( !OpFileSystem::IsExist( fileName ) )
		{
			assert( false && "user config file not found" );
			continue;
		}

		CNrpUser* user = NULL;
		if( className == CNrpPlayer::ClassName() ) 
			user = new CNrpPlayer( fileName );
		else
		{
			if( className == CNrpAiUser::ClassName() )
				user = new CNrpAiUser( fileName );
			else
			{
				if( className == NrpTester::ClassName() )
					user = new NrpTester( name );
				else
					user = new CNrpUser( className, name );


				user->Load( fileName );
			}
		}

		assert( user );
		AddUser( user );
	}
}
Пример #21
0
	ERROR_CODE Lobby::EnterUser(User* pUser)
	{
		if (m_UserIndexDic.size() >= m_MaxUserCount) {
			return ERROR_CODE::LOBBY_ENTER_MAX_USER_COUNT;
		}

		if (FindUser(pUser->GetIndex()) != nullptr) {
			return ERROR_CODE::LOBBY_ENTER_USER_DUPLICATION;
		}

		auto addRet = AddUser(pUser);
		if (addRet != ERROR_CODE::NONE) {
			return addRet;
		}

		pUser->EnterLobby(m_LobbyIndex);

		m_UserIndexDic.insert({ pUser->GetIndex(), pUser });
		m_UserIDDic.insert({ pUser->GetID().c_str(), pUser });

		return ERROR_CODE::NONE;
	}
Пример #22
0
void 
UserManager::CheckAndAddWellknownAccount( StringClass &chassisSerialNumber  ){

	User			*pUser, *pNewUser = NULL;
	U32				i;

	for( i = 0; i < GetManagedObjectCount(); i++ ){
		pUser = (User *)GetManagedObject( i );
		if( pUser->GetUserName() == StringClass(DEFAULT_SECURE_USER_NAME) ){
			pNewUser = pUser;
			break;
		}
	}

	if( pNewUser && (pNewUser->GetPassword() != chassisSerialNumber ) ){
		ValueSet		*pVs = new ValueSet();
		DesignatorId	id = pNewUser->GetDesignatorId();
		UnicodeString	s = pNewUser->GetPassword();
		
		pVs->AddGenericValue( (char *)&id, sizeof(id), SSAPI_USER_MANAGER_CHANGE_PASSWORD_OBJECT_ID );
		pVs->AddString( &s, SSAPI_USER_MANAGER_CHANGE_PASSWORD_OLD_PASSWORD );
		s = UnicodeString(StringClass(chassisSerialNumber));
		pVs->AddString( &s,SSAPI_USER_MANAGER_CHANGE_PASSWORD_NEW_PASSWORD );
		ChangePassword(	*pVs,
						new SsapiLocalResponder(this,
												(LOCAL_EVENT_CALLBACK)METHOD_ADDRESS(UserManager, DummyCallback) ) );
		delete pVs;
	}
	else if( !pNewUser ){
		// create a new dude
		pNewUser = new User( GetListenManager() );
		pNewUser->SetUserName( UnicodeString(StringClass(DEFAULT_SECURE_USER_NAME))  );
		pNewUser->SetPassword( UnicodeString(StringClass(chassisSerialNumber))  );
		AddUser(pNewUser,
				new SsapiLocalResponder(this,
										(LOCAL_EVENT_CALLBACK)METHOD_ADDRESS(UserManager, DummyCallback) ) );
		delete pNewUser;
	}
}
Пример #23
0
int AuthConfig::Run()
{
	ReadFromFile();
	ShowMainMenu();

	while (true)
	{
		std::cout << "> ";

		char key = (char)_getch();
		std::cout << key << std::endl;
		if (key == '9')
			break;

		else if (key == '1')
			ListRealms();
		else if (key == '2')
			AddRealm();
		else if (key == '3')
			RemoveRealm();
		else if (key == '4')
			ListUsers();
		else if (key == '5')
			AddUser();
		else if (key == '6')
			RemoveUser();
		else if (key == '7')
			ChangeUserRealm();
		else if (key == '8')
			ChangeUserPassword();
		else if (key == '?')
			ShowMainMenu();
		else
			UnrecognizedCmd();
	}

	return 0;
}
Пример #24
0
void StartCrystalTimer(unsigned char TimerId,
                       unsigned char (*pCallback) (void),
                       unsigned int Ticks)
{   
  if ( pCallback == 0 )
  {
    PrintString("Invalid function pointer given to StartTimer0\r\n"); 
  }
  
  /* assign callback */
  switch (TimerId)
  {
  case 1: pCrystalCallback1 = pCallback; break;
  case 2: pCrystalCallback2 = pCallback; break;
  case 3: pCrystalCallback3 = pCallback; break;
  case 4: pCrystalCallback4 = pCallback; break;
  default: break;
    
  }
  
  AddUser(TimerId,Ticks);
  
}
Пример #25
0
int LocalUser::Load(const char *path) {
  CSJson::Reader reader;
  path_ = path;

  if (!CCFileUtils::sharedFileUtils()->isFileExist(std::string(path))) {
    return AddUser();
  }

  unsigned long size = 4096;
  unsigned char *buf = CCFileUtils::sharedFileUtils()->getFileData(path, "rb", &size);

  if (!reader.parse(std::string((char *)buf), root_, false)) {
    CCLOG("parse %s error", path);
    return -1;
  }

  stageid_ = root_.get("stage", 0).asInt();
  heart_ = root_.get("heart", 0).asInt();
  eventlock_ = root_["eventlock"];
  CCLOG("Tset %d %d", stageid_, heart_);
  delete buf;
  return 0;
}
Пример #26
0
Файл: db.c Проект: Ethylix/child
void loadanopedb()
{
    char accname[50];
    char md5_pass[40];
    char email[EMAILLEN+1];
    int acclvl;
    char channelname[CHANLEN+1];
    char owner[50];
    char entrymsg[200];
    User *uptr,*owner_ptr;
    Chan *chan_ptr;
    MYSQL_RES *result;
    MYSQL_ROW row;
    char *pass;

    if (!reconnect_to_db()) {
        fprintf(stderr,"Cannot connect to db\n");
        operlog("Cannot connect to db");
        return;
    }

    mysql_query(&mysql2,"SELECT display,pass,email FROM anope_ns_core");
    if ((result = mysql_use_result(&mysql2)) == NULL) {
        printf("CRITICAL: Cannot load anope user db: mysql_use_result returned NULL !\n");
        return;
    }
    while ((row = mysql_fetch_row(result))) {
        bzero(accname,50);
        bzero(md5_pass,40);
        bzero(email,EMAILLEN);
        strncpy(accname,row[0],50);

        if (row[1][0] == '\0') {
            printf("ANOPE ERROR: User %s does not have any pass !\n",accname);
            continue;
        }
        if (me.anopemd5 == 0) {
            pass = md5_hash(row[1]);
            strncpy(md5_pass,pass,40);
            free(pass);
        } else
            strncpy(md5_pass,row[1],40);

        strncpy(email,row[2],EMAILLEN);

        if (find_user(accname))
            continue;

        uptr = AddUser(accname,1);
        uptr->lastseen = time(NULL);
        uptr->options = 0;
        uptr->timeout = TIMEOUT_DFLT;
        bzero(uptr->vhost,HOSTLEN);
        bzero(uptr->md5_pass,34);
        strncpy(uptr->md5_pass,md5_pass,32);
        strncpy(uptr->email,email,EMAILLEN);
    }

    mysql_query(&mysql2,"SELECT name,founder,entry_message FROM anope_cs_info");
    if ((result = mysql_use_result(&mysql2)) == NULL) {
        printf("CRITICAL: Cannot load anope chan db: mysql_use_result returned NULL !\n");
        return;
    }
    while((row = mysql_fetch_row(result))) {
        strncpy(channelname,row[0],CHANLEN);
        strncpy(owner,row[1],50);
        strncpy(entrymsg,row[2],200);

        if (find_channel(channelname))
            continue;

        owner_ptr = find_user(owner);
        if (!owner_ptr) {
            fprintf(stderr,"ANOPE ERROR: Cannot load channel %s with owner %s : find_user returned NULL !!\n",channelname,owner);
            continue;
        }

        chan_ptr = CreateChannel(channelname,owner,time(NULL));

        chan_ptr->autolimit = 0;
        strncpy(chan_ptr->entrymsg,entrymsg,sizeof(chan_ptr->entrymsg)-1);
        bzero(chan_ptr->mlock,50);
    }

    mysql_query(&mysql2,"SELECT channel,display,level FROM anope_cs_access");
    if ((result = mysql_use_result(&mysql2)) == NULL) {
        printf("CRITICAL: Cannot load anope channel access db: mysql_use_result returned NULL !\n");
        return;
    }
    while((row = mysql_fetch_row(result))) {
        strncpy(channelname,row[0],CHANLEN);
        strncpy(accname,row[1],50);
        acclvl = strtol(row[2],NULL,10);
        chan_ptr = find_channel(channelname);
        if (!chan_ptr) {
            fprintf(stderr,"ANOPE ERROR: Cannot load access for user %s for channel %s : find_channel returned NULL !!\n",accname,channelname);
            continue;
        }

        uptr = find_user(accname);
        if (!uptr) {
            fprintf(stderr,"ANOPE ERROR: Cannot load access for user %s for channel %s : find_user returned NULL !!\n",accname,channelname);
            continue;
        }

        if (find_cflag(accname,channelname))
            continue;

        if (acclvl < CHLEV_OWNER)
            AddUserToChannel(uptr,chan_ptr,acclvl,0);
    }

    mysql_close(&mysql);
}
static INT_PTR Service_AddEvent(WPARAM wParam, LPARAM lParam)
{
	GCEVENT *gce = (GCEVENT*)lParam, save_gce;
	GCDEST *gcd = NULL, save_gcd;
	TCHAR* pWnd = NULL;
	char* pMod = NULL;
	BOOL bIsHighlighted = FALSE;
	BOOL bRemoveFlag = FALSE;
	int iRetVal = GC_EVENT_ERROR;

	if ( gce == NULL )
		return GC_EVENT_ERROR;

	gcd = gce->pDest;
	if ( gcd == NULL )
		return GC_EVENT_ERROR;

	if ( gce->cbSize != SIZEOF_STRUCT_GCEVENT_V1 && gce->cbSize != SIZEOF_STRUCT_GCEVENT_V2 )
		return GC_EVENT_WRONGVER;

	if ( !IsEventSupported( gcd->iType ) )
		return GC_EVENT_ERROR;

	EnterCriticalSection(&cs);

	#if defined( _UNICODE )
		if ( !( gce->dwFlags & GC_UNICODE )) {
			save_gce = *gce;
			save_gcd = *gce->pDest;
			gce->pDest->ptszID = a2tf( gce->pDest->ptszID, gce->dwFlags );
			gce->ptszUID       = a2tf( gce->ptszUID,       gce->dwFlags );
			gce->ptszNick      = a2tf( gce->ptszNick,      gce->dwFlags );
			gce->ptszStatus    = a2tf( gce->ptszStatus,    gce->dwFlags );
			gce->ptszText      = a2tf( gce->ptszText,      gce->dwFlags );
			gce->ptszUserInfo  = a2tf( gce->ptszUserInfo,  gce->dwFlags );
		}
	#endif

	// Do different things according to type of event
	switch(gcd->iType) {
	case GC_EVENT_ADDGROUP:
		{
			STATUSINFO* si = SM_AddStatus( gce->pDest->ptszID, gce->pDest->pszModule, gce->ptszStatus);
			if ( si && gce->dwItemData)
				si->hIcon = CopyIcon((HICON)gce->dwItemData);
		}
		iRetVal = 0;
		goto LBL_Exit;

	case GC_EVENT_CHUID:
	case GC_EVENT_CHANGESESSIONAME:
	case GC_EVENT_SETITEMDATA:
	case GC_EVENT_GETITEMDATA:
	case GC_EVENT_CONTROL:
	case GC_EVENT_SETSBTEXT:
	case GC_EVENT_ACK:
	case GC_EVENT_SENDMESSAGE :
	case GC_EVENT_SETSTATUSEX :
		iRetVal = DoControl(gce, wParam);
		goto LBL_Exit;

	case GC_EVENT_SETCONTACTSTATUS:
		iRetVal = SM_SetContactStatus( gce->pDest->ptszID, gce->pDest->pszModule, gce->ptszUID, (WORD)gce->dwItemData );
		goto LBL_Exit;

	case GC_EVENT_TOPIC:
	{
		SESSION_INFO* si = SM_FindSession(gce->pDest->ptszID, gce->pDest->pszModule);
		if ( si ) {
			if ( gce->pszText ) {
				replaceStr( &si->ptszTopic, gce->ptszText);
				DBWriteContactSettingTString( si->windowData.hContact, si->pszModule , "Topic", RemoveFormatting( si->ptszTopic ));
				if ( DBGetContactSettingByte( NULL, "Chat", "TopicOnClist", 0 ))
					DBWriteContactSettingTString( si->windowData.hContact, "CList" , "StatusMsg", RemoveFormatting( si->ptszTopic ));
		}	}
		break;
	}
	case GC_EVENT_ADDSTATUS:
		SM_GiveStatus( gce->pDest->ptszID, gce->pDest->pszModule, gce->ptszUID, gce->ptszStatus );
		break;

	case GC_EVENT_REMOVESTATUS:
		SM_TakeStatus( gce->pDest->ptszID, gce->pDest->pszModule, gce->ptszUID, gce->ptszStatus);
		break;

	case GC_EVENT_MESSAGE:
	case GC_EVENT_ACTION:
		if ( !gce->bIsMe && gce->pDest->pszID && gce->pszText ) {
			SESSION_INFO* si = SM_FindSession( gce->pDest->ptszID, gce->pDest->pszModule );
			if ( si )
				if ( IsHighlighted( si, gce->ptszText ))
					bIsHighlighted = TRUE;
		}
		break;

	case GC_EVENT_NICK:
		SM_ChangeNick( gce->pDest->ptszID, gce->pDest->pszModule, gce);
		break;

	case GC_EVENT_JOIN:
		AddUser(gce);
		break;

	case GC_EVENT_PART:
	case GC_EVENT_QUIT:
	case GC_EVENT_KICK:
		bRemoveFlag = TRUE;
		break;
	}

	// Decide which window (log) should have the event
	if ( gcd->pszID ) {
		pWnd = gcd->ptszID;
		pMod = gcd->pszModule;
	}
	else if ( gcd->iType == GC_EVENT_NOTICE || gcd->iType == GC_EVENT_INFORMATION ) {
		SESSION_INFO* si = GetActiveSession();
		if ( si && !lstrcmpA( si->pszModule, gcd->pszModule )) {
			pWnd = si->ptszID;
			pMod = si->pszModule;
		}
		else {
			iRetVal = 0;
			goto LBL_Exit;
		}
	}
	else {
		// Send the event to all windows with a user pszUID. Used for broadcasting QUIT etc
		SM_AddEventToAllMatchingUID( gce );
		if ( !bRemoveFlag ) {
			iRetVal = 0;
			goto LBL_Exit;
	}	}

	// add to log
	if ( pWnd ) {
		SESSION_INFO* si = SM_FindSession(pWnd, pMod);

		// fix for IRC's old stuyle mode notifications. Should not affect any other protocol
		if ((gce->pDest->iType == GC_EVENT_ADDSTATUS || gce->pDest->iType == GC_EVENT_REMOVESTATUS) && !( gce->dwFlags & GCEF_ADDTOLOG )) {
			iRetVal = 0;
			goto LBL_Exit;
		}

		if (gce && gce->pDest->iType == GC_EVENT_JOIN && gce->time == 0) {
			iRetVal = 0;
			goto LBL_Exit;
		}

		if (si && (si->bInitDone || gce->pDest->iType == GC_EVENT_TOPIC || (gce->pDest->iType == GC_EVENT_JOIN && gce->bIsMe))) {
			if (SM_AddEvent(pWnd, pMod, gce, bIsHighlighted) && si->hWnd) {
				SendMessage(si->hWnd, GC_ADDLOG, 0, 0);
			}
			else if (si->hWnd) {
				SendMessage(si->hWnd, GC_REDRAWLOG2, 0, 0);
			}
			DoSoundsFlashPopupTrayStuff(si, gce, bIsHighlighted, 0);
			if ((gce->dwFlags & GCEF_ADDTOLOG) && g_Settings.LoggingEnabled)
				LogToFile(si, gce);
		}

		if ( !bRemoveFlag ) {
			iRetVal = 0;
			goto LBL_Exit;
	}	}

	if ( bRemoveFlag )
		iRetVal = ( SM_RemoveUser( gce->pDest->ptszID, gce->pDest->pszModule, gce->ptszUID ) == 0 ) ? 1 : 0;

LBL_Exit:
	LeaveCriticalSection(&cs);

	#if defined( _UNICODE )
		if ( !( gce->dwFlags & GC_UNICODE )) {
			mir_free((void*)gce->ptszText );
			mir_free((void*)gce->ptszNick );
			mir_free((void*)gce->ptszUID );
			mir_free((void*)gce->ptszStatus );
			mir_free((void*)gce->ptszUserInfo );
			mir_free((void*)gce->pDest->ptszID );
			*gce = save_gce;
			*gce->pDest = save_gcd;
		}
	#endif

	return iRetVal;
}
Пример #28
0
// Server is started, lets run our loop :D
void CWorldServer::ServerLoop( )
{
	fd_set		fds;
	int			activity;
    maxfd = 0;
	sockaddr_in	ClientInfo;
	SOCKET		NewSocket;
	timeval		timeout;
	maxfd = sock;
	OnServerStep();

	//LMA BEGIN
	//MySQL Ping (every hour)
	//20070623, 221000
	UINT time_last_ping=clock();
	UINT delay_ping=3600000;

	//LMA END

	do
	{

        //LMA BEGIN
        //MySQL Ping
        //20070623, 221000
        UINT etime = (UINT)round((clock( ) - time_last_ping));
        if(etime>=delay_ping)
        {
            time_last_ping=clock();
            Ping();
        }
        //LMA END

        timeout.tv_sec = 0;
        timeout.tv_usec = 1000;
        NewSocket = INVALID_SOCKET;
        FD_ZERO( &fds );
        pthread_mutex_lock( &PlayerMutex );
		if(!Config.usethreads)
    	   FillFDS( &fds );
		FD_SET( sock, &fds );
		activity = select( maxfd+1, &fds, NULL, NULL, &timeout );
		if ( activity == 0 )
        {
            pthread_mutex_unlock( &PlayerMutex );
        	#ifdef _WIN32
        	Sleep(1);
        	#else
        	usleep(1);
        	#endif
            continue;
        }
		if ( activity < 0 && errno != EINTR )
        {
			#ifdef _WIN32
			Log( MSG_ERROR, "Select command failed. Error #%i", WSAGetLastError() );
			#else
			Log( MSG_ERROR, "Select command failed. Error #%i", errno );
			#endif
			isActive = false;
		}
		if ( FD_ISSET( sock, &fds ) && ConnectedClients < 1024 )
        {
			int clientinfolen = sizeof( sockaddr_in );
            #ifdef _WIN32
       		NewSocket = accept( sock, (sockaddr*)&ClientInfo, (int*)&clientinfolen );
       		#else
    		NewSocket = accept( sock, (sockaddr*)&ClientInfo, (socklen_t*)&clientinfolen );
            #endif
			// TODO: check if server is full
			if (NewSocket != INVALID_SOCKET)
			{
				if(!isBanned(&ClientInfo))
					AddUser( NewSocket, &ClientInfo );
				else
				{
					Log( MSG_WARNING, "Banned client tried to connect: %s", inet_ntoa( ClientInfo.sin_addr ) );
					close( NewSocket );
				}
			}
			else
			{
			    #ifdef _WIN32
			    Log( MSG_ERROR, "Error accepting socket: %i", WSAGetLastError() );
			    #else
			    Log( MSG_ERROR, "Error accepting socket: %i", errno );
			    #endif
            }
		}
		if(!Config.usethreads)
    		HandleClients( &fds );
    	pthread_mutex_unlock( &PlayerMutex );
    	#ifdef _WIN32
    	Sleep(1);
    	#else
    	usleep(1);
    	#endif
	} while( isActive );
}
Пример #29
0
void ChannelAgent::MessageReceived(BMessage* msg)
{
	int32 i(0);

	switch (msg->what) {
	case M_USER_QUIT: {
		const char* nick(NULL);

		msg->FindString("nick", &nick);

		if (RemoveUser(nick)) {
			BMessage display;

			if (msg->FindMessage("display", &display) == B_NO_ERROR)
				ClientAgent::MessageReceived(&display);
		}
	} break;

	case M_USER_ADD: {
		const char* nick(NULL);
		bool ignore(false);

		int32 iStatus(STATUS_NORMAL_BIT);

		msg->FindString("nick", &nick);
		msg->FindBool("ignore", &ignore);
		if (nick == NULL) {
			printf("ERROR: attempted to AddUser an empty nick in ChannelAgent, channel: %s\n",
				   fId.String());
			break;
		}

		if (ignore) iStatus |= STATUS_IGNORE_BIT;

		AddUser(nick, iStatus);

		BMessage display;
		if (msg->FindMessage("display", &display) == B_NO_ERROR)
			ClientAgent::MessageReceived(&display);
	} break;

	case M_CHANGE_NICK: {
		const char* oldNick(NULL), *newNick(NULL);
		NameItem* item(NULL);
		int32 thePos(-1);

		if ((msg->FindString("oldnick", &oldNick) != B_OK) ||
			(msg->FindString("newnick", &newNick) != B_OK)) {
			printf("Error: invalid pointer, ChannelAgent::MessageReceived, M_CHANGE_NICK");
			break;
		}

		if (fMyNick.ICompare(oldNick) == 0 && !IsHidden())
			vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_NICK, newNick);

		if (((thePos = FindPosition(oldNick)) >= 0) &&
			((item = (static_cast<NameItem*>(fNamesList->ItemAt(thePos)))) != 0)) {
			item->SetName(newNick);
			fNamesList->SortItems(SortNames);
			if (fLastExpansion.ICompare(oldNick, fLastExpansion.Length()) == 0) {
				int32 count(fRecentNicks.CountItems());
				BString* name(NULL);

				for (i = 0; i < count; i++)
					if ((name = fRecentNicks.ItemAt(i))->ICompare(oldNick) == 0) {
						if (fLastExpansion.ICompare(newNick, fLastExpansion.Length()) == 0)
							name->SetTo(newNick);
						else
							delete fRecentNicks.RemoveItemAt(i);
						break;
					}
				count = fCompletionNicks.CountItems();
				for (i = 0; i < count; i++)
					if ((name = fCompletionNicks.ItemAt(i))->ICompare(oldNick) == 0) {
						if (fLastExpansion.ICompare(newNick, fLastExpansion.Length()) == 0)
							name->SetTo(newNick);
						else
							delete fCompletionNicks.RemoveItemAt(i);
						break;
					}
			}
		} else
			break;

		ClientAgent::MessageReceived(msg);
	} break;

	case M_CHANNEL_NAMES: {
		for (i = 0; msg->HasString("nick", i); ++i) {
			const char* nick(NULL);
			bool founder(false), protect(false), op(false), voice(false), helper(false),
				ignored(false);

			msg->FindString("nick", i, &nick);
			msg->FindBool("founder", i, &founder);
			msg->FindBool("protect", i, &protect);
			msg->FindBool("op", i, &op);
			msg->FindBool("voice", i, &voice);
			msg->FindBool("helper", i, &helper);
			msg->FindBool("ignored", i, &ignored);

			if (FindPosition(nick) < 0) {
				int32 iStatus(ignored ? STATUS_IGNORE_BIT : 0);

				if (founder) {
					++nick;
					++fOpsCount;
					iStatus |= STATUS_FOUNDER_BIT;
				} else if (protect) {
					++nick;
					++fOpsCount;
					iStatus |= STATUS_PROTECTED_BIT;
				} else if (op) {
					++nick;
					++fOpsCount;
					iStatus |= STATUS_OP_BIT;
				} else if (voice) {
					++nick;
					iStatus |= STATUS_VOICE_BIT;
				} else if (helper) {
					++nick;
					iStatus |= STATUS_HELPER_BIT;
				} else
					iStatus |= STATUS_NORMAL_BIT;

				fUserCount++;

				fNamesList->AddItem(new NameItem(nick, iStatus));
			}
		}

		fNamesList->SortItems(SortNames);

		if (!IsHidden()) {
			BString buffer;
			buffer << fOpsCount;
			vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_OPS, buffer.String());

			buffer = "";
			buffer << fUserCount;
			vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_USERS, buffer.String());
		}
	} break;

	case M_RESIZE_VIEW: {
		BPoint point;
		msg->FindPoint("loc", &point);
		point.x -= Frame().left;
		float offset((int32)(point.x - (fNamesScroll->Frame().left)));
		fResize->MoveBy(offset, 0.0);
		fTextScroll->ResizeBy(offset, 0.0);
		fNamesScroll->ResizeBy(-offset, 0.0);
		fNamesScroll->MoveBy(offset, 0.0);
		BRect namesRect(0, 0, fNamesScroll->Bounds().Width(), 0);
		vision_app->SetRect("namesListRect", namesRect);
	} break;

	case M_SERVER_DISCONNECT: {
		// clear names list on disconnect
		fNamesList->ClearList();
		fOpsCount = 0;
		fUserCount = 0;

		// clear heuristics completion list - this ensures that no stale nicks are left
		// over in it after reconnect -- list will quickly be rebuilt anyhow if there
		// is any conversation whatsoever going on
		while (fRecentNicks.CountItems() > 0) delete fRecentNicks.RemoveItemAt(0L);

	} break;

	case M_REJOIN: {
		const char* newNick(NULL);

		if (msg->FindString("nickname", &newNick) != B_OK) {
			printf("Error: ChannelAgent::MessageReceived, M_REJOIN: invalid pointer\n");
			break;
		}

		fMyNick = newNick; // update nickname (might have changed on reconnect)

		if (!IsHidden())
			vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_NICK, fMyNick.String());

		Display(S_CHANNEL_RECON_REJOIN B_UTF8_ELLIPSIS "\n", C_ERROR, C_BACKGROUND, F_SERVER);

		// send join cmd
		BMessage send(M_SERVER_SEND);
		AddSend(&send, "JOIN ");
		AddSend(&send, fId);
		if (fChanKey != "") {
			AddSend(&send, " ");
			AddSend(&send, fChanKey);
		}
		AddSend(&send, endl);
	} break;

	case M_CHANNEL_TOPIC: {
		const char* theTopic(NULL);
		BString buffer;

		if (msg->FindString("topic", &theTopic) != B_OK) {
			printf("ChannelAgent::MessageReceived, M_CHANNEL_TOPIC: invalid pointer\n");
			break;
		}
		fTopic = theTopic;

		if (!IsHidden())
			vision_app->pClientWin()->pStatusView()->SetItemValue(
				STATUS_META, FilterCrap(theTopic, true).String());

		BMessage display;

		if (msg->FindMessage("display", &display) == B_NO_ERROR)
			ClientAgent::MessageReceived(&display);
	} break;

	case M_OPEN_MSGAGENT: {
		const char* theNick(NULL);
		msg->FindString("nick", &theNick);

		if (theNick == NULL) {
			NameItem* myUser;
			int32 pos = fNamesList->CurrentSelection();
			if (pos >= 0) {
				myUser = static_cast<NameItem*>(fNamesList->ItemAt(pos));
				BString targetNick = myUser->Name();
				msg->AddString("nick", targetNick.String());
			}
		}

		fSMsgr.SendMessage(msg);
	} break;

	case M_CHANNEL_GOT_KICKED: {
		const char* theChannel(NULL), *kicker(NULL), *rest(NULL);

		if ((msg->FindString("channel", &theChannel) != B_OK) ||
			(msg->FindString("kicker", &kicker) != B_OK) ||
			(msg->FindString("rest", &rest) != B_OK)) {
			printf("Error: ClientAgent::MessageReceived, M_CHANNEL_GOT_KICKED, invalid pointer\n");
			break;
		}

		BMessage wegotkicked(M_DISPLAY); // "you were kicked"
		BString buffer;
		buffer += S_CHANNEL_GOT_KICKED;
		buffer += theChannel;
		buffer += " " S_CHANNEL_GOT_KICKED2 " ";
		buffer += kicker;
		buffer += " (";
		buffer += rest;
		buffer += ")\n";
		PackDisplay(&wegotkicked, buffer.String(), C_QUIT, C_BACKGROUND, F_TEXT);

		// clean up
		fNamesList->ClearList();
		fOpsCount = 0;
		fUserCount = 0;

		fMsgr.SendMessage(&wegotkicked);

		BMessage attemptrejoin(M_DISPLAY); // "you were kicked"
		buffer = S_CHANNEL_REJOIN;
		buffer += theChannel;
		buffer += B_UTF8_ELLIPSIS "\n";
		PackDisplay(&attemptrejoin, buffer.String(), C_QUIT, C_BACKGROUND, F_TEXT);
		fMsgr.SendMessage(&attemptrejoin);

		BMessage send(M_SERVER_SEND);
		AddSend(&send, "JOIN ");
		AddSend(&send, theChannel);
		if (fChanKey != "") {
			AddSend(&send, " ");
			AddSend(&send, fChanKey);
		}
		AddSend(&send, endl);
	} break;

	case M_CHANNEL_MODE: {
		ModeEvent(msg);
	} break;

	case M_CHANNEL_MSG: {
		bool hasNick(false);
		BString tempString, theNick, knownAs;
		msg->FindString("msgz", &tempString);
		msg->FindString("nick", &theNick);
		if (theNick != fMyNick) FirstKnownAs(tempString, knownAs, &hasNick);

		if (IsHidden()) {
			UpdateStatus((hasNick) ? WIN_NICK_BIT : WIN_NEWS_BIT);

			if (hasNick) {
				if (tempString[0] == '\1') {
					tempString.RemoveFirst("\1ACTION ");
					tempString.RemoveLast("\1");
				}

				BNotification notification(B_INFORMATION_NOTIFICATION);
				notification.SetGroup(BString("Vision"));
				entry_ref ref = vision_app->AppRef();
				notification.SetOnClickFile(&ref);
				notification.SetTitle(fServerName.String());
				BString content;
				content.SetToFormat("%s - %s said: %s", fId.String(), theNick.String(),
									tempString.String());
				notification.SetContent(content);
				notification.Send();
			}
		} else if (hasNick)
			system_beep(kSoundEventNames[(uint32)seNickMentioned]);

		ClientAgent::MessageReceived(msg);
	} break;

	case M_CHANNEL_MODES: {
		const char* mode(NULL), *chan(NULL), *msgz(NULL);

		if ((msg->FindString("mode", &mode) != B_OK) || (msg->FindString("chan", &chan) != B_OK) ||
			(msg->FindString("msgz", &msgz) != B_OK)) {
			printf("Error: ChannelAgent::MessageReceived, M_CHANNEL_MODES: invalid pointer\n");
			break;
		}

		if (fId.ICompare(chan) == 0) {
			BString realMode(GetWord(mode, 1));
			int32 place(2);

			if (realMode.FindFirst("l") >= 0) fChanLimit = GetWord(mode, place++);

			if (realMode.FindFirst("k") >= 0) {
				fChanKey = GetWord(mode, place++);

				// u2 may not send the channel key, thats why we stored the /join cmd
				// in a string in ParseCmd
				if (fChanKey == "*" && fIrcdtype == IRCD_UNDERNET) {
					BString tempId(fId);
					tempId.Remove(0, 1); // remove any #, &, !, blah.

					if (vision_app->pClientWin()->joinStrings.FindFirst(tempId) < 1) {
						// can't find the join cmd for this channel in joinStrings!
					} else {
						BString joinStringsL(vision_app->pClientWin()->joinStrings);

						// FindLast to make sure we get the last attempt (user might have
						// tried several keys)
						int32 idPos(joinStringsL.FindLast(tempId));
						BString tempKeyString;
						joinStringsL.MoveInto(tempKeyString, idPos, joinStringsL.Length());

						fChanKey = GetWord(tempKeyString.String(), 2);
					}
				} // end u2-kludge stuff
			}
			fChanMode = mode;
			if (!IsHidden())
				vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_MODES,
																	  fChanMode.String());
		}

		BMessage dispMsg(M_DISPLAY);
		PackDisplay(&dispMsg, msgz, C_OP, C_BACKGROUND, F_TEXT);
		BMessenger display(this);
		display.SendMessage(&dispMsg);
	} break;

	case M_NAMES_POPUP_MODE: {
		const char* inaction(NULL);

		msg->FindString("action", &inaction);

		int32 count(0), index(0);

		BString victims, targetNick, action(inaction), modechar, polarity;

		NameItem* myUser(NULL);

		/// action ///
		if (action.FindFirst("voice") >= 0)
			modechar = "v";
		else if (action.FindFirst("op") >= 0)
			modechar = "o";
		else
			break;

		/// polarity ///
		if (action.FindFirst("de") >= 0)
			polarity += " -";
		else
			polarity += " +";

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			victims += " ";
			victims += targetNick;
			count++;
		}

		BString command("/mode ");
		command += fId;
		command += polarity;

		for (i = 0; i < count; i++) command += modechar;

		command += victims;

		ParseCmd(command.String());
	} break;

	case M_NAMES_POPUP_CTCP: {
		const char* inaction(NULL);

		msg->FindString("action", &inaction);

		int32 index(0);
		BString victims, targetNick, action(inaction);
		NameItem* myUser(NULL);
		action.ToUpper();

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			victims += targetNick;
			victims += ",";
		}

		victims.RemoveLast(",");

		BString command("/ctcp ");
		command += victims;
		command += " ";
		command += action;

		ParseCmd(command.String());
	} break;

	case M_NAMES_POPUP_WHOIS: {
		int32 index(0);
		BString victims, targetNick;
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			victims += targetNick;
			victims += ",";
		}

		victims.RemoveLast(",");

		BString command("/whois ");
		command += victims;

		ParseCmd(command.String());
	} break;

	case M_NAMES_POPUP_NOTIFY: {
		int32 index(0);
		BString victims, targetNick;
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			victims += targetNick;
			victims += " ";
		}

		victims.RemoveLast(",");

		BString command("/notify ");
		command += victims;

		ParseCmd(command.String());

	} break;

	case M_NAMES_POPUP_DCCCHAT: {
		int32 index(0);
		BString targetNick;
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			BString command("/dcc chat ");
			command += targetNick;

			ParseCmd(command.String());
		}
	} break;

	case M_NAMES_POPUP_DCCSEND: {
		int32 index(0);
		BString targetNick;
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			BString command("/dcc send ");
			command += targetNick;

			ParseCmd(command.String());
		}
	} break;

	case M_NAMES_POPUP_KICK: {
		int32 index(0);
		BString targetNick, kickMsg(vision_app->GetCommand(CMD_KICK));
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			BString command("/kick ");
			command += targetNick;
			command += " ";
			command += kickMsg;

			ParseCmd(command.String());
		}
	} break;

	case M_STATUS_ADDITEMS: {
		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(0, ""), true);

		vision_app->pClientWin()->pStatusView()->AddItem(
			new StatusItem(S_STATUS_LAG, "", STATUS_ALIGN_LEFT), true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(0, "", STATUS_ALIGN_LEFT),
														 true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(S_STATUS_USERS, ""), true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(S_STATUS_OPS, ""), true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(S_STATUS_MODES, ""), true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem("", "", STATUS_ALIGN_LEFT),
														 true);

		// The false bool for SetItemValue() tells the StatusView not to Invalidate() the view.
		// We send true on the last SetItemValue().
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_SERVER, fServerName.String(),
															  false);
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_LAG, fMyLag.String(), false);
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_NICK, fMyNick.String(), false);
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_MODES, fChanMode.String(),
															  false);
		vision_app->pClientWin()->pStatusView()->SetItemValue(
			STATUS_META, FilterCrap(fTopic.String(), true).String());

		BString buffer;
		buffer << fUserCount;
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_USERS, buffer.String(), false);
		buffer = "";
		buffer << fOpsCount;
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_OPS, buffer.String(), true);
	} break;

	case M_CHANNEL_OPTIONS_SHOW: {
		if (fChanOpt)
			fChanOpt->Activate();
		else {
			fChanOpt = new ChannelOptions(fId.String(), this);
			fChanOpt->Show();
		}
	} break;

	case M_CHANNEL_OPTIONS_CLOSE: {
		fChanOpt = NULL;
	} break;

	case M_CLIENT_QUIT: {
		if ((msg->HasBool("vision:part") && msg->FindBool("vision:part")) ||
			(msg->HasBool("vision:winlist") && msg->FindBool("vision:winlist"))) {
			BMessage send(M_SERVER_SEND);
			AddSend(&send, "PART ");
			AddSend(&send, fId);
			if (msg->HasString("vision:partmsg")) {
				AddSend(&send, " :");
				AddSend(&send, msg->FindString("vision:partmsg"));
			}
			AddSend(&send, endl);
		}
		ClientAgent::MessageReceived(msg);
	} break;

	default:
		ClientAgent::MessageReceived(msg);
	}
}
Пример #30
0
void C4Network2IRCChannel::OnJoin(const char *szUser)
	{
	// Add user (do not set prefix)
	if(!getUser(szUser))
		AddUser(szUser);
	}