Chat protocol rewrite (#5117)
[oweals/minetest.git] / src / clientiface.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include <sstream>
21
22 #include "clientiface.h"
23 #include "remoteplayer.h"
24 #include "settings.h"
25 #include "mapblock.h"
26 #include "network/connection.h"
27 #include "serverenvironment.h"
28 #include "map.h"
29 #include "emerge.h"
30 #include "content_sao.h"              // TODO this is used for cleanup of only
31 #include "log.h"
32 #include "network/serveropcodes.h"
33 #include "util/srp.h"
34 #include "face_position_cache.h"
35
36 const char *ClientInterface::statenames[] = {
37         "Invalid",
38         "Disconnecting",
39         "Denied",
40         "Created",
41         "AwaitingInit2",
42         "HelloSent",
43         "InitDone",
44         "DefinitionsSent",
45         "Active",
46         "SudoMode",
47 };
48
49
50
51 std::string ClientInterface::state2Name(ClientState state)
52 {
53         return statenames[state];
54 }
55
56 void RemoteClient::ResendBlockIfOnWire(v3s16 p)
57 {
58         // if this block is on wire, mark it for sending again as soon as possible
59         if (m_blocks_sending.find(p) != m_blocks_sending.end()) {
60                 SetBlockNotSent(p);
61         }
62 }
63
64 void RemoteClient::GetNextBlocks (
65                 ServerEnvironment *env,
66                 EmergeManager * emerge,
67                 float dtime,
68                 std::vector<PrioritySortedBlockTransfer> &dest)
69 {
70         DSTACK(FUNCTION_NAME);
71
72
73         // Increment timers
74         m_nothing_to_send_pause_timer -= dtime;
75         m_nearest_unsent_reset_timer += dtime;
76
77         if(m_nothing_to_send_pause_timer >= 0)
78                 return;
79
80         RemotePlayer *player = env->getPlayer(peer_id);
81         // This can happen sometimes; clients and players are not in perfect sync.
82         if (!player)
83                 return;
84
85         PlayerSAO *sao = player->getPlayerSAO();
86         if (!sao)
87                 return;
88
89         // Won't send anything if already sending
90         if(m_blocks_sending.size() >= g_settings->getU16
91                         ("max_simultaneous_block_sends_per_client"))
92         {
93                 //infostream<<"Not sending any blocks, Queue full."<<std::endl;
94                 return;
95         }
96
97         v3f playerpos = sao->getBasePosition();
98         v3f playerspeed = player->getSpeed();
99         v3f playerspeeddir(0,0,0);
100         if(playerspeed.getLength() > 1.0*BS)
101                 playerspeeddir = playerspeed / playerspeed.getLength();
102         // Predict to next block
103         v3f playerpos_predicted = playerpos + playerspeeddir*MAP_BLOCKSIZE*BS;
104
105         v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);
106
107         v3s16 center = getNodeBlockPos(center_nodepos);
108
109         // Camera position and direction
110         v3f camera_pos = sao->getEyePosition();
111         v3f camera_dir = v3f(0,0,1);
112         camera_dir.rotateYZBy(sao->getPitch());
113         camera_dir.rotateXZBy(sao->getYaw());
114
115         /*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<","
116                         <<camera_dir.Z<<")"<<std::endl;*/
117
118         /*
119                 Get the starting value of the block finder radius.
120         */
121
122         if(m_last_center != center)
123         {
124                 m_nearest_unsent_d = 0;
125                 m_last_center = center;
126         }
127
128         /*infostream<<"m_nearest_unsent_reset_timer="
129                         <<m_nearest_unsent_reset_timer<<std::endl;*/
130
131         // Reset periodically to workaround for some bugs or stuff
132         if(m_nearest_unsent_reset_timer > 20.0)
133         {
134                 m_nearest_unsent_reset_timer = 0;
135                 m_nearest_unsent_d = 0;
136                 //infostream<<"Resetting m_nearest_unsent_d for "
137                 //              <<server->getPlayerName(peer_id)<<std::endl;
138         }
139
140         //s16 last_nearest_unsent_d = m_nearest_unsent_d;
141         s16 d_start = m_nearest_unsent_d;
142
143         //infostream<<"d_start="<<d_start<<std::endl;
144
145         u16 max_simul_sends_setting = g_settings->getU16
146                         ("max_simultaneous_block_sends_per_client");
147         u16 max_simul_sends_usually = max_simul_sends_setting;
148
149         /*
150                 Check the time from last addNode/removeNode.
151
152                 Decrease send rate if player is building stuff.
153         */
154         m_time_from_building += dtime;
155         if(m_time_from_building < g_settings->getFloat(
156                                 "full_block_send_enable_min_time_from_building"))
157         {
158                 max_simul_sends_usually
159                         = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
160         }
161
162         /*
163                 Number of blocks sending + number of blocks selected for sending
164         */
165         u32 num_blocks_selected = m_blocks_sending.size();
166
167         /*
168                 next time d will be continued from the d from which the nearest
169                 unsent block was found this time.
170
171                 This is because not necessarily any of the blocks found this
172                 time are actually sent.
173         */
174         s32 new_nearest_unsent_d = -1;
175
176         // get view range and camera fov from the client
177         s16 wanted_range = sao->getWantedRange();
178         float camera_fov = sao->getFov();
179         // if FOV, wanted_range are not available (old client), fall back to old default
180         if (wanted_range <= 0) wanted_range = 1000;
181         if (camera_fov <= 0) camera_fov = (72.0*M_PI/180) * 4./3.;
182
183         const s16 full_d_max = MYMIN(g_settings->getS16("max_block_send_distance"), wanted_range);
184         const s16 d_opt = MYMIN(g_settings->getS16("block_send_optimize_distance"), wanted_range);
185         const s16 d_blocks_in_sight = full_d_max * BS * MAP_BLOCKSIZE;
186         //infostream << "Fov from client " << camera_fov << " full_d_max " << full_d_max << std::endl;
187
188         s16 d_max = full_d_max;
189         s16 d_max_gen = MYMIN(g_settings->getS16("max_block_generate_distance"), wanted_range);
190
191         // Don't loop very much at a time
192         s16 max_d_increment_at_time = 2;
193         if(d_max > d_start + max_d_increment_at_time)
194                 d_max = d_start + max_d_increment_at_time;
195
196         s32 nearest_emerged_d = -1;
197         s32 nearest_emergefull_d = -1;
198         s32 nearest_sent_d = -1;
199         //bool queue_is_full = false;
200
201         const v3s16 cam_pos_nodes = floatToInt(camera_pos, BS);
202         const bool occ_cull = g_settings->getBool("server_side_occlusion_culling");
203
204         s16 d;
205         for(d = d_start; d <= d_max; d++) {
206                 /*
207                         Get the border/face dot coordinates of a "d-radiused"
208                         box
209                 */
210                 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
211
212                 std::vector<v3s16>::iterator li;
213                 for(li = list.begin(); li != list.end(); ++li) {
214                         v3s16 p = *li + center;
215
216                         /*
217                                 Send throttling
218                                 - Don't allow too many simultaneous transfers
219                                 - EXCEPT when the blocks are very close
220
221                                 Also, don't send blocks that are already flying.
222                         */
223
224                         // Start with the usual maximum
225                         u16 max_simul_dynamic = max_simul_sends_usually;
226
227                         // If block is very close, allow full maximum
228                         if(d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
229                                 max_simul_dynamic = max_simul_sends_setting;
230
231                         // Don't select too many blocks for sending
232                         if (num_blocks_selected >= max_simul_dynamic) {
233                                 //queue_is_full = true;
234                                 goto queue_full_break;
235                         }
236
237                         // Don't send blocks that are currently being transferred
238                         if (m_blocks_sending.find(p) != m_blocks_sending.end())
239                                 continue;
240
241                         /*
242                                 Do not go over max mapgen limit
243                         */
244                         if (blockpos_over_max_limit(p))
245                                 continue;
246
247                         // If this is true, inexistent block will be made from scratch
248                         bool generate = d <= d_max_gen;
249
250                         /*
251                                 Don't generate or send if not in sight
252                                 FIXME This only works if the client uses a small enough
253                                 FOV setting. The default of 72 degrees is fine.
254                         */
255
256                         f32 dist;
257                         if (!isBlockInSight(p, camera_pos, camera_dir, camera_fov, d_blocks_in_sight, &dist)) {
258                                 continue;
259                         }
260
261                         /*
262                                 Don't send already sent blocks
263                         */
264                         {
265                                 if(m_blocks_sent.find(p) != m_blocks_sent.end())
266                                 {
267                                         continue;
268                                 }
269                         }
270
271                         /*
272                                 Check if map has this block
273                         */
274                         MapBlock *block = env->getMap().getBlockNoCreateNoEx(p);
275
276                         bool surely_not_found_on_disk = false;
277                         bool block_is_invalid = false;
278                         if (block) {
279                                 // Reset usage timer, this block will be of use in the future.
280                                 block->resetUsageTimer();
281
282                                 // Block is dummy if data doesn't exist.
283                                 // It means it has been not found from disk and not generated
284                                 if(block->isDummy())
285                                 {
286                                         surely_not_found_on_disk = true;
287                                 }
288
289                                 if(block->isGenerated() == false)
290                                         block_is_invalid = true;
291
292                                 /*
293                                         If block is not close, don't send it unless it is near
294                                         ground level.
295
296                                         Block is near ground level if night-time mesh
297                                         differs from day-time mesh.
298                                 */
299                                 if(d >= d_opt)
300                                 {
301                                         if(block->getDayNightDiff() == false)
302                                                 continue;
303                                 }
304
305                                 if (occ_cull && !block_is_invalid &&
306                                                 env->getMap().isBlockOccluded(block, cam_pos_nodes)) {
307                                         continue;
308                                 }
309                         }
310
311                         /*
312                                 If block has been marked to not exist on disk (dummy)
313                                 and generating new ones is not wanted, skip block.
314                         */
315                         if(generate == false && surely_not_found_on_disk == true)
316                         {
317                                 // get next one.
318                                 continue;
319                         }
320
321                         /*
322                                 Add inexistent block to emerge queue.
323                         */
324                         if(block == NULL || surely_not_found_on_disk || block_is_invalid)
325                         {
326                                 if (emerge->enqueueBlockEmerge(peer_id, p, generate)) {
327                                         if (nearest_emerged_d == -1)
328                                                 nearest_emerged_d = d;
329                                 } else {
330                                         if (nearest_emergefull_d == -1)
331                                                 nearest_emergefull_d = d;
332                                         goto queue_full_break;
333                                 }
334
335                                 // get next one.
336                                 continue;
337                         }
338
339                         if(nearest_sent_d == -1)
340                                 nearest_sent_d = d;
341
342                         /*
343                                 Add block to send queue
344                         */
345                         PrioritySortedBlockTransfer q((float)dist, p, peer_id);
346
347                         dest.push_back(q);
348
349                         num_blocks_selected += 1;
350                 }
351         }
352 queue_full_break:
353
354         // If nothing was found for sending and nothing was queued for
355         // emerging, continue next time browsing from here
356         if(nearest_emerged_d != -1){
357                 new_nearest_unsent_d = nearest_emerged_d;
358         } else if(nearest_emergefull_d != -1){
359                 new_nearest_unsent_d = nearest_emergefull_d;
360         } else {
361                 if(d > full_d_max){
362                         new_nearest_unsent_d = 0;
363                         m_nothing_to_send_pause_timer = 2.0;
364                 } else {
365                         if(nearest_sent_d != -1)
366                                 new_nearest_unsent_d = nearest_sent_d;
367                         else
368                                 new_nearest_unsent_d = d;
369                 }
370         }
371
372         if(new_nearest_unsent_d != -1)
373                 m_nearest_unsent_d = new_nearest_unsent_d;
374 }
375
376 void RemoteClient::GotBlock(v3s16 p)
377 {
378         if (m_blocks_modified.find(p) == m_blocks_modified.end()) {
379                 if (m_blocks_sending.find(p) != m_blocks_sending.end())
380                         m_blocks_sending.erase(p);
381                 else
382                         m_excess_gotblocks++;
383
384                 m_blocks_sent.insert(p);
385         }
386 }
387
388 void RemoteClient::SentBlock(v3s16 p)
389 {
390         if (m_blocks_modified.find(p) != m_blocks_modified.end())
391                 m_blocks_modified.erase(p);
392
393         if(m_blocks_sending.find(p) == m_blocks_sending.end())
394                 m_blocks_sending[p] = 0.0;
395         else
396                 infostream<<"RemoteClient::SentBlock(): Sent block"
397                                 " already in m_blocks_sending"<<std::endl;
398 }
399
400 void RemoteClient::SetBlockNotSent(v3s16 p)
401 {
402         m_nearest_unsent_d = 0;
403         m_nothing_to_send_pause_timer = 0;
404
405         if(m_blocks_sending.find(p) != m_blocks_sending.end())
406                 m_blocks_sending.erase(p);
407         if(m_blocks_sent.find(p) != m_blocks_sent.end())
408                 m_blocks_sent.erase(p);
409         m_blocks_modified.insert(p);
410 }
411
412 void RemoteClient::SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks)
413 {
414         m_nearest_unsent_d = 0;
415         m_nothing_to_send_pause_timer = 0;
416
417         for(std::map<v3s16, MapBlock*>::iterator
418                         i = blocks.begin();
419                         i != blocks.end(); ++i)
420         {
421                 v3s16 p = i->first;
422                 m_blocks_modified.insert(p);
423
424                 if(m_blocks_sending.find(p) != m_blocks_sending.end())
425                         m_blocks_sending.erase(p);
426                 if(m_blocks_sent.find(p) != m_blocks_sent.end())
427                         m_blocks_sent.erase(p);
428         }
429 }
430
431 void RemoteClient::notifyEvent(ClientStateEvent event)
432 {
433         std::ostringstream myerror;
434         switch (m_state)
435         {
436         case CS_Invalid:
437                 //intentionally do nothing
438                 break;
439         case CS_Created:
440                 switch (event) {
441                 case CSE_Hello:
442                         m_state = CS_HelloSent;
443                         break;
444                 case CSE_InitLegacy:
445                         m_state = CS_AwaitingInit2;
446                         break;
447                 case CSE_Disconnect:
448                         m_state = CS_Disconnecting;
449                         break;
450                 case CSE_SetDenied:
451                         m_state = CS_Denied;
452                         break;
453                 /* GotInit2 SetDefinitionsSent SetMediaSent */
454                 default:
455                         myerror << "Created: Invalid client state transition! " << event;
456                         throw ClientStateError(myerror.str());
457                 }
458                 break;
459         case CS_Denied:
460                 /* don't do anything if in denied state */
461                 break;
462         case CS_HelloSent:
463                 switch(event)
464                 {
465                 case CSE_AuthAccept:
466                         m_state = CS_AwaitingInit2;
467                         if ((chosen_mech == AUTH_MECHANISM_SRP)
468                                         || (chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD))
469                                 srp_verifier_delete((SRPVerifier *) auth_data);
470                         chosen_mech = AUTH_MECHANISM_NONE;
471                         break;
472                 case CSE_Disconnect:
473                         m_state = CS_Disconnecting;
474                         break;
475                 case CSE_SetDenied:
476                         m_state = CS_Denied;
477                         if ((chosen_mech == AUTH_MECHANISM_SRP)
478                                         || (chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD))
479                                 srp_verifier_delete((SRPVerifier *) auth_data);
480                         chosen_mech = AUTH_MECHANISM_NONE;
481                         break;
482                 default:
483                         myerror << "HelloSent: Invalid client state transition! " << event;
484                         throw ClientStateError(myerror.str());
485                 }
486                 break;
487         case CS_AwaitingInit2:
488                 switch(event)
489                 {
490                 case CSE_GotInit2:
491                         confirmSerializationVersion();
492                         m_state = CS_InitDone;
493                         break;
494                 case CSE_Disconnect:
495                         m_state = CS_Disconnecting;
496                         break;
497                 case CSE_SetDenied:
498                         m_state = CS_Denied;
499                         break;
500
501                 /* Init SetDefinitionsSent SetMediaSent */
502                 default:
503                         myerror << "InitSent: Invalid client state transition! " << event;
504                         throw ClientStateError(myerror.str());
505                 }
506                 break;
507
508         case CS_InitDone:
509                 switch(event)
510                 {
511                 case CSE_SetDefinitionsSent:
512                         m_state = CS_DefinitionsSent;
513                         break;
514                 case CSE_Disconnect:
515                         m_state = CS_Disconnecting;
516                         break;
517                 case CSE_SetDenied:
518                         m_state = CS_Denied;
519                         break;
520
521                 /* Init GotInit2 SetMediaSent */
522                 default:
523                         myerror << "InitDone: Invalid client state transition! " << event;
524                         throw ClientStateError(myerror.str());
525                 }
526                 break;
527         case CS_DefinitionsSent:
528                 switch(event)
529                 {
530                 case CSE_SetClientReady:
531                         m_state = CS_Active;
532                         break;
533                 case CSE_Disconnect:
534                         m_state = CS_Disconnecting;
535                         break;
536                 case CSE_SetDenied:
537                         m_state = CS_Denied;
538                         break;
539                 /* Init GotInit2 SetDefinitionsSent */
540                 default:
541                         myerror << "DefinitionsSent: Invalid client state transition! " << event;
542                         throw ClientStateError(myerror.str());
543                 }
544                 break;
545         case CS_Active:
546                 switch(event)
547                 {
548                 case CSE_SetDenied:
549                         m_state = CS_Denied;
550                         break;
551                 case CSE_Disconnect:
552                         m_state = CS_Disconnecting;
553                         break;
554                 case CSE_SudoSuccess:
555                         m_state = CS_SudoMode;
556                         if ((chosen_mech == AUTH_MECHANISM_SRP)
557                                         || (chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD))
558                                 srp_verifier_delete((SRPVerifier *) auth_data);
559                         chosen_mech = AUTH_MECHANISM_NONE;
560                         break;
561                 /* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */
562                 default:
563                         myerror << "Active: Invalid client state transition! " << event;
564                         throw ClientStateError(myerror.str());
565                         break;
566                 }
567                 break;
568         case CS_SudoMode:
569                 switch(event)
570                 {
571                 case CSE_SetDenied:
572                         m_state = CS_Denied;
573                         break;
574                 case CSE_Disconnect:
575                         m_state = CS_Disconnecting;
576                         break;
577                 case CSE_SudoLeave:
578                         m_state = CS_Active;
579                         break;
580                 default:
581                         myerror << "Active: Invalid client state transition! " << event;
582                         throw ClientStateError(myerror.str());
583                         break;
584                 }
585                 break;
586         case CS_Disconnecting:
587                 /* we are already disconnecting */
588                 break;
589         }
590 }
591
592 u64 RemoteClient::uptime() const
593 {
594         return porting::getTimeS() - m_connection_time;
595 }
596
597 ClientInterface::ClientInterface(con::Connection* con)
598 :
599         m_con(con),
600         m_env(NULL),
601         m_print_info_timer(0.0)
602 {
603
604 }
605 ClientInterface::~ClientInterface()
606 {
607         /*
608                 Delete clients
609         */
610         {
611                 MutexAutoLock clientslock(m_clients_mutex);
612
613                 for (RemoteClientMap::iterator i = m_clients.begin();
614                         i != m_clients.end(); ++i) {
615                         // Delete client
616                         delete i->second;
617                 }
618         }
619 }
620
621 std::vector<u16> ClientInterface::getClientIDs(ClientState min_state)
622 {
623         std::vector<u16> reply;
624         MutexAutoLock clientslock(m_clients_mutex);
625
626         for (RemoteClientMap::iterator i = m_clients.begin();
627                 i != m_clients.end(); ++i) {
628                 if (i->second->getState() >= min_state)
629                         reply.push_back(i->second->peer_id);
630         }
631
632         return reply;
633 }
634
635 void ClientInterface::step(float dtime)
636 {
637         m_print_info_timer += dtime;
638         if(m_print_info_timer >= 30.0)
639         {
640                 m_print_info_timer = 0.0;
641                 UpdatePlayerList();
642         }
643 }
644
645 void ClientInterface::UpdatePlayerList()
646 {
647         if (m_env) {
648                 std::vector<u16> clients = getClientIDs();
649                 m_clients_names.clear();
650
651
652                 if(!clients.empty())
653                         infostream<<"Players:"<<std::endl;
654
655                 for (std::vector<u16>::iterator i = clients.begin(); i != clients.end(); ++i) {
656                         RemotePlayer *player = m_env->getPlayer(*i);
657
658                         if (player == NULL)
659                                 continue;
660
661                         infostream << "* " << player->getName() << "\t";
662
663                         {
664                                 MutexAutoLock clientslock(m_clients_mutex);
665                                 RemoteClient* client = lockedGetClientNoEx(*i);
666                                 if (client)
667                                         client->PrintInfo(infostream);
668                         }
669
670                         m_clients_names.push_back(player->getName());
671                 }
672         }
673 }
674
675 void ClientInterface::send(u16 peer_id, u8 channelnum,
676                 NetworkPacket* pkt, bool reliable)
677 {
678         m_con->Send(peer_id, channelnum, pkt, reliable);
679 }
680
681 void ClientInterface::sendToAll(NetworkPacket *pkt)
682 {
683         MutexAutoLock clientslock(m_clients_mutex);
684         for (RemoteClientMap::iterator i = m_clients.begin();
685                         i != m_clients.end(); ++i) {
686                 RemoteClient *client = i->second;
687
688                 if (client->net_proto_version != 0) {
689                         m_con->Send(client->peer_id,
690                                         clientCommandFactoryTable[pkt->getCommand()].channel, pkt,
691                                         clientCommandFactoryTable[pkt->getCommand()].reliable);
692                 }
693         }
694 }
695
696 void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt,
697                 u16 min_proto_ver)
698 {
699         MutexAutoLock clientslock(m_clients_mutex);
700         for (std::unordered_map<u16, RemoteClient*>::iterator i = m_clients.begin();
701                         i != m_clients.end(); ++i) {
702                 RemoteClient *client = i->second;
703                 NetworkPacket *pkt_to_send = nullptr;
704
705                 if (client->net_proto_version >= min_proto_ver) {
706                         pkt_to_send = pkt;
707                 } else if (client->net_proto_version != 0) {
708                         pkt_to_send = legacypkt;
709                 } else {
710                         warningstream << "Client with unhandled version to handle: '"
711                                 << client->net_proto_version << "'";
712                         continue;
713                 }
714
715                 m_con->Send(client->peer_id,
716                         clientCommandFactoryTable[pkt_to_send->getCommand()].channel,
717                         pkt_to_send,
718                         clientCommandFactoryTable[pkt_to_send->getCommand()].reliable);
719         }
720 }
721
722 RemoteClient* ClientInterface::getClientNoEx(u16 peer_id, ClientState state_min)
723 {
724         MutexAutoLock clientslock(m_clients_mutex);
725         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
726         // The client may not exist; clients are immediately removed if their
727         // access is denied, and this event occurs later then.
728         if (n == m_clients.end())
729                 return NULL;
730
731         if (n->second->getState() >= state_min)
732                 return n->second;
733         else
734                 return NULL;
735 }
736
737 RemoteClient* ClientInterface::lockedGetClientNoEx(u16 peer_id, ClientState state_min)
738 {
739         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
740         // The client may not exist; clients are immediately removed if their
741         // access is denied, and this event occurs later then.
742         if (n == m_clients.end())
743                 return NULL;
744
745         if (n->second->getState() >= state_min)
746                 return n->second;
747         else
748                 return NULL;
749 }
750
751 ClientState ClientInterface::getClientState(u16 peer_id)
752 {
753         MutexAutoLock clientslock(m_clients_mutex);
754         RemoteClientMap::const_iterator n = m_clients.find(peer_id);
755         // The client may not exist; clients are immediately removed if their
756         // access is denied, and this event occurs later then.
757         if (n == m_clients.end())
758                 return CS_Invalid;
759
760         return n->second->getState();
761 }
762
763 void ClientInterface::setPlayerName(u16 peer_id,std::string name)
764 {
765         MutexAutoLock clientslock(m_clients_mutex);
766         RemoteClientMap::iterator n = m_clients.find(peer_id);
767         // The client may not exist; clients are immediately removed if their
768         // access is denied, and this event occurs later then.
769         if (n != m_clients.end())
770                 n->second->setName(name);
771 }
772
773 void ClientInterface::DeleteClient(u16 peer_id)
774 {
775         MutexAutoLock conlock(m_clients_mutex);
776
777         // Error check
778         RemoteClientMap::iterator n = m_clients.find(peer_id);
779         // The client may not exist; clients are immediately removed if their
780         // access is denied, and this event occurs later then.
781         if (n == m_clients.end())
782                 return;
783
784         /*
785                 Mark objects to be not known by the client
786         */
787         //TODO this should be done by client destructor!!!
788         RemoteClient *client = n->second;
789         // Handle objects
790         for (std::set<u16>::iterator i = client->m_known_objects.begin();
791                         i != client->m_known_objects.end(); ++i) {
792                 // Get object
793                 u16 id = *i;
794                 ServerActiveObject* obj = m_env->getActiveObject(id);
795
796                 if(obj && obj->m_known_by_count > 0)
797                         obj->m_known_by_count--;
798         }
799
800         // Delete client
801         delete m_clients[peer_id];
802         m_clients.erase(peer_id);
803 }
804
805 void ClientInterface::CreateClient(u16 peer_id)
806 {
807         MutexAutoLock conlock(m_clients_mutex);
808
809         // Error check
810         RemoteClientMap::iterator n = m_clients.find(peer_id);
811         // The client shouldn't already exist
812         if (n != m_clients.end()) return;
813
814         // Create client
815         RemoteClient *client = new RemoteClient();
816         client->peer_id = peer_id;
817         m_clients[client->peer_id] = client;
818 }
819
820 void ClientInterface::event(u16 peer_id, ClientStateEvent event)
821 {
822         {
823                 MutexAutoLock clientlock(m_clients_mutex);
824
825                 // Error check
826                 RemoteClientMap::iterator n = m_clients.find(peer_id);
827
828                 // No client to deliver event
829                 if (n == m_clients.end())
830                         return;
831                 n->second->notifyEvent(event);
832         }
833
834         if ((event == CSE_SetClientReady) ||
835                 (event == CSE_Disconnect)     ||
836                 (event == CSE_SetDenied))
837         {
838                 UpdatePlayerList();
839         }
840 }
841
842 u16 ClientInterface::getProtocolVersion(u16 peer_id)
843 {
844         MutexAutoLock conlock(m_clients_mutex);
845
846         // Error check
847         RemoteClientMap::iterator n = m_clients.find(peer_id);
848
849         // No client to get version
850         if (n == m_clients.end())
851                 return 0;
852
853         return n->second->net_proto_version;
854 }
855
856 void ClientInterface::setClientVersion(u16 peer_id, u8 major, u8 minor, u8 patch, std::string full)
857 {
858         MutexAutoLock conlock(m_clients_mutex);
859
860         // Error check
861         RemoteClientMap::iterator n = m_clients.find(peer_id);
862
863         // No client to set versions
864         if (n == m_clients.end())
865                 return;
866
867         n->second->setVersionInfo(major,minor,patch,full);
868 }