/** * @luafunc table Team::getPlayers() * * @brief Get a table containing all players on a team. * * @code * local players = team:getPlayers() * for i, v in ipairs(players) do * print(v:getName()) * end * @endcode * * @return A table of \link LuaPlayerInfo LuaPlayerInfos \endlink currently on this * team. */ S32 Team::lua_getPlayers(lua_State *L) { ServerGame *game = GameManager::getServerGame(); TNLAssert(game->getPlayerCount() == game->getClientCount(), "Mismatched player counts!"); S32 pushed = 0; lua_newtable(L); // Create a table, with no slots pre-allocated for our data for(S32 i = 0; i < game->getClientCount(); i++) { ClientInfo *clientInfo = game->getClientInfo(i); if(clientInfo->getTeamIndex() == mTeamIndex) { clientInfo->getPlayerInfo()->push(L); pushed++; // Increment pushed before using it because Lua uses 1-based arrays lua_rawseti(L, 1, pushed); } } for(S32 i = 0; i < game->getRobotCount(); i ++) { if(game->getBot(i)->getTeam() == mTeamIndex) { game->getBot(i)->getPlayerInfo()->push(L); pushed++; // Increment pushed before using it because Lua uses 1-based arrays lua_rawseti(L, 1, pushed); } } return 1; }
// Makes sure that the mTeams[] structure has the proper player counts // Needs to be called manually before accessing the structure // Bot counts do work on client. Yay! // Rating may only work on server... not tested on client void Game::countTeamPlayers() const { for(S32 i = 0; i < getTeamCount(); i++) { TNLAssert(dynamic_cast<Team *>(getTeam(i)), "Invalid team"); // Assert for safety static_cast<Team *>(getTeam(i))->clearStats(); // static_cast for speed } for(S32 i = 0; i < getClientCount(); i++) { ClientInfo *clientInfo = getClientInfo(i); S32 teamIndex = clientInfo->getTeamIndex(); if(teamIndex >= 0 && teamIndex < getTeamCount()) { // Robot could be neutral or hostile, skip out-of-range team numbers TNLAssert(dynamic_cast<Team *>(getTeam(teamIndex)), "Invalid team"); Team *team = static_cast<Team *>(getTeam(teamIndex)); if(clientInfo->isRobot()) team->incrementBotCount(); else team->incrementPlayerCount(); // The following bit won't work on the client... if(isServer()) { const F32 BASE_RATING = .1f; team->addRating(max(clientInfo->getCalculatedRating(), BASE_RATING)); } } } }
bool createAccount(std::string user, std::string password, std::string epr, std::string clientHome) { ClientInfo *clientinfo = new ClientInfo(); clientinfo->setName(user); clientinfo->setSsn("1111"); CreateAccountRequest *request = new CreateAccountRequest(); request->setClientinfo(clientinfo); request->setPassword(password); TraderClientStub *stub = new TraderClientStub(clientHome,epr); if(stub) { CreateAccountResponse *response = stub->createAccount(request); if(response) std::cout<<"RESULTS , Your user id is "<<response->getUserid()<<std::endl; delete stub; return true; } return false; }
/** * @luafunc table LuaGameInfo::getPlayers() * * @brief Get a list of the players in the game. * * @return A table containing the LuaPlayerInfo for each player (and robot) in * the game */ S32 LuaGameInfo::lua_getPlayers(lua_State *L) { ServerGame *game = mServerGame; S32 pushed = 0; // Count of pushed objects lua_newtable(L); // Create a table, with no slots pre-allocated for our data for(S32 i = 0; i < game->getClientCount(); i++) { ClientInfo *clientInfo = game->getClientInfo(i); if(clientInfo->getPlayerInfo() == NULL || clientInfo->isRobot()) // Skip defunct players and bots continue; clientInfo->getPlayerInfo()->push(L); pushed++; // Increment pushed before using it because Lua uses 1-based arrays lua_rawseti(L, 1, pushed); } for(S32 i = 0; i < game->getRobotCount(); i ++) { game->getBot(i)->getPlayerInfo()->push(L); pushed++; // Increment pushed before using it because Lua uses 1-based arrays lua_rawseti(L, 1, pushed); } return 1; }
int Network::recvFromSocket(void) { int len; int id; socklen_t socklen; static ClientInfo stranger(1); ClientInfo *nstranger; socklen = sizeof(saddrin); //bullshit len = recvfrom(get_connected(0)->get_socket(), get_connected(0)->get_buffer(), get_connected(0)->get_len(), 0, (saddr *)&stranger.get_info(), &socklen); if (len < 1) { get_connected(0)->get_buffer()[0] = 0; return (false); } get_connected(0)->get_filled() = len; if (UDPDuplicate(&stranger, id)) // verificationd des duplicats return (id); if (!(nstranger = new ClientInfo(_len))) return (false); nstranger->get_info() = stranger.get_info(); new_connected(++_id, nstranger); // en udp c'est le rcv qui dit qui vient de se connecter, on stocke ca return (_id); }
ClientGame *GamePair::addClientAndSetRole(const string &name, ClientInfo::ClientRole role) { ClientGame *client = addClient(name); ClientInfo *clientInfo = server->findClientInfo(name); clientInfo->setRole(role); return client; }
ClientInfo* ClientInfo::create(AbstractMessagingPort* messagingPort) { ClientInfo * info = _tlInfo.get(); massert(16472, "A ClientInfo already exists for this thread", !info); info = new ClientInfo(messagingPort); info->setAuthorizationManager(new AuthorizationManager(new AuthExternalStateMongos())); _tlInfo.reset( info ); info->newRequest(); return info; }
ClientInfo * ClientInfo::get() { ClientInfo * info = _tlInfo.get(); if ( ! info ) { info = new ClientInfo(); _tlInfo.reset( info ); info->newRequest(); } return info; }
// Currently only used on client, for various effects // Will return NULL if ship is out-of-scope... we have ClientInfos for all players, but not aways their ships Ship *Game::findShip(const StringTableEntry &clientName) { ClientInfo *clientInfo = findClientInfo(clientName); if(clientInfo) return clientInfo->getShip(); else return NULL; }
ClientInfo* ClientInfo::create(AbstractMessagingPort* messagingPort) { ClientInfo * info = _tlInfo.get(); massert(16472, "A ClientInfo already exists for this thread", !info); info = new ClientInfo(messagingPort); _tlInfo.reset( info ); info->_setupAuth(); info->newRequest(); return info; }
bool ClientList::isAnyDataSocketSet(fd_set* fds, ClientInfo** out) { for (ClientInfoList::iterator iter = clientList.begin(); iter != clientList.end(); iter++) { ClientInfo* info = *iter; if (FD_ISSET(info->getDataSocket(), fds)) { *out = info; return true; } } return false; }
/* * * */ int Network::connectToSocket(std::string host, std::string port) { ClientInfo *stranger = new ClientInfo(_len); int id; if (!stranger) return (false); stranger->setAddr(AF_INET, port.c_str(), host.c_str()); //prépare la connexion udp vers un serveur if (UDPDuplicate(stranger, id)) // verificationd des duplicats return (id); new_connected(++_id, stranger); return (_id); }
virtual bool run(const string& dbName, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) { LastError *le = lastError.disableForCommand(); { assert( le ); if ( le->msg.size() && le->nPrev == 1 ) { le->appendSelf( result ); return true; } } ClientInfo * client = ClientInfo::get(); return client->getLastError( cmdObj , result ); }
ClientInfo * ClientInfo::get(AbstractMessagingPort* messagingPort) { ClientInfo * info = _tlInfo.get(); if (!info) { info = create(messagingPort); } massert(16483, mongoutils::str::stream() << "AbstractMessagingPort was provided to ClientInfo::get" << " but differs from the one stored in the current ClientInfo object. " << "Current ClientInfo messaging port " << (info->port() ? "is not" : "is") << " NULL", messagingPort == NULL || messagingPort == info->port()); return info; }
void GamePair::addBotClientAndSetTeam(const string &name, S32 teamIndex) { ServerGame *server = GameManager::getServerGame(); server->addBot(Vector<string>(), ClientInfo::ClassRobotAddedByAutoleveler); // Get most recently added clientInfo ClientInfo *clientInfo = server->getClientInfo(server->getClientInfos()->size() - 1); ASSERT_TRUE(clientInfo->isRobot()) << "This is supposed to be a robot!"; // Normally, in a game, a ship or bot would be destroyed and would respawn when their team changes, and upon // respawning the BfObject representing that ship would be on the correct team. Not so here (where we are // taking lots of shortcuts); here we need to manually assign a new team to the robot object in addition to // it's more "official" setting on the ClientInfo. clientInfo->setTeamIndex(teamIndex); clientInfo->getShip()->setTeam(teamIndex); }
void ClientHandler::HandleEvent(EventJoin& event, ClientInfo& client) { Cli::writeDebugMsg("Handling join event"); std::lock_guard<std::mutex> lock(mtx); // find client auto itr = m_ClientToRoomMap.find( (void*)&client ); if(itr == m_ClientToRoomMap.end()) { // Make sure it returned something Cli::writeLogMsg(Cli::LOGTYPE_ERROR, "Unable find client in map"); client.Disconnect(); return; } try { // Set new name *itr->second.name_ptr = event.getUser(); // Change room if different: std::shared_ptr<Room> newRoom_ptr = roomHandler.getRoom(event.getTargetRoom()); if( itr->second.room_ptr != newRoom_ptr ) { // Move to new room: itr->second.room_ptr->removeClient(itr->second.client_ptr); itr->second.room_ptr = newRoom_ptr; itr->second.room_ptr->addClient(itr->second.client_ptr); } EventMsg eventMsg("Server", *itr->second.name_ptr + std::string(" joined ") + itr->second.room_ptr->getName()); itr->second.room_ptr->broadcastMsg(eventMsg); }catch (...) { Cli::writeLogMsg(Cli::LOGTYPE_ERROR, "Exception during Join update"); } }
// teamIndex is optional ClientGame *GamePair::addClient(ClientGame *clientGame) { ServerGame *server = GameManager::getServerGame(); clientGame->joinLocalGame(server->getNetInterface()); // Client will have owner privs! // We need to turn off TNL's bandwidth controls so our tests can run faster. FASTER!!@! clientGame->getConnectionToServer()->useZeroLatencyForTesting(); ClientInfo *clientInfo = server->findClientInfo(clientGame->getClientInfo()->getName().getString()); if(!clientInfo->isRobot()) clientInfo->getConnection()->useZeroLatencyForTesting(); return clientGame; }
void ClientHandler::HandleEvent(EventWho& event, ClientInfo & client) { Cli::writeDebugMsg("Handling Who event"); std::lock_guard<std::mutex> lock(mtx); auto itrRqClient = m_ClientToRoomMap.find( (void*)&client ); // Find iterator for requesting client if(itrRqClient == m_ClientToRoomMap.end()) { // Make sure it returned something Cli::writeLogMsg(Cli::LOGTYPE_ERROR, "Unable find client in map"); client.Disconnect(); return; } try { std::string clients_str("Room " + itrRqClient->second.room_ptr->getName() + " contains: "); // Iterate through the list clients in the room and add names to the string: for(auto itList = itrRqClient->second.room_ptr->clients_.begin(); itList != itrRqClient->second.room_ptr->clients_.end(); itList++) { auto itrClientN = m_ClientToRoomMap.find( (void*)(*itList).get() ); // Find iterator to client n in the room. clients_str.append(*itrClientN->second.name_ptr); clients_str.append(","); } // Send message event with the result: EventMsg e_msg("Server", clients_str); EventVariant eventOut = e_msg; itrRqClient->second.client_ptr->Send(eventOut); } catch (...) { Cli::writeLogMsg(Cli::LOGTYPE_ERROR, "Exception: Creating or transmitting who response"); } }
int Network::acceptSocket(void) { socklen_t socklen; ClientInfo *stranger = new ClientInfo(_len); if (!stranger) return (0); socklen = sizeof(saddrin); if ((stranger->get_socket() = accept(get_connected(0)->get_socket(), (saddr *)&(stranger->get_info()), &socklen)) < 0) { delete stranger; return (0); } new_connected(++_id, stranger); _change = true; return (_id); }
/****************************************************************************** * Send a DCOP message to to the client which owns the specified calendar, * notifying it of a change in calendar status. */ void AlarmDaemon::notifyCalStatus(const ADCalendar *cal) { ClientInfo *client = ClientInfo::get(cal); if(!client) return; QCString appname = client->appName(); if(kapp->dcopClient()->isApplicationRegistered(static_cast<const char *>(appname))) { KAlarmd::CalendarStatus change = cal->available() ? (cal->enabled() ? KAlarmd::CALENDAR_ENABLED : KAlarmd::CALENDAR_DISABLED) : KAlarmd::CALENDAR_UNAVAILABLE; kdDebug(5900) << "AlarmDaemon::notifyCalStatus() sending:" << appname << " -> " << change << endl; AlarmGuiIface_stub stub(appname, client->dcopObject()); stub.alarmDaemonUpdate(change, cal->urlString()); if(!stub.ok()) kdError(5900) << "AlarmDaemon::notifyCalStatus(): dcop send failed:" << appname << endl; } }
int HttpListener::checkAccess( struct conn_data * pData ) { struct sockaddr * pPeer = ( struct sockaddr *) pData->achPeerAddr; if (( AF_INET6 == pPeer->sa_family )&& ( IN6_IS_ADDR_V4MAPPED( &((struct sockaddr_in6 *)pPeer)->sin6_addr )) ) { pPeer->sa_family = AF_INET; ((struct sockaddr_in *)pPeer)->sin_addr.s_addr = *((in_addr_t *)&pData->achPeerAddr[20]); } ClientInfo * pInfo = HttpGlobals::getClientCache()->getClientInfo( pPeer ); pData->pInfo = pInfo; if ( D_ENABLED( DL_MORE )) LOG_D(( "[%s] New connection from %s:%d.", getAddrStr(), pInfo->getAddrString(), ntohs( ((struct sockaddr_in*)pPeer)->sin_port) )); return pInfo->checkAccess(); }
bool ClusterWriteCmd::run( const string& dbName, BSONObj& cmdObj, int options, string& errMsg, BSONObjBuilder& result, bool ) { BatchedCommandRequest request( _writeType ); BatchedCommandResponse response; ClusterWriter writer( true /* autosplit */, 0 /* timeout */ ); // TODO: if we do namespace parsing, push this to the type if ( !request.parseBSON( cmdObj, &errMsg ) || !request.isValid( &errMsg ) ) { // Batch parse failure response.setOk( false ); response.setErrCode( ErrorCodes::FailedToParse ); response.setErrMessage( errMsg ); } else { // Fixup the namespace to be a full ns internally NamespaceString nss( dbName, request.getNS() ); request.setNS( nss.ns() ); writer.write( request, &response ); } dassert( response.isValid( NULL ) ); // Save the last opTimes written on each shard for this client, to allow GLE to work if ( ClientInfo::exists() && writer.getStats().hasShardStats() ) { ClientInfo* clientInfo = ClientInfo::get( NULL ); clientInfo->addHostOpTimes( writer.getStats().getShardStats().getWriteOpTimes() ); } // TODO // There's a pending issue about how to report response here. If we use // the command infra-structure, we should reuse the 'errmsg' field. But // we have already filed that message inside the BatchCommandResponse. // return response.getOk(); result.appendElements( response.toBSON() ); return true; }
bool Network::createSocket(std::string proto, int &type) { struct protoent *pe; ClientInfo *current; if (_connected.find(0) != _connected.end()) return (false); if (!(current = (new ClientInfo(_len)))) return (false); if (!(pe = getprotobyname(proto.c_str()))) return (false); if ((current->get_socket() = socket(_family, type, pe->p_proto)) == -1) { delete current; return (false); } _connected[++_id] = current; //stockage de la socket return (true); }
// Look for $gleStats in a command response, and fill in ClientInfo with the data, // if found. // This data will be used by subsequent GLE calls, to ensure we look for the correct // write on the correct PRIMARY. void saveGLEStats(const BSONObj& result, const std::string& hostString) { if (!ClientInfo::exists()) { return; } if (result[kGLEStatsFieldName].type() != Object) { return; } std::string errmsg; ConnectionString shardConn = ConnectionString::parse(hostString, errmsg); BSONElement subobj = result[kGLEStatsFieldName]; OpTime lastOpTime = subobj[kGLEStatsLastOpTimeFieldName]._opTime(); OID electionId = subobj[kGLEStatsElectionIdFieldName].OID(); ClientInfo* clientInfo = ClientInfo::get( NULL ); LOG(4) << "saveGLEStats lastOpTime:" << lastOpTime << " electionId:" << electionId; clientInfo->addHostOpTime(shardConn, HostOpTime(lastOpTime, electionId)); }
bool ClientInfo::operator==(const ClientInfo& rh) { if(this->getIPAddressString().compare( rh.getIPAddressString() ) == 0) { return true; } else { return false; } }
// By rebuilding everything every tick, menus can be dynamically updated void PlayerMenuUserInterface::idle(U32 timeDelta) { clearMenuItems(); GameConnection *conn = getGame()->getConnectionToServer(); if(!conn) return; char c[] = "A"; // Dummy shortcut key for(S32 i = 0; i < getGame()->getClientCount(); i++) { ClientInfo *clientInfo = ((Game *)getGame())->getClientInfo(i); // Lame! strncpy(c, clientInfo->getName().getString(), 1); // Grab first char of name for a shortcut key // Will be used to show admin/player/robot prefix on menu PlayerType pt = clientInfo->isRobot() ? PlayerTypeRobot : (clientInfo->isAdmin() ? PlayerTypeAdmin : PlayerTypePlayer); PlayerMenuItem *newItem = new PlayerMenuItem(i, clientInfo->getName().getString(), playerSelectedCallback, InputCodeManager::stringToInputCode(c), pt); newItem->setUnselectedColor(getGame()->getTeamColor(clientInfo->getTeamIndex())); addMenuItem(newItem); } sortMenuItems(); if(action == PlayerActionKick) mMenuTitle = "CHOOSE PLAYER TO KICK"; else if(action == PlayerActionChangeTeam) mMenuTitle = "CHOOSE WHOSE TEAM TO CHANGE"; else TNLAssert(false, "Unknown action!"); }
// Find winner of a non-team based game IndividualGameResults Game::getIndividualGameWinner() const { S32 clientCount = getClientCount(); if(clientCount == 1) return IndividualGameResults(OnlyOnePlayerOrTeam, getClientInfo(0)); ClientInfo *winningClient = getClientInfo(0); GameEndStatus status = HasWinner; for(S32 i = 1; i < clientCount; i++) { ClientInfo *clientInfo = getClientInfo(i); if(clientInfo->getScore() == winningClient->getScore()) status = Tied; else if(clientInfo->getScore() > winningClient->getScore()) { winningClient = clientInfo; status = HasWinner; } } return IndividualGameResults(status, winningClient); }
// The nexus is open. A ship has entered it. Now what? // Runs on server only void NexusGameType::shipTouchNexus(Ship *ship, NexusZone *nexus) { FlagItem *flag = findFirstFlag(ship); if(!flag) // findFirstFlag can return NULL return; S32 flagsReturned = flag->getFlagCount(); if(flagsReturned == 0) return; updateScore(ship, ReturnFlagsToNexus, flagsReturned); nexus->s2cFlagsReturned(); // Alert the Nexus that someone has returned flags to it ClientInfo *clientInfo = ship->getClientInfo(); if(clientInfo) // Should always be true!! { if(!isGameOver()) // Avoid flooding messages at end of game { S32 score = getEventScore(TeamScore, ReturnFlagsToNexus, flag->getFlagCount()); s2cNexusMessage(NexusMsgScore, clientInfo->getName().getString(), flag->getFlagCount(), score); } // See if this event qualifies for an achievement if(flagsReturned >= 25 && // Return 25+ flags clientInfo && clientInfo->isAuthenticated() && // Player must be authenticated getGame()->getPlayerCount() >= 4 && // Game must have 4+ human players getGame()->getAuthenticatedPlayerCount() >= 2 && // Two of whom must be authenticated !hasFlagSpawns() && !hasPredeployedFlags() && // Level can have no flag spawns, nor any predeployed flags !clientInfo->hasBadge(BADGE_TWENTY_FIVE_FLAGS)) // Player doesn't already have the badge { achievementAchieved(BADGE_TWENTY_FIVE_FLAGS, clientInfo->getName()); } } flag->changeFlagCount(0); }
static void announce_friends_online_status(int sockfd) { map<int, ClientInfo*> map_fdcl; map<string, int> map_clfd; //iterator for socketfd_to_clients map map<int, ClientInfo*>::iterator it_fdcl; //ierator for clients_to_sockfd map map<string, int>::iterator it_clfd; map<string, string> groups; //iterator for friends within groups map<string, string>::iterator it_f; string friend_name, friends; stringstream announcement; int friend_sockfd, pos, next_pos, len; char buff[BUFFER_LENGTH]; map_fdcl = server->get_sockfd_to_clients(); it_fdcl = map_fdcl.find(sockfd); assert(it_fdcl != map_fdcl.end()); ClientInfo *client = it_fdcl->second; groups = server->get_list_of_friends(client->get_username()); it_f = groups.begin(); for (; it_f != groups.end(); it_f++) { friends = it_f->second; next_pos = friends.find(","); len = friends.length(); for (pos = 0; pos != string::npos && pos < len; pos = next_pos + 1, next_pos = friends.find(",", pos)) { if (next_pos == string::npos) { friend_name = friends.substr(pos, len); next_pos = len; } else friend_name = friends.substr(pos, next_pos); dprintf("[SERVER]%s is friend of %s\n", friend_name.c_str(), client->get_username().c_str()); map_clfd = server->get_clients_to_sockfd(); it_clfd = map_clfd.find(friend_name); if (it_clfd == map_clfd.end()) { //friend is not online, do nothing cout << friend_name << " is not online!\n"; continue; } friend_sockfd = it_clfd->second; //send to friend_socket (client.username, client.ip, client.port); announcement << FRIEND_IS_ONLINE << " " << client->get_username() << " " << client->get_ip() << " " << client->get_port(); cout << "Sending " << announcement << endl; assert(send(friend_sockfd, announcement.str().c_str(), announcement.str().length() + 1, 0) >= 0); server->send_friends_list(friend_sockfd, friend_name); } } }
/****************************************************************************** * DCOP call to change whether KAlarm should be started when an event needs to * be notified to it. * N.B. This method must not return a bool because DCOPClient::call() can cause * a hang if the daemon happens to send a notification to KAlarm at the * same time as KAlarm calls this DCCOP method. */ void AlarmDaemon::registerChange(const QCString &appName, bool startClient) { kdDebug(5900) << "AlarmDaemon::registerChange(" << appName << ", " << startClient << ")" << endl; KAlarmd::RegisterResult result; ClientInfo *client = ClientInfo::get(appName); if(!client) return; // can't access client to tell it the result if(startClient && KStandardDirs::findExe(appName).isNull()) { kdError() << "AlarmDaemon::registerChange(): app not found" << endl; result = KAlarmd::NOT_FOUND; } else { client->setStartClient(startClient); ADConfigData::writeClient(appName, client); result = KAlarmd::SUCCESS; } // Notify the client of whether the call succeeded. AlarmGuiIface_stub stub(appName, client->dcopObject()); stub.registered(true, result, DAEMON_VERSION_NUM); kdDebug(5900) << "AlarmDaemon::registerChange() -> " << result << endl; }