]> git.lizzy.rs Git - minetest.git/blob - src/server.cpp
Fix object duplication bug
[minetest.git] / src / server.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "server.h"
21 #include "utility.h"
22 #include <iostream>
23 #include "clientserver.h"
24 #include "map.h"
25 #include "jmutexautolock.h"
26 #include "main.h"
27 #include "constants.h"
28 #include "voxel.h"
29 #include "materials.h"
30 #include "mineral.h"
31 #include "config.h"
32 #include "servercommand.h"
33 #include "filesys.h"
34 #include "content_mapnode.h"
35 #include "content_craft.h"
36 #include "content_nodemeta.h"
37 #include "mapblock.h"
38 #include "serverobject.h"
39 #include "settings.h"
40 #include "profiler.h"
41 #include "log.h"
42
43 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
44
45 #define BLOCK_EMERGE_FLAG_FROMDISK (1<<0)
46
47 class MapEditEventIgnorer
48 {
49 public:
50         MapEditEventIgnorer(bool *flag):
51                 m_flag(flag)
52         {
53                 if(*m_flag == false)
54                         *m_flag = true;
55                 else
56                         m_flag = NULL;
57         }
58
59         ~MapEditEventIgnorer()
60         {
61                 if(m_flag)
62                 {
63                         assert(*m_flag);
64                         *m_flag = false;
65                 }
66         }
67         
68 private:
69         bool *m_flag;
70 };
71
72 void * ServerThread::Thread()
73 {
74         ThreadStarted();
75
76         log_register_thread("ServerThread");
77
78         DSTACK(__FUNCTION_NAME);
79
80         BEGIN_DEBUG_EXCEPTION_HANDLER
81
82         while(getRun())
83         {
84                 try{
85                         //TimeTaker timer("AsyncRunStep() + Receive()");
86
87                         {
88                                 //TimeTaker timer("AsyncRunStep()");
89                                 m_server->AsyncRunStep();
90                         }
91                 
92                         //infostream<<"Running m_server->Receive()"<<std::endl;
93                         m_server->Receive();
94                 }
95                 catch(con::NoIncomingDataException &e)
96                 {
97                 }
98                 catch(con::PeerNotFoundException &e)
99                 {
100                         infostream<<"Server: PeerNotFoundException"<<std::endl;
101                 }
102         }
103         
104         END_DEBUG_EXCEPTION_HANDLER(errorstream)
105
106         return NULL;
107 }
108
109 void * EmergeThread::Thread()
110 {
111         ThreadStarted();
112
113         log_register_thread("EmergeThread");
114
115         DSTACK(__FUNCTION_NAME);
116
117         BEGIN_DEBUG_EXCEPTION_HANDLER
118
119         bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
120         
121         /*
122                 Get block info from queue, emerge them and send them
123                 to clients.
124
125                 After queue is empty, exit.
126         */
127         while(getRun())
128         {
129                 QueuedBlockEmerge *qptr = m_server->m_emerge_queue.pop();
130                 if(qptr == NULL)
131                         break;
132                 
133                 SharedPtr<QueuedBlockEmerge> q(qptr);
134
135                 v3s16 &p = q->pos;
136                 v2s16 p2d(p.X,p.Z);
137
138                 /*
139                         Do not generate over-limit
140                 */
141                 if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
142                 || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
143                 || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
144                 || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
145                 || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
146                 || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
147                         continue;
148                         
149                 //infostream<<"EmergeThread::Thread(): running"<<std::endl;
150
151                 //TimeTaker timer("block emerge");
152                 
153                 /*
154                         Try to emerge it from somewhere.
155
156                         If it is only wanted as optional, only loading from disk
157                         will be allowed.
158                 */
159                 
160                 /*
161                         Check if any peer wants it as non-optional. In that case it
162                         will be generated.
163
164                         Also decrement the emerge queue count in clients.
165                 */
166
167                 bool only_from_disk = true;
168
169                 {
170                         core::map<u16, u8>::Iterator i;
171                         for(i=q->peer_ids.getIterator(); i.atEnd()==false; i++)
172                         {
173                                 //u16 peer_id = i.getNode()->getKey();
174
175                                 // Check flags
176                                 u8 flags = i.getNode()->getValue();
177                                 if((flags & BLOCK_EMERGE_FLAG_FROMDISK) == false)
178                                         only_from_disk = false;
179                                 
180                         }
181                 }
182                 
183                 if(enable_mapgen_debug_info)
184                         infostream<<"EmergeThread: p="
185                                         <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
186                                         <<"only_from_disk="<<only_from_disk<<std::endl;
187                 
188                 ServerMap &map = ((ServerMap&)m_server->m_env.getMap());
189                         
190                 //core::map<v3s16, MapBlock*> changed_blocks;
191                 //core::map<v3s16, MapBlock*> lighting_invalidated_blocks;
192
193                 MapBlock *block = NULL;
194                 bool got_block = true;
195                 core::map<v3s16, MapBlock*> modified_blocks;
196                 
197                 /*
198                         Fetch block from map or generate a single block
199                 */
200                 {
201                         JMutexAutoLock envlock(m_server->m_env_mutex);
202                         
203                         // Load sector if it isn't loaded
204                         if(map.getSectorNoGenerateNoEx(p2d) == NULL)
205                                 //map.loadSectorFull(p2d);
206                                 map.loadSectorMeta(p2d);
207
208                         block = map.getBlockNoCreateNoEx(p);
209                         if(!block || block->isDummy() || !block->isGenerated())
210                         {
211                                 if(enable_mapgen_debug_info)
212                                         infostream<<"EmergeThread: not in memory, loading"<<std::endl;
213
214                                 // Get, load or create sector
215                                 /*ServerMapSector *sector =
216                                                 (ServerMapSector*)map.createSector(p2d);*/
217
218                                 // Load/generate block
219
220                                 /*block = map.emergeBlock(p, sector, changed_blocks,
221                                                 lighting_invalidated_blocks);*/
222
223                                 block = map.loadBlock(p);
224                                 
225                                 if(only_from_disk == false)
226                                 {
227                                         if(block == NULL || block->isGenerated() == false)
228                                         {
229                                                 if(enable_mapgen_debug_info)
230                                                         infostream<<"EmergeThread: generating"<<std::endl;
231                                                 block = map.generateBlock(p, modified_blocks);
232                                         }
233                                 }
234
235                                 if(enable_mapgen_debug_info)
236                                         infostream<<"EmergeThread: ended up with: "
237                                                         <<analyze_block(block)<<std::endl;
238
239                                 if(block == NULL)
240                                 {
241                                         got_block = false;
242                                 }
243                                 else
244                                 {
245                                         /*
246                                                 Ignore map edit events, they will not need to be
247                                                 sent to anybody because the block hasn't been sent
248                                                 to anybody
249                                         */
250                                         MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
251                                         
252                                         // Activate objects and stuff
253                                         m_server->m_env.activateBlock(block, 3600);
254                                 }
255                         }
256                         else
257                         {
258                                 /*if(block->getLightingExpired()){
259                                         lighting_invalidated_blocks[block->getPos()] = block;
260                                 }*/
261                         }
262
263                         // TODO: Some additional checking and lighting updating,
264                         //       see emergeBlock
265                 }
266
267                 {//envlock
268                 JMutexAutoLock envlock(m_server->m_env_mutex);
269                 
270                 if(got_block)
271                 {
272                         /*
273                                 Collect a list of blocks that have been modified in
274                                 addition to the fetched one.
275                         */
276
277 #if 0
278                         if(lighting_invalidated_blocks.size() > 0)
279                         {
280                                 /*infostream<<"lighting "<<lighting_invalidated_blocks.size()
281                                                 <<" blocks"<<std::endl;*/
282                         
283                                 // 50-100ms for single block generation
284                                 //TimeTaker timer("** EmergeThread updateLighting");
285                                 
286                                 // Update lighting without locking the environment mutex,
287                                 // add modified blocks to changed blocks
288                                 map.updateLighting(lighting_invalidated_blocks, modified_blocks);
289                         }
290                                 
291                         // Add all from changed_blocks to modified_blocks
292                         for(core::map<v3s16, MapBlock*>::Iterator i = changed_blocks.getIterator();
293                                         i.atEnd() == false; i++)
294                         {
295                                 MapBlock *block = i.getNode()->getValue();
296                                 modified_blocks.insert(block->getPos(), block);
297                         }
298 #endif
299                 }
300                 // If we got no block, there should be no invalidated blocks
301                 else
302                 {
303                         //assert(lighting_invalidated_blocks.size() == 0);
304                 }
305
306                 }//envlock
307
308                 /*
309                         Set sent status of modified blocks on clients
310                 */
311         
312                 // NOTE: Server's clients are also behind the connection mutex
313                 JMutexAutoLock lock(m_server->m_con_mutex);
314
315                 /*
316                         Add the originally fetched block to the modified list
317                 */
318                 if(got_block)
319                 {
320                         modified_blocks.insert(p, block);
321                 }
322                 
323                 /*
324                         Set the modified blocks unsent for all the clients
325                 */
326                 
327                 for(core::map<u16, RemoteClient*>::Iterator
328                                 i = m_server->m_clients.getIterator();
329                                 i.atEnd() == false; i++)
330                 {
331                         RemoteClient *client = i.getNode()->getValue();
332                         
333                         if(modified_blocks.size() > 0)
334                         {
335                                 // Remove block from sent history
336                                 client->SetBlocksNotSent(modified_blocks);
337                         }
338                 }
339                 
340         }
341
342         END_DEBUG_EXCEPTION_HANDLER(errorstream)
343
344         return NULL;
345 }
346
347 void RemoteClient::GetNextBlocks(Server *server, float dtime,
348                 core::array<PrioritySortedBlockTransfer> &dest)
349 {
350         DSTACK(__FUNCTION_NAME);
351         
352         /*u32 timer_result;
353         TimeTaker timer("RemoteClient::GetNextBlocks", &timer_result);*/
354         
355         // Increment timers
356         m_nothing_to_send_pause_timer -= dtime;
357         
358         if(m_nothing_to_send_pause_timer >= 0)
359         {
360                 // Keep this reset
361                 m_nearest_unsent_reset_timer = 0;
362                 return;
363         }
364
365         // Won't send anything if already sending
366         if(m_blocks_sending.size() >= g_settings->getU16
367                         ("max_simultaneous_block_sends_per_client"))
368         {
369                 //infostream<<"Not sending any blocks, Queue full."<<std::endl;
370                 return;
371         }
372
373         //TimeTaker timer("RemoteClient::GetNextBlocks");
374         
375         Player *player = server->m_env.getPlayer(peer_id);
376
377         assert(player != NULL);
378
379         v3f playerpos = player->getPosition();
380         v3f playerspeed = player->getSpeed();
381         v3f playerspeeddir(0,0,0);
382         if(playerspeed.getLength() > 1.0*BS)
383                 playerspeeddir = playerspeed / playerspeed.getLength();
384         // Predict to next block
385         v3f playerpos_predicted = playerpos + playerspeeddir*MAP_BLOCKSIZE*BS;
386
387         v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);
388
389         v3s16 center = getNodeBlockPos(center_nodepos);
390         
391         // Camera position and direction
392         v3f camera_pos = player->getEyePosition();
393         v3f camera_dir = v3f(0,0,1);
394         camera_dir.rotateYZBy(player->getPitch());
395         camera_dir.rotateXZBy(player->getYaw());
396
397         /*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<","
398                         <<camera_dir.Z<<")"<<std::endl;*/
399
400         /*
401                 Get the starting value of the block finder radius.
402         */
403                 
404         if(m_last_center != center)
405         {
406                 m_nearest_unsent_d = 0;
407                 m_last_center = center;
408         }
409
410         /*infostream<<"m_nearest_unsent_reset_timer="
411                         <<m_nearest_unsent_reset_timer<<std::endl;*/
412                         
413         // This has to be incremented only when the nothing to send pause
414         // is not active
415         m_nearest_unsent_reset_timer += dtime;
416         
417         // Reset periodically to avoid possible bugs or other mishaps
418         if(m_nearest_unsent_reset_timer > 10.0)
419         {
420                 m_nearest_unsent_reset_timer = 0;
421                 m_nearest_unsent_d = 0;
422                 /*infostream<<"Resetting m_nearest_unsent_d for "
423                                 <<server->getPlayerName(peer_id)<<std::endl;*/
424         }
425
426         //s16 last_nearest_unsent_d = m_nearest_unsent_d;
427         s16 d_start = m_nearest_unsent_d;
428
429         //infostream<<"d_start="<<d_start<<std::endl;
430
431         u16 max_simul_sends_setting = g_settings->getU16
432                         ("max_simultaneous_block_sends_per_client");
433         u16 max_simul_sends_usually = max_simul_sends_setting;
434
435         /*
436                 Check the time from last addNode/removeNode.
437                 
438                 Decrease send rate if player is building stuff.
439         */
440         m_time_from_building += dtime;
441         if(m_time_from_building < g_settings->getFloat(
442                                 "full_block_send_enable_min_time_from_building"))
443         {
444                 max_simul_sends_usually
445                         = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
446         }
447         
448         /*
449                 Number of blocks sending + number of blocks selected for sending
450         */
451         u32 num_blocks_selected = m_blocks_sending.size();
452         
453         /*
454                 next time d will be continued from the d from which the nearest
455                 unsent block was found this time.
456
457                 This is because not necessarily any of the blocks found this
458                 time are actually sent.
459         */
460         s32 new_nearest_unsent_d = -1;
461
462         s16 d_max = g_settings->getS16("max_block_send_distance");
463         s16 d_max_gen = g_settings->getS16("max_block_generate_distance");
464         
465         // Don't loop very much at a time
466         if(d_max > d_start+1)
467                 d_max = d_start+1;
468         /*if(d_max_gen > d_start+2)
469                 d_max_gen = d_start+2;*/
470         
471         //infostream<<"Starting from "<<d_start<<std::endl;
472
473         bool sending_something = false;
474
475         bool no_blocks_found_for_sending = true;
476
477         bool queue_is_full = false;
478         
479         s16 d;
480         for(d = d_start; d <= d_max; d++)
481         {
482                 //infostream<<"RemoteClient::SendBlocks(): d="<<d<<std::endl;
483                 
484                 /*
485                         If m_nearest_unsent_d was changed by the EmergeThread
486                         (it can change it to 0 through SetBlockNotSent),
487                         update our d to it.
488                         Else update m_nearest_unsent_d
489                 */
490                 /*if(m_nearest_unsent_d != last_nearest_unsent_d)
491                 {
492                         d = m_nearest_unsent_d;
493                         last_nearest_unsent_d = m_nearest_unsent_d;
494                 }*/
495
496                 /*
497                         Get the border/face dot coordinates of a "d-radiused"
498                         box
499                 */
500                 core::list<v3s16> list;
501                 getFacePositions(list, d);
502                 
503                 core::list<v3s16>::Iterator li;
504                 for(li=list.begin(); li!=list.end(); li++)
505                 {
506                         v3s16 p = *li + center;
507                         
508                         /*
509                                 Send throttling
510                                 - Don't allow too many simultaneous transfers
511                                 - EXCEPT when the blocks are very close
512
513                                 Also, don't send blocks that are already flying.
514                         */
515                         
516                         // Start with the usual maximum
517                         u16 max_simul_dynamic = max_simul_sends_usually;
518                         
519                         // If block is very close, allow full maximum
520                         if(d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
521                                 max_simul_dynamic = max_simul_sends_setting;
522
523                         // Don't select too many blocks for sending
524                         if(num_blocks_selected >= max_simul_dynamic)
525                         {
526                                 queue_is_full = true;
527                                 goto queue_full_break;
528                         }
529                         
530                         // Don't send blocks that are currently being transferred
531                         if(m_blocks_sending.find(p) != NULL)
532                                 continue;
533                 
534                         /*
535                                 Do not go over-limit
536                         */
537                         if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
538                         || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
539                         || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
540                         || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
541                         || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
542                         || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
543                                 continue;
544                 
545                         // If this is true, inexistent block will be made from scratch
546                         bool generate = d <= d_max_gen;
547                         
548                         {
549                                 /*// Limit the generating area vertically to 2/3
550                                 if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3)
551                                         generate = false;*/
552
553                                 // Limit the send area vertically to 2/3
554                                 if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3)
555                                         continue;
556                         }
557
558 #if 1
559                         /*
560                                 If block is far away, don't generate it unless it is
561                                 near ground level.
562                         */
563                         if(d >= 4)
564                         {
565         #if 1
566                                 // Block center y in nodes
567                                 f32 y = (f32)(p.Y * MAP_BLOCKSIZE + MAP_BLOCKSIZE/2);
568                                 // Don't generate if it's very high or very low
569                                 if(y < -64 || y > 64)
570                                         generate = false;
571         #endif
572         #if 0
573                                 v2s16 p2d_nodes_center(
574                                         MAP_BLOCKSIZE*p.X,
575                                         MAP_BLOCKSIZE*p.Z);
576                                 
577                                 // Get ground height in nodes
578                                 s16 gh = server->m_env.getServerMap().findGroundLevel(
579                                                 p2d_nodes_center);
580
581                                 // If differs a lot, don't generate
582                                 if(fabs(gh - y) > MAP_BLOCKSIZE*2)
583                                         generate = false;
584                                         // Actually, don't even send it
585                                         //continue;
586         #endif
587                         }
588 #endif
589
590                         //infostream<<"d="<<d<<std::endl;
591                         
592                         /*
593                                 Don't generate or send if not in sight
594                                 FIXME This only works if the client uses a small enough
595                                 FOV setting. The default of 72 degrees is fine.
596                         */
597
598                         float camera_fov = (72.0*PI/180) * 4./3.;
599                         if(isBlockInSight(p, camera_pos, camera_dir, camera_fov, 10000*BS) == false)
600                         {
601                                 continue;
602                         }
603                         
604                         /*
605                                 Don't send already sent blocks
606                         */
607                         {
608                                 if(m_blocks_sent.find(p) != NULL)
609                                 {
610                                         continue;
611                                 }
612                         }
613
614                         /*
615                                 Check if map has this block
616                         */
617                         MapBlock *block = server->m_env.getMap().getBlockNoCreateNoEx(p);
618                         
619                         bool surely_not_found_on_disk = false;
620                         bool block_is_invalid = false;
621                         if(block != NULL)
622                         {
623                                 // Reset usage timer, this block will be of use in the future.
624                                 block->resetUsageTimer();
625
626                                 // Block is dummy if data doesn't exist.
627                                 // It means it has been not found from disk and not generated
628                                 if(block->isDummy())
629                                 {
630                                         surely_not_found_on_disk = true;
631                                 }
632                                 
633                                 // Block is valid if lighting is up-to-date and data exists
634                                 if(block->isValid() == false)
635                                 {
636                                         block_is_invalid = true;
637                                 }
638                                 
639                                 /*if(block->isFullyGenerated() == false)
640                                 {
641                                         block_is_invalid = true;
642                                 }*/
643
644 #if 0
645                                 v2s16 p2d(p.X, p.Z);
646                                 ServerMap *map = (ServerMap*)(&server->m_env.getMap());
647                                 v2s16 chunkpos = map->sector_to_chunk(p2d);
648                                 if(map->chunkNonVolatile(chunkpos) == false)
649                                         block_is_invalid = true;
650 #endif
651                                 if(block->isGenerated() == false)
652                                         block_is_invalid = true;
653 #if 1
654                                 /*
655                                         If block is not close, don't send it unless it is near
656                                         ground level.
657
658                                         Block is near ground level if night-time mesh
659                                         differs from day-time mesh.
660                                 */
661                                 if(d > 3)
662                                 {
663                                         if(block->dayNightDiffed() == false)
664                                                 continue;
665                                 }
666 #endif
667                         }
668
669                         /*
670                                 If block has been marked to not exist on disk (dummy)
671                                 and generating new ones is not wanted, skip block.
672                         */
673                         if(generate == false && surely_not_found_on_disk == true)
674                         {
675                                 // get next one.
676                                 continue;
677                         }
678
679                         /*
680                                 Record the lowest d from which a block has been
681                                 found being not sent and possibly to exist
682                         */
683                         if(no_blocks_found_for_sending)
684                         {
685                                 if(generate == true)
686                                         new_nearest_unsent_d = d;
687                         }
688
689                         no_blocks_found_for_sending = false;
690                                         
691                         /*
692                                 Add inexistent block to emerge queue.
693                         */
694                         if(block == NULL || surely_not_found_on_disk || block_is_invalid)
695                         {
696                                 //TODO: Get value from somewhere
697                                 // Allow only one block in emerge queue
698                                 //if(server->m_emerge_queue.peerItemCount(peer_id) < 1)
699                                 // Allow two blocks in queue per client
700                                 if(server->m_emerge_queue.peerItemCount(peer_id) < 2)
701                                 {
702                                         //infostream<<"Adding block to emerge queue"<<std::endl;
703                                         
704                                         // Add it to the emerge queue and trigger the thread
705                                         
706                                         u8 flags = 0;
707                                         if(generate == false)
708                                                 flags |= BLOCK_EMERGE_FLAG_FROMDISK;
709                                         
710                                         server->m_emerge_queue.addBlock(peer_id, p, flags);
711                                         server->m_emergethread.trigger();
712                                 }
713                                 
714                                 // get next one.
715                                 continue;
716                         }
717
718                         /*
719                                 Add block to send queue
720                         */
721
722                         PrioritySortedBlockTransfer q((float)d, p, peer_id);
723
724                         dest.push_back(q);
725
726                         num_blocks_selected += 1;
727                         sending_something = true;
728                 }
729         }
730 queue_full_break:
731
732         //infostream<<"Stopped at "<<d<<std::endl;
733         
734         if(no_blocks_found_for_sending)
735         {
736                 if(queue_is_full == false)
737                         new_nearest_unsent_d = d;
738         }
739
740         if(new_nearest_unsent_d != -1)
741                 m_nearest_unsent_d = new_nearest_unsent_d;
742
743         if(sending_something == false)
744         {
745                 m_nothing_to_send_counter++;
746                 if((s16)m_nothing_to_send_counter >=
747                                 g_settings->getS16("max_block_send_distance"))
748                 {
749                         // Pause time in seconds
750                         m_nothing_to_send_pause_timer = 1.0;
751                         /*infostream<<"nothing to send to "
752                                         <<server->getPlayerName(peer_id)
753                                         <<" (d="<<d<<")"<<std::endl;*/
754                 }
755         }
756         else
757         {
758                 m_nothing_to_send_counter = 0;
759         }
760
761         /*timer_result = timer.stop(true);
762         if(timer_result != 0)
763                 infostream<<"GetNextBlocks duration: "<<timer_result<<" (!=0)"<<std::endl;*/
764 }
765
766 void RemoteClient::SendObjectData(
767                 Server *server,
768                 float dtime,
769                 core::map<v3s16, bool> &stepped_blocks
770         )
771 {
772         DSTACK(__FUNCTION_NAME);
773
774         // Can't send anything without knowing version
775         if(serialization_version == SER_FMT_VER_INVALID)
776         {
777                 infostream<<"RemoteClient::SendObjectData(): Not sending, no version."
778                                 <<std::endl;
779                 return;
780         }
781
782         /*
783                 Send a TOCLIENT_OBJECTDATA packet.
784                 Sent as unreliable.
785
786                 u16 command
787                 u16 number of player positions
788                 for each player:
789                         u16 peer_id
790                         v3s32 position*100
791                         v3s32 speed*100
792                         s32 pitch*100
793                         s32 yaw*100
794                 u16 count of blocks
795                 for each block:
796                         block objects
797         */
798
799         std::ostringstream os(std::ios_base::binary);
800         u8 buf[12];
801         
802         // Write command
803         writeU16(buf, TOCLIENT_OBJECTDATA);
804         os.write((char*)buf, 2);
805         
806         /*
807                 Get and write player data
808         */
809         
810         // Get connected players
811         core::list<Player*> players = server->m_env.getPlayers(true);
812
813         // Write player count
814         u16 playercount = players.size();
815         writeU16(buf, playercount);
816         os.write((char*)buf, 2);
817
818         core::list<Player*>::Iterator i;
819         for(i = players.begin();
820                         i != players.end(); i++)
821         {
822                 Player *player = *i;
823
824                 v3f pf = player->getPosition();
825                 v3f sf = player->getSpeed();
826
827                 v3s32 position_i(pf.X*100, pf.Y*100, pf.Z*100);
828                 v3s32 speed_i   (sf.X*100, sf.Y*100, sf.Z*100);
829                 s32   pitch_i   (player->getPitch() * 100);
830                 s32   yaw_i     (player->getYaw() * 100);
831                 
832                 writeU16(buf, player->peer_id);
833                 os.write((char*)buf, 2);
834                 writeV3S32(buf, position_i);
835                 os.write((char*)buf, 12);
836                 writeV3S32(buf, speed_i);
837                 os.write((char*)buf, 12);
838                 writeS32(buf, pitch_i);
839                 os.write((char*)buf, 4);
840                 writeS32(buf, yaw_i);
841                 os.write((char*)buf, 4);
842         }
843         
844         /*
845                 Get and write object data (dummy, for compatibility)
846         */
847
848         // Write block count
849         writeU16(buf, 0);
850         os.write((char*)buf, 2);
851
852         /*
853                 Send data
854         */
855         
856         //infostream<<"Server: Sending object data to "<<peer_id<<std::endl;
857
858         // Make data buffer
859         std::string s = os.str();
860         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
861         // Send as unreliable
862         server->m_con.Send(peer_id, 0, data, false);
863 }
864
865 void RemoteClient::GotBlock(v3s16 p)
866 {
867         if(m_blocks_sending.find(p) != NULL)
868                 m_blocks_sending.remove(p);
869         else
870         {
871                 /*infostream<<"RemoteClient::GotBlock(): Didn't find in"
872                                 " m_blocks_sending"<<std::endl;*/
873                 m_excess_gotblocks++;
874         }
875         m_blocks_sent.insert(p, true);
876 }
877
878 void RemoteClient::SentBlock(v3s16 p)
879 {
880         if(m_blocks_sending.find(p) == NULL)
881                 m_blocks_sending.insert(p, 0.0);
882         else
883                 infostream<<"RemoteClient::SentBlock(): Sent block"
884                                 " already in m_blocks_sending"<<std::endl;
885 }
886
887 void RemoteClient::SetBlockNotSent(v3s16 p)
888 {
889         m_nearest_unsent_d = 0;
890         
891         if(m_blocks_sending.find(p) != NULL)
892                 m_blocks_sending.remove(p);
893         if(m_blocks_sent.find(p) != NULL)
894                 m_blocks_sent.remove(p);
895 }
896
897 void RemoteClient::SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks)
898 {
899         m_nearest_unsent_d = 0;
900         
901         for(core::map<v3s16, MapBlock*>::Iterator
902                         i = blocks.getIterator();
903                         i.atEnd()==false; i++)
904         {
905                 v3s16 p = i.getNode()->getKey();
906
907                 if(m_blocks_sending.find(p) != NULL)
908                         m_blocks_sending.remove(p);
909                 if(m_blocks_sent.find(p) != NULL)
910                         m_blocks_sent.remove(p);
911         }
912 }
913
914 /*
915         PlayerInfo
916 */
917
918 PlayerInfo::PlayerInfo()
919 {
920         name[0] = 0;
921         avg_rtt = 0;
922 }
923
924 void PlayerInfo::PrintLine(std::ostream *s)
925 {
926         (*s)<<id<<": ";
927         (*s)<<"\""<<name<<"\" ("
928                         <<(position.X/10)<<","<<(position.Y/10)
929                         <<","<<(position.Z/10)<<") ";
930         address.print(s);
931         (*s)<<" avg_rtt="<<avg_rtt;
932         (*s)<<std::endl;
933 }
934
935 u32 PIChecksum(core::list<PlayerInfo> &l)
936 {
937         core::list<PlayerInfo>::Iterator i;
938         u32 checksum = 1;
939         u32 a = 10;
940         for(i=l.begin(); i!=l.end(); i++)
941         {
942                 checksum += a * (i->id+1);
943                 checksum ^= 0x435aafcd;
944                 a *= 10;
945         }
946         return checksum;
947 }
948
949 /*
950         Server
951 */
952
953 Server::Server(
954                 std::string mapsavedir,
955                 std::string configpath
956         ):
957         m_env(new ServerMap(mapsavedir), this),
958         m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
959         m_authmanager(mapsavedir+"/auth.txt"),
960         m_banmanager(mapsavedir+"/ipban.txt"),
961         m_thread(this),
962         m_emergethread(this),
963         m_time_counter(0),
964         m_time_of_day_send_timer(0),
965         m_uptime(0),
966         m_mapsavedir(mapsavedir),
967         m_configpath(configpath),
968         m_shutdown_requested(false),
969         m_ignore_map_edit_events(false),
970         m_ignore_map_edit_events_peer_id(0)
971 {
972         m_liquid_transform_timer = 0.0;
973         m_print_info_timer = 0.0;
974         m_objectdata_timer = 0.0;
975         m_emergethread_trigger_timer = 0.0;
976         m_savemap_timer = 0.0;
977         
978         m_env_mutex.Init();
979         m_con_mutex.Init();
980         m_step_dtime_mutex.Init();
981         m_step_dtime = 0.0;
982         
983         // Register us to receive map edit events
984         m_env.getMap().addEventReceiver(this);
985
986         // If file exists, load environment metadata
987         if(fs::PathExists(m_mapsavedir+"/env_meta.txt"))
988         {
989                 infostream<<"Server: Loading environment metadata"<<std::endl;
990                 m_env.loadMeta(m_mapsavedir);
991         }
992
993         // Load players
994         infostream<<"Server: Loading players"<<std::endl;
995         m_env.deSerializePlayers(m_mapsavedir);
996 }
997
998 Server::~Server()
999 {
1000         infostream<<"Server::~Server()"<<std::endl;
1001
1002         /*
1003                 Send shutdown message
1004         */
1005         {
1006                 JMutexAutoLock conlock(m_con_mutex);
1007                 
1008                 std::wstring line = L"*** Server shutting down";
1009
1010                 /*
1011                         Send the message to clients
1012                 */
1013                 for(core::map<u16, RemoteClient*>::Iterator
1014                         i = m_clients.getIterator();
1015                         i.atEnd() == false; i++)
1016                 {
1017                         // Get client and check that it is valid
1018                         RemoteClient *client = i.getNode()->getValue();
1019                         assert(client->peer_id == i.getNode()->getKey());
1020                         if(client->serialization_version == SER_FMT_VER_INVALID)
1021                                 continue;
1022
1023                         try{
1024                                 SendChatMessage(client->peer_id, line);
1025                         }
1026                         catch(con::PeerNotFoundException &e)
1027                         {}
1028                 }
1029         }
1030         
1031         {
1032                 JMutexAutoLock envlock(m_env_mutex);
1033
1034                 /*
1035                         Save players
1036                 */
1037                 infostream<<"Server: Saving players"<<std::endl;
1038                 m_env.serializePlayers(m_mapsavedir);
1039
1040                 /*
1041                         Save environment metadata
1042                 */
1043                 infostream<<"Server: Saving environment metadata"<<std::endl;
1044                 m_env.saveMeta(m_mapsavedir);
1045         }
1046                 
1047         /*
1048                 Stop threads
1049         */
1050         stop();
1051         
1052         /*
1053                 Delete clients
1054         */
1055         {
1056                 JMutexAutoLock clientslock(m_con_mutex);
1057
1058                 for(core::map<u16, RemoteClient*>::Iterator
1059                         i = m_clients.getIterator();
1060                         i.atEnd() == false; i++)
1061                 {
1062                         /*// Delete player
1063                         // NOTE: These are removed by env destructor
1064                         {
1065                                 u16 peer_id = i.getNode()->getKey();
1066                                 JMutexAutoLock envlock(m_env_mutex);
1067                                 m_env.removePlayer(peer_id);
1068                         }*/
1069                         
1070                         // Delete client
1071                         delete i.getNode()->getValue();
1072                 }
1073         }
1074 }
1075
1076 void Server::start(unsigned short port)
1077 {
1078         DSTACK(__FUNCTION_NAME);
1079         // Stop thread if already running
1080         m_thread.stop();
1081         
1082         // Initialize connection
1083         m_con.setTimeoutMs(30);
1084         m_con.Serve(port);
1085
1086         // Start thread
1087         m_thread.setRun(true);
1088         m_thread.Start();
1089         
1090         infostream<<"Server: Started on port "<<port<<std::endl;
1091 }
1092
1093 void Server::stop()
1094 {
1095         DSTACK(__FUNCTION_NAME);
1096         
1097         infostream<<"Server: Stopping and waiting threads"<<std::endl;
1098
1099         // Stop threads (set run=false first so both start stopping)
1100         m_thread.setRun(false);
1101         m_emergethread.setRun(false);
1102         m_thread.stop();
1103         m_emergethread.stop();
1104         
1105         infostream<<"Server: Threads stopped"<<std::endl;
1106 }
1107
1108 void Server::step(float dtime)
1109 {
1110         DSTACK(__FUNCTION_NAME);
1111         // Limit a bit
1112         if(dtime > 2.0)
1113                 dtime = 2.0;
1114         {
1115                 JMutexAutoLock lock(m_step_dtime_mutex);
1116                 m_step_dtime += dtime;
1117         }
1118 }
1119
1120 void Server::AsyncRunStep()
1121 {
1122         DSTACK(__FUNCTION_NAME);
1123         
1124         g_profiler->add("Server::AsyncRunStep (num)", 1);
1125         
1126         float dtime;
1127         {
1128                 JMutexAutoLock lock1(m_step_dtime_mutex);
1129                 dtime = m_step_dtime;
1130         }
1131         
1132         {
1133                 ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
1134                 // Send blocks to clients
1135                 SendBlocks(dtime);
1136         }
1137         
1138         if(dtime < 0.001)
1139                 return;
1140         
1141         g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
1142
1143         //infostream<<"Server steps "<<dtime<<std::endl;
1144         //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
1145         
1146         {
1147                 JMutexAutoLock lock1(m_step_dtime_mutex);
1148                 m_step_dtime -= dtime;
1149         }
1150
1151         /*
1152                 Update uptime
1153         */
1154         {
1155                 m_uptime.set(m_uptime.get() + dtime);
1156         }
1157         
1158         {
1159                 // Process connection's timeouts
1160                 JMutexAutoLock lock2(m_con_mutex);
1161                 ScopeProfiler sp(g_profiler, "Server: connection timeout processing");
1162                 m_con.RunTimeouts(dtime);
1163         }
1164         
1165         {
1166                 // This has to be called so that the client list gets synced
1167                 // with the peer list of the connection
1168                 handlePeerChanges();
1169         }
1170
1171         /*
1172                 Update m_time_of_day and overall game time
1173         */
1174         {
1175                 JMutexAutoLock envlock(m_env_mutex);
1176
1177                 m_time_counter += dtime;
1178                 f32 speed = g_settings->getFloat("time_speed") * 24000./(24.*3600);
1179                 u32 units = (u32)(m_time_counter*speed);
1180                 m_time_counter -= (f32)units / speed;
1181                 
1182                 m_env.setTimeOfDay((m_env.getTimeOfDay() + units) % 24000);
1183                 
1184                 //infostream<<"Server: m_time_of_day = "<<m_time_of_day.get()<<std::endl;
1185
1186                 /*
1187                         Send to clients at constant intervals
1188                 */
1189
1190                 m_time_of_day_send_timer -= dtime;
1191                 if(m_time_of_day_send_timer < 0.0)
1192                 {
1193                         m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
1194
1195                         //JMutexAutoLock envlock(m_env_mutex);
1196                         JMutexAutoLock conlock(m_con_mutex);
1197
1198                         for(core::map<u16, RemoteClient*>::Iterator
1199                                 i = m_clients.getIterator();
1200                                 i.atEnd() == false; i++)
1201                         {
1202                                 RemoteClient *client = i.getNode()->getValue();
1203                                 //Player *player = m_env.getPlayer(client->peer_id);
1204                                 
1205                                 SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
1206                                                 m_env.getTimeOfDay());
1207                                 // Send as reliable
1208                                 m_con.Send(client->peer_id, 0, data, true);
1209                         }
1210                 }
1211         }
1212
1213         {
1214                 JMutexAutoLock lock(m_env_mutex);
1215                 // Step environment
1216                 ScopeProfiler sp(g_profiler, "SEnv step");
1217                 ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG);
1218                 m_env.step(dtime);
1219         }
1220                 
1221         const float map_timer_and_unload_dtime = 5.15;
1222         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
1223         {
1224                 JMutexAutoLock lock(m_env_mutex);
1225                 // Run Map's timers and unload unused data
1226                 ScopeProfiler sp(g_profiler, "Server: map timer and unload");
1227                 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
1228                                 g_settings->getFloat("server_unload_unused_data_timeout"));
1229         }
1230         
1231         /*
1232                 Do background stuff
1233         */
1234         
1235         /*
1236                 Transform liquids
1237         */
1238         m_liquid_transform_timer += dtime;
1239         if(m_liquid_transform_timer >= 1.00)
1240         {
1241                 m_liquid_transform_timer -= 1.00;
1242                 
1243                 JMutexAutoLock lock(m_env_mutex);
1244
1245                 ScopeProfiler sp(g_profiler, "Server: liquid transform");
1246
1247                 core::map<v3s16, MapBlock*> modified_blocks;
1248                 m_env.getMap().transformLiquids(modified_blocks);
1249 #if 0           
1250                 /*
1251                         Update lighting
1252                 */
1253                 core::map<v3s16, MapBlock*> lighting_modified_blocks;
1254                 ServerMap &map = ((ServerMap&)m_env.getMap());
1255                 map.updateLighting(modified_blocks, lighting_modified_blocks);
1256                 
1257                 // Add blocks modified by lighting to modified_blocks
1258                 for(core::map<v3s16, MapBlock*>::Iterator
1259                                 i = lighting_modified_blocks.getIterator();
1260                                 i.atEnd() == false; i++)
1261                 {
1262                         MapBlock *block = i.getNode()->getValue();
1263                         modified_blocks.insert(block->getPos(), block);
1264                 }
1265 #endif
1266                 /*
1267                         Set the modified blocks unsent for all the clients
1268                 */
1269                 
1270                 JMutexAutoLock lock2(m_con_mutex);
1271
1272                 for(core::map<u16, RemoteClient*>::Iterator
1273                                 i = m_clients.getIterator();
1274                                 i.atEnd() == false; i++)
1275                 {
1276                         RemoteClient *client = i.getNode()->getValue();
1277                         
1278                         if(modified_blocks.size() > 0)
1279                         {
1280                                 // Remove block from sent history
1281                                 client->SetBlocksNotSent(modified_blocks);
1282                         }
1283                 }
1284         }
1285
1286         // Periodically print some info
1287         {
1288                 float &counter = m_print_info_timer;
1289                 counter += dtime;
1290                 if(counter >= 30.0)
1291                 {
1292                         counter = 0.0;
1293
1294                         JMutexAutoLock lock2(m_con_mutex);
1295                         
1296                         if(m_clients.size() != 0)
1297                                 infostream<<"Players:"<<std::endl;
1298                         for(core::map<u16, RemoteClient*>::Iterator
1299                                 i = m_clients.getIterator();
1300                                 i.atEnd() == false; i++)
1301                         {
1302                                 //u16 peer_id = i.getNode()->getKey();
1303                                 RemoteClient *client = i.getNode()->getValue();
1304                                 Player *player = m_env.getPlayer(client->peer_id);
1305                                 if(player==NULL)
1306                                         continue;
1307                                 infostream<<"* "<<player->getName()<<"\t";
1308                                 client->PrintInfo(infostream);
1309                         }
1310                 }
1311         }
1312
1313         //if(g_settings->getBool("enable_experimental"))
1314         {
1315
1316         /*
1317                 Check added and deleted active objects
1318         */
1319         {
1320                 //infostream<<"Server: Checking added and deleted active objects"<<std::endl;
1321                 JMutexAutoLock envlock(m_env_mutex);
1322                 JMutexAutoLock conlock(m_con_mutex);
1323
1324                 ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
1325
1326                 // Radius inside which objects are active
1327                 s16 radius = g_settings->getS16("active_object_send_range_blocks");
1328                 radius *= MAP_BLOCKSIZE;
1329
1330                 for(core::map<u16, RemoteClient*>::Iterator
1331                         i = m_clients.getIterator();
1332                         i.atEnd() == false; i++)
1333                 {
1334                         RemoteClient *client = i.getNode()->getValue();
1335                         Player *player = m_env.getPlayer(client->peer_id);
1336                         if(player==NULL)
1337                         {
1338                                 // This can happen if the client timeouts somehow
1339                                 /*infostream<<"WARNING: "<<__FUNCTION_NAME<<": Client "
1340                                                 <<client->peer_id
1341                                                 <<" has no associated player"<<std::endl;*/
1342                                 continue;
1343                         }
1344                         v3s16 pos = floatToInt(player->getPosition(), BS);
1345
1346                         core::map<u16, bool> removed_objects;
1347                         core::map<u16, bool> added_objects;
1348                         m_env.getRemovedActiveObjects(pos, radius,
1349                                         client->m_known_objects, removed_objects);
1350                         m_env.getAddedActiveObjects(pos, radius,
1351                                         client->m_known_objects, added_objects);
1352                         
1353                         // Ignore if nothing happened
1354                         if(removed_objects.size() == 0 && added_objects.size() == 0)
1355                         {
1356                                 //infostream<<"active objects: none changed"<<std::endl;
1357                                 continue;
1358                         }
1359                         
1360                         std::string data_buffer;
1361
1362                         char buf[4];
1363                         
1364                         // Handle removed objects
1365                         writeU16((u8*)buf, removed_objects.size());
1366                         data_buffer.append(buf, 2);
1367                         for(core::map<u16, bool>::Iterator
1368                                         i = removed_objects.getIterator();
1369                                         i.atEnd()==false; i++)
1370                         {
1371                                 // Get object
1372                                 u16 id = i.getNode()->getKey();
1373                                 ServerActiveObject* obj = m_env.getActiveObject(id);
1374
1375                                 // Add to data buffer for sending
1376                                 writeU16((u8*)buf, i.getNode()->getKey());
1377                                 data_buffer.append(buf, 2);
1378                                 
1379                                 // Remove from known objects
1380                                 client->m_known_objects.remove(i.getNode()->getKey());
1381
1382                                 if(obj && obj->m_known_by_count > 0)
1383                                         obj->m_known_by_count--;
1384                         }
1385
1386                         // Handle added objects
1387                         writeU16((u8*)buf, added_objects.size());
1388                         data_buffer.append(buf, 2);
1389                         for(core::map<u16, bool>::Iterator
1390                                         i = added_objects.getIterator();
1391                                         i.atEnd()==false; i++)
1392                         {
1393                                 // Get object
1394                                 u16 id = i.getNode()->getKey();
1395                                 ServerActiveObject* obj = m_env.getActiveObject(id);
1396                                 
1397                                 // Get object type
1398                                 u8 type = ACTIVEOBJECT_TYPE_INVALID;
1399                                 if(obj == NULL)
1400                                         infostream<<"WARNING: "<<__FUNCTION_NAME
1401                                                         <<": NULL object"<<std::endl;
1402                                 else
1403                                         type = obj->getType();
1404
1405                                 // Add to data buffer for sending
1406                                 writeU16((u8*)buf, id);
1407                                 data_buffer.append(buf, 2);
1408                                 writeU8((u8*)buf, type);
1409                                 data_buffer.append(buf, 1);
1410                                 
1411                                 if(obj)
1412                                         data_buffer.append(serializeLongString(
1413                                                         obj->getClientInitializationData()));
1414                                 else
1415                                         data_buffer.append(serializeLongString(""));
1416
1417                                 // Add to known objects
1418                                 client->m_known_objects.insert(i.getNode()->getKey(), false);
1419
1420                                 if(obj)
1421                                         obj->m_known_by_count++;
1422                         }
1423
1424                         // Send packet
1425                         SharedBuffer<u8> reply(2 + data_buffer.size());
1426                         writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD);
1427                         memcpy((char*)&reply[2], data_buffer.c_str(),
1428                                         data_buffer.size());
1429                         // Send as reliable
1430                         m_con.Send(client->peer_id, 0, reply, true);
1431
1432                         infostream<<"Server: Sent object remove/add: "
1433                                         <<removed_objects.size()<<" removed, "
1434                                         <<added_objects.size()<<" added, "
1435                                         <<"packet size is "<<reply.getSize()<<std::endl;
1436                 }
1437
1438 #if 0
1439                 /*
1440                         Collect a list of all the objects known by the clients
1441                         and report it back to the environment.
1442                 */
1443
1444                 core::map<u16, bool> all_known_objects;
1445
1446                 for(core::map<u16, RemoteClient*>::Iterator
1447                         i = m_clients.getIterator();
1448                         i.atEnd() == false; i++)
1449                 {
1450                         RemoteClient *client = i.getNode()->getValue();
1451                         // Go through all known objects of client
1452                         for(core::map<u16, bool>::Iterator
1453                                         i = client->m_known_objects.getIterator();
1454                                         i.atEnd()==false; i++)
1455                         {
1456                                 u16 id = i.getNode()->getKey();
1457                                 all_known_objects[id] = true;
1458                         }
1459                 }
1460                 
1461                 m_env.setKnownActiveObjects(whatever);
1462 #endif
1463
1464         }
1465
1466         /*
1467                 Send object messages
1468         */
1469         {
1470                 JMutexAutoLock envlock(m_env_mutex);
1471                 JMutexAutoLock conlock(m_con_mutex);
1472
1473                 ScopeProfiler sp(g_profiler, "Server: sending object messages");
1474
1475                 // Key = object id
1476                 // Value = data sent by object
1477                 core::map<u16, core::list<ActiveObjectMessage>* > buffered_messages;
1478
1479                 // Get active object messages from environment
1480                 for(;;)
1481                 {
1482                         ActiveObjectMessage aom = m_env.getActiveObjectMessage();
1483                         if(aom.id == 0)
1484                                 break;
1485                         
1486                         core::list<ActiveObjectMessage>* message_list = NULL;
1487                         core::map<u16, core::list<ActiveObjectMessage>* >::Node *n;
1488                         n = buffered_messages.find(aom.id);
1489                         if(n == NULL)
1490                         {
1491                                 message_list = new core::list<ActiveObjectMessage>;
1492                                 buffered_messages.insert(aom.id, message_list);
1493                         }
1494                         else
1495                         {
1496                                 message_list = n->getValue();
1497                         }
1498                         message_list->push_back(aom);
1499                 }
1500                 
1501                 // Route data to every client
1502                 for(core::map<u16, RemoteClient*>::Iterator
1503                         i = m_clients.getIterator();
1504                         i.atEnd()==false; i++)
1505                 {
1506                         RemoteClient *client = i.getNode()->getValue();
1507                         std::string reliable_data;
1508                         std::string unreliable_data;
1509                         // Go through all objects in message buffer
1510                         for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1511                                         j = buffered_messages.getIterator();
1512                                         j.atEnd()==false; j++)
1513                         {
1514                                 // If object is not known by client, skip it
1515                                 u16 id = j.getNode()->getKey();
1516                                 if(client->m_known_objects.find(id) == NULL)
1517                                         continue;
1518                                 // Get message list of object
1519                                 core::list<ActiveObjectMessage>* list = j.getNode()->getValue();
1520                                 // Go through every message
1521                                 for(core::list<ActiveObjectMessage>::Iterator
1522                                                 k = list->begin(); k != list->end(); k++)
1523                                 {
1524                                         // Compose the full new data with header
1525                                         ActiveObjectMessage aom = *k;
1526                                         std::string new_data;
1527                                         // Add object id
1528                                         char buf[2];
1529                                         writeU16((u8*)&buf[0], aom.id);
1530                                         new_data.append(buf, 2);
1531                                         // Add data
1532                                         new_data += serializeString(aom.datastring);
1533                                         // Add data to buffer
1534                                         if(aom.reliable)
1535                                                 reliable_data += new_data;
1536                                         else
1537                                                 unreliable_data += new_data;
1538                                 }
1539                         }
1540                         /*
1541                                 reliable_data and unreliable_data are now ready.
1542                                 Send them.
1543                         */
1544                         if(reliable_data.size() > 0)
1545                         {
1546                                 SharedBuffer<u8> reply(2 + reliable_data.size());
1547                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1548                                 memcpy((char*)&reply[2], reliable_data.c_str(),
1549                                                 reliable_data.size());
1550                                 // Send as reliable
1551                                 m_con.Send(client->peer_id, 0, reply, true);
1552                         }
1553                         if(unreliable_data.size() > 0)
1554                         {
1555                                 SharedBuffer<u8> reply(2 + unreliable_data.size());
1556                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1557                                 memcpy((char*)&reply[2], unreliable_data.c_str(),
1558                                                 unreliable_data.size());
1559                                 // Send as unreliable
1560                                 m_con.Send(client->peer_id, 0, reply, false);
1561                         }
1562
1563                         /*if(reliable_data.size() > 0 || unreliable_data.size() > 0)
1564                         {
1565                                 infostream<<"Server: Size of object message data: "
1566                                                 <<"reliable: "<<reliable_data.size()
1567                                                 <<", unreliable: "<<unreliable_data.size()
1568                                                 <<std::endl;
1569                         }*/
1570                 }
1571
1572                 // Clear buffered_messages
1573                 for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1574                                 i = buffered_messages.getIterator();
1575                                 i.atEnd()==false; i++)
1576                 {
1577                         delete i.getNode()->getValue();
1578                 }
1579         }
1580
1581         } // enable_experimental
1582
1583         /*
1584                 Send queued-for-sending map edit events.
1585         */
1586         {
1587                 // Don't send too many at a time
1588                 //u32 count = 0;
1589
1590                 // Single change sending is disabled if queue size is not small
1591                 bool disable_single_change_sending = false;
1592                 if(m_unsent_map_edit_queue.size() >= 4)
1593                         disable_single_change_sending = true;
1594
1595                 bool got_any_events = false;
1596
1597                 // We'll log the amount of each
1598                 Profiler prof;
1599
1600                 while(m_unsent_map_edit_queue.size() != 0)
1601                 {
1602                         got_any_events = true;
1603
1604                         MapEditEvent* event = m_unsent_map_edit_queue.pop_front();
1605                         
1606                         // Players far away from the change are stored here.
1607                         // Instead of sending the changes, MapBlocks are set not sent
1608                         // for them.
1609                         core::list<u16> far_players;
1610
1611                         if(event->type == MEET_ADDNODE)
1612                         {
1613                                 //infostream<<"Server: MEET_ADDNODE"<<std::endl;
1614                                 prof.add("MEET_ADDNODE", 1);
1615                                 if(disable_single_change_sending)
1616                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1617                                                         &far_players, 5);
1618                                 else
1619                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1620                                                         &far_players, 30);
1621                         }
1622                         else if(event->type == MEET_REMOVENODE)
1623                         {
1624                                 //infostream<<"Server: MEET_REMOVENODE"<<std::endl;
1625                                 prof.add("MEET_REMOVENODE", 1);
1626                                 if(disable_single_change_sending)
1627                                         sendRemoveNode(event->p, event->already_known_by_peer,
1628                                                         &far_players, 5);
1629                                 else
1630                                         sendRemoveNode(event->p, event->already_known_by_peer,
1631                                                         &far_players, 30);
1632                         }
1633                         else if(event->type == MEET_BLOCK_NODE_METADATA_CHANGED)
1634                         {
1635                                 infostream<<"Server: MEET_BLOCK_NODE_METADATA_CHANGED"<<std::endl;
1636                                 prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1);
1637                                 setBlockNotSent(event->p);
1638                         }
1639                         else if(event->type == MEET_OTHER)
1640                         {
1641                                 infostream<<"Server: MEET_OTHER"<<std::endl;
1642                                 prof.add("MEET_OTHER", 1);
1643                                 for(core::map<v3s16, bool>::Iterator
1644                                                 i = event->modified_blocks.getIterator();
1645                                                 i.atEnd()==false; i++)
1646                                 {
1647                                         v3s16 p = i.getNode()->getKey();
1648                                         setBlockNotSent(p);
1649                                 }
1650                         }
1651                         else
1652                         {
1653                                 prof.add("unknown", 1);
1654                                 infostream<<"WARNING: Server: Unknown MapEditEvent "
1655                                                 <<((u32)event->type)<<std::endl;
1656                         }
1657                         
1658                         /*
1659                                 Set blocks not sent to far players
1660                         */
1661                         if(far_players.size() > 0)
1662                         {
1663                                 // Convert list format to that wanted by SetBlocksNotSent
1664                                 core::map<v3s16, MapBlock*> modified_blocks2;
1665                                 for(core::map<v3s16, bool>::Iterator
1666                                                 i = event->modified_blocks.getIterator();
1667                                                 i.atEnd()==false; i++)
1668                                 {
1669                                         v3s16 p = i.getNode()->getKey();
1670                                         modified_blocks2.insert(p,
1671                                                         m_env.getMap().getBlockNoCreateNoEx(p));
1672                                 }
1673                                 // Set blocks not sent
1674                                 for(core::list<u16>::Iterator
1675                                                 i = far_players.begin();
1676                                                 i != far_players.end(); i++)
1677                                 {
1678                                         u16 peer_id = *i;
1679                                         RemoteClient *client = getClient(peer_id);
1680                                         if(client==NULL)
1681                                                 continue;
1682                                         client->SetBlocksNotSent(modified_blocks2);
1683                                 }
1684                         }
1685
1686                         delete event;
1687
1688                         /*// Don't send too many at a time
1689                         count++;
1690                         if(count >= 1 && m_unsent_map_edit_queue.size() < 100)
1691                                 break;*/
1692                 }
1693
1694                 if(got_any_events)
1695                 {
1696                         infostream<<"Server: MapEditEvents:"<<std::endl;
1697                         prof.print(infostream);
1698                 }
1699                 
1700         }
1701
1702         /*
1703                 Send object positions
1704         */
1705         {
1706                 float &counter = m_objectdata_timer;
1707                 counter += dtime;
1708                 if(counter >= g_settings->getFloat("objectdata_interval"))
1709                 {
1710                         JMutexAutoLock lock1(m_env_mutex);
1711                         JMutexAutoLock lock2(m_con_mutex);
1712
1713                         ScopeProfiler sp(g_profiler, "Server: sending player positions");
1714
1715                         SendObjectData(counter);
1716
1717                         counter = 0.0;
1718                 }
1719         }
1720         
1721         /*
1722                 Trigger emergethread (it somehow gets to a non-triggered but
1723                 bysy state sometimes)
1724         */
1725         {
1726                 float &counter = m_emergethread_trigger_timer;
1727                 counter += dtime;
1728                 if(counter >= 2.0)
1729                 {
1730                         counter = 0.0;
1731                         
1732                         m_emergethread.trigger();
1733                 }
1734         }
1735
1736         // Save map, players and auth stuff
1737         {
1738                 float &counter = m_savemap_timer;
1739                 counter += dtime;
1740                 if(counter >= g_settings->getFloat("server_map_save_interval"))
1741                 {
1742                         counter = 0.0;
1743
1744                         ScopeProfiler sp(g_profiler, "Server: saving stuff");
1745
1746                         // Auth stuff
1747                         if(m_authmanager.isModified())
1748                                 m_authmanager.save();
1749
1750                         //Bann stuff
1751                         if(m_banmanager.isModified())
1752                                 m_banmanager.save();
1753                         
1754                         // Map
1755                         JMutexAutoLock lock(m_env_mutex);
1756
1757                         /*// Unload unused data (delete from memory)
1758                         m_env.getMap().unloadUnusedData(
1759                                         g_settings->getFloat("server_unload_unused_sectors_timeout"));
1760                                         */
1761                         /*u32 deleted_count = m_env.getMap().unloadUnusedData(
1762                                         g_settings->getFloat("server_unload_unused_sectors_timeout"));
1763                                         */
1764
1765                         // Save only changed parts
1766                         m_env.getMap().save(true);
1767
1768                         /*if(deleted_count > 0)
1769                         {
1770                                 infostream<<"Server: Unloaded "<<deleted_count
1771                                                 <<" blocks from memory"<<std::endl;
1772                         }*/
1773
1774                         // Save players
1775                         m_env.serializePlayers(m_mapsavedir);
1776                         
1777                         // Save environment metadata
1778                         m_env.saveMeta(m_mapsavedir);
1779                 }
1780         }
1781 }
1782
1783 void Server::Receive()
1784 {
1785         DSTACK(__FUNCTION_NAME);
1786         u32 data_maxsize = 10000;
1787         Buffer<u8> data(data_maxsize);
1788         u16 peer_id;
1789         u32 datasize;
1790         try{
1791                 {
1792                         JMutexAutoLock conlock(m_con_mutex);
1793                         datasize = m_con.Receive(peer_id, *data, data_maxsize);
1794                 }
1795
1796                 // This has to be called so that the client list gets synced
1797                 // with the peer list of the connection
1798                 handlePeerChanges();
1799
1800                 ProcessData(*data, datasize, peer_id);
1801         }
1802         catch(con::InvalidIncomingDataException &e)
1803         {
1804                 infostream<<"Server::Receive(): "
1805                                 "InvalidIncomingDataException: what()="
1806                                 <<e.what()<<std::endl;
1807         }
1808         catch(con::PeerNotFoundException &e)
1809         {
1810                 //NOTE: This is not needed anymore
1811                 
1812                 // The peer has been disconnected.
1813                 // Find the associated player and remove it.
1814
1815                 /*JMutexAutoLock envlock(m_env_mutex);
1816
1817                 infostream<<"ServerThread: peer_id="<<peer_id
1818                                 <<" has apparently closed connection. "
1819                                 <<"Removing player."<<std::endl;
1820
1821                 m_env.removePlayer(peer_id);*/
1822         }
1823 }
1824
1825 void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
1826 {
1827         DSTACK(__FUNCTION_NAME);
1828         // Environment is locked first.
1829         JMutexAutoLock envlock(m_env_mutex);
1830         JMutexAutoLock conlock(m_con_mutex);
1831         
1832         con::Peer *peer;
1833         try{
1834                 peer = m_con.GetPeer(peer_id);
1835         }
1836         catch(con::PeerNotFoundException &e)
1837         {
1838                 infostream<<"Server::ProcessData(): Cancelling: peer "
1839                                 <<peer_id<<" not found"<<std::endl;
1840                 return;
1841         }
1842
1843         // drop player if is ip is banned
1844         if(m_banmanager.isIpBanned(peer->address.serializeString())){
1845                 SendAccessDenied(m_con, peer_id,
1846                                 L"Your ip is banned. Banned name was "
1847                                 +narrow_to_wide(m_banmanager.getBanName(
1848                                         peer->address.serializeString())));
1849                 m_con.deletePeer(peer_id, false);
1850                 return;
1851         }
1852         
1853         u8 peer_ser_ver = getClient(peer->id)->serialization_version;
1854
1855         try
1856         {
1857
1858         if(datasize < 2)
1859                 return;
1860
1861         ToServerCommand command = (ToServerCommand)readU16(&data[0]);
1862         
1863         if(command == TOSERVER_INIT)
1864         {
1865                 // [0] u16 TOSERVER_INIT
1866                 // [2] u8 SER_FMT_VER_HIGHEST
1867                 // [3] u8[20] player_name
1868                 // [23] u8[28] password <--- can be sent without this, from old versions
1869
1870                 if(datasize < 2+1+PLAYERNAME_SIZE)
1871                         return;
1872
1873                 infostream<<"Server: Got TOSERVER_INIT from "
1874                                 <<peer->id<<std::endl;
1875
1876                 // First byte after command is maximum supported
1877                 // serialization version
1878                 u8 client_max = data[2];
1879                 u8 our_max = SER_FMT_VER_HIGHEST;
1880                 // Use the highest version supported by both
1881                 u8 deployed = core::min_(client_max, our_max);
1882                 // If it's lower than the lowest supported, give up.
1883                 if(deployed < SER_FMT_VER_LOWEST)
1884                         deployed = SER_FMT_VER_INVALID;
1885
1886                 //peer->serialization_version = deployed;
1887                 getClient(peer->id)->pending_serialization_version = deployed;
1888                 
1889                 if(deployed == SER_FMT_VER_INVALID)
1890                 {
1891                         infostream<<"Server: Cannot negotiate "
1892                                         "serialization version with peer "
1893                                         <<peer_id<<std::endl;
1894                         SendAccessDenied(m_con, peer_id,
1895                                         L"Your client is too old (map format)");
1896                         return;
1897                 }
1898                 
1899                 /*
1900                         Read and check network protocol version
1901                 */
1902
1903                 u16 net_proto_version = 0;
1904                 if(datasize >= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2)
1905                 {
1906                         net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]);
1907                 }
1908
1909                 getClient(peer->id)->net_proto_version = net_proto_version;
1910
1911                 if(net_proto_version == 0)
1912                 {
1913                         SendAccessDenied(m_con, peer_id,
1914                                         L"Your client is too old. Please upgrade.");
1915                         return;
1916                 }
1917                 
1918                 /* Uhh... this should actually be a warning but let's do it like this */
1919                 if(g_settings->getBool("strict_protocol_version_checking"))
1920                 {
1921                         if(net_proto_version < PROTOCOL_VERSION)
1922                         {
1923                                 SendAccessDenied(m_con, peer_id,
1924                                                 L"Your client is too old. Please upgrade.");
1925                                 return;
1926                         }
1927                 }
1928
1929                 /*
1930                         Set up player
1931                 */
1932                 
1933                 // Get player name
1934                 char playername[PLAYERNAME_SIZE];
1935                 for(u32 i=0; i<PLAYERNAME_SIZE-1; i++)
1936                 {
1937                         playername[i] = data[3+i];
1938                 }
1939                 playername[PLAYERNAME_SIZE-1] = 0;
1940                 
1941                 if(playername[0]=='\0')
1942                 {
1943                         infostream<<"Server: Player has empty name"<<std::endl;
1944                         SendAccessDenied(m_con, peer_id,
1945                                         L"Empty name");
1946                         return;
1947                 }
1948
1949                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1950                 {
1951                         infostream<<"Server: Player has invalid name"<<std::endl;
1952                         SendAccessDenied(m_con, peer_id,
1953                                         L"Name contains unallowed characters");
1954                         return;
1955                 }
1956
1957                 // Get password
1958                 char password[PASSWORD_SIZE];
1959                 if(datasize < 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE)
1960                 {
1961                         // old version - assume blank password
1962                         password[0] = 0;
1963                 }
1964                 else
1965                 {
1966                                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
1967                                 {
1968                                         password[i] = data[23+i];
1969                                 }
1970                                 password[PASSWORD_SIZE-1] = 0;
1971                 }
1972                 
1973                 std::string checkpwd;
1974                 if(m_authmanager.exists(playername))
1975                 {
1976                         checkpwd = m_authmanager.getPassword(playername);
1977                 }
1978                 else
1979                 {
1980                         checkpwd = g_settings->get("default_password");
1981                 }
1982                 
1983                 /*infostream<<"Server: Client gave password '"<<password
1984                                 <<"', the correct one is '"<<checkpwd<<"'"<<std::endl;*/
1985                 
1986                 if(password != checkpwd && m_authmanager.exists(playername))
1987                 {
1988                         infostream<<"Server: peer_id="<<peer_id
1989                                         <<": supplied invalid password for "
1990                                         <<playername<<std::endl;
1991                         SendAccessDenied(m_con, peer_id, L"Invalid password");
1992                         return;
1993                 }
1994                 
1995                 // Add player to auth manager
1996                 if(m_authmanager.exists(playername) == false)
1997                 {
1998                         infostream<<"Server: adding player "<<playername
1999                                         <<" to auth manager"<<std::endl;
2000                         m_authmanager.add(playername);
2001                         m_authmanager.setPassword(playername, checkpwd);
2002                         m_authmanager.setPrivs(playername,
2003                                         stringToPrivs(g_settings->get("default_privs")));
2004                         m_authmanager.save();
2005                 }
2006                 
2007                 // Enforce user limit.
2008                 // Don't enforce for users that have some admin right
2009                 if(m_clients.size() >= g_settings->getU16("max_users") &&
2010                                 (m_authmanager.getPrivs(playername)
2011                                         & (PRIV_SERVER|PRIV_BAN|PRIV_PRIVS)) == 0 &&
2012                                 playername != g_settings->get("name"))
2013                 {
2014                         SendAccessDenied(m_con, peer_id, L"Too many users.");
2015                         return;
2016                 }
2017
2018                 // Get player
2019                 Player *player = emergePlayer(playername, password, peer_id);
2020
2021                 // If failed, cancel
2022                 if(player == NULL)
2023                 {
2024                         infostream<<"Server: peer_id="<<peer_id
2025                                         <<": failed to emerge player"<<std::endl;
2026                         return;
2027                 }
2028
2029                 /*
2030                         Answer with a TOCLIENT_INIT
2031                 */
2032                 {
2033                         SharedBuffer<u8> reply(2+1+6+8);
2034                         writeU16(&reply[0], TOCLIENT_INIT);
2035                         writeU8(&reply[2], deployed);
2036                         writeV3S16(&reply[2+1], floatToInt(player->getPosition()+v3f(0,BS/2,0), BS));
2037                         writeU64(&reply[2+1+6], m_env.getServerMap().getSeed());
2038                         
2039                         // Send as reliable
2040                         m_con.Send(peer_id, 0, reply, true);
2041                 }
2042
2043                 /*
2044                         Send complete position information
2045                 */
2046                 SendMovePlayer(player);
2047
2048                 return;
2049         }
2050
2051         if(command == TOSERVER_INIT2)
2052         {
2053                 infostream<<"Server: Got TOSERVER_INIT2 from "
2054                                 <<peer->id<<std::endl;
2055
2056
2057                 getClient(peer->id)->serialization_version
2058                                 = getClient(peer->id)->pending_serialization_version;
2059
2060                 /*
2061                         Send some initialization data
2062                 */
2063                 
2064                 // Send player info to all players
2065                 SendPlayerInfos();
2066
2067                 // Send inventory to player
2068                 UpdateCrafting(peer->id);
2069                 SendInventory(peer->id);
2070
2071                 // Send player items to all players
2072                 SendPlayerItems();
2073
2074                 Player *player = m_env.getPlayer(peer_id);
2075
2076                 // Send HP
2077                 SendPlayerHP(player);
2078                 
2079                 // Send time of day
2080                 {
2081                         SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
2082                                         m_env.getTimeOfDay());
2083                         m_con.Send(peer->id, 0, data, true);
2084                 }
2085                 
2086                 // Send information about server to player in chat
2087                 SendChatMessage(peer_id, getStatusString());
2088                 
2089                 // Send information about joining in chat
2090                 {
2091                         std::wstring name = L"unknown";
2092                         Player *player = m_env.getPlayer(peer_id);
2093                         if(player != NULL)
2094                                 name = narrow_to_wide(player->getName());
2095                         
2096                         std::wstring message;
2097                         message += L"*** ";
2098                         message += name;
2099                         message += L" joined game";
2100                         BroadcastChatMessage(message);
2101                 }
2102                 
2103                 // Warnings about protocol version can be issued here
2104                 if(getClient(peer->id)->net_proto_version < PROTOCOL_VERSION)
2105                 {
2106                         SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER");
2107                 }
2108
2109                 /*
2110                         Check HP, respawn if necessary
2111                 */
2112                 HandlePlayerHP(player, 0);
2113
2114                 /*
2115                         Print out action
2116                 */
2117                 {
2118                         std::ostringstream os(std::ios_base::binary);
2119                         for(core::map<u16, RemoteClient*>::Iterator
2120                                 i = m_clients.getIterator();
2121                                 i.atEnd() == false; i++)
2122                         {
2123                                 RemoteClient *client = i.getNode()->getValue();
2124                                 assert(client->peer_id == i.getNode()->getKey());
2125                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2126                                         continue;
2127                                 // Get player
2128                                 Player *player = m_env.getPlayer(client->peer_id);
2129                                 if(!player)
2130                                         continue;
2131                                 // Get name of player
2132                                 os<<player->getName()<<" ";
2133                         }
2134
2135                         actionstream<<player->getName()<<" joins game. List of players: "
2136                                         <<os.str()<<std::endl;
2137                 }
2138
2139                 return;
2140         }
2141
2142         if(peer_ser_ver == SER_FMT_VER_INVALID)
2143         {
2144                 infostream<<"Server::ProcessData(): Cancelling: Peer"
2145                                 " serialization format invalid or not initialized."
2146                                 " Skipping incoming command="<<command<<std::endl;
2147                 return;
2148         }
2149         
2150         Player *player = m_env.getPlayer(peer_id);
2151
2152         if(player == NULL){
2153                 infostream<<"Server::ProcessData(): Cancelling: "
2154                                 "No player for peer_id="<<peer_id
2155                                 <<std::endl;
2156                 return;
2157         }
2158         if(command == TOSERVER_PLAYERPOS)
2159         {
2160                 if(datasize < 2+12+12+4+4)
2161                         return;
2162         
2163                 u32 start = 0;
2164                 v3s32 ps = readV3S32(&data[start+2]);
2165                 v3s32 ss = readV3S32(&data[start+2+12]);
2166                 f32 pitch = (f32)readS32(&data[2+12+12]) / 100.0;
2167                 f32 yaw = (f32)readS32(&data[2+12+12+4]) / 100.0;
2168                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
2169                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
2170                 pitch = wrapDegrees(pitch);
2171                 yaw = wrapDegrees(yaw);
2172
2173                 player->setPosition(position);
2174                 player->setSpeed(speed);
2175                 player->setPitch(pitch);
2176                 player->setYaw(yaw);
2177                 
2178                 /*infostream<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
2179                                 <<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
2180                                 <<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
2181         }
2182         else if(command == TOSERVER_GOTBLOCKS)
2183         {
2184                 if(datasize < 2+1)
2185                         return;
2186                 
2187                 /*
2188                         [0] u16 command
2189                         [2] u8 count
2190                         [3] v3s16 pos_0
2191                         [3+6] v3s16 pos_1
2192                         ...
2193                 */
2194
2195                 u16 count = data[2];
2196                 for(u16 i=0; i<count; i++)
2197                 {
2198                         if((s16)datasize < 2+1+(i+1)*6)
2199                                 throw con::InvalidIncomingDataException
2200                                         ("GOTBLOCKS length is too short");
2201                         v3s16 p = readV3S16(&data[2+1+i*6]);
2202                         /*infostream<<"Server: GOTBLOCKS ("
2203                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2204                         RemoteClient *client = getClient(peer_id);
2205                         client->GotBlock(p);
2206                 }
2207         }
2208         else if(command == TOSERVER_DELETEDBLOCKS)
2209         {
2210                 if(datasize < 2+1)
2211                         return;
2212                 
2213                 /*
2214                         [0] u16 command
2215                         [2] u8 count
2216                         [3] v3s16 pos_0
2217                         [3+6] v3s16 pos_1
2218                         ...
2219                 */
2220
2221                 u16 count = data[2];
2222                 for(u16 i=0; i<count; i++)
2223                 {
2224                         if((s16)datasize < 2+1+(i+1)*6)
2225                                 throw con::InvalidIncomingDataException
2226                                         ("DELETEDBLOCKS length is too short");
2227                         v3s16 p = readV3S16(&data[2+1+i*6]);
2228                         /*infostream<<"Server: DELETEDBLOCKS ("
2229                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2230                         RemoteClient *client = getClient(peer_id);
2231                         client->SetBlockNotSent(p);
2232                 }
2233         }
2234         else if(command == TOSERVER_CLICK_OBJECT)
2235         {
2236                 infostream<<"Server: CLICK_OBJECT not supported anymore"<<std::endl;
2237                 return;
2238         }
2239         else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
2240         {
2241                 if(datasize < 7)
2242                         return;
2243
2244                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2245                         return;
2246
2247                 /*
2248                         length: 7
2249                         [0] u16 command
2250                         [2] u8 button (0=left, 1=right)
2251                         [3] u16 id
2252                         [5] u16 item
2253                 */
2254                 u8 button = readU8(&data[2]);
2255                 u16 id = readS16(&data[3]);
2256                 u16 item_i = readU16(&data[5]);
2257         
2258                 ServerActiveObject *obj = m_env.getActiveObject(id);
2259
2260                 if(obj == NULL)
2261                 {
2262                         infostream<<"Server: CLICK_ACTIVEOBJECT: object not found"
2263                                         <<std::endl;
2264                         return;
2265                 }
2266
2267                 // Skip if object has been removed
2268                 if(obj->m_removed)
2269                         return;
2270                 
2271                 //TODO: Check that object is reasonably close
2272                 
2273                 // Left click, pick object up (usually)
2274                 if(button == 0)
2275                 {
2276                         /*
2277                                 Try creating inventory item
2278                         */
2279                         InventoryItem *item = obj->createPickedUpItem();
2280                         
2281                         if(item)
2282                         {
2283                                 InventoryList *ilist = player->inventory.getList("main");
2284                                 if(ilist != NULL)
2285                                 {
2286                                         actionstream<<player->getName()<<" picked up "
2287                                                         <<item->getName()<<std::endl;
2288                                         if(g_settings->getBool("creative_mode") == false)
2289                                         {
2290                                                 // Skip if inventory has no free space
2291                                                 if(ilist->roomForItem(item) == false)
2292                                                 {
2293                                                         infostream<<"Player inventory has no free space"<<std::endl;
2294                                                         return;
2295                                                 }
2296
2297                                                 // Add to inventory and send inventory
2298                                                 ilist->addItem(item);
2299                                                 UpdateCrafting(player->peer_id);
2300                                                 SendInventory(player->peer_id);
2301                                         }
2302
2303                                         // Remove object from environment
2304                                         obj->m_removed = true;
2305                                 }
2306                         }
2307                         else
2308                         {
2309                                 /*
2310                                         Item cannot be picked up. Punch it instead.
2311                                 */
2312
2313                                 actionstream<<player->getName()<<" punches object "
2314                                                 <<obj->getId()<<std::endl;
2315
2316                                 ToolItem *titem = NULL;
2317                                 std::string toolname = "";
2318
2319                                 InventoryList *mlist = player->inventory.getList("main");
2320                                 if(mlist != NULL)
2321                                 {
2322                                         InventoryItem *item = mlist->getItem(item_i);
2323                                         if(item && (std::string)item->getName() == "ToolItem")
2324                                         {
2325                                                 titem = (ToolItem*)item;
2326                                                 toolname = titem->getToolName();
2327                                         }
2328                                 }
2329
2330                                 v3f playerpos = player->getPosition();
2331                                 v3f objpos = obj->getBasePosition();
2332                                 v3f dir = (objpos - playerpos).normalize();
2333                                 
2334                                 u16 wear = obj->punch(toolname, dir, player->getName());
2335                                 
2336                                 if(titem)
2337                                 {
2338                                         bool weared_out = titem->addWear(wear);
2339                                         if(weared_out)
2340                                                 mlist->deleteItem(item_i);
2341                                         SendInventory(player->peer_id);
2342                                 }
2343                         }
2344                 }
2345                 // Right click, do something with object
2346                 if(button == 1)
2347                 {
2348                         actionstream<<player->getName()<<" right clicks object "
2349                                         <<obj->getId()<<std::endl;
2350
2351                         // Track hp changes super-crappily
2352                         u16 oldhp = player->hp;
2353                         
2354                         // Do stuff
2355                         obj->rightClick(player);
2356                         
2357                         // Send back stuff
2358                         if(player->hp != oldhp)
2359                         {
2360                                 SendPlayerHP(player);
2361                         }
2362                 }
2363         }
2364         else if(command == TOSERVER_GROUND_ACTION)
2365         {
2366                 if(datasize < 17)
2367                         return;
2368                 /*
2369                         length: 17
2370                         [0] u16 command
2371                         [2] u8 action
2372                         [3] v3s16 nodepos_undersurface
2373                         [9] v3s16 nodepos_abovesurface
2374                         [15] u16 item
2375                         actions:
2376                         0: start digging
2377                         1: place block
2378                         2: stop digging (all parameters ignored)
2379                         3: digging completed
2380                 */
2381                 u8 action = readU8(&data[2]);
2382                 v3s16 p_under;
2383                 p_under.X = readS16(&data[3]);
2384                 p_under.Y = readS16(&data[5]);
2385                 p_under.Z = readS16(&data[7]);
2386                 v3s16 p_over;
2387                 p_over.X = readS16(&data[9]);
2388                 p_over.Y = readS16(&data[11]);
2389                 p_over.Z = readS16(&data[13]);
2390                 u16 item_i = readU16(&data[15]);
2391
2392                 //TODO: Check that target is reasonably close
2393                 
2394                 /*
2395                         0: start digging
2396                 */
2397                 if(action == 0)
2398                 {
2399                         /*
2400                                 NOTE: This can be used in the future to check if
2401                                 somebody is cheating, by checking the timing.
2402                         */
2403                 } // action == 0
2404
2405                 /*
2406                         2: stop digging
2407                 */
2408                 else if(action == 2)
2409                 {
2410 #if 0
2411                         RemoteClient *client = getClient(peer->id);
2412                         JMutexAutoLock digmutex(client->m_dig_mutex);
2413                         client->m_dig_tool_item = -1;
2414 #endif
2415                 }
2416
2417                 /*
2418                         3: Digging completed
2419                 */
2420                 else if(action == 3)
2421                 {
2422                         // Mandatory parameter; actually used for nothing
2423                         core::map<v3s16, MapBlock*> modified_blocks;
2424
2425                         content_t material = CONTENT_IGNORE;
2426                         u8 mineral = MINERAL_NONE;
2427
2428                         bool cannot_remove_node = false;
2429
2430                         try
2431                         {
2432                                 MapNode n = m_env.getMap().getNode(p_under);
2433                                 // Get mineral
2434                                 mineral = n.getMineral();
2435                                 // Get material at position
2436                                 material = n.getContent();
2437                                 // If not yet cancelled
2438                                 if(cannot_remove_node == false)
2439                                 {
2440                                         // If it's not diggable, do nothing
2441                                         if(content_diggable(material) == false)
2442                                         {
2443                                                 infostream<<"Server: Not finishing digging: "
2444                                                                 <<"Node not diggable"
2445                                                                 <<std::endl;
2446                                                 cannot_remove_node = true;
2447                                         }
2448                                 }
2449                                 // If not yet cancelled
2450                                 if(cannot_remove_node == false)
2451                                 {
2452                                         // Get node metadata
2453                                         NodeMetadata *meta = m_env.getMap().getNodeMetadata(p_under);
2454                                         if(meta && meta->nodeRemovalDisabled() == true)
2455                                         {
2456                                                 infostream<<"Server: Not finishing digging: "
2457                                                                 <<"Node metadata disables removal"
2458                                                                 <<std::endl;
2459                                                 cannot_remove_node = true;
2460                                         }
2461                                 }
2462                         }
2463                         catch(InvalidPositionException &e)
2464                         {
2465                                 infostream<<"Server: Not finishing digging: Node not found."
2466                                                 <<" Adding block to emerge queue."
2467                                                 <<std::endl;
2468                                 m_emerge_queue.addBlock(peer_id,
2469                                                 getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2470                                 cannot_remove_node = true;
2471                         }
2472
2473                         // Make sure the player is allowed to do it
2474                         if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2475                         {
2476                                 infostream<<"Player "<<player->getName()<<" cannot remove node"
2477                                                 <<" because privileges are "<<getPlayerPrivs(player)
2478                                                 <<std::endl;
2479                                 cannot_remove_node = true;
2480                         }
2481
2482                         /*
2483                                 If node can't be removed, set block to be re-sent to
2484                                 client and quit.
2485                         */
2486                         if(cannot_remove_node)
2487                         {
2488                                 infostream<<"Server: Not finishing digging."<<std::endl;
2489
2490                                 // Client probably has wrong data.
2491                                 // Set block not sent, so that client will get
2492                                 // a valid one.
2493                                 infostream<<"Client "<<peer_id<<" tried to dig "
2494                                                 <<"node; but node cannot be removed."
2495                                                 <<" setting MapBlock not sent."<<std::endl;
2496                                 RemoteClient *client = getClient(peer_id);
2497                                 v3s16 blockpos = getNodeBlockPos(p_under);
2498                                 client->SetBlockNotSent(blockpos);
2499                                         
2500                                 return;
2501                         }
2502                         
2503                         actionstream<<player->getName()<<" digs "<<PP(p_under)
2504                                         <<", gets material "<<(int)material<<", mineral "
2505                                         <<(int)mineral<<std::endl;
2506                         
2507                         /*
2508                                 Send the removal to all close-by players.
2509                                 - If other player is close, send REMOVENODE
2510                                 - Otherwise set blocks not sent
2511                         */
2512                         core::list<u16> far_players;
2513                         sendRemoveNode(p_under, peer_id, &far_players, 30);
2514                         
2515                         /*
2516                                 Update and send inventory
2517                         */
2518
2519                         if(g_settings->getBool("creative_mode") == false)
2520                         {
2521                                 /*
2522                                         Wear out tool
2523                                 */
2524                                 InventoryList *mlist = player->inventory.getList("main");
2525                                 if(mlist != NULL)
2526                                 {
2527                                         InventoryItem *item = mlist->getItem(item_i);
2528                                         if(item && (std::string)item->getName() == "ToolItem")
2529                                         {
2530                                                 ToolItem *titem = (ToolItem*)item;
2531                                                 std::string toolname = titem->getToolName();
2532
2533                                                 // Get digging properties for material and tool
2534                                                 DiggingProperties prop =
2535                                                                 getDiggingProperties(material, toolname);
2536
2537                                                 if(prop.diggable == false)
2538                                                 {
2539                                                         infostream<<"Server: WARNING: Player digged"
2540                                                                         <<" with impossible material + tool"
2541                                                                         <<" combination"<<std::endl;
2542                                                 }
2543                                                 
2544                                                 bool weared_out = titem->addWear(prop.wear);
2545
2546                                                 if(weared_out)
2547                                                 {
2548                                                         mlist->deleteItem(item_i);
2549                                                 }
2550                                         }
2551                                 }
2552
2553                                 /*
2554                                         Add dug item to inventory
2555                                 */
2556
2557                                 InventoryItem *item = NULL;
2558
2559                                 if(mineral != MINERAL_NONE)
2560                                         item = getDiggedMineralItem(mineral);
2561                                 
2562                                 // If not mineral
2563                                 if(item == NULL)
2564                                 {
2565                                         std::string &dug_s = content_features(material).dug_item;
2566                                         if(dug_s != "")
2567                                         {
2568                                                 std::istringstream is(dug_s, std::ios::binary);
2569                                                 item = InventoryItem::deSerialize(is);
2570                                         }
2571                                 }
2572                                 
2573                                 if(item != NULL)
2574                                 {
2575                                         // Add a item to inventory
2576                                         player->inventory.addItem("main", item);
2577
2578                                         // Send inventory
2579                                         UpdateCrafting(player->peer_id);
2580                                         SendInventory(player->peer_id);
2581                                 }
2582
2583                                 item = NULL;
2584
2585                                 if(mineral != MINERAL_NONE)
2586                                   item = getDiggedMineralItem(mineral);
2587                         
2588                                 // If not mineral
2589                                 if(item == NULL)
2590                                 {
2591                                         std::string &extra_dug_s = content_features(material).extra_dug_item;
2592                                         s32 extra_rarity = content_features(material).extra_dug_item_rarity;
2593                                         if(extra_dug_s != "" && extra_rarity != 0
2594                                            && myrand() % extra_rarity == 0)
2595                                         {
2596                                                 std::istringstream is(extra_dug_s, std::ios::binary);
2597                                                 item = InventoryItem::deSerialize(is);
2598                                         }
2599                                 }
2600                         
2601                                 if(item != NULL)
2602                                 {
2603                                         // Add a item to inventory
2604                                         player->inventory.addItem("main", item);
2605
2606                                         // Send inventory
2607                                         UpdateCrafting(player->peer_id);
2608                                         SendInventory(player->peer_id);
2609                                 }
2610                         }
2611
2612                         /*
2613                                 Remove the node
2614                                 (this takes some time so it is done after the quick stuff)
2615                         */
2616                         {
2617                                 MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2618
2619                                 m_env.getMap().removeNodeAndUpdate(p_under, modified_blocks);
2620                         }
2621                         /*
2622                                 Set blocks not sent to far players
2623                         */
2624                         for(core::list<u16>::Iterator
2625                                         i = far_players.begin();
2626                                         i != far_players.end(); i++)
2627                         {
2628                                 u16 peer_id = *i;
2629                                 RemoteClient *client = getClient(peer_id);
2630                                 if(client==NULL)
2631                                         continue;
2632                                 client->SetBlocksNotSent(modified_blocks);
2633                         }
2634                 }
2635                 
2636                 /*
2637                         1: place block
2638                 */
2639                 else if(action == 1)
2640                 {
2641
2642                         InventoryList *ilist = player->inventory.getList("main");
2643                         if(ilist == NULL)
2644                                 return;
2645
2646                         // Get item
2647                         InventoryItem *item = ilist->getItem(item_i);
2648                         
2649                         // If there is no item, it is not possible to add it anywhere
2650                         if(item == NULL)
2651                                 return;
2652                         
2653                         /*
2654                                 Handle material items
2655                         */
2656                         if(std::string("MaterialItem") == item->getName())
2657                         {
2658                                 try{
2659                                         // Don't add a node if this is not a free space
2660                                         MapNode n2 = m_env.getMap().getNode(p_over);
2661                                         bool no_enough_privs =
2662                                                         ((getPlayerPrivs(player) & PRIV_BUILD)==0);
2663                                         if(no_enough_privs)
2664                                                 infostream<<"Player "<<player->getName()<<" cannot add node"
2665                                                         <<" because privileges are "<<getPlayerPrivs(player)
2666                                                         <<std::endl;
2667
2668                                         if(content_features(n2).buildable_to == false
2669                                                 || no_enough_privs)
2670                                         {
2671                                                 // Client probably has wrong data.
2672                                                 // Set block not sent, so that client will get
2673                                                 // a valid one.
2674                                                 infostream<<"Client "<<peer_id<<" tried to place"
2675                                                                 <<" node in invalid position; setting"
2676                                                                 <<" MapBlock not sent."<<std::endl;
2677                                                 RemoteClient *client = getClient(peer_id);
2678                                                 v3s16 blockpos = getNodeBlockPos(p_over);
2679                                                 client->SetBlockNotSent(blockpos);
2680                                                 return;
2681                                         }
2682                                 }
2683                                 catch(InvalidPositionException &e)
2684                                 {
2685                                         infostream<<"Server: Ignoring ADDNODE: Node not found"
2686                                                         <<" Adding block to emerge queue."
2687                                                         <<std::endl;
2688                                         m_emerge_queue.addBlock(peer_id,
2689                                                         getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2690                                         return;
2691                                 }
2692
2693                                 // Reset build time counter
2694                                 getClient(peer->id)->m_time_from_building = 0.0;
2695                                 
2696                                 // Create node data
2697                                 MaterialItem *mitem = (MaterialItem*)item;
2698                                 MapNode n;
2699                                 n.setContent(mitem->getMaterial());
2700
2701                                 actionstream<<player->getName()<<" places material "
2702                                                 <<(int)mitem->getMaterial()
2703                                                 <<" at "<<PP(p_under)<<std::endl;
2704                         
2705                                 // Calculate direction for wall mounted stuff
2706                                 if(content_features(n).wall_mounted)
2707                                         n.param2 = packDir(p_under - p_over);
2708
2709                                 // Calculate the direction for furnaces and chests and stuff
2710                                 if(content_features(n).param_type == CPT_FACEDIR_SIMPLE)
2711                                 {
2712                                         v3f playerpos = player->getPosition();
2713                                         v3f blockpos = intToFloat(p_over, BS) - playerpos;
2714                                         blockpos = blockpos.normalize();
2715                                         n.param1 = 0;
2716                                         if (fabs(blockpos.X) > fabs(blockpos.Z)) {
2717                                                 if (blockpos.X < 0)
2718                                                         n.param1 = 3;
2719                                                 else
2720                                                         n.param1 = 1;
2721                                         } else {
2722                                                 if (blockpos.Z < 0)
2723                                                         n.param1 = 2;
2724                                                 else
2725                                                         n.param1 = 0;
2726                                         }
2727                                 }
2728
2729                                 /*
2730                                         Send to all close-by players
2731                                 */
2732                                 core::list<u16> far_players;
2733                                 sendAddNode(p_over, n, 0, &far_players, 30);
2734                                 
2735                                 /*
2736                                         Handle inventory
2737                                 */
2738                                 InventoryList *ilist = player->inventory.getList("main");
2739                                 if(g_settings->getBool("creative_mode") == false && ilist)
2740                                 {
2741                                         // Remove from inventory and send inventory
2742                                         if(mitem->getCount() == 1)
2743                                                 ilist->deleteItem(item_i);
2744                                         else
2745                                                 mitem->remove(1);
2746                                         // Send inventory
2747                                         UpdateCrafting(peer_id);
2748                                         SendInventory(peer_id);
2749                                 }
2750                                 
2751                                 /*
2752                                         Add node.
2753
2754                                         This takes some time so it is done after the quick stuff
2755                                 */
2756                                 core::map<v3s16, MapBlock*> modified_blocks;
2757                                 {
2758                                         MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2759
2760                                         std::string p_name = std::string(player->getName());
2761                                         m_env.getMap().addNodeAndUpdate(p_over, n, modified_blocks, p_name);
2762                                 }
2763                                 /*
2764                                         Set blocks not sent to far players
2765                                 */
2766                                 for(core::list<u16>::Iterator
2767                                                 i = far_players.begin();
2768                                                 i != far_players.end(); i++)
2769                                 {
2770                                         u16 peer_id = *i;
2771                                         RemoteClient *client = getClient(peer_id);
2772                                         if(client==NULL)
2773                                                 continue;
2774                                         client->SetBlocksNotSent(modified_blocks);
2775                                 }
2776
2777                                 /*
2778                                         Calculate special events
2779                                 */
2780                                 
2781                                 /*if(n.d == CONTENT_MESE)
2782                                 {
2783                                         u32 count = 0;
2784                                         for(s16 z=-1; z<=1; z++)
2785                                         for(s16 y=-1; y<=1; y++)
2786                                         for(s16 x=-1; x<=1; x++)
2787                                         {
2788                                                 
2789                                         }
2790                                 }*/
2791                         }
2792                         /*
2793                                 Place other item (not a block)
2794                         */
2795                         else
2796                         {
2797                                 v3s16 blockpos = getNodeBlockPos(p_over);
2798                                 
2799                                 /*
2800                                         Check that the block is loaded so that the item
2801                                         can properly be added to the static list too
2802                                 */
2803                                 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(blockpos);
2804                                 if(block==NULL)
2805                                 {
2806                                         infostream<<"Error while placing object: "
2807                                                         "block not found"<<std::endl;
2808                                         return;
2809                                 }
2810
2811                                 /*
2812                                         If in creative mode, item dropping is disabled unless
2813                                         player has build privileges
2814                                 */
2815                                 if(g_settings->getBool("creative_mode") &&
2816                                         (getPlayerPrivs(player) & PRIV_BUILD) == 0)
2817                                 {
2818                                         infostream<<"Not allowing player to drop item: "
2819                                                         "creative mode and no build privs"<<std::endl;
2820                                         return;
2821                                 }
2822
2823                                 // Calculate a position for it
2824                                 v3f pos = intToFloat(p_over, BS);
2825                                 //pos.Y -= BS*0.45;
2826                                 pos.Y -= BS*0.25; // let it drop a bit
2827                                 // Randomize a bit
2828                                 pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2829                                 pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2830
2831                                 /*
2832                                         Create the object
2833                                 */
2834                                 ServerActiveObject *obj = item->createSAO(&m_env, 0, pos);
2835
2836                                 if(obj == NULL)
2837                                 {
2838                                         infostream<<"WARNING: item resulted in NULL object, "
2839                                                         <<"not placing onto map"
2840                                                         <<std::endl;
2841                                 }
2842                                 else
2843                                 {
2844                                         actionstream<<player->getName()<<" places "<<item->getName()
2845                                                         <<" at "<<PP(p_over)<<std::endl;
2846                                 
2847                                         // Add the object to the environment
2848                                         m_env.addActiveObject(obj);
2849                                         
2850                                         infostream<<"Placed object"<<std::endl;
2851
2852                                         if(g_settings->getBool("creative_mode") == false)
2853                                         {
2854                                                 // Delete the right amount of items from the slot
2855                                                 u16 dropcount = item->getDropCount();
2856                                                 
2857                                                 // Delete item if all gone
2858                                                 if(item->getCount() <= dropcount)
2859                                                 {
2860                                                         if(item->getCount() < dropcount)
2861                                                                 infostream<<"WARNING: Server: dropped more items"
2862                                                                                 <<" than the slot contains"<<std::endl;
2863                                                         
2864                                                         InventoryList *ilist = player->inventory.getList("main");
2865                                                         if(ilist)
2866                                                                 // Remove from inventory and send inventory
2867                                                                 ilist->deleteItem(item_i);
2868                                                 }
2869                                                 // Else decrement it
2870                                                 else
2871                                                         item->remove(dropcount);
2872                                                 
2873                                                 // Send inventory
2874                                                 UpdateCrafting(peer_id);
2875                                                 SendInventory(peer_id);
2876                                         }
2877                                 }
2878                         }
2879
2880                 } // action == 1
2881
2882                 /*
2883                         Catch invalid actions
2884                 */
2885                 else
2886                 {
2887                         infostream<<"WARNING: Server: Invalid action "
2888                                         <<action<<std::endl;
2889                 }
2890         }
2891 #if 0
2892         else if(command == TOSERVER_RELEASE)
2893         {
2894                 if(datasize < 3)
2895                         return;
2896                 /*
2897                         length: 3
2898                         [0] u16 command
2899                         [2] u8 button
2900                 */
2901                 infostream<<"TOSERVER_RELEASE ignored"<<std::endl;
2902         }
2903 #endif
2904         else if(command == TOSERVER_SIGNTEXT)
2905         {
2906                 infostream<<"Server: TOSERVER_SIGNTEXT not supported anymore"
2907                                 <<std::endl;
2908                 return;
2909         }
2910         else if(command == TOSERVER_SIGNNODETEXT)
2911         {
2912                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2913                         return;
2914                 /*
2915                         u16 command
2916                         v3s16 p
2917                         u16 textlen
2918                         textdata
2919                 */
2920                 std::string datastring((char*)&data[2], datasize-2);
2921                 std::istringstream is(datastring, std::ios_base::binary);
2922                 u8 buf[6];
2923                 // Read stuff
2924                 is.read((char*)buf, 6);
2925                 v3s16 p = readV3S16(buf);
2926                 is.read((char*)buf, 2);
2927                 u16 textlen = readU16(buf);
2928                 std::string text;
2929                 for(u16 i=0; i<textlen; i++)
2930                 {
2931                         is.read((char*)buf, 1);
2932                         text += (char)buf[0];
2933                 }
2934
2935                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
2936                 if(!meta)
2937                         return;
2938                 if(meta->typeId() != CONTENT_SIGN_WALL)
2939                         return;
2940                 SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
2941                 signmeta->setText(text);
2942                 
2943                 actionstream<<player->getName()<<" writes \""<<text<<"\" to sign "
2944                                 <<" at "<<PP(p)<<std::endl;
2945                                 
2946                 v3s16 blockpos = getNodeBlockPos(p);
2947                 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(blockpos);
2948                 if(block)
2949                 {
2950                         block->setChangedFlag();
2951                 }
2952
2953                 for(core::map<u16, RemoteClient*>::Iterator
2954                         i = m_clients.getIterator();
2955                         i.atEnd()==false; i++)
2956                 {
2957                         RemoteClient *client = i.getNode()->getValue();
2958                         client->SetBlockNotSent(blockpos);
2959                 }
2960         }
2961         else if(command == TOSERVER_INVENTORY_ACTION)
2962         {
2963                 /*// Ignore inventory changes if in creative mode
2964                 if(g_settings->getBool("creative_mode") == true)
2965                 {
2966                         infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
2967                                         <<std::endl;
2968                         return;
2969                 }*/
2970                 // Strip command and create a stream
2971                 std::string datastring((char*)&data[2], datasize-2);
2972                 infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
2973                 std::istringstream is(datastring, std::ios_base::binary);
2974                 // Create an action
2975                 InventoryAction *a = InventoryAction::deSerialize(is);
2976                 if(a != NULL)
2977                 {
2978                         // Create context
2979                         InventoryContext c;
2980                         c.current_player = player;
2981
2982                         /*
2983                                 Handle craftresult specially if not in creative mode
2984                         */
2985                         bool disable_action = false;
2986                         if(a->getType() == IACTION_MOVE
2987                                         && g_settings->getBool("creative_mode") == false)
2988                         {
2989                                 IMoveAction *ma = (IMoveAction*)a;
2990                                 if(ma->to_inv == "current_player" &&
2991                                                 ma->from_inv == "current_player")
2992                                 {
2993                                         InventoryList *rlist = player->inventory.getList("craftresult");
2994                                         assert(rlist);
2995                                         InventoryList *clist = player->inventory.getList("craft");
2996                                         assert(clist);
2997                                         InventoryList *mlist = player->inventory.getList("main");
2998                                         assert(mlist);
2999                                         /*
3000                                                 Craftresult is no longer preview if something
3001                                                 is moved into it
3002                                         */
3003                                         if(ma->to_list == "craftresult"
3004                                                         && ma->from_list != "craftresult")
3005                                         {
3006                                                 // If it currently is a preview, remove
3007                                                 // its contents
3008                                                 if(player->craftresult_is_preview)
3009                                                 {
3010                                                         rlist->deleteItem(0);
3011                                                 }
3012                                                 player->craftresult_is_preview = false;
3013                                         }
3014                                         /*
3015                                                 Crafting takes place if this condition is true.
3016                                         */
3017                                         if(player->craftresult_is_preview &&
3018                                                         ma->from_list == "craftresult")
3019                                         {
3020                                                 player->craftresult_is_preview = false;
3021                                                 clist->decrementMaterials(1);
3022                                                 
3023                                                 /* Print out action */
3024                                                 InventoryList *list =
3025                                                                 player->inventory.getList("craftresult");
3026                                                 assert(list);
3027                                                 InventoryItem *item = list->getItem(0);
3028                                                 std::string itemname = "NULL";
3029                                                 if(item)
3030                                                         itemname = item->getName();
3031                                                 actionstream<<player->getName()<<" crafts "
3032                                                                 <<itemname<<std::endl;
3033                                         }
3034                                         /*
3035                                                 If the craftresult is placed on itself, move it to
3036                                                 main inventory instead of doing the action
3037                                         */
3038                                         if(ma->to_list == "craftresult"
3039                                                         && ma->from_list == "craftresult")
3040                                         {
3041                                                 disable_action = true;
3042                                                 
3043                                                 InventoryItem *item1 = rlist->changeItem(0, NULL);
3044                                                 mlist->addItem(item1);
3045                                         }
3046                                 }
3047                                 // Disallow moving items if not allowed to build
3048                                 else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
3049                                 {
3050                                         return;
3051                                 }
3052                                 // if it's a locking chest, only allow the owner or server admins to move items
3053                                 else if (ma->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3054                                 {
3055                                         Strfnd fn(ma->from_inv);
3056                                         std::string id0 = fn.next(":");
3057                                         if(id0 == "nodemeta")
3058                                         {
3059                                                 v3s16 p;
3060                                                 p.X = stoi(fn.next(","));
3061                                                 p.Y = stoi(fn.next(","));
3062                                                 p.Z = stoi(fn.next(","));
3063                                                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
3064                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3065                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3066                                                         if (lcm->getOwner() != player->getName())
3067                                                                 return;
3068                                                 }
3069                                         }
3070                                 }
3071                                 else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3072                                 {
3073                                         Strfnd fn(ma->to_inv);
3074                                         std::string id0 = fn.next(":");
3075                                         if(id0 == "nodemeta")
3076                                         {
3077                                                 v3s16 p;
3078                                                 p.X = stoi(fn.next(","));
3079                                                 p.Y = stoi(fn.next(","));
3080                                                 p.Z = stoi(fn.next(","));
3081                                                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
3082                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3083                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3084                                                         if (lcm->getOwner() != player->getName())
3085                                                                 return;
3086                                                 }
3087                                         }
3088                                 }
3089                         }
3090                         
3091                         if(disable_action == false)
3092                         {
3093                                 // Feed action to player inventory
3094                                 a->apply(&c, this);
3095                                 // Eat the action
3096                                 delete a;
3097                         }
3098                         else
3099                         {
3100                                 // Send inventory
3101                                 UpdateCrafting(player->peer_id);
3102                                 SendInventory(player->peer_id);
3103                         }
3104                 }
3105                 else
3106                 {
3107                         infostream<<"TOSERVER_INVENTORY_ACTION: "
3108                                         <<"InventoryAction::deSerialize() returned NULL"
3109                                         <<std::endl;
3110                 }
3111         }
3112         else if(command == TOSERVER_CHAT_MESSAGE)
3113         {
3114                 /*
3115                         u16 command
3116                         u16 length
3117                         wstring message
3118                 */
3119                 u8 buf[6];
3120                 std::string datastring((char*)&data[2], datasize-2);
3121                 std::istringstream is(datastring, std::ios_base::binary);
3122                 
3123                 // Read stuff
3124                 is.read((char*)buf, 2);
3125                 u16 len = readU16(buf);
3126                 
3127                 std::wstring message;
3128                 for(u16 i=0; i<len; i++)
3129                 {
3130                         is.read((char*)buf, 2);
3131                         message += (wchar_t)readU16(buf);
3132                 }
3133
3134                 // Get player name of this client
3135                 std::wstring name = narrow_to_wide(player->getName());
3136                 
3137                 // Line to send to players
3138                 std::wstring line;
3139                 // Whether to send to the player that sent the line
3140                 bool send_to_sender = false;
3141                 // Whether to send to other players
3142                 bool send_to_others = false;
3143                 
3144                 // Local player gets all privileges regardless of
3145                 // what's set on their account.
3146                 u64 privs = getPlayerPrivs(player);
3147
3148                 // Parse commands
3149                 if(message[0] == L'/')
3150                 {
3151                         size_t strip_size = 1;
3152                         if (message[1] == L'#') // support old-style commans
3153                                 ++strip_size;
3154                         message = message.substr(strip_size);
3155
3156                         WStrfnd f1(message);
3157                         f1.next(L" "); // Skip over /#whatever
3158                         std::wstring paramstring = f1.next(L"");
3159
3160                         ServerCommandContext *ctx = new ServerCommandContext(
3161                                 str_split(message, L' '),
3162                                 paramstring,
3163                                 this,
3164                                 &m_env,
3165                                 player,
3166                                 privs);
3167
3168                         std::wstring reply(processServerCommand(ctx));
3169                         send_to_sender = ctx->flags & SEND_TO_SENDER;
3170                         send_to_others = ctx->flags & SEND_TO_OTHERS;
3171
3172                         if (ctx->flags & SEND_NO_PREFIX)
3173                                 line += reply;
3174                         else
3175                                 line += L"Server: " + reply;
3176
3177                         delete ctx;
3178
3179                 }
3180                 else
3181                 {
3182                         if(privs & PRIV_SHOUT)
3183                         {
3184                                 line += L"<";
3185                                 line += name;
3186                                 line += L"> ";
3187                                 line += message;
3188                                 send_to_others = true;
3189                         }
3190                         else
3191                         {
3192                                 line += L"Server: You are not allowed to shout";
3193                                 send_to_sender = true;
3194                         }
3195                 }
3196                 
3197                 if(line != L"")
3198                 {
3199                         if(send_to_others)
3200                                 actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
3201
3202                         /*
3203                                 Send the message to clients
3204                         */
3205                         for(core::map<u16, RemoteClient*>::Iterator
3206                                 i = m_clients.getIterator();
3207                                 i.atEnd() == false; i++)
3208                         {
3209                                 // Get client and check that it is valid
3210                                 RemoteClient *client = i.getNode()->getValue();
3211                                 assert(client->peer_id == i.getNode()->getKey());
3212                                 if(client->serialization_version == SER_FMT_VER_INVALID)
3213                                         continue;
3214
3215                                 // Filter recipient
3216                                 bool sender_selected = (peer_id == client->peer_id);
3217                                 if(sender_selected == true && send_to_sender == false)
3218                                         continue;
3219                                 if(sender_selected == false && send_to_others == false)
3220                                         continue;
3221
3222                                 SendChatMessage(client->peer_id, line);
3223                         }
3224                 }
3225         }
3226         else if(command == TOSERVER_DAMAGE)
3227         {
3228                 std::string datastring((char*)&data[2], datasize-2);
3229                 std::istringstream is(datastring, std::ios_base::binary);
3230                 u8 damage = readU8(is);
3231
3232                 if(g_settings->getBool("enable_damage"))
3233                 {
3234                         actionstream<<player->getName()<<" damaged by "
3235                                         <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
3236                                         <<std::endl;
3237                                 
3238                         HandlePlayerHP(player, damage);
3239                 }
3240                 else
3241                 {
3242                         SendPlayerHP(player);
3243                 }
3244         }
3245         else if(command == TOSERVER_PASSWORD)
3246         {
3247                 /*
3248                         [0] u16 TOSERVER_PASSWORD
3249                         [2] u8[28] old password
3250                         [30] u8[28] new password
3251                 */
3252
3253                 if(datasize != 2+PASSWORD_SIZE*2)
3254                         return;
3255                 /*char password[PASSWORD_SIZE];
3256                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3257                         password[i] = data[2+i];
3258                 password[PASSWORD_SIZE-1] = 0;*/
3259                 std::string oldpwd;
3260                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3261                 {
3262                         char c = data[2+i];
3263                         if(c == 0)
3264                                 break;
3265                         oldpwd += c;
3266                 }
3267                 std::string newpwd;
3268                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3269                 {
3270                         char c = data[2+PASSWORD_SIZE+i];
3271                         if(c == 0)
3272                                 break;
3273                         newpwd += c;
3274                 }
3275
3276                 infostream<<"Server: Client requests a password change from "
3277                                 <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
3278
3279                 std::string playername = player->getName();
3280
3281                 if(m_authmanager.exists(playername) == false)
3282                 {
3283                         infostream<<"Server: playername not found in authmanager"<<std::endl;
3284                         // Wrong old password supplied!!
3285                         SendChatMessage(peer_id, L"playername not found in authmanager");
3286                         return;
3287                 }
3288
3289                 std::string checkpwd = m_authmanager.getPassword(playername);
3290
3291                 if(oldpwd != checkpwd)
3292                 {
3293                         infostream<<"Server: invalid old password"<<std::endl;
3294                         // Wrong old password supplied!!
3295                         SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
3296                         return;
3297                 }
3298
3299                 actionstream<<player->getName()<<" changes password"<<std::endl;
3300
3301                 m_authmanager.setPassword(playername, newpwd);
3302                 
3303                 infostream<<"Server: password change successful for "<<playername
3304                                 <<std::endl;
3305                 SendChatMessage(peer_id, L"Password change successful");
3306         }
3307         else if(command == TOSERVER_PLAYERITEM)
3308         {
3309                 if (datasize < 2+2)
3310                         return;
3311
3312                 u16 item = readU16(&data[2]);
3313                 player->wieldItem(item);
3314                 SendWieldedItem(player);
3315         }
3316         else if(command == TOSERVER_RESPAWN)
3317         {
3318                 if(player->hp != 0)
3319                         return;
3320                 
3321                 RespawnPlayer(player);
3322                 
3323                 actionstream<<player->getName()<<" respawns at "
3324                                 <<PP(player->getPosition()/BS)<<std::endl;
3325         }
3326         else
3327         {
3328                 infostream<<"Server::ProcessData(): Ignoring "
3329                                 "unknown command "<<command<<std::endl;
3330         }
3331         
3332         } //try
3333         catch(SendFailedException &e)
3334         {
3335                 errorstream<<"Server::ProcessData(): SendFailedException: "
3336                                 <<"what="<<e.what()
3337                                 <<std::endl;
3338         }
3339 }
3340
3341 void Server::onMapEditEvent(MapEditEvent *event)
3342 {
3343         //infostream<<"Server::onMapEditEvent()"<<std::endl;
3344         if(m_ignore_map_edit_events)
3345                 return;
3346         MapEditEvent *e = event->clone();
3347         m_unsent_map_edit_queue.push_back(e);
3348 }
3349
3350 Inventory* Server::getInventory(InventoryContext *c, std::string id)
3351 {
3352         if(id == "current_player")
3353         {
3354                 assert(c->current_player);
3355                 return &(c->current_player->inventory);
3356         }
3357         
3358         Strfnd fn(id);
3359         std::string id0 = fn.next(":");
3360
3361         if(id0 == "nodemeta")
3362         {
3363                 v3s16 p;
3364                 p.X = stoi(fn.next(","));
3365                 p.Y = stoi(fn.next(","));
3366                 p.Z = stoi(fn.next(","));
3367                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
3368                 if(meta)
3369                         return meta->getInventory();
3370                 infostream<<"nodemeta at ("<<p.X<<","<<p.Y<<","<<p.Z<<"): "
3371                                 <<"no metadata found"<<std::endl;
3372                 return NULL;
3373         }
3374
3375         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3376         return NULL;
3377 }
3378 void Server::inventoryModified(InventoryContext *c, std::string id)
3379 {
3380         if(id == "current_player")
3381         {
3382                 assert(c->current_player);
3383                 // Send inventory
3384                 UpdateCrafting(c->current_player->peer_id);
3385                 SendInventory(c->current_player->peer_id);
3386                 return;
3387         }
3388         
3389         Strfnd fn(id);
3390         std::string id0 = fn.next(":");
3391
3392         if(id0 == "nodemeta")
3393         {
3394                 v3s16 p;
3395                 p.X = stoi(fn.next(","));
3396                 p.Y = stoi(fn.next(","));
3397                 p.Z = stoi(fn.next(","));
3398                 v3s16 blockpos = getNodeBlockPos(p);
3399
3400                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
3401                 if(meta)
3402                         meta->inventoryModified();
3403
3404                 for(core::map<u16, RemoteClient*>::Iterator
3405                         i = m_clients.getIterator();
3406                         i.atEnd()==false; i++)
3407                 {
3408                         RemoteClient *client = i.getNode()->getValue();
3409                         client->SetBlockNotSent(blockpos);
3410                 }
3411
3412                 return;
3413         }
3414
3415         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3416 }
3417
3418 core::list<PlayerInfo> Server::getPlayerInfo()
3419 {
3420         DSTACK(__FUNCTION_NAME);
3421         JMutexAutoLock envlock(m_env_mutex);
3422         JMutexAutoLock conlock(m_con_mutex);
3423         
3424         core::list<PlayerInfo> list;
3425
3426         core::list<Player*> players = m_env.getPlayers();
3427         
3428         core::list<Player*>::Iterator i;
3429         for(i = players.begin();
3430                         i != players.end(); i++)
3431         {
3432                 PlayerInfo info;
3433
3434                 Player *player = *i;
3435
3436                 try{
3437                         con::Peer *peer = m_con.GetPeer(player->peer_id);
3438                         // Copy info from peer to info struct
3439                         info.id = peer->id;
3440                         info.address = peer->address;
3441                         info.avg_rtt = peer->avg_rtt;
3442                 }
3443                 catch(con::PeerNotFoundException &e)
3444                 {
3445                         // Set dummy peer info
3446                         info.id = 0;
3447                         info.address = Address(0,0,0,0,0);
3448                         info.avg_rtt = 0.0;
3449                 }
3450
3451                 snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName());
3452                 info.position = player->getPosition();
3453
3454                 list.push_back(info);
3455         }
3456
3457         return list;
3458 }
3459
3460
3461 void Server::peerAdded(con::Peer *peer)
3462 {
3463         DSTACK(__FUNCTION_NAME);
3464         infostream<<"Server::peerAdded(): peer->id="
3465                         <<peer->id<<std::endl;
3466         
3467         PeerChange c;
3468         c.type = PEER_ADDED;
3469         c.peer_id = peer->id;
3470         c.timeout = false;
3471         m_peer_change_queue.push_back(c);
3472 }
3473
3474 void Server::deletingPeer(con::Peer *peer, bool timeout)
3475 {
3476         DSTACK(__FUNCTION_NAME);
3477         infostream<<"Server::deletingPeer(): peer->id="
3478                         <<peer->id<<", timeout="<<timeout<<std::endl;
3479         
3480         PeerChange c;
3481         c.type = PEER_REMOVED;
3482         c.peer_id = peer->id;
3483         c.timeout = timeout;
3484         m_peer_change_queue.push_back(c);
3485 }
3486
3487 /*
3488         Static send methods
3489 */
3490
3491 void Server::SendHP(con::Connection &con, u16 peer_id, u8 hp)
3492 {
3493         DSTACK(__FUNCTION_NAME);
3494         std::ostringstream os(std::ios_base::binary);
3495
3496         writeU16(os, TOCLIENT_HP);
3497         writeU8(os, hp);
3498
3499         // Make data buffer
3500         std::string s = os.str();
3501         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3502         // Send as reliable
3503         con.Send(peer_id, 0, data, true);
3504 }
3505
3506 void Server::SendAccessDenied(con::Connection &con, u16 peer_id,
3507                 const std::wstring &reason)
3508 {
3509         DSTACK(__FUNCTION_NAME);
3510         std::ostringstream os(std::ios_base::binary);
3511
3512         writeU16(os, TOCLIENT_ACCESS_DENIED);
3513         os<<serializeWideString(reason);
3514
3515         // Make data buffer
3516         std::string s = os.str();
3517         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3518         // Send as reliable
3519         con.Send(peer_id, 0, data, true);
3520 }
3521
3522 void Server::SendDeathscreen(con::Connection &con, u16 peer_id,
3523                 bool set_camera_point_target, v3f camera_point_target)
3524 {
3525         DSTACK(__FUNCTION_NAME);
3526         std::ostringstream os(std::ios_base::binary);
3527
3528         writeU16(os, TOCLIENT_DEATHSCREEN);
3529         writeU8(os, set_camera_point_target);
3530         writeV3F1000(os, camera_point_target);
3531
3532         // Make data buffer
3533         std::string s = os.str();
3534         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3535         // Send as reliable
3536         con.Send(peer_id, 0, data, true);
3537 }
3538
3539 /*
3540         Non-static send methods
3541 */
3542
3543 void Server::SendObjectData(float dtime)
3544 {
3545         DSTACK(__FUNCTION_NAME);
3546
3547         core::map<v3s16, bool> stepped_blocks;
3548         
3549         for(core::map<u16, RemoteClient*>::Iterator
3550                 i = m_clients.getIterator();
3551                 i.atEnd() == false; i++)
3552         {
3553                 u16 peer_id = i.getNode()->getKey();
3554                 RemoteClient *client = i.getNode()->getValue();
3555                 assert(client->peer_id == peer_id);
3556                 
3557                 if(client->serialization_version == SER_FMT_VER_INVALID)
3558                         continue;
3559                 
3560                 client->SendObjectData(this, dtime, stepped_blocks);
3561         }
3562 }
3563
3564 void Server::SendPlayerInfos()
3565 {
3566         DSTACK(__FUNCTION_NAME);
3567
3568         //JMutexAutoLock envlock(m_env_mutex);
3569         
3570         // Get connected players
3571         core::list<Player*> players = m_env.getPlayers(true);
3572         
3573         u32 player_count = players.getSize();
3574         u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
3575
3576         SharedBuffer<u8> data(datasize);
3577         writeU16(&data[0], TOCLIENT_PLAYERINFO);
3578         
3579         u32 start = 2;
3580         core::list<Player*>::Iterator i;
3581         for(i = players.begin();
3582                         i != players.end(); i++)
3583         {
3584                 Player *player = *i;
3585
3586                 /*infostream<<"Server sending player info for player with "
3587                                 "peer_id="<<player->peer_id<<std::endl;*/
3588                 
3589                 writeU16(&data[start], player->peer_id);
3590                 memset((char*)&data[start+2], 0, PLAYERNAME_SIZE);
3591                 snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName());
3592                 start += 2+PLAYERNAME_SIZE;
3593         }
3594
3595         //JMutexAutoLock conlock(m_con_mutex);
3596
3597         // Send as reliable
3598         m_con.SendToAll(0, data, true);
3599 }
3600
3601 void Server::SendInventory(u16 peer_id)
3602 {
3603         DSTACK(__FUNCTION_NAME);
3604         
3605         Player* player = m_env.getPlayer(peer_id);
3606         assert(player);
3607
3608         /*
3609                 Serialize it
3610         */
3611
3612         std::ostringstream os;
3613         //os.imbue(std::locale("C"));
3614
3615         player->inventory.serialize(os);
3616
3617         std::string s = os.str();
3618         
3619         SharedBuffer<u8> data(s.size()+2);
3620         writeU16(&data[0], TOCLIENT_INVENTORY);
3621         memcpy(&data[2], s.c_str(), s.size());
3622         
3623         // Send as reliable
3624         m_con.Send(peer_id, 0, data, true);
3625 }
3626
3627 std::string getWieldedItemString(const Player *player)
3628 {
3629         const InventoryItem *item = player->getWieldItem();
3630         if (item == NULL)
3631                 return std::string("");
3632         std::ostringstream os(std::ios_base::binary);
3633         item->serialize(os);
3634         return os.str();
3635 }
3636
3637 void Server::SendWieldedItem(const Player* player)
3638 {
3639         DSTACK(__FUNCTION_NAME);
3640
3641         assert(player);
3642
3643         std::ostringstream os(std::ios_base::binary);
3644
3645         writeU16(os, TOCLIENT_PLAYERITEM);
3646         writeU16(os, 1);
3647         writeU16(os, player->peer_id);
3648         os<<serializeString(getWieldedItemString(player));
3649
3650         // Make data buffer
3651         std::string s = os.str();
3652         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3653
3654         m_con.SendToAll(0, data, true);
3655 }
3656
3657 void Server::SendPlayerItems()
3658 {
3659         DSTACK(__FUNCTION_NAME);
3660
3661         std::ostringstream os(std::ios_base::binary);
3662         core::list<Player *> players = m_env.getPlayers(true);
3663
3664         writeU16(os, TOCLIENT_PLAYERITEM);
3665         writeU16(os, players.size());
3666         core::list<Player *>::Iterator i;
3667         for(i = players.begin(); i != players.end(); ++i)
3668         {
3669                 Player *p = *i;
3670                 writeU16(os, p->peer_id);
3671                 os<<serializeString(getWieldedItemString(p));
3672         }
3673
3674         // Make data buffer
3675         std::string s = os.str();
3676         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3677
3678         m_con.SendToAll(0, data, true);
3679 }
3680
3681 void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
3682 {
3683         DSTACK(__FUNCTION_NAME);
3684         
3685         std::ostringstream os(std::ios_base::binary);
3686         u8 buf[12];
3687         
3688         // Write command
3689         writeU16(buf, TOCLIENT_CHAT_MESSAGE);
3690         os.write((char*)buf, 2);
3691         
3692         // Write length
3693         writeU16(buf, message.size());
3694         os.write((char*)buf, 2);
3695         
3696         // Write string
3697         for(u32 i=0; i<message.size(); i++)
3698         {
3699                 u16 w = message[i];
3700                 writeU16(buf, w);
3701                 os.write((char*)buf, 2);
3702         }
3703         
3704         // Make data buffer
3705         std::string s = os.str();
3706         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3707         // Send as reliable
3708         m_con.Send(peer_id, 0, data, true);
3709 }
3710
3711 void Server::BroadcastChatMessage(const std::wstring &message)
3712 {
3713         for(core::map<u16, RemoteClient*>::Iterator
3714                 i = m_clients.getIterator();
3715                 i.atEnd() == false; i++)
3716         {
3717                 // Get client and check that it is valid
3718                 RemoteClient *client = i.getNode()->getValue();
3719                 assert(client->peer_id == i.getNode()->getKey());
3720                 if(client->serialization_version == SER_FMT_VER_INVALID)
3721                         continue;
3722
3723                 SendChatMessage(client->peer_id, message);
3724         }
3725 }
3726
3727 void Server::SendPlayerHP(Player *player)
3728 {
3729         SendHP(m_con, player->peer_id, player->hp);
3730 }
3731
3732 void Server::SendMovePlayer(Player *player)
3733 {
3734         DSTACK(__FUNCTION_NAME);
3735         std::ostringstream os(std::ios_base::binary);
3736
3737         writeU16(os, TOCLIENT_MOVE_PLAYER);
3738         writeV3F1000(os, player->getPosition());
3739         writeF1000(os, player->getPitch());
3740         writeF1000(os, player->getYaw());
3741         
3742         {
3743                 v3f pos = player->getPosition();
3744                 f32 pitch = player->getPitch();
3745                 f32 yaw = player->getYaw();
3746                 infostream<<"Server sending TOCLIENT_MOVE_PLAYER"
3747                                 <<" pos=("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
3748                                 <<" pitch="<<pitch
3749                                 <<" yaw="<<yaw
3750                                 <<std::endl;
3751         }
3752
3753         // Make data buffer
3754         std::string s = os.str();
3755         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3756         // Send as reliable
3757         m_con.Send(player->peer_id, 0, data, true);
3758 }
3759
3760 void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
3761         core::list<u16> *far_players, float far_d_nodes)
3762 {
3763         float maxd = far_d_nodes*BS;
3764         v3f p_f = intToFloat(p, BS);
3765
3766         // Create packet
3767         u32 replysize = 8;
3768         SharedBuffer<u8> reply(replysize);
3769         writeU16(&reply[0], TOCLIENT_REMOVENODE);
3770         writeS16(&reply[2], p.X);
3771         writeS16(&reply[4], p.Y);
3772         writeS16(&reply[6], p.Z);
3773
3774         for(core::map<u16, RemoteClient*>::Iterator
3775                 i = m_clients.getIterator();
3776                 i.atEnd() == false; i++)
3777         {
3778                 // Get client and check that it is valid
3779                 RemoteClient *client = i.getNode()->getValue();
3780                 assert(client->peer_id == i.getNode()->getKey());
3781                 if(client->serialization_version == SER_FMT_VER_INVALID)
3782                         continue;
3783
3784                 // Don't send if it's the same one
3785                 if(client->peer_id == ignore_id)
3786                         continue;
3787                 
3788                 if(far_players)
3789                 {
3790                         // Get player
3791                         Player *player = m_env.getPlayer(client->peer_id);
3792                         if(player)
3793                         {
3794                                 // If player is far away, only set modified blocks not sent
3795                                 v3f player_pos = player->getPosition();
3796                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3797                                 {
3798                                         far_players->push_back(client->peer_id);
3799                                         continue;
3800                                 }
3801                         }
3802                 }
3803
3804                 // Send as reliable
3805                 m_con.Send(client->peer_id, 0, reply, true);
3806         }
3807 }
3808
3809 void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
3810                 core::list<u16> *far_players, float far_d_nodes)
3811 {
3812         float maxd = far_d_nodes*BS;
3813         v3f p_f = intToFloat(p, BS);
3814
3815         for(core::map<u16, RemoteClient*>::Iterator
3816                 i = m_clients.getIterator();
3817                 i.atEnd() == false; i++)
3818         {
3819                 // Get client and check that it is valid
3820                 RemoteClient *client = i.getNode()->getValue();
3821                 assert(client->peer_id == i.getNode()->getKey());
3822                 if(client->serialization_version == SER_FMT_VER_INVALID)
3823                         continue;
3824
3825                 // Don't send if it's the same one
3826                 if(client->peer_id == ignore_id)
3827                         continue;
3828
3829                 if(far_players)
3830                 {
3831                         // Get player
3832                         Player *player = m_env.getPlayer(client->peer_id);
3833                         if(player)
3834                         {
3835                                 // If player is far away, only set modified blocks not sent
3836                                 v3f player_pos = player->getPosition();
3837                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3838                                 {
3839                                         far_players->push_back(client->peer_id);
3840                                         continue;
3841                                 }
3842                         }
3843                 }
3844
3845                 // Create packet
3846                 u32 replysize = 8 + MapNode::serializedLength(client->serialization_version);
3847                 SharedBuffer<u8> reply(replysize);
3848                 writeU16(&reply[0], TOCLIENT_ADDNODE);
3849                 writeS16(&reply[2], p.X);
3850                 writeS16(&reply[4], p.Y);
3851                 writeS16(&reply[6], p.Z);
3852                 n.serialize(&reply[8], client->serialization_version);
3853
3854                 // Send as reliable
3855                 m_con.Send(client->peer_id, 0, reply, true);
3856         }
3857 }
3858
3859 void Server::setBlockNotSent(v3s16 p)
3860 {
3861         for(core::map<u16, RemoteClient*>::Iterator
3862                 i = m_clients.getIterator();
3863                 i.atEnd()==false; i++)
3864         {
3865                 RemoteClient *client = i.getNode()->getValue();
3866                 client->SetBlockNotSent(p);
3867         }
3868 }
3869
3870 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
3871 {
3872         DSTACK(__FUNCTION_NAME);
3873
3874         v3s16 p = block->getPos();
3875         
3876 #if 0
3877         // Analyze it a bit
3878         bool completely_air = true;
3879         for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
3880         for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
3881         for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
3882         {
3883                 if(block->getNodeNoEx(v3s16(x0,y0,z0)).d != CONTENT_AIR)
3884                 {
3885                         completely_air = false;
3886                         x0 = y0 = z0 = MAP_BLOCKSIZE; // Break out
3887                 }
3888         }
3889
3890         // Print result
3891         infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<"): ";
3892         if(completely_air)
3893                 infostream<<"[completely air] ";
3894         infostream<<std::endl;
3895 #endif
3896
3897         /*
3898                 Create a packet with the block in the right format
3899         */
3900         
3901         std::ostringstream os(std::ios_base::binary);
3902         block->serialize(os, ver);
3903         std::string s = os.str();
3904         SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
3905
3906         u32 replysize = 8 + blockdata.getSize();
3907         SharedBuffer<u8> reply(replysize);
3908         writeU16(&reply[0], TOCLIENT_BLOCKDATA);
3909         writeS16(&reply[2], p.X);
3910         writeS16(&reply[4], p.Y);
3911         writeS16(&reply[6], p.Z);
3912         memcpy(&reply[8], *blockdata, blockdata.getSize());
3913
3914         /*infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<")"
3915                         <<":  \tpacket size: "<<replysize<<std::endl;*/
3916         
3917         /*
3918                 Send packet
3919         */
3920         m_con.Send(peer_id, 1, reply, true);
3921 }
3922
3923 void Server::SendBlocks(float dtime)
3924 {
3925         DSTACK(__FUNCTION_NAME);
3926
3927         JMutexAutoLock envlock(m_env_mutex);
3928         JMutexAutoLock conlock(m_con_mutex);
3929
3930         //TimeTaker timer("Server::SendBlocks");
3931
3932         core::array<PrioritySortedBlockTransfer> queue;
3933
3934         s32 total_sending = 0;
3935         
3936         {
3937                 ScopeProfiler sp(g_profiler, "Server: selecting blocks for sending");
3938
3939                 for(core::map<u16, RemoteClient*>::Iterator
3940                         i = m_clients.getIterator();
3941                         i.atEnd() == false; i++)
3942                 {
3943                         RemoteClient *client = i.getNode()->getValue();
3944                         assert(client->peer_id == i.getNode()->getKey());
3945
3946                         total_sending += client->SendingCount();
3947                         
3948                         if(client->serialization_version == SER_FMT_VER_INVALID)
3949                                 continue;
3950                         
3951                         client->GetNextBlocks(this, dtime, queue);
3952                 }
3953         }
3954
3955         // Sort.
3956         // Lowest priority number comes first.
3957         // Lowest is most important.
3958         queue.sort();
3959
3960         for(u32 i=0; i<queue.size(); i++)
3961         {
3962                 //TODO: Calculate limit dynamically
3963                 if(total_sending >= g_settings->getS32
3964                                 ("max_simultaneous_block_sends_server_total"))
3965                         break;
3966                 
3967                 PrioritySortedBlockTransfer q = queue[i];
3968
3969                 MapBlock *block = NULL;
3970                 try
3971                 {
3972                         block = m_env.getMap().getBlockNoCreate(q.pos);
3973                 }
3974                 catch(InvalidPositionException &e)
3975                 {
3976                         continue;
3977                 }
3978
3979                 RemoteClient *client = getClient(q.peer_id);
3980
3981                 SendBlockNoLock(q.peer_id, block, client->serialization_version);
3982
3983                 client->SentBlock(q.pos);
3984
3985                 total_sending++;
3986         }
3987 }
3988
3989 /*
3990         Something random
3991 */
3992
3993 void Server::HandlePlayerHP(Player *player, s16 damage)
3994 {
3995         if(player->hp > damage)
3996         {
3997                 player->hp -= damage;
3998                 SendPlayerHP(player);
3999         }
4000         else
4001         {
4002                 infostream<<"Server::HandlePlayerHP(): Player "
4003                                 <<player->getName()<<" dies"<<std::endl;
4004                 
4005                 player->hp = 0;
4006                 
4007                 //TODO: Throw items around
4008                 
4009                 // Handle players that are not connected
4010                 if(player->peer_id == PEER_ID_INEXISTENT){
4011                         RespawnPlayer(player);
4012                         return;
4013                 }
4014
4015                 SendPlayerHP(player);
4016                 
4017                 RemoteClient *client = getClient(player->peer_id);
4018                 if(client->net_proto_version >= 3)
4019                 {
4020                         SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
4021                 }
4022                 else
4023                 {
4024                         RespawnPlayer(player);
4025                 }
4026         }
4027 }
4028
4029 void Server::RespawnPlayer(Player *player)
4030 {
4031         v3f pos = findSpawnPos(m_env.getServerMap());
4032         player->setPosition(pos);
4033         player->hp = 20;
4034         SendMovePlayer(player);
4035         SendPlayerHP(player);
4036 }
4037
4038 void Server::UpdateCrafting(u16 peer_id)
4039 {
4040         DSTACK(__FUNCTION_NAME);
4041         
4042         Player* player = m_env.getPlayer(peer_id);
4043         assert(player);
4044
4045         /*
4046                 Calculate crafting stuff
4047         */
4048         if(g_settings->getBool("creative_mode") == false)
4049         {
4050                 InventoryList *clist = player->inventory.getList("craft");
4051                 InventoryList *rlist = player->inventory.getList("craftresult");
4052
4053                 if(rlist && rlist->getUsedSlots() == 0)
4054                         player->craftresult_is_preview = true;
4055
4056                 if(rlist && player->craftresult_is_preview)
4057                 {
4058                         rlist->clearItems();
4059                 }
4060                 if(clist && rlist && player->craftresult_is_preview)
4061                 {
4062                         InventoryItem *items[9];
4063                         for(u16 i=0; i<9; i++)
4064                         {
4065                                 items[i] = clist->getItem(i);
4066                         }
4067                         
4068                         // Get result of crafting grid
4069                         InventoryItem *result = craft_get_result(items);
4070                         if(result)
4071                                 rlist->addItem(result);
4072                 }
4073         
4074         } // if creative_mode == false
4075 }
4076
4077 RemoteClient* Server::getClient(u16 peer_id)
4078 {
4079         DSTACK(__FUNCTION_NAME);
4080         //JMutexAutoLock lock(m_con_mutex);
4081         core::map<u16, RemoteClient*>::Node *n;
4082         n = m_clients.find(peer_id);
4083         // A client should exist for all peers
4084         assert(n != NULL);
4085         return n->getValue();
4086 }
4087
4088 std::wstring Server::getStatusString()
4089 {
4090         std::wostringstream os(std::ios_base::binary);
4091         os<<L"# Server: ";
4092         // Version
4093         os<<L"version="<<narrow_to_wide(VERSION_STRING);
4094         // Uptime
4095         os<<L", uptime="<<m_uptime.get();
4096         // Information about clients
4097         os<<L", clients={";
4098         for(core::map<u16, RemoteClient*>::Iterator
4099                 i = m_clients.getIterator();
4100                 i.atEnd() == false; i++)
4101         {
4102                 // Get client and check that it is valid
4103                 RemoteClient *client = i.getNode()->getValue();
4104                 assert(client->peer_id == i.getNode()->getKey());
4105                 if(client->serialization_version == SER_FMT_VER_INVALID)
4106                         continue;
4107                 // Get player
4108                 Player *player = m_env.getPlayer(client->peer_id);
4109                 // Get name of player
4110                 std::wstring name = L"unknown";
4111                 if(player != NULL)
4112                         name = narrow_to_wide(player->getName());
4113                 // Add name to information string
4114                 os<<name<<L",";
4115         }
4116         os<<L"}";
4117         if(((ServerMap*)(&m_env.getMap()))->isSavingEnabled() == false)
4118                 os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
4119         if(g_settings->get("motd") != "")
4120                 os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
4121         return os.str();
4122 }
4123
4124 // Saves g_settings to configpath given at initialization
4125 void Server::saveConfig()
4126 {
4127         if(m_configpath != "")
4128                 g_settings->updateConfigFile(m_configpath.c_str());
4129 }
4130
4131 void Server::notifyPlayer(const char *name, const std::wstring msg)
4132 {
4133         Player *player = m_env.getPlayer(name);
4134         if(!player)
4135                 return;
4136         SendChatMessage(player->peer_id, std::wstring(L"Server: -!- ")+msg);
4137 }
4138
4139 void Server::notifyPlayers(const std::wstring msg)
4140 {
4141         BroadcastChatMessage(msg);
4142 }
4143
4144 v3f findSpawnPos(ServerMap &map)
4145 {
4146         //return v3f(50,50,50)*BS;
4147
4148         v2s16 nodepos;
4149         s16 groundheight = 0;
4150         
4151 #if 0
4152         nodepos = v2s16(0,0);
4153         groundheight = 20;
4154 #endif
4155
4156 #if 1
4157         // Try to find a good place a few times
4158         for(s32 i=0; i<1000; i++)
4159         {
4160                 s32 range = 1 + i;
4161                 // We're going to try to throw the player to this position
4162                 nodepos = v2s16(-range + (myrand()%(range*2)),
4163                                 -range + (myrand()%(range*2)));
4164                 v2s16 sectorpos = getNodeSectorPos(nodepos);
4165                 // Get sector (NOTE: Don't get because it's slow)
4166                 //m_env.getMap().emergeSector(sectorpos);
4167                 // Get ground height at point (fallbacks to heightmap function)
4168                 groundheight = map.findGroundLevel(nodepos);
4169                 // Don't go underwater
4170                 if(groundheight < WATER_LEVEL)
4171                 {
4172                         //infostream<<"-> Underwater"<<std::endl;
4173                         continue;
4174                 }
4175                 // Don't go to high places
4176                 if(groundheight > WATER_LEVEL + 4)
4177                 {
4178                         //infostream<<"-> Underwater"<<std::endl;
4179                         continue;
4180                 }
4181
4182                 // Found a good place
4183                 //infostream<<"Searched through "<<i<<" places."<<std::endl;
4184                 break;
4185         }
4186 #endif
4187         
4188         // If no suitable place was not found, go above water at least.
4189         if(groundheight < WATER_LEVEL)
4190                 groundheight = WATER_LEVEL;
4191
4192         return intToFloat(v3s16(
4193                         nodepos.X,
4194                         groundheight + 3,
4195                         nodepos.Y
4196                         ), BS);
4197 }
4198
4199 Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id)
4200 {
4201         /*
4202                 Try to get an existing player
4203         */
4204         Player *player = m_env.getPlayer(name);
4205         if(player != NULL)
4206         {
4207                 // If player is already connected, cancel
4208                 if(player->peer_id != 0)
4209                 {
4210                         infostream<<"emergePlayer(): Player already connected"<<std::endl;
4211                         return NULL;
4212                 }
4213
4214                 // Got one.
4215                 player->peer_id = peer_id;
4216                 
4217                 // Reset inventory to creative if in creative mode
4218                 if(g_settings->getBool("creative_mode"))
4219                 {
4220                         // Warning: double code below
4221                         // Backup actual inventory
4222                         player->inventory_backup = new Inventory();
4223                         *(player->inventory_backup) = player->inventory;
4224                         // Set creative inventory
4225                         craft_set_creative_inventory(player);
4226                 }
4227
4228                 return player;
4229         }
4230
4231         /*
4232                 If player with the wanted peer_id already exists, cancel.
4233         */
4234         if(m_env.getPlayer(peer_id) != NULL)
4235         {
4236                 infostream<<"emergePlayer(): Player with wrong name but same"
4237                                 " peer_id already exists"<<std::endl;
4238                 return NULL;
4239         }
4240         
4241         /*
4242                 Create a new player
4243         */
4244         {
4245                 player = new ServerRemotePlayer();
4246                 //player->peer_id = c.peer_id;
4247                 //player->peer_id = PEER_ID_INEXISTENT;
4248                 player->peer_id = peer_id;
4249                 player->updateName(name);
4250                 m_authmanager.add(name);
4251                 m_authmanager.setPassword(name, password);
4252                 m_authmanager.setPrivs(name,
4253                                 stringToPrivs(g_settings->get("default_privs")));
4254
4255                 /*
4256                         Set player position
4257                 */
4258                 
4259                 infostream<<"Server: Finding spawn place for player \""
4260                                 <<player->getName()<<"\""<<std::endl;
4261
4262                 v3f pos = findSpawnPos(m_env.getServerMap());
4263
4264                 player->setPosition(pos);
4265
4266                 /*
4267                         Add player to environment
4268                 */
4269
4270                 m_env.addPlayer(player);
4271
4272                 /*
4273                         Add stuff to inventory
4274                 */
4275                 
4276                 if(g_settings->getBool("creative_mode"))
4277                 {
4278                         // Warning: double code above
4279                         // Backup actual inventory
4280                         player->inventory_backup = new Inventory();
4281                         *(player->inventory_backup) = player->inventory;
4282                         // Set creative inventory
4283                         craft_set_creative_inventory(player);
4284                 }
4285                 else if(g_settings->getBool("give_initial_stuff"))
4286                 {
4287                         craft_give_initial_stuff(player);
4288                 }
4289
4290                 return player;
4291                 
4292         } // create new player
4293 }
4294
4295 void Server::handlePeerChange(PeerChange &c)
4296 {
4297         JMutexAutoLock envlock(m_env_mutex);
4298         JMutexAutoLock conlock(m_con_mutex);
4299         
4300         if(c.type == PEER_ADDED)
4301         {
4302                 /*
4303                         Add
4304                 */
4305
4306                 // Error check
4307                 core::map<u16, RemoteClient*>::Node *n;
4308                 n = m_clients.find(c.peer_id);
4309                 // The client shouldn't already exist
4310                 assert(n == NULL);
4311
4312                 // Create client
4313                 RemoteClient *client = new RemoteClient();
4314                 client->peer_id = c.peer_id;
4315                 m_clients.insert(client->peer_id, client);
4316
4317         } // PEER_ADDED
4318         else if(c.type == PEER_REMOVED)
4319         {
4320                 /*
4321                         Delete
4322                 */
4323
4324                 // Error check
4325                 core::map<u16, RemoteClient*>::Node *n;
4326                 n = m_clients.find(c.peer_id);
4327                 // The client should exist
4328                 assert(n != NULL);
4329                 
4330                 /*
4331                         Mark objects to be not known by the client
4332                 */
4333                 RemoteClient *client = n->getValue();
4334                 // Handle objects
4335                 for(core::map<u16, bool>::Iterator
4336                                 i = client->m_known_objects.getIterator();
4337                                 i.atEnd()==false; i++)
4338                 {
4339                         // Get object
4340                         u16 id = i.getNode()->getKey();
4341                         ServerActiveObject* obj = m_env.getActiveObject(id);
4342                         
4343                         if(obj && obj->m_known_by_count > 0)
4344                                 obj->m_known_by_count--;
4345                 }
4346
4347                 // Collect information about leaving in chat
4348                 std::wstring message;
4349                 {
4350                         Player *player = m_env.getPlayer(c.peer_id);
4351                         if(player != NULL)
4352                         {
4353                                 std::wstring name = narrow_to_wide(player->getName());
4354                                 message += L"*** ";
4355                                 message += name;
4356                                 message += L" left game";
4357                                 if(c.timeout)
4358                                         message += L" (timed out)";
4359                         }
4360                 }
4361
4362                 /*// Delete player
4363                 {
4364                         m_env.removePlayer(c.peer_id);
4365                 }*/
4366
4367                 // Set player client disconnected
4368                 {
4369                         Player *player = m_env.getPlayer(c.peer_id);
4370                         if(player != NULL)
4371                                 player->peer_id = 0;
4372                         
4373                         /*
4374                                 Print out action
4375                         */
4376                         if(player != NULL)
4377                         {
4378                                 std::ostringstream os(std::ios_base::binary);
4379                                 for(core::map<u16, RemoteClient*>::Iterator
4380                                         i = m_clients.getIterator();
4381                                         i.atEnd() == false; i++)
4382                                 {
4383                                         RemoteClient *client = i.getNode()->getValue();
4384                                         assert(client->peer_id == i.getNode()->getKey());
4385                                         if(client->serialization_version == SER_FMT_VER_INVALID)
4386                                                 continue;
4387                                         // Get player
4388                                         Player *player = m_env.getPlayer(client->peer_id);
4389                                         if(!player)
4390                                                 continue;
4391                                         // Get name of player
4392                                         os<<player->getName()<<" ";
4393                                 }
4394
4395                                 actionstream<<player->getName()<<" "
4396                                                 <<(c.timeout?"times out.":"leaves game.")
4397                                                 <<" List of players: "
4398                                                 <<os.str()<<std::endl;
4399                         }
4400                 }
4401                 
4402                 // Delete client
4403                 delete m_clients[c.peer_id];
4404                 m_clients.remove(c.peer_id);
4405
4406                 // Send player info to all remaining clients
4407                 SendPlayerInfos();
4408                 
4409                 // Send leave chat message to all remaining clients
4410                 BroadcastChatMessage(message);
4411                 
4412         } // PEER_REMOVED
4413         else
4414         {
4415                 assert(0);
4416         }
4417 }
4418
4419 void Server::handlePeerChanges()
4420 {
4421         while(m_peer_change_queue.size() > 0)
4422         {
4423                 PeerChange c = m_peer_change_queue.pop_front();
4424
4425                 infostream<<"Server: Handling peer change: "
4426                                 <<"id="<<c.peer_id<<", timeout="<<c.timeout
4427                                 <<std::endl;
4428
4429                 handlePeerChange(c);
4430         }
4431 }
4432
4433 u64 Server::getPlayerPrivs(Player *player)
4434 {
4435         if(player==NULL)
4436                 return 0;
4437         std::string playername = player->getName();
4438         // Local player gets all privileges regardless of
4439         // what's set on their account.
4440         if(g_settings->get("name") == playername)
4441         {
4442                 return PRIV_ALL;
4443         }
4444         else
4445         {
4446                 return getPlayerAuthPrivs(playername);
4447         }
4448 }
4449
4450 void dedicated_server_loop(Server &server, bool &kill)
4451 {
4452         DSTACK(__FUNCTION_NAME);
4453         
4454         infostream<<DTIME<<std::endl;
4455         infostream<<"========================"<<std::endl;
4456         infostream<<"Running dedicated server"<<std::endl;
4457         infostream<<"========================"<<std::endl;
4458         infostream<<std::endl;
4459
4460         IntervalLimiter m_profiler_interval;
4461
4462         for(;;)
4463         {
4464                 // This is kind of a hack but can be done like this
4465                 // because server.step() is very light
4466                 {
4467                         ScopeProfiler sp(g_profiler, "dedicated server sleep");
4468                         sleep_ms(30);
4469                 }
4470                 server.step(0.030);
4471
4472                 if(server.getShutdownRequested() || kill)
4473                 {
4474                         infostream<<DTIME<<" dedicated_server_loop(): Quitting."<<std::endl;
4475                         break;
4476                 }
4477
4478                 /*
4479                         Profiler
4480                 */
4481                 float profiler_print_interval =
4482                                 g_settings->getFloat("profiler_print_interval");
4483                 if(profiler_print_interval != 0)
4484                 {
4485                         if(m_profiler_interval.step(0.030, profiler_print_interval))
4486                         {
4487                                 infostream<<"Profiler:"<<std::endl;
4488                                 g_profiler->print(infostream);
4489                                 g_profiler->clear();
4490                         }
4491                 }
4492                 
4493                 /*
4494                         Player info
4495                 */
4496                 static int counter = 0;
4497                 counter--;
4498                 if(counter <= 0)
4499                 {
4500                         counter = 10;
4501
4502                         core::list<PlayerInfo> list = server.getPlayerInfo();
4503                         core::list<PlayerInfo>::Iterator i;
4504                         static u32 sum_old = 0;
4505                         u32 sum = PIChecksum(list);
4506                         if(sum != sum_old)
4507                         {
4508                                 infostream<<DTIME<<"Player info:"<<std::endl;
4509                                 for(i=list.begin(); i!=list.end(); i++)
4510                                 {
4511                                         i->PrintLine(&infostream);
4512                                 }
4513                         }
4514                         sum_old = sum;
4515                 }
4516         }
4517 }
4518
4519