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