void SudokuGrid::SpreadBan(int row, int column, int value) noexcept
{
    for (int r = 0; r < 9; ++r)
        if (r != row) Ban(r, column, value);

    for (int c = 0; c < 9; ++c)
        if (c != column) Ban(row, c, value);

    int boxRow = (row / 3) * 3;
    int boxColumn = (column / 3) * 3;

    for (int r = 0; r < 3; ++r)
    {
        int rr = boxRow + r;
        if (rr == row) continue;

        for (int c = 0; c < 3; ++c)
        {
            int cc = boxColumn + c;
            if (cc == column) continue;

            Ban(rr, cc, value);
        }
    }
}
Exemple #2
0
ChatCommandPack SMOnlineRoom::ParseCommands(MString& data, unsigned int clientNum) {
    MString command;
    m_cNum = clientNum;

    if (data.find("/") != 0) {
        return ChatCommandPack(NONE);
    }
    command = GetCommand(data);

    ChatCommandPack ccp;

    if (m_clients[clientNum]->IsAdmin())
    {
        if (Announce(command, data, ccp))
            return ccp;
        if (Drop(command, data, ccp))
            return ccp;
    }

    if (Kick(command, data, ccp))
        return ccp;
    if (Ban(command, data, ccp))
        return ccp;
    if (Msg(command, data, ccp))
        return ccp;

    return ccp;
}
IncomingDataParser::IncomingDataParser(Application* app) : app_(app) {
  // Connect all the signals
  // due the player is in a different thread, we cannot access these functions
  // directly
  connect(this, SIGNAL(Play()), app_->player(), SLOT(Play()));
  connect(this, SIGNAL(PlayPause()), app_->player(), SLOT(PlayPause()));
  connect(this, SIGNAL(Pause()), app_->player(), SLOT(Pause()));
  connect(this, SIGNAL(Stop()), app_->player(), SLOT(Stop()));
  connect(this, SIGNAL(StopAfterCurrent()), app_->player(),
          SLOT(StopAfterCurrent()));
  connect(this, SIGNAL(Next()), app_->player(), SLOT(Next()));
  connect(this, SIGNAL(Previous()), app_->player(), SLOT(Previous()));
  connect(this, SIGNAL(SetVolume(int)), app_->player(), SLOT(SetVolume(int)));
  connect(this, SIGNAL(PlayAt(int, Engine::TrackChangeFlags, bool)),
          app_->player(), SLOT(PlayAt(int, Engine::TrackChangeFlags, bool)));
  connect(this, SIGNAL(SeekTo(int)), app_->player(), SLOT(SeekTo(int)));

  connect(this, SIGNAL(SetActivePlaylist(int)), app_->playlist_manager(),
          SLOT(SetActivePlaylist(int)));
  connect(this, SIGNAL(ShuffleCurrent()), app_->playlist_manager(),
          SLOT(ShuffleCurrent()));
  connect(this, SIGNAL(SetRepeatMode(PlaylistSequence::RepeatMode)),
          app_->playlist_manager()->sequence(),
          SLOT(SetRepeatMode(PlaylistSequence::RepeatMode)));
  connect(this, SIGNAL(SetShuffleMode(PlaylistSequence::ShuffleMode)),
          app_->playlist_manager()->sequence(),
          SLOT(SetShuffleMode(PlaylistSequence::ShuffleMode)));
  connect(this, SIGNAL(InsertUrls(int, const QList<QUrl>&, int, bool, bool)),
          app_->playlist_manager(),
          SLOT(InsertUrls(int, const QList<QUrl>&, int, bool, bool)));
  connect(this, SIGNAL(RemoveSongs(int, const QList<int>&)),
          app_->playlist_manager(),
          SLOT(RemoveItemsWithoutUndo(int, const QList<int>&)));
  connect(this, SIGNAL(Open(int)), app_->playlist_manager(), SLOT(Open(int)));
  connect(this, SIGNAL(Close(int)), app_->playlist_manager(), SLOT(Close(int)));

  connect(this, SIGNAL(RateCurrentSong(double)), app_->playlist_manager(),
          SLOT(RateCurrentSong(double)));

#ifdef HAVE_LIBLASTFM
  connect(this, SIGNAL(Love()), InternetModel::Service<LastFMService>(),
          SLOT(Love()));
  connect(this, SIGNAL(Ban()), InternetModel::Service<LastFMService>(),
          SLOT(Ban()));
#endif
}
Exemple #4
0
int CNetBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)
{
	if(pRange->IsValid())
		return Ban(&m_BanRangePool, pRange, Seconds, pReason);

	Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)");
	return -1;
}
Exemple #5
0
CRemoteConsoleClient :: CRemoteConsoleClient( CUDPServer *socket, sockaddr_in endPoint, int banTime, bool authed ) :
	m_Socket( socket ),
	m_EndPoint( endPoint ),
	m_LastReceived( GetTime( ) ),
	m_Authed( authed ),
	m_LastPinged( 0 )
{
	Ban( banTime );
}
Exemple #6
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);
}
Exemple #7
0
CRemoteConsoleClient :: CRemoteConsoleClient( const CRemoteConsole &rcon, const QHostAddress &address, quint16 port, int banTime, bool authed ) :
m_RCon( rcon ),
m_Address( address ),
m_Port( port ),
m_LastReceived( 0 ),
m_LastPinged( 0 ),
m_Authed( authed )
{
	Ban( banTime );
}
bool SudokuGrid::Solve() noexcept
{
    int minCount = 10;
    int row = -1;
    int column = -1;

    for (int r = 0; r < 9; ++r)
    {
        for (int c = 0; c < 9; ++c)
        {
            int index = IndexOf(r, c);
            int valueCount = CountLegalValues(index);

            if (valueCount == 0)
            {
                return false;
            }
            else if (valueCount > 1 && valueCount < minCount)
            {
                minCount = valueCount;
                row = r;
                column = c;
            }
        }
    }

    if (minCount < 10)
    {
        int index = IndexOf(row, column);

        for (int i = 0; i < 9; ++i)
        {
            if (!_banned.test(index + i))
            {
                SudokuGrid grid(*this);
                grid.Set(row, column, i);

                if (grid.Solve())
                {
                    *this = grid;
                    return true;
                }
                else
                {
                    Ban(row, column, i);
                }
            }
        }

        return false;
    }

    return true;
}
Exemple #9
0
bool CSecurity::Complain(const IN_ADDR* pAddress, int nBanLength, int nExpire, int nCount)
{
	CQuickLock oLock( m_pSection );

	const DWORD tNow = static_cast< DWORD >( time( NULL ) );

	CComplain* pComplain = NULL;
	if ( m_Complains.Lookup( pAddress->s_addr, pComplain ) )
	{
		if ( pComplain->m_nExpire < tNow )
		{
			pComplain->m_nScore = 1;
		}
		else
		{
			pComplain->m_nScore ++;
			if ( pComplain->m_nScore > nCount )
			{
				m_Complains.RemoveKey( pAddress->s_addr );
				delete pComplain;
				Ban( pAddress, nBanLength );
				return true;
			}
		}
	}
	else
	{
		pComplain = new CComplain;
		pComplain->m_nScore = 1;
		m_Complains.SetAt( pAddress->s_addr, pComplain );
	}

	pComplain->m_nExpire = tNow + nExpire;

	return false;
}
int CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason)
{
	// validate address
	if(Server()->m_RconClientID >= 0 && Server()->m_RconClientID < MAX_CLIENTS &&
		Server()->m_aClients[Server()->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)
	{
		if(NetMatch(pData, Server()->m_NetServer.ClientAddr(Server()->m_RconClientID)))
		{
			Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (you can't ban yourself)");
			return -1;
		}

		for(int i = 0; i < MAX_CLIENTS; ++i)
		{
			if(i == Server()->m_RconClientID || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
				continue;

			if(Server()->m_aClients[i].m_Authed >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))
			{
				Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)");
				return -1;
			}
		}
	}
	else if(Server()->m_RconClientID == IServer::RCON_CID_VOTE)
	{
		for(int i = 0; i < MAX_CLIENTS; ++i)
		{
			if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
				continue;

			if(Server()->m_aClients[i].m_Authed != CServer::AUTHED_NO && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))
			{
				Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)");
				return -1;
			}
		}
	}

	int Result = Ban(pBanPool, pData, Seconds, pReason);
	if(Result != 0)
		return Result;

	// drop banned clients
	typename T::CDataType Data = *pData;
	for(int i = 0; i < MAX_CLIENTS; ++i)
	{
		if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
			continue;

		if(NetMatch(&Data, Server()->m_NetServer.ClientAddr(i)))
		{
			CNetHash NetHash(&Data);
			char aBuf[256];
			MakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER);
			Server()->m_NetServer.Drop(i, aBuf);
		}
	}

	return Result;
}
Exemple #11
0
void cServerDC::DCKickNick(ostream *use_os,cUser *OP, const string &Nick, const string &Reason, int flags)
{
	ostringstream ostr;
	cUser *user = mUserList.GetUserByNick(Nick);
	string NewReason(Reason);
	cKick OldKick;

	// Check if it is possible to kick the user
	if(user && user->mxConn &&
	    (user->mClass + (int) mC.classdif_kick <= OP->mClass) &&
	    (OP->Can(eUR_KICK, mTime.Sec())) &&
		//mClass >= eUC_OPERATOR) &&
	    (OP->mNick != Nick))
	{
		if (user->mProtectFrom < OP->mClass) {
			if(flags & eKCK_Reason) {
				user->mToBan = false;
				// auto kickban
				if(mP.mKickBanPattern.Exec(Reason) >= 0) {
					unsigned u = 0;
					string bantime;
					mP.mKickBanPattern.Extract(1,Reason,bantime);
					if(bantime.size()) {
						ostringstream os;
						if(!(u=Str2Period(bantime,os))) DCPublicHS(os.str(),OP->mxConn);
					}
					if (u > mC.tban_max)
						u = mC.tban_max;
					if (
						(!u && OP->Can(eUR_PBAN, this->mTime)) ||
						((u > 0) &&
						 ((u > mC.tban_kick) && OP->Can(eUR_TBAN, this->mTime)) ||
						 (u <= mC.tban_kick)
						)
					  )
						user->mToBan = true;

					user->mBanTime = u;
					if ( mC.msg_replace_ban.size())
						mP.mKickBanPattern.Replace(0, NewReason, mC.msg_replace_ban);
				}
				mKickList->AddKick(user->mxConn, OP->mNick, &Reason, OldKick);

				if(Reason.size()) {
					string omsg;
					ostr << OP->mNick << " is kicking " << Nick << " because: " << NewReason;
					omsg = ostr.str();
					if(!mC.hide_all_kicks && !OP->mHideKick)
						SendToAll(omsg, OP->mHideKicksForClass ,int(eUC_MASTER));

					if(flags & eKCK_PM) {
						ostr.str(mEmpty);
						ostr << autosprintf(_("You have been kicked because %s"), NewReason.c_str());
						DCPrivateHS(ostr.str(), user->mxConn, &OP->mNick);
					}
				}
			}

			if(flags & eKCK_Drop) {
				// Send the message to the kicker
				ostr.str(mEmpty);
				if(flags & eKCK_TBAN)
					ostr << autosprintf(_("Kicked user %s"), Nick.c_str());
				else
					ostr << autosprintf(_("Dropped user %s"), Nick.c_str());
				ostr << " (IP: " << user->mxConn->AddrIP();
				if(user->mxConn->AddrHost().length())
					ostr << ", host: " << user->mxConn->AddrHost();
				ostr << ")";

				if(user->mxConn->Log(2))
					user->mxConn->LogStream() << "Kicked by " << OP->mNick << ", ban " << mC.tban_kick << "s"<< endl;
				if(OP->Log(3))
					OP->LogStream() << "Kicking " << Nick << endl;

				bool Disconnect = true;
				mKickList->AddKick(user->mxConn, OP->mNick, NULL, OldKick);
				if (OldKick.mReason.size()) {
					#ifndef WITHOUT_PLUGINS
					Disconnect = mCallBacks.mOnOperatorKicks.CallAll(OP, user, &OldKick.mReason);
					#endif
				} else {
					#ifndef WITHOUT_PLUGINS
					Disconnect = mCallBacks.mOnOperatorDrops.CallAll(OP, user);
					#endif
				}
				if (Disconnect) {
					user->mxConn->CloseNice(1000, eCR_KICKED);
					if (!(flags & eKCK_TBAN)) {
						string msg(OP->mNick);
						msg += " ";
						msg += _("dropped");
						ReportUserToOpchat(user->mxConn,msg, mC.dest_drop_chat);
					}
				} else
					ostr << "\n" << _("User cannot be kicked.");

				// temp ban kicked user
				if (flags & eKCK_TBAN) {
					cBan Ban(this);
					cKick Kick;

					mKickList->FindKick(Kick, user->mNick, OP->mNick, 30, true, true);

					if(user->mToBan) {
						mBanList->NewBan(Ban, Kick, user->mBanTime, eBF_NICKIP);
						ostr << " " << _("and banned") << " ";
						Ban.DisplayKick(ostr);
					} else {
						mBanList->NewBan(Ban, Kick, mC.tban_kick, eBF_NICKIP);
						ostr << " " << _("and banned") << " ";
						Ban.DisplayKick(ostr);
					}
					mBanList->AddBan(Ban);
				}
				if (!use_os)
					DCPublicHS(ostr.str(),OP->mxConn);
				else
					(*use_os) << ostr.str();
			}
		} else if(flags & eKCK_Drop) {
			ostr.str(mEmpty);
			ostr << autosprintf(_("Error kicking user %s because he is protected against all classes below %d"), Nick.c_str(), user->mProtectFrom);
			DCPublicHS(ostr.str(),OP->mxConn);
		}
	}
}
Exemple #12
0
int cServerDC::ValidateUser(cConnDC *conn, const string &nick, int &closeReason)
{
	// first validate the IP and host if any
	stringstream errmsg,os;
	// Default close reason
	closeReason = eCR_INVALID_USER;
	if (!conn) return 0;
	//time_t n;
	bool close=false;

	// phase 1: test nick validity
	// phase 2: test ip/host ban (registered users pass)
	// phase 3: test nickban
	// then we're done

	static cRegUserInfo *sRegInfo = new cRegUserInfo;
	if ((nick.size() < mC.max_nick * 2 ) && mR->FindRegInfo(*sRegInfo,nick) && !conn->mRegInfo ) {
		conn->mRegInfo = sRegInfo;
		sRegInfo = new cRegUserInfo;
	}

	// Validate nick
	tVAL_NICK vn = ValidateNick(nick, (conn->GetTheoricalClass() >= eUC_REGUSER ));
	if(vn != eVN_OK) {
		close=true;
		if(vn == eVN_BANNED) {
			errmsg << _("Do not reconnect too fast.") << " ";
			closeReason = eCR_RECONNECT;
		}
		else
			errmsg << _("Bad nickname") << ": ";
		if (conn->Log(2))
			conn->LogStream() << "Bad nick: '" << nick << "' (" << vn << ")" << endl;
	}
	switch(vn) {
		case eVN_OK:
		break;
		case eVN_CHARS:
			errmsg << _("Unallowed characters in your nick.");
			if(mC.nick_chars.size())
				 errmsg << autosprintf(_("use these: %s"), mC.nick_chars.c_str());
		break;
		case eVN_SHORT:
			errmsg << _("Your nick is too short.");
		break;
		case eVN_LONG:
			errmsg << _("Your nick is too long.");
		break;
		case eVN_USED: // never happens
			errmsg << _("Your nick is already in use.");
		break;
		case eVN_PREFIX:
			errmsg << autosprintf(_("Invalid nick prefix. Use: %s"), mC.nick_prefix.c_str());
		break;
		case eVN_NOT_REGED_OP:
			errmsg << _("Operator not registered.");
		break;
		case eVN_BANNED:
			errmsg << autosprintf(_("Wait %s before reconnecting."), cTime(mBanList->IsNickTempBanned(nick) - cTime().Sec()).AsPeriod().AsString().c_str());
		break;
		default:
			errmsg << _("Unknown error.");
		break;
	}

	if (close) {
		if (vn == eVN_USED) {
			static string omsg;
			omsg = "$ValidateDenide";
			conn->Send(omsg);
		}

		DCPublicHS(errmsg.str(), conn);
		if (conn->Log(3)) conn->LogStream() << "Bad nick: " << errmsg.str() << endl;
		return 0;
	}

	cBan Ban(this);
	bool banned = false;

	if (conn->GetTheoricalClass() < eUC_MASTER) { // master class is immune
		// here we cant check share ban because user hasnt sent $MyINFO yet
		if (conn->GetTheoricalClass() == eUC_NORMUSER)
			banned = mBanList->TestBan(Ban, conn, nick, eBF_NICK | eBF_NICKIP | eBF_RANGE | eBF_HOST2 | eBF_HOST1 | eBF_HOST3 | eBF_HOSTR1 | eBF_PREFIX);
		else // registered users avoid prefix ban check because we might actually ban a prefix for unregistered users, but let registered users to use it
			banned = mBanList->TestBan(Ban, conn, nick, eBF_NICK | eBF_NICKIP | eBF_RANGE | eBF_HOST2 | eBF_HOST1 | eBF_HOST3 | eBF_HOSTR1);
	}

	if (banned) {
		errmsg << _("You are banned from this hub.") << "\r\n";
		Ban.DisplayUser(errmsg);
		DCPublicHS(errmsg.str(), conn);
		if (conn->Log(1)) conn->LogStream() << "Unallowed user (" << Ban.mType << "), closing" << endl;
		return 0;
	}

	if (mC.nick_prefix_cc) {
		if (conn->mCC.size() && conn->mCC != "--") {
			string Prefix("[");
			Prefix += conn->mCC;
			Prefix += "]";

			if (StrCompare(nick, 0, 4, Prefix) != 0) {
				errmsg << autosprintf(_("Please add %s in front of your nick."), Prefix.c_str());
				close = conn->GetTheoricalClass() < eUC_REGUSER;
			}
		}
	}

	if (close) {
		DCPublicHS(errmsg.str(), conn);
		return 0;
	}

	return 1;
}
Exemple #13
0
void IncomingDataParser::Parse(const pb::remote::Message& msg) {
  close_connection_ = false;

  RemoteClient* client = qobject_cast<RemoteClient*>(sender());

  // Now check what's to do
  switch (msg.type()) {
    case pb::remote::CONNECT:
      ClientConnect(msg);
      break;
    case pb::remote::DISCONNECT:
      close_connection_ = true;
      break;
    case pb::remote::REQUEST_PLAYLISTS:
      SendPlaylists(msg);
      break;
    case pb::remote::REQUEST_PLAYLIST_SONGS:
      GetPlaylistSongs(msg);
      break;
    case pb::remote::SET_VOLUME:
      emit SetVolume(msg.request_set_volume().volume());
      break;
    case pb::remote::PLAY:
      emit Play();
      break;
    case pb::remote::PLAYPAUSE:
      emit PlayPause();
      break;
    case pb::remote::PAUSE:
      emit Pause();
      break;
    case pb::remote::STOP:
      emit Stop();
      break;
    case pb::remote::STOP_AFTER:
      emit StopAfterCurrent();
      break;
    case pb::remote::NEXT:
      emit Next();
      break;
    case pb::remote::PREVIOUS:
      emit Previous();
      break;
    case pb::remote::CHANGE_SONG:
      ChangeSong(msg);
      break;
    case pb::remote::SHUFFLE_PLAYLIST:
      emit ShuffleCurrent();
      break;
    case pb::remote::REPEAT:
      SetRepeatMode(msg.repeat());
      break;
    case pb::remote::SHUFFLE:
      SetShuffleMode(msg.shuffle());
      break;
    case pb::remote::SET_TRACK_POSITION:
      emit SeekTo(msg.request_set_track_position().position());
      break;
    case pb::remote::INSERT_URLS:
      InsertUrls(msg);
      break;
    case pb::remote::REMOVE_SONGS:
      RemoveSongs(msg);
      break;
    case pb::remote::OPEN_PLAYLIST:
      OpenPlaylist(msg);
      break;
    case pb::remote::CLOSE_PLAYLIST:
      ClosePlaylist(msg);
      break;
    case pb::remote::LOVE:
      emit Love();
      break;
    case pb::remote::BAN:
      emit Ban();
      break;
    case pb::remote::GET_LYRICS:
      emit GetLyrics();
      break;
    case pb::remote::DOWNLOAD_SONGS:
      emit SendSongs(msg.request_download_songs(), client);
      break;
    case pb::remote::SONG_OFFER_RESPONSE:
      emit ResponseSongOffer(client, msg.response_song_offer().accepted());
      break;
    case pb::remote::GET_LIBRARY:
      emit SendLibrary(client);
      break;
    case pb::remote::RATE_SONG:
      RateSong(msg);
      break;
    default:
      break;
  }
}
Exemple #14
0
/* ' @param Cantidad Specifies how many items in that slot are you trying to sell / buy */
void Comercio(eModoComercio Modo, int UserIndex, int NpcIndex, int Slot, int Cantidad) {
	/* '************************************************* */
	/* 'Author: Nacho (Integer) */
	/* 'Last modified: 07/06/2010 */
	/* '27/07/08 (MarKoxX) | New changes in the way of trading (now when you buy it rounds to ceil and when you sell it rounds to floor) */
	/* '  - 06/13/08 (NicoNZ) */
	/* '07/06/2010: ZaMa - Los objetos se loguean si superan la cantidad de 1k (antes era solo si eran 1k). */
	/* '************************************************* */
	int Precio;
	struct Obj Objeto;

	if (Cantidad < 1 || Slot < 1) {
		return;
	}

	if (Modo == eModoComercio_Compra) {
		if (Slot > MAX_INVENTORY_SLOTS) {
			return;
		} else if (Cantidad > MAX_INVENTORY_OBJS) {
			SendData(SendTarget_ToAll, 0,
					dakara::protocol::server::BuildConsoleMsg(
							UserList[UserIndex].Name + " ha sido baneado por el sistema anti-cheats.",
							FontTypeNames_FONTTYPE_FIGHT));
			Ban(UserList[UserIndex].Name, "Sistema Anti Cheats",
					"Intentar hackear el sistema de comercio. Quiso comprar demasiados ítems:" + vb6::CStr(Cantidad));
			UserList[UserIndex].flags.Ban = 1;
			WriteErrorMsg(UserIndex, "Has sido baneado por el Sistema AntiCheat.");
			FlushBuffer(UserIndex);
			CloseSocket(UserIndex);
			return;
		} else if (!(Npclist[NpcIndex].Invent.Object[Slot].Amount > 0)) {
			return;
		}

		if (Cantidad > Npclist[NpcIndex].Invent.Object[Slot].Amount) {
			Cantidad = Npclist[UserList[UserIndex].flags.TargetNPC].Invent.Object[Slot].Amount;
		}

		Objeto.Amount = Cantidad;
		Objeto.ObjIndex = Npclist[NpcIndex].Invent.Object[Slot].ObjIndex;

		/* 'El precio, cuando nos venden algo, lo tenemos que redondear para arriba. */
		/* 'Es decir, 1.1 = 2, por lo cual se hace de la siguiente forma Precio = Clng(PrecioFinal + 0.5) Siempre va a darte el proximo numero. O el "Techo" (MarKoxX) */

		Precio = vb6::CLng(
				(ObjData[Npclist[NpcIndex].Invent.Object[Slot].ObjIndex].Valor / Descuento(UserIndex)
						* Cantidad) + 0.5);

		if (UserList[UserIndex].Stats.GLD < Precio) {
			WriteConsoleMsg(UserIndex, "No tienes suficiente dinero.", FontTypeNames_FONTTYPE_INFO);
			return;
		}

		if (MeterItemEnInventario(UserIndex, Objeto) == false) {
			/* 'Call WriteConsoleMsg(UserIndex, "No puedes cargar mas objetos.", FontTypeNames.FONTTYPE_INFO) */
			EnviarNpcInv(UserIndex, UserList[UserIndex].flags.TargetNPC);
			WriteTradeOK(UserIndex);
			return;
		}

		UserList[UserIndex].Stats.GLD = UserList[UserIndex].Stats.GLD - Precio;

		QuitarNpcInvItem(UserList[UserIndex].flags.TargetNPC, vb6::CByte(Slot), Cantidad);

		/* 'Bien, ahora logueo de ser necesario. Pablo (ToxicWaste) 07/09/07 */
		/* 'Es un Objeto que tenemos que loguear? */
		if (ObjData[Objeto.ObjIndex].Log == 1) {
			LogDesarrollo(
					UserList[UserIndex].Name + " compró del NPC " + std::to_string(Objeto.Amount) + " "
							+ ObjData[Objeto.ObjIndex].Name);
			/* 'Es mucha cantidad? */
		} else if (Objeto.Amount >= 1000) {
			/* 'Si no es de los prohibidos de loguear, lo logueamos. */
			if (ObjData[Objeto.ObjIndex].NoLog != 1) {
				LogDesarrollo(
						UserList[UserIndex].Name + " compró del NPC " + std::to_string(Objeto.Amount) + " "
								+ ObjData[Objeto.ObjIndex].Name);
			}
		}

		/* 'Agregado para que no se vuelvan a vender las llaves si se recargan los .dat. */
		if (ObjData[Objeto.ObjIndex].OBJType == eOBJType_otLlaves) {
			WriteVar(GetDatPath(DATPATH::NPCs),
					"NPC" + vb6::CStr(Npclist[NpcIndex].Numero),
					"obj" + vb6::CStr(Slot),
					vb6::CStr(Objeto.ObjIndex) + "-0");
			logVentaCasa(UserList[UserIndex].Name + " compró " + ObjData[Objeto.ObjIndex].Name);
		}

	} else if (Modo == eModoComercio_Venta) {

		if (Cantidad > UserList[UserIndex].Invent.Object[Slot].Amount) {
			Cantidad = UserList[UserIndex].Invent.Object[Slot].Amount;
		}

		Objeto.Amount = Cantidad;
		Objeto.ObjIndex = UserList[UserIndex].Invent.Object[Slot].ObjIndex;

		if (Objeto.ObjIndex == 0) {
			return;

		} else if (ObjData[Objeto.ObjIndex].Intransferible == 1
				|| ObjData[Objeto.ObjIndex].NoComerciable == 1) {
			WriteConsoleMsg(UserIndex, "No puedes vender este tipo de objeto.", FontTypeNames_FONTTYPE_INFO);
			return;
		} else if ((Npclist[NpcIndex].TipoItems != ObjData[Objeto.ObjIndex].OBJType
				&& Npclist[NpcIndex].TipoItems != eOBJType_otCualquiera) || Objeto.ObjIndex == iORO) {
			WriteConsoleMsg(UserIndex, "Lo siento, no estoy interesado en este tipo de objetos.",
					FontTypeNames_FONTTYPE_INFO);
			EnviarNpcInv(UserIndex, UserList[UserIndex].flags.TargetNPC);
			WriteTradeOK(UserIndex);
			return;
		} else if (ObjData[Objeto.ObjIndex].Real == 1) {
			if (Npclist[NpcIndex].Name != "SR") {
				WriteConsoleMsg(UserIndex,
						"Las armaduras del ejército real sólo pueden ser vendidas a los sastres reales.",
						FontTypeNames_FONTTYPE_INFO);
				EnviarNpcInv(UserIndex, UserList[UserIndex].flags.TargetNPC);
				WriteTradeOK(UserIndex);
				return;
			}
		} else if (ObjData[Objeto.ObjIndex].Caos == 1) {
			if (Npclist[NpcIndex].Name != "SC") {
				WriteConsoleMsg(UserIndex,
						"Las armaduras de la legión oscura sólo pueden ser vendidas a los sastres del demonio.",
						FontTypeNames_FONTTYPE_INFO);
				EnviarNpcInv(UserIndex, UserList[UserIndex].flags.TargetNPC);
				WriteTradeOK(UserIndex);
				return;
			}
		} else if (UserList[UserIndex].Invent.Object[Slot].Amount < 0 || Cantidad == 0) {
			return;
		} else if (Slot<vb6::LBound(UserList[UserIndex].Invent.Object) || Slot>vb6::UBound(UserList[UserIndex].Invent.Object)) {
			EnviarNpcInv(UserIndex, UserList[UserIndex].flags.TargetNPC);
			return;
		} else if (UserTienePrivilegio(UserIndex, PlayerType_Consejero)) {
			WriteConsoleMsg(UserIndex, "No puedes vender ítems.", FontTypeNames_FONTTYPE_WARNING);
			EnviarNpcInv(UserIndex, UserList[UserIndex].flags.TargetNPC);
			WriteTradeOK(UserIndex);
			return;
		}

		QuitarUserInvItem(UserIndex, Slot, Cantidad);

		/* 'Precio = Round(ObjData(Objeto.ObjIndex).valor / REDUCTOR_PRECIOVENTA * Cantidad, 0) */
		Precio = vb6::Fix(SalePrice(Objeto.ObjIndex) * Cantidad);
		UserList[UserIndex].Stats.GLD = UserList[UserIndex].Stats.GLD + Precio;

		if (UserList[UserIndex].Stats.GLD > MAXORO) {
			UserList[UserIndex].Stats.GLD = MAXORO;
		}

		int NpcSlot;
		NpcSlot = SlotEnNPCInv(NpcIndex, Objeto.ObjIndex, Objeto.Amount);

		/* 'Slot valido */
		if (NpcSlot <= MAX_INVENTORY_SLOTS) {
			/* 'Mete el obj en el slot */
			Npclist[NpcIndex].Invent.Object[NpcSlot].ObjIndex = Objeto.ObjIndex;
			Npclist[NpcIndex].Invent.Object[NpcSlot].Amount = Npclist[NpcIndex].Invent.Object[NpcSlot].Amount
					+ Objeto.Amount;
			if (Npclist[NpcIndex].Invent.Object[NpcSlot].Amount > MAX_INVENTORY_OBJS) {
				Npclist[NpcIndex].Invent.Object[NpcSlot].Amount = MAX_INVENTORY_OBJS;
			}
		}

		/* 'Bien, ahora logueo de ser necesario. Pablo (ToxicWaste) 07/09/07 */
		/* 'Es un Objeto que tenemos que loguear? */
		if (ObjData[Objeto.ObjIndex].Log == 1) {
			LogDesarrollo(
					UserList[UserIndex].Name + " vendió al NPC " + std::to_string(Objeto.Amount) + " "
							+ ObjData[Objeto.ObjIndex].Name);
			/* 'Es mucha cantidad? */
		} else if (Objeto.Amount >= 1000) {
			/* 'Si no es de los prohibidos de loguear, lo logueamos. */
			if (ObjData[Objeto.ObjIndex].NoLog != 1) {
				LogDesarrollo(
						UserList[UserIndex].Name + " vendió al NPC " + std::to_string(Objeto.Amount) + " "
								+ ObjData[Objeto.ObjIndex].Name);
			}
		}

	}

	UpdateUserInv(true, UserIndex, 0);
	WriteUpdateUserStats(UserIndex);
	EnviarNpcInv(UserIndex, UserList[UserIndex].flags.TargetNPC);
	WriteTradeOK(UserIndex);

	SubirSkill(UserIndex, eSkill_Comerciar, true);
}
Exemple #15
0
int CNetBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason)
{
	return Ban(&m_BanAddrPool, pAddr, Seconds, pReason);
}
GlobalShortcuts::GlobalShortcuts(QWidget* parent)
    : QWidget(parent),
      gnome_backend_(nullptr),
      system_backend_(nullptr),
      use_gnome_(false),
      rating_signals_mapper_(new QSignalMapper(this)) {
  settings_.beginGroup(kSettingsGroup);

  // Create actions
  AddShortcut("play", tr("Play"), SIGNAL(Play()));
  AddShortcut("pause", tr("Pause"), SIGNAL(Pause()));
  AddShortcut("play_pause", tr("Play/Pause"), SIGNAL(PlayPause()),
              QKeySequence(Qt::Key_MediaPlay));
  AddShortcut("stop", tr("Stop"), SIGNAL(Stop()),
              QKeySequence(Qt::Key_MediaStop));
  AddShortcut("stop_after", tr("Stop playing after current track"),
              SIGNAL(StopAfter()));
  AddShortcut("next_track", tr("Next track"), SIGNAL(Next()),
              QKeySequence(Qt::Key_MediaNext));
  AddShortcut("prev_track", tr("Previous track"), SIGNAL(Previous()),
              QKeySequence(Qt::Key_MediaPrevious));
  AddShortcut("inc_volume", tr("Increase volume"), SIGNAL(IncVolume()));
  AddShortcut("dec_volume", tr("Decrease volume"), SIGNAL(DecVolume()));
  AddShortcut("mute", tr("Mute"), SIGNAL(Mute()));
  AddShortcut("seek_forward", tr("Seek forward"), SIGNAL(SeekForward()));
  AddShortcut("seek_backward", tr("Seek backward"), SIGNAL(SeekBackward()));
  AddShortcut("show_hide", tr("Show/Hide"), SIGNAL(ShowHide()));
  AddShortcut("show_osd", tr("Show OSD"), SIGNAL(ShowOSD()));
  AddShortcut(
      "toggle_pretty_osd", tr("Toggle Pretty OSD"),
      SIGNAL(TogglePrettyOSD()));  // Toggling possible only for pretty OSD
  AddShortcut("shuffle_mode", tr("Change shuffle mode"),
              SIGNAL(CycleShuffleMode()));
  AddShortcut("repeat_mode", tr("Change repeat mode"),
              SIGNAL(CycleRepeatMode()));
  AddShortcut("toggle_last_fm_scrobbling",
              tr("Enable/disable Last.fm scrobbling"),
              SIGNAL(ToggleScrobbling()));
  AddShortcut("love_last_fm_scrobbling", tr("Love (Last.fm scrobbling)"),
              SIGNAL(Love()));
  AddShortcut("ban_last_fm_scrobbling", tr("Ban (Last.fm scrobbling)"),
              SIGNAL(Ban()));

  AddRatingShortcut("rate_zero_star", tr("Rate the current song 0 stars"),
                    rating_signals_mapper_, 0);
  AddRatingShortcut("rate_one_star", tr("Rate the current song 1 star"),
                    rating_signals_mapper_, 1);
  AddRatingShortcut("rate_two_star", tr("Rate the current song 2 stars"),
                    rating_signals_mapper_, 2);
  AddRatingShortcut("rate_three_star", tr("Rate the current song 3 stars"),
                    rating_signals_mapper_, 3);
  AddRatingShortcut("rate_four_star", tr("Rate the current song 4 stars"),
                    rating_signals_mapper_, 4);
  AddRatingShortcut("rate_five_star", tr("Rate the current song 5 stars"),
                    rating_signals_mapper_, 5);

  connect(rating_signals_mapper_, SIGNAL(mapped(int)),
          SIGNAL(RateCurrentSong(int)));

  // Create backends - these do the actual shortcut registration
  gnome_backend_ = new GnomeGlobalShortcutBackend(this);

#ifndef Q_OS_DARWIN
  system_backend_ = new QxtGlobalShortcutBackend(this);
#else
  system_backend_ = new MacGlobalShortcutBackend(this);
#endif

  ReloadSettings();
}
bool cFloodprotect::CheckFlood(cConnDC * conn, tFloodType ft)
{
	if (conn && conn->mpUser && conn->mpUser->mClass >= eUC_OPERATOR) return true;

	unsigned long Hash = cBanList::Ip2Num(conn->AddrIP());

	if(mUserInfo.ContainsHash(Hash))
	{
		cTime now;
		sUserInfo * usr = 0;
		usr = mUserInfo.GetByHash(Hash);

		if(!usr || (usr && usr->mDisabled)) return false;

		usr->mElapsedTime += now.Get() - usr->mLastAction;
		usr->mLastAction = now;
		usr->mActionCounter++;

		usr->addFloodType(ft); // registers the current action type for later analysis

		if(usr->mActionCounter == 10)
		{
			//10/10 = freq > 1 Hz
			//10/10 - freq = 1 Hz - 0.33 Hz
			//10/30 = freq < 0.33 Hz
			if(usr->mElapsedTime.Sec() < 10) // 10 actions, 1 Hz or higher is high frequency
			{
				ostringstream os;
				string text, floodtype;

				int cnt = KickAll(conn);

				switch(ft)
				{
					case eFT_CHAT: floodtype = "MAIN CHAT"; break;
					case eFT_PRIVATE: floodtype = "PRIVATE CHAT"; break;
					case eFT_SEARCH: floodtype = "SEARCH"; break;
					case eFT_MYINFO: floodtype = "MYINFO"; break;
					default: floodtype = "UNKNOWN"; break;
				}

				os << "\r\n";
				os << "FLOODPROTECT: User is trying to " << floodtype << " flood the server. Number of affected connections: " << cnt << ". Banned for " << mCfg.mBanTimeOnFlood << " secs!\r\n";
				os << "FLOODPROTECT: Frequecy is: " << usr->mActionCounter / (usr->mElapsedTime.Sec() + (usr->mElapsedTime.tv_usec / 1000000.)) << " Hz\r\n";
				os << "FLOODPROTECT: Detected flood types are: " << usr->getFloodTypes();
				text = os.str();
				mS->ReportUserToOpchat(conn, text, false);

				cBan Ban(mS);
				cKick Kick;

				Kick.mOp = mS->mC.hub_security;
				Kick.mIP = usr->mIP;
				Kick.mTime = cTime().Sec();
				Kick.mReason = "HIGH FLOOD FREQUENCY DETECTED!";
				mS->mBanList->NewBan(Ban, Kick, mCfg.mBanTimeOnFlood, eBF_IP);
				mS->mBanList->AddBan(Ban);
				usr->mDisabled = true;
				usr->mActionCounter = 0;
				usr->mElapsedTime = cTime(0,0);
				return false;
			}
			if((usr->mElapsedTime.Sec() >= 10) && (usr->mElapsedTime.Sec() < 30)) // between 0.33 Hz and 1 Hz is medium frequency
			{
				//string text;
				//ostringstream os;
				//os << "\r\n";
				//os << "FLOODPROTECT: Frequecy is: " << usr->mActionCounter / (usr->mElapsedTime.Sec() + (usr->mElapsedTime.tv_usec / 1000000.)) << " Hz\r\n";
				//os << "FLOODPROTECT: Detected flood types are: " << usr->getFloodTypes();
				//text = os.str();
				//mS->ReportUserToOpchat(conn, text, false);
				conn->CloseNow();
				usr->mActionCounter = 0;
				usr->mElapsedTime = cTime(0,0);
				return false;
			}
			if(usr->mElapsedTime.Sec() >= 30) // less than 0.33 Hz is low frequency
			{
				//string text;
				//ostringstream os;
				//os << "\r\n";
				//os << "FLOODPROTECT: Frequecy is: " << usr->mActionCounter / (usr->mElapsedTime.Sec() + (usr->mElapsedTime.tv_usec / 1000000.)) << " Hz\r\n";
				//os << "FLOODPROTECT: Detected action types are: " << usr->getFloodTypes();
				//text = os.str();
				//mS->ReportUserToOpchat(conn, text, false);
			        usr->mActionCounter = 0;
			        usr->mElapsedTime = cTime(0,0);
			        return true;
			}
		}
	}
	else
	{
		cTime now;
		sUserInfo * usr;
		usr = new sUserInfo(conn->AddrIP());
		if(!usr) return false;
		usr->mLastAction = now;
		usr->mElapsedTime = cTime(0,0);
		mUserInfo.AddWithHash(usr, Hash);
	}
	return true;
}