]> git.lizzy.rs Git - dragonfireclient.git/blob - src/server.cpp
Better spawn position finding and checking
[dragonfireclient.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         SharedBuffer<u8> data;
1781         u16 peer_id;
1782         u32 datasize;
1783         try{
1784                 {
1785                         JMutexAutoLock conlock(m_con_mutex);
1786                         datasize = m_con.Receive(peer_id, data);
1787                 }
1788
1789                 // This has to be called so that the client list gets synced
1790                 // with the peer list of the connection
1791                 handlePeerChanges();
1792
1793                 ProcessData(*data, datasize, peer_id);
1794         }
1795         catch(con::InvalidIncomingDataException &e)
1796         {
1797                 infostream<<"Server::Receive(): "
1798                                 "InvalidIncomingDataException: what()="
1799                                 <<e.what()<<std::endl;
1800         }
1801         catch(con::PeerNotFoundException &e)
1802         {
1803                 //NOTE: This is not needed anymore
1804                 
1805                 // The peer has been disconnected.
1806                 // Find the associated player and remove it.
1807
1808                 /*JMutexAutoLock envlock(m_env_mutex);
1809
1810                 infostream<<"ServerThread: peer_id="<<peer_id
1811                                 <<" has apparently closed connection. "
1812                                 <<"Removing player."<<std::endl;
1813
1814                 m_env.removePlayer(peer_id);*/
1815         }
1816 }
1817
1818 void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
1819 {
1820         DSTACK(__FUNCTION_NAME);
1821         // Environment is locked first.
1822         JMutexAutoLock envlock(m_env_mutex);
1823         JMutexAutoLock conlock(m_con_mutex);
1824         
1825         try{
1826                 Address address = m_con.GetPeerAddress(peer_id);
1827
1828                 // drop player if is ip is banned
1829                 if(m_banmanager.isIpBanned(address.serializeString())){
1830                         SendAccessDenied(m_con, peer_id,
1831                                         L"Your ip is banned. Banned name was "
1832                                         +narrow_to_wide(m_banmanager.getBanName(
1833                                                 address.serializeString())));
1834                         m_con.DeletePeer(peer_id);
1835                         return;
1836                 }
1837         }
1838         catch(con::PeerNotFoundException &e)
1839         {
1840                 infostream<<"Server::ProcessData(): Cancelling: peer "
1841                                 <<peer_id<<" not found"<<std::endl;
1842                 return;
1843         }
1844
1845         u8 peer_ser_ver = getClient(peer_id)->serialization_version;
1846
1847         try
1848         {
1849
1850         if(datasize < 2)
1851                 return;
1852
1853         ToServerCommand command = (ToServerCommand)readU16(&data[0]);
1854         
1855         if(command == TOSERVER_INIT)
1856         {
1857                 // [0] u16 TOSERVER_INIT
1858                 // [2] u8 SER_FMT_VER_HIGHEST
1859                 // [3] u8[20] player_name
1860                 // [23] u8[28] password <--- can be sent without this, from old versions
1861
1862                 if(datasize < 2+1+PLAYERNAME_SIZE)
1863                         return;
1864
1865                 infostream<<"Server: Got TOSERVER_INIT from "
1866                                 <<peer_id<<std::endl;
1867
1868                 // First byte after command is maximum supported
1869                 // serialization version
1870                 u8 client_max = data[2];
1871                 u8 our_max = SER_FMT_VER_HIGHEST;
1872                 // Use the highest version supported by both
1873                 u8 deployed = core::min_(client_max, our_max);
1874                 // If it's lower than the lowest supported, give up.
1875                 if(deployed < SER_FMT_VER_LOWEST)
1876                         deployed = SER_FMT_VER_INVALID;
1877
1878                 //peer->serialization_version = deployed;
1879                 getClient(peer_id)->pending_serialization_version = deployed;
1880                 
1881                 if(deployed == SER_FMT_VER_INVALID)
1882                 {
1883                         infostream<<"Server: Cannot negotiate "
1884                                         "serialization version with peer "
1885                                         <<peer_id<<std::endl;
1886                         SendAccessDenied(m_con, peer_id,
1887                                         L"Your client is too old (map format)");
1888                         return;
1889                 }
1890                 
1891                 /*
1892                         Read and check network protocol version
1893                 */
1894
1895                 u16 net_proto_version = 0;
1896                 if(datasize >= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2)
1897                 {
1898                         net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]);
1899                 }
1900
1901                 getClient(peer_id)->net_proto_version = net_proto_version;
1902
1903                 if(net_proto_version == 0)
1904                 {
1905                         SendAccessDenied(m_con, peer_id,
1906                                         L"Your client is too old. Please upgrade.");
1907                         return;
1908                 }
1909                 
1910                 /* Uhh... this should actually be a warning but let's do it like this */
1911                 if(g_settings->getBool("strict_protocol_version_checking"))
1912                 {
1913                         if(net_proto_version < PROTOCOL_VERSION)
1914                         {
1915                                 SendAccessDenied(m_con, peer_id,
1916                                                 L"Your client is too old. Please upgrade.");
1917                                 return;
1918                         }
1919                 }
1920
1921                 /*
1922                         Set up player
1923                 */
1924                 
1925                 // Get player name
1926                 char playername[PLAYERNAME_SIZE];
1927                 for(u32 i=0; i<PLAYERNAME_SIZE-1; i++)
1928                 {
1929                         playername[i] = data[3+i];
1930                 }
1931                 playername[PLAYERNAME_SIZE-1] = 0;
1932                 
1933                 if(playername[0]=='\0')
1934                 {
1935                         infostream<<"Server: Player has empty name"<<std::endl;
1936                         SendAccessDenied(m_con, peer_id,
1937                                         L"Empty name");
1938                         return;
1939                 }
1940
1941                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1942                 {
1943                         infostream<<"Server: Player has invalid name"<<std::endl;
1944                         SendAccessDenied(m_con, peer_id,
1945                                         L"Name contains unallowed characters");
1946                         return;
1947                 }
1948
1949                 // Get password
1950                 char password[PASSWORD_SIZE];
1951                 if(datasize < 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE)
1952                 {
1953                         // old version - assume blank password
1954                         password[0] = 0;
1955                 }
1956                 else
1957                 {
1958                                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
1959                                 {
1960                                         password[i] = data[23+i];
1961                                 }
1962                                 password[PASSWORD_SIZE-1] = 0;
1963                 }
1964                 
1965                 std::string checkpwd;
1966                 if(m_authmanager.exists(playername))
1967                 {
1968                         checkpwd = m_authmanager.getPassword(playername);
1969                 }
1970                 else
1971                 {
1972                         checkpwd = g_settings->get("default_password");
1973                 }
1974                 
1975                 /*infostream<<"Server: Client gave password '"<<password
1976                                 <<"', the correct one is '"<<checkpwd<<"'"<<std::endl;*/
1977                 
1978                 if(password != checkpwd && m_authmanager.exists(playername))
1979                 {
1980                         infostream<<"Server: peer_id="<<peer_id
1981                                         <<": supplied invalid password for "
1982                                         <<playername<<std::endl;
1983                         SendAccessDenied(m_con, peer_id, L"Invalid password");
1984                         return;
1985                 }
1986                 
1987                 // Add player to auth manager
1988                 if(m_authmanager.exists(playername) == false)
1989                 {
1990                         infostream<<"Server: adding player "<<playername
1991                                         <<" to auth manager"<<std::endl;
1992                         m_authmanager.add(playername);
1993                         m_authmanager.setPassword(playername, checkpwd);
1994                         m_authmanager.setPrivs(playername,
1995                                         stringToPrivs(g_settings->get("default_privs")));
1996                         m_authmanager.save();
1997                 }
1998                 
1999                 // Enforce user limit.
2000                 // Don't enforce for users that have some admin right
2001                 if(m_clients.size() >= g_settings->getU16("max_users") &&
2002                                 (m_authmanager.getPrivs(playername)
2003                                         & (PRIV_SERVER|PRIV_BAN|PRIV_PRIVS)) == 0 &&
2004                                 playername != g_settings->get("name"))
2005                 {
2006                         SendAccessDenied(m_con, peer_id, L"Too many users.");
2007                         return;
2008                 }
2009
2010                 // Get player
2011                 Player *player = emergePlayer(playername, password, peer_id);
2012
2013                 // If failed, cancel
2014                 if(player == NULL)
2015                 {
2016                         infostream<<"Server: peer_id="<<peer_id
2017                                         <<": failed to emerge player"<<std::endl;
2018                         return;
2019                 }
2020
2021                 /*
2022                         Answer with a TOCLIENT_INIT
2023                 */
2024                 {
2025                         SharedBuffer<u8> reply(2+1+6+8);
2026                         writeU16(&reply[0], TOCLIENT_INIT);
2027                         writeU8(&reply[2], deployed);
2028                         writeV3S16(&reply[2+1], floatToInt(player->getPosition()+v3f(0,BS/2,0), BS));
2029                         writeU64(&reply[2+1+6], m_env.getServerMap().getSeed());
2030                         
2031                         // Send as reliable
2032                         m_con.Send(peer_id, 0, reply, true);
2033                 }
2034
2035                 /*
2036                         Send complete position information
2037                 */
2038                 SendMovePlayer(player);
2039
2040                 return;
2041         }
2042
2043         if(command == TOSERVER_INIT2)
2044         {
2045                 infostream<<"Server: Got TOSERVER_INIT2 from "
2046                                 <<peer_id<<std::endl;
2047
2048
2049                 getClient(peer_id)->serialization_version
2050                                 = getClient(peer_id)->pending_serialization_version;
2051
2052                 /*
2053                         Send some initialization data
2054                 */
2055                 
2056                 // Send player info to all players
2057                 SendPlayerInfos();
2058
2059                 // Send inventory to player
2060                 UpdateCrafting(peer_id);
2061                 SendInventory(peer_id);
2062
2063                 // Send player items to all players
2064                 SendPlayerItems();
2065
2066                 Player *player = m_env.getPlayer(peer_id);
2067
2068                 // Send HP
2069                 SendPlayerHP(player);
2070                 
2071                 // Send time of day
2072                 {
2073                         SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
2074                                         m_env.getTimeOfDay());
2075                         m_con.Send(peer_id, 0, data, true);
2076                 }
2077                 
2078                 // Send information about server to player in chat
2079                 SendChatMessage(peer_id, getStatusString());
2080                 
2081                 // Send information about joining in chat
2082                 {
2083                         std::wstring name = L"unknown";
2084                         Player *player = m_env.getPlayer(peer_id);
2085                         if(player != NULL)
2086                                 name = narrow_to_wide(player->getName());
2087                         
2088                         std::wstring message;
2089                         message += L"*** ";
2090                         message += name;
2091                         message += L" joined game";
2092                         BroadcastChatMessage(message);
2093                 }
2094                 
2095                 // Warnings about protocol version can be issued here
2096                 if(getClient(peer_id)->net_proto_version < PROTOCOL_VERSION)
2097                 {
2098                         SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER");
2099                 }
2100
2101                 /*
2102                         Check HP, respawn if necessary
2103                 */
2104                 HandlePlayerHP(player, 0);
2105
2106                 /*
2107                         Print out action
2108                 */
2109                 {
2110                         std::ostringstream os(std::ios_base::binary);
2111                         for(core::map<u16, RemoteClient*>::Iterator
2112                                 i = m_clients.getIterator();
2113                                 i.atEnd() == false; i++)
2114                         {
2115                                 RemoteClient *client = i.getNode()->getValue();
2116                                 assert(client->peer_id == i.getNode()->getKey());
2117                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2118                                         continue;
2119                                 // Get player
2120                                 Player *player = m_env.getPlayer(client->peer_id);
2121                                 if(!player)
2122                                         continue;
2123                                 // Get name of player
2124                                 os<<player->getName()<<" ";
2125                         }
2126
2127                         actionstream<<player->getName()<<" joins game. List of players: "
2128                                         <<os.str()<<std::endl;
2129                 }
2130
2131                 return;
2132         }
2133
2134         if(peer_ser_ver == SER_FMT_VER_INVALID)
2135         {
2136                 infostream<<"Server::ProcessData(): Cancelling: Peer"
2137                                 " serialization format invalid or not initialized."
2138                                 " Skipping incoming command="<<command<<std::endl;
2139                 return;
2140         }
2141         
2142         Player *player = m_env.getPlayer(peer_id);
2143
2144         if(player == NULL){
2145                 infostream<<"Server::ProcessData(): Cancelling: "
2146                                 "No player for peer_id="<<peer_id
2147                                 <<std::endl;
2148                 return;
2149         }
2150         if(command == TOSERVER_PLAYERPOS)
2151         {
2152                 if(datasize < 2+12+12+4+4)
2153                         return;
2154         
2155                 u32 start = 0;
2156                 v3s32 ps = readV3S32(&data[start+2]);
2157                 v3s32 ss = readV3S32(&data[start+2+12]);
2158                 f32 pitch = (f32)readS32(&data[2+12+12]) / 100.0;
2159                 f32 yaw = (f32)readS32(&data[2+12+12+4]) / 100.0;
2160                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
2161                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
2162                 pitch = wrapDegrees(pitch);
2163                 yaw = wrapDegrees(yaw);
2164
2165                 player->setPosition(position);
2166                 player->setSpeed(speed);
2167                 player->setPitch(pitch);
2168                 player->setYaw(yaw);
2169                 
2170                 /*infostream<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
2171                                 <<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
2172                                 <<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
2173         }
2174         else if(command == TOSERVER_GOTBLOCKS)
2175         {
2176                 if(datasize < 2+1)
2177                         return;
2178                 
2179                 /*
2180                         [0] u16 command
2181                         [2] u8 count
2182                         [3] v3s16 pos_0
2183                         [3+6] v3s16 pos_1
2184                         ...
2185                 */
2186
2187                 u16 count = data[2];
2188                 for(u16 i=0; i<count; i++)
2189                 {
2190                         if((s16)datasize < 2+1+(i+1)*6)
2191                                 throw con::InvalidIncomingDataException
2192                                         ("GOTBLOCKS length is too short");
2193                         v3s16 p = readV3S16(&data[2+1+i*6]);
2194                         /*infostream<<"Server: GOTBLOCKS ("
2195                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2196                         RemoteClient *client = getClient(peer_id);
2197                         client->GotBlock(p);
2198                 }
2199         }
2200         else if(command == TOSERVER_DELETEDBLOCKS)
2201         {
2202                 if(datasize < 2+1)
2203                         return;
2204                 
2205                 /*
2206                         [0] u16 command
2207                         [2] u8 count
2208                         [3] v3s16 pos_0
2209                         [3+6] v3s16 pos_1
2210                         ...
2211                 */
2212
2213                 u16 count = data[2];
2214                 for(u16 i=0; i<count; i++)
2215                 {
2216                         if((s16)datasize < 2+1+(i+1)*6)
2217                                 throw con::InvalidIncomingDataException
2218                                         ("DELETEDBLOCKS length is too short");
2219                         v3s16 p = readV3S16(&data[2+1+i*6]);
2220                         /*infostream<<"Server: DELETEDBLOCKS ("
2221                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2222                         RemoteClient *client = getClient(peer_id);
2223                         client->SetBlockNotSent(p);
2224                 }
2225         }
2226         else if(command == TOSERVER_CLICK_OBJECT)
2227         {
2228                 infostream<<"Server: CLICK_OBJECT not supported anymore"<<std::endl;
2229                 return;
2230         }
2231         else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
2232         {
2233                 if(datasize < 7)
2234                         return;
2235
2236                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2237                         return;
2238
2239                 /*
2240                         length: 7
2241                         [0] u16 command
2242                         [2] u8 button (0=left, 1=right)
2243                         [3] u16 id
2244                         [5] u16 item
2245                 */
2246                 u8 button = readU8(&data[2]);
2247                 u16 id = readS16(&data[3]);
2248                 u16 item_i = readU16(&data[5]);
2249         
2250                 ServerActiveObject *obj = m_env.getActiveObject(id);
2251
2252                 if(obj == NULL)
2253                 {
2254                         infostream<<"Server: CLICK_ACTIVEOBJECT: object not found"
2255                                         <<std::endl;
2256                         return;
2257                 }
2258
2259                 // Skip if object has been removed
2260                 if(obj->m_removed)
2261                         return;
2262                 
2263                 //TODO: Check that object is reasonably close
2264                 
2265                 // Left click, pick object up (usually)
2266                 if(button == 0)
2267                 {
2268                         /*
2269                                 Try creating inventory item
2270                         */
2271                         InventoryItem *item = obj->createPickedUpItem();
2272                         
2273                         if(item)
2274                         {
2275                                 InventoryList *ilist = player->inventory.getList("main");
2276                                 if(ilist != NULL)
2277                                 {
2278                                         actionstream<<player->getName()<<" picked up "
2279                                                         <<item->getName()<<std::endl;
2280                                         if(g_settings->getBool("creative_mode") == false)
2281                                         {
2282                                                 // Skip if inventory has no free space
2283                                                 if(ilist->roomForItem(item) == false)
2284                                                 {
2285                                                         infostream<<"Player inventory has no free space"<<std::endl;
2286                                                         return;
2287                                                 }
2288
2289                                                 // Add to inventory and send inventory
2290                                                 ilist->addItem(item);
2291                                                 UpdateCrafting(player->peer_id);
2292                                                 SendInventory(player->peer_id);
2293                                         }
2294
2295                                         // Remove object from environment
2296                                         obj->m_removed = true;
2297                                 }
2298                         }
2299                         else
2300                         {
2301                                 /*
2302                                         Item cannot be picked up. Punch it instead.
2303                                 */
2304
2305                                 actionstream<<player->getName()<<" punches object "
2306                                                 <<obj->getId()<<std::endl;
2307
2308                                 ToolItem *titem = NULL;
2309                                 std::string toolname = "";
2310
2311                                 InventoryList *mlist = player->inventory.getList("main");
2312                                 if(mlist != NULL)
2313                                 {
2314                                         InventoryItem *item = mlist->getItem(item_i);
2315                                         if(item && (std::string)item->getName() == "ToolItem")
2316                                         {
2317                                                 titem = (ToolItem*)item;
2318                                                 toolname = titem->getToolName();
2319                                         }
2320                                 }
2321
2322                                 v3f playerpos = player->getPosition();
2323                                 v3f objpos = obj->getBasePosition();
2324                                 v3f dir = (objpos - playerpos).normalize();
2325                                 
2326                                 u16 wear = obj->punch(toolname, dir, player->getName());
2327                                 
2328                                 if(titem)
2329                                 {
2330                                         bool weared_out = titem->addWear(wear);
2331                                         if(weared_out)
2332                                                 mlist->deleteItem(item_i);
2333                                         SendInventory(player->peer_id);
2334                                 }
2335                         }
2336                 }
2337                 // Right click, do something with object
2338                 if(button == 1)
2339                 {
2340                         actionstream<<player->getName()<<" right clicks object "
2341                                         <<obj->getId()<<std::endl;
2342
2343                         // Track hp changes super-crappily
2344                         u16 oldhp = player->hp;
2345                         
2346                         // Do stuff
2347                         obj->rightClick(player);
2348                         
2349                         // Send back stuff
2350                         if(player->hp != oldhp)
2351                         {
2352                                 SendPlayerHP(player);
2353                         }
2354                 }
2355         }
2356         else if(command == TOSERVER_GROUND_ACTION)
2357         {
2358                 if(datasize < 17)
2359                         return;
2360                 /*
2361                         length: 17
2362                         [0] u16 command
2363                         [2] u8 action
2364                         [3] v3s16 nodepos_undersurface
2365                         [9] v3s16 nodepos_abovesurface
2366                         [15] u16 item
2367                         actions:
2368                         0: start digging
2369                         1: place block
2370                         2: stop digging (all parameters ignored)
2371                         3: digging completed
2372                 */
2373                 u8 action = readU8(&data[2]);
2374                 v3s16 p_under;
2375                 p_under.X = readS16(&data[3]);
2376                 p_under.Y = readS16(&data[5]);
2377                 p_under.Z = readS16(&data[7]);
2378                 v3s16 p_over;
2379                 p_over.X = readS16(&data[9]);
2380                 p_over.Y = readS16(&data[11]);
2381                 p_over.Z = readS16(&data[13]);
2382                 u16 item_i = readU16(&data[15]);
2383
2384                 //TODO: Check that target is reasonably close
2385                 
2386                 /*
2387                         0: start digging
2388                 */
2389                 if(action == 0)
2390                 {
2391                         /*
2392                                 NOTE: This can be used in the future to check if
2393                                 somebody is cheating, by checking the timing.
2394                         */
2395                 } // action == 0
2396
2397                 /*
2398                         2: stop digging
2399                 */
2400                 else if(action == 2)
2401                 {
2402 #if 0
2403                         RemoteClient *client = getClient(peer_id);
2404                         JMutexAutoLock digmutex(client->m_dig_mutex);
2405                         client->m_dig_tool_item = -1;
2406 #endif
2407                 }
2408
2409                 /*
2410                         3: Digging completed
2411                 */
2412                 else if(action == 3)
2413                 {
2414                         // Mandatory parameter; actually used for nothing
2415                         core::map<v3s16, MapBlock*> modified_blocks;
2416
2417                         content_t material = CONTENT_IGNORE;
2418                         u8 mineral = MINERAL_NONE;
2419
2420                         bool cannot_remove_node = false;
2421
2422                         try
2423                         {
2424                                 MapNode n = m_env.getMap().getNode(p_under);
2425                                 // Get mineral
2426                                 mineral = n.getMineral();
2427                                 // Get material at position
2428                                 material = n.getContent();
2429                                 // If not yet cancelled
2430                                 if(cannot_remove_node == false)
2431                                 {
2432                                         // If it's not diggable, do nothing
2433                                         if(content_diggable(material) == false)
2434                                         {
2435                                                 infostream<<"Server: Not finishing digging: "
2436                                                                 <<"Node not diggable"
2437                                                                 <<std::endl;
2438                                                 cannot_remove_node = true;
2439                                         }
2440                                 }
2441                                 // If not yet cancelled
2442                                 if(cannot_remove_node == false)
2443                                 {
2444                                         // Get node metadata
2445                                         NodeMetadata *meta = m_env.getMap().getNodeMetadata(p_under);
2446                                         if(meta && meta->nodeRemovalDisabled() == true)
2447                                         {
2448                                                 infostream<<"Server: Not finishing digging: "
2449                                                                 <<"Node metadata disables removal"
2450                                                                 <<std::endl;
2451                                                 cannot_remove_node = true;
2452                                         }
2453                                 }
2454                         }
2455                         catch(InvalidPositionException &e)
2456                         {
2457                                 infostream<<"Server: Not finishing digging: Node not found."
2458                                                 <<" Adding block to emerge queue."
2459                                                 <<std::endl;
2460                                 m_emerge_queue.addBlock(peer_id,
2461                                                 getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2462                                 cannot_remove_node = true;
2463                         }
2464
2465                         // Make sure the player is allowed to do it
2466                         if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2467                         {
2468                                 infostream<<"Player "<<player->getName()<<" cannot remove node"
2469                                                 <<" because privileges are "<<getPlayerPrivs(player)
2470                                                 <<std::endl;
2471                                 cannot_remove_node = true;
2472                         }
2473
2474                         /*
2475                                 If node can't be removed, set block to be re-sent to
2476                                 client and quit.
2477                         */
2478                         if(cannot_remove_node)
2479                         {
2480                                 infostream<<"Server: Not finishing digging."<<std::endl;
2481
2482                                 // Client probably has wrong data.
2483                                 // Set block not sent, so that client will get
2484                                 // a valid one.
2485                                 infostream<<"Client "<<peer_id<<" tried to dig "
2486                                                 <<"node; but node cannot be removed."
2487                                                 <<" setting MapBlock not sent."<<std::endl;
2488                                 RemoteClient *client = getClient(peer_id);
2489                                 v3s16 blockpos = getNodeBlockPos(p_under);
2490                                 client->SetBlockNotSent(blockpos);
2491                                         
2492                                 return;
2493                         }
2494                         
2495                         actionstream<<player->getName()<<" digs "<<PP(p_under)
2496                                         <<", gets material "<<(int)material<<", mineral "
2497                                         <<(int)mineral<<std::endl;
2498                         
2499                         /*
2500                                 Send the removal to all close-by players.
2501                                 - If other player is close, send REMOVENODE
2502                                 - Otherwise set blocks not sent
2503                         */
2504                         core::list<u16> far_players;
2505                         sendRemoveNode(p_under, peer_id, &far_players, 30);
2506                         
2507                         /*
2508                                 Update and send inventory
2509                         */
2510
2511                         if(g_settings->getBool("creative_mode") == false)
2512                         {
2513                                 /*
2514                                         Wear out tool
2515                                 */
2516                                 InventoryList *mlist = player->inventory.getList("main");
2517                                 if(mlist != NULL)
2518                                 {
2519                                         InventoryItem *item = mlist->getItem(item_i);
2520                                         if(item && (std::string)item->getName() == "ToolItem")
2521                                         {
2522                                                 ToolItem *titem = (ToolItem*)item;
2523                                                 std::string toolname = titem->getToolName();
2524
2525                                                 // Get digging properties for material and tool
2526                                                 DiggingProperties prop =
2527                                                                 getDiggingProperties(material, toolname);
2528
2529                                                 if(prop.diggable == false)
2530                                                 {
2531                                                         infostream<<"Server: WARNING: Player digged"
2532                                                                         <<" with impossible material + tool"
2533                                                                         <<" combination"<<std::endl;
2534                                                 }
2535                                                 
2536                                                 bool weared_out = titem->addWear(prop.wear);
2537
2538                                                 if(weared_out)
2539                                                 {
2540                                                         mlist->deleteItem(item_i);
2541                                                 }
2542                                         }
2543                                 }
2544
2545                                 /*
2546                                         Add dug item to inventory
2547                                 */
2548
2549                                 InventoryItem *item = NULL;
2550
2551                                 if(mineral != MINERAL_NONE)
2552                                         item = getDiggedMineralItem(mineral);
2553                                 
2554                                 // If not mineral
2555                                 if(item == NULL)
2556                                 {
2557                                         std::string &dug_s = content_features(material).dug_item;
2558                                         if(dug_s != "")
2559                                         {
2560                                                 std::istringstream is(dug_s, std::ios::binary);
2561                                                 item = InventoryItem::deSerialize(is);
2562                                         }
2563                                 }
2564                                 
2565                                 if(item != NULL)
2566                                 {
2567                                         // Add a item to inventory
2568                                         player->inventory.addItem("main", item);
2569
2570                                         // Send inventory
2571                                         UpdateCrafting(player->peer_id);
2572                                         SendInventory(player->peer_id);
2573                                 }
2574
2575                                 item = NULL;
2576
2577                                 if(mineral != MINERAL_NONE)
2578                                   item = getDiggedMineralItem(mineral);
2579                         
2580                                 // If not mineral
2581                                 if(item == NULL)
2582                                 {
2583                                         std::string &extra_dug_s = content_features(material).extra_dug_item;
2584                                         s32 extra_rarity = content_features(material).extra_dug_item_rarity;
2585                                         if(extra_dug_s != "" && extra_rarity != 0
2586                                            && myrand() % extra_rarity == 0)
2587                                         {
2588                                                 std::istringstream is(extra_dug_s, std::ios::binary);
2589                                                 item = InventoryItem::deSerialize(is);
2590                                         }
2591                                 }
2592                         
2593                                 if(item != NULL)
2594                                 {
2595                                         // Add a item to inventory
2596                                         player->inventory.addItem("main", item);
2597
2598                                         // Send inventory
2599                                         UpdateCrafting(player->peer_id);
2600                                         SendInventory(player->peer_id);
2601                                 }
2602                         }
2603
2604                         /*
2605                                 Remove the node
2606                                 (this takes some time so it is done after the quick stuff)
2607                         */
2608                         {
2609                                 MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2610
2611                                 m_env.getMap().removeNodeAndUpdate(p_under, modified_blocks);
2612                         }
2613                         /*
2614                                 Set blocks not sent to far players
2615                         */
2616                         for(core::list<u16>::Iterator
2617                                         i = far_players.begin();
2618                                         i != far_players.end(); i++)
2619                         {
2620                                 u16 peer_id = *i;
2621                                 RemoteClient *client = getClient(peer_id);
2622                                 if(client==NULL)
2623                                         continue;
2624                                 client->SetBlocksNotSent(modified_blocks);
2625                         }
2626                 }
2627                 
2628                 /*
2629                         1: place block
2630                 */
2631                 else if(action == 1)
2632                 {
2633
2634                         InventoryList *ilist = player->inventory.getList("main");
2635                         if(ilist == NULL)
2636                                 return;
2637
2638                         // Get item
2639                         InventoryItem *item = ilist->getItem(item_i);
2640                         
2641                         // If there is no item, it is not possible to add it anywhere
2642                         if(item == NULL)
2643                                 return;
2644                         
2645                         /*
2646                                 Handle material items
2647                         */
2648                         if(std::string("MaterialItem") == item->getName())
2649                         {
2650                                 try{
2651                                         // Don't add a node if this is not a free space
2652                                         MapNode n2 = m_env.getMap().getNode(p_over);
2653                                         bool no_enough_privs =
2654                                                         ((getPlayerPrivs(player) & PRIV_BUILD)==0);
2655                                         if(no_enough_privs)
2656                                                 infostream<<"Player "<<player->getName()<<" cannot add node"
2657                                                         <<" because privileges are "<<getPlayerPrivs(player)
2658                                                         <<std::endl;
2659
2660                                         if(content_features(n2).buildable_to == false
2661                                                 || no_enough_privs)
2662                                         {
2663                                                 // Client probably has wrong data.
2664                                                 // Set block not sent, so that client will get
2665                                                 // a valid one.
2666                                                 infostream<<"Client "<<peer_id<<" tried to place"
2667                                                                 <<" node in invalid position; setting"
2668                                                                 <<" MapBlock not sent."<<std::endl;
2669                                                 RemoteClient *client = getClient(peer_id);
2670                                                 v3s16 blockpos = getNodeBlockPos(p_over);
2671                                                 client->SetBlockNotSent(blockpos);
2672                                                 return;
2673                                         }
2674                                 }
2675                                 catch(InvalidPositionException &e)
2676                                 {
2677                                         infostream<<"Server: Ignoring ADDNODE: Node not found"
2678                                                         <<" Adding block to emerge queue."
2679                                                         <<std::endl;
2680                                         m_emerge_queue.addBlock(peer_id,
2681                                                         getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2682                                         return;
2683                                 }
2684
2685                                 // Reset build time counter
2686                                 getClient(peer_id)->m_time_from_building = 0.0;
2687                                 
2688                                 // Create node data
2689                                 MaterialItem *mitem = (MaterialItem*)item;
2690                                 MapNode n;
2691                                 n.setContent(mitem->getMaterial());
2692
2693                                 actionstream<<player->getName()<<" places material "
2694                                                 <<(int)mitem->getMaterial()
2695                                                 <<" at "<<PP(p_under)<<std::endl;
2696                         
2697                                 // Calculate direction for wall mounted stuff
2698                                 if(content_features(n).wall_mounted)
2699                                         n.param2 = packDir(p_under - p_over);
2700
2701                                 // Calculate the direction for furnaces and chests and stuff
2702                                 if(content_features(n).param_type == CPT_FACEDIR_SIMPLE)
2703                                 {
2704                                         v3f playerpos = player->getPosition();
2705                                         v3f blockpos = intToFloat(p_over, BS) - playerpos;
2706                                         blockpos = blockpos.normalize();
2707                                         n.param1 = 0;
2708                                         if (fabs(blockpos.X) > fabs(blockpos.Z)) {
2709                                                 if (blockpos.X < 0)
2710                                                         n.param1 = 3;
2711                                                 else
2712                                                         n.param1 = 1;
2713                                         } else {
2714                                                 if (blockpos.Z < 0)
2715                                                         n.param1 = 2;
2716                                                 else
2717                                                         n.param1 = 0;
2718                                         }
2719                                 }
2720
2721                                 /*
2722                                         Send to all close-by players
2723                                 */
2724                                 core::list<u16> far_players;
2725                                 sendAddNode(p_over, n, 0, &far_players, 30);
2726                                 
2727                                 /*
2728                                         Handle inventory
2729                                 */
2730                                 InventoryList *ilist = player->inventory.getList("main");
2731                                 if(g_settings->getBool("creative_mode") == false && ilist)
2732                                 {
2733                                         // Remove from inventory and send inventory
2734                                         if(mitem->getCount() == 1)
2735                                                 ilist->deleteItem(item_i);
2736                                         else
2737                                                 mitem->remove(1);
2738                                         // Send inventory
2739                                         UpdateCrafting(peer_id);
2740                                         SendInventory(peer_id);
2741                                 }
2742                                 
2743                                 /*
2744                                         Add node.
2745
2746                                         This takes some time so it is done after the quick stuff
2747                                 */
2748                                 core::map<v3s16, MapBlock*> modified_blocks;
2749                                 {
2750                                         MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2751
2752                                         std::string p_name = std::string(player->getName());
2753                                         m_env.getMap().addNodeAndUpdate(p_over, n, modified_blocks, p_name);
2754                                 }
2755                                 /*
2756                                         Set blocks not sent to far players
2757                                 */
2758                                 for(core::list<u16>::Iterator
2759                                                 i = far_players.begin();
2760                                                 i != far_players.end(); i++)
2761                                 {
2762                                         u16 peer_id = *i;
2763                                         RemoteClient *client = getClient(peer_id);
2764                                         if(client==NULL)
2765                                                 continue;
2766                                         client->SetBlocksNotSent(modified_blocks);
2767                                 }
2768
2769                                 /*
2770                                         Calculate special events
2771                                 */
2772                                 
2773                                 /*if(n.d == CONTENT_MESE)
2774                                 {
2775                                         u32 count = 0;
2776                                         for(s16 z=-1; z<=1; z++)
2777                                         for(s16 y=-1; y<=1; y++)
2778                                         for(s16 x=-1; x<=1; x++)
2779                                         {
2780                                                 
2781                                         }
2782                                 }*/
2783                         }
2784                         /*
2785                                 Place other item (not a block)
2786                         */
2787                         else
2788                         {
2789                                 v3s16 blockpos = getNodeBlockPos(p_over);
2790                                 
2791                                 /*
2792                                         Check that the block is loaded so that the item
2793                                         can properly be added to the static list too
2794                                 */
2795                                 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(blockpos);
2796                                 if(block==NULL)
2797                                 {
2798                                         infostream<<"Error while placing object: "
2799                                                         "block not found"<<std::endl;
2800                                         return;
2801                                 }
2802
2803                                 /*
2804                                         If in creative mode, item dropping is disabled unless
2805                                         player has build privileges
2806                                 */
2807                                 if(g_settings->getBool("creative_mode") &&
2808                                         (getPlayerPrivs(player) & PRIV_BUILD) == 0)
2809                                 {
2810                                         infostream<<"Not allowing player to drop item: "
2811                                                         "creative mode and no build privs"<<std::endl;
2812                                         return;
2813                                 }
2814
2815                                 // Calculate a position for it
2816                                 v3f pos = intToFloat(p_over, BS);
2817                                 //pos.Y -= BS*0.45;
2818                                 pos.Y -= BS*0.25; // let it drop a bit
2819                                 // Randomize a bit
2820                                 pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2821                                 pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2822
2823                                 /*
2824                                         Create the object
2825                                 */
2826                                 ServerActiveObject *obj = item->createSAO(&m_env, 0, pos);
2827
2828                                 if(obj == NULL)
2829                                 {
2830                                         infostream<<"WARNING: item resulted in NULL object, "
2831                                                         <<"not placing onto map"
2832                                                         <<std::endl;
2833                                 }
2834                                 else
2835                                 {
2836                                         actionstream<<player->getName()<<" places "<<item->getName()
2837                                                         <<" at "<<PP(p_over)<<std::endl;
2838                                 
2839                                         // Add the object to the environment
2840                                         m_env.addActiveObject(obj);
2841                                         
2842                                         infostream<<"Placed object"<<std::endl;
2843
2844                                         if(g_settings->getBool("creative_mode") == false)
2845                                         {
2846                                                 // Delete the right amount of items from the slot
2847                                                 u16 dropcount = item->getDropCount();
2848                                                 
2849                                                 // Delete item if all gone
2850                                                 if(item->getCount() <= dropcount)
2851                                                 {
2852                                                         if(item->getCount() < dropcount)
2853                                                                 infostream<<"WARNING: Server: dropped more items"
2854                                                                                 <<" than the slot contains"<<std::endl;
2855                                                         
2856                                                         InventoryList *ilist = player->inventory.getList("main");
2857                                                         if(ilist)
2858                                                                 // Remove from inventory and send inventory
2859                                                                 ilist->deleteItem(item_i);
2860                                                 }
2861                                                 // Else decrement it
2862                                                 else
2863                                                         item->remove(dropcount);
2864                                                 
2865                                                 // Send inventory
2866                                                 UpdateCrafting(peer_id);
2867                                                 SendInventory(peer_id);
2868                                         }
2869                                 }
2870                         }
2871
2872                 } // action == 1
2873
2874                 /*
2875                         Catch invalid actions
2876                 */
2877                 else
2878                 {
2879                         infostream<<"WARNING: Server: Invalid action "
2880                                         <<action<<std::endl;
2881                 }
2882         }
2883 #if 0
2884         else if(command == TOSERVER_RELEASE)
2885         {
2886                 if(datasize < 3)
2887                         return;
2888                 /*
2889                         length: 3
2890                         [0] u16 command
2891                         [2] u8 button
2892                 */
2893                 infostream<<"TOSERVER_RELEASE ignored"<<std::endl;
2894         }
2895 #endif
2896         else if(command == TOSERVER_SIGNTEXT)
2897         {
2898                 infostream<<"Server: TOSERVER_SIGNTEXT not supported anymore"
2899                                 <<std::endl;
2900                 return;
2901         }
2902         else if(command == TOSERVER_SIGNNODETEXT)
2903         {
2904                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2905                         return;
2906                 /*
2907                         u16 command
2908                         v3s16 p
2909                         u16 textlen
2910                         textdata
2911                 */
2912                 std::string datastring((char*)&data[2], datasize-2);
2913                 std::istringstream is(datastring, std::ios_base::binary);
2914                 u8 buf[6];
2915                 // Read stuff
2916                 is.read((char*)buf, 6);
2917                 v3s16 p = readV3S16(buf);
2918                 is.read((char*)buf, 2);
2919                 u16 textlen = readU16(buf);
2920                 std::string text;
2921                 for(u16 i=0; i<textlen; i++)
2922                 {
2923                         is.read((char*)buf, 1);
2924                         text += (char)buf[0];
2925                 }
2926
2927                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
2928                 if(!meta)
2929                         return;
2930                 if(meta->typeId() != CONTENT_SIGN_WALL)
2931                         return;
2932                 SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
2933                 signmeta->setText(text);
2934                 
2935                 actionstream<<player->getName()<<" writes \""<<text<<"\" to sign "
2936                                 <<" at "<<PP(p)<<std::endl;
2937                                 
2938                 v3s16 blockpos = getNodeBlockPos(p);
2939                 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(blockpos);
2940                 if(block)
2941                 {
2942                         block->setChangedFlag();
2943                 }
2944
2945                 for(core::map<u16, RemoteClient*>::Iterator
2946                         i = m_clients.getIterator();
2947                         i.atEnd()==false; i++)
2948                 {
2949                         RemoteClient *client = i.getNode()->getValue();
2950                         client->SetBlockNotSent(blockpos);
2951                 }
2952         }
2953         else if(command == TOSERVER_INVENTORY_ACTION)
2954         {
2955                 /*// Ignore inventory changes if in creative mode
2956                 if(g_settings->getBool("creative_mode") == true)
2957                 {
2958                         infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
2959                                         <<std::endl;
2960                         return;
2961                 }*/
2962                 // Strip command and create a stream
2963                 std::string datastring((char*)&data[2], datasize-2);
2964                 infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
2965                 std::istringstream is(datastring, std::ios_base::binary);
2966                 // Create an action
2967                 InventoryAction *a = InventoryAction::deSerialize(is);
2968                 if(a != NULL)
2969                 {
2970                         // Create context
2971                         InventoryContext c;
2972                         c.current_player = player;
2973
2974                         /*
2975                                 Handle craftresult specially if not in creative mode
2976                         */
2977                         bool disable_action = false;
2978                         if(a->getType() == IACTION_MOVE
2979                                         && g_settings->getBool("creative_mode") == false)
2980                         {
2981                                 IMoveAction *ma = (IMoveAction*)a;
2982                                 if(ma->to_inv == "current_player" &&
2983                                                 ma->from_inv == "current_player")
2984                                 {
2985                                         InventoryList *rlist = player->inventory.getList("craftresult");
2986                                         assert(rlist);
2987                                         InventoryList *clist = player->inventory.getList("craft");
2988                                         assert(clist);
2989                                         InventoryList *mlist = player->inventory.getList("main");
2990                                         assert(mlist);
2991                                         /*
2992                                                 Craftresult is no longer preview if something
2993                                                 is moved into it
2994                                         */
2995                                         if(ma->to_list == "craftresult"
2996                                                         && ma->from_list != "craftresult")
2997                                         {
2998                                                 // If it currently is a preview, remove
2999                                                 // its contents
3000                                                 if(player->craftresult_is_preview)
3001                                                 {
3002                                                         rlist->deleteItem(0);
3003                                                 }
3004                                                 player->craftresult_is_preview = false;
3005                                         }
3006                                         /*
3007                                                 Crafting takes place if this condition is true.
3008                                         */
3009                                         if(player->craftresult_is_preview &&
3010                                                         ma->from_list == "craftresult")
3011                                         {
3012                                                 player->craftresult_is_preview = false;
3013                                                 clist->decrementMaterials(1);
3014                                                 
3015                                                 /* Print out action */
3016                                                 InventoryList *list =
3017                                                                 player->inventory.getList("craftresult");
3018                                                 assert(list);
3019                                                 InventoryItem *item = list->getItem(0);
3020                                                 std::string itemname = "NULL";
3021                                                 if(item)
3022                                                         itemname = item->getName();
3023                                                 actionstream<<player->getName()<<" crafts "
3024                                                                 <<itemname<<std::endl;
3025                                         }
3026                                         /*
3027                                                 If the craftresult is placed on itself, move it to
3028                                                 main inventory instead of doing the action
3029                                         */
3030                                         if(ma->to_list == "craftresult"
3031                                                         && ma->from_list == "craftresult")
3032                                         {
3033                                                 disable_action = true;
3034                                                 
3035                                                 InventoryItem *item1 = rlist->changeItem(0, NULL);
3036                                                 mlist->addItem(item1);
3037                                         }
3038                                 }
3039                                 // Disallow moving items if not allowed to build
3040                                 else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
3041                                 {
3042                                         return;
3043                                 }
3044                                 // if it's a locking chest, only allow the owner or server admins to move items
3045                                 else if (ma->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3046                                 {
3047                                         Strfnd fn(ma->from_inv);
3048                                         std::string id0 = fn.next(":");
3049                                         if(id0 == "nodemeta")
3050                                         {
3051                                                 v3s16 p;
3052                                                 p.X = stoi(fn.next(","));
3053                                                 p.Y = stoi(fn.next(","));
3054                                                 p.Z = stoi(fn.next(","));
3055                                                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
3056                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3057                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3058                                                         if (lcm->getOwner() != player->getName())
3059                                                                 return;
3060                                                 }
3061                                         }
3062                                 }
3063                                 else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3064                                 {
3065                                         Strfnd fn(ma->to_inv);
3066                                         std::string id0 = fn.next(":");
3067                                         if(id0 == "nodemeta")
3068                                         {
3069                                                 v3s16 p;
3070                                                 p.X = stoi(fn.next(","));
3071                                                 p.Y = stoi(fn.next(","));
3072                                                 p.Z = stoi(fn.next(","));
3073                                                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
3074                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3075                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3076                                                         if (lcm->getOwner() != player->getName())
3077                                                                 return;
3078                                                 }
3079                                         }
3080                                 }
3081                         }
3082                         
3083                         if(disable_action == false)
3084                         {
3085                                 // Feed action to player inventory
3086                                 a->apply(&c, this);
3087                                 // Eat the action
3088                                 delete a;
3089                         }
3090                         else
3091                         {
3092                                 // Send inventory
3093                                 UpdateCrafting(player->peer_id);
3094                                 SendInventory(player->peer_id);
3095                         }
3096                 }
3097                 else
3098                 {
3099                         infostream<<"TOSERVER_INVENTORY_ACTION: "
3100                                         <<"InventoryAction::deSerialize() returned NULL"
3101                                         <<std::endl;
3102                 }
3103         }
3104         else if(command == TOSERVER_CHAT_MESSAGE)
3105         {
3106                 /*
3107                         u16 command
3108                         u16 length
3109                         wstring message
3110                 */
3111                 u8 buf[6];
3112                 std::string datastring((char*)&data[2], datasize-2);
3113                 std::istringstream is(datastring, std::ios_base::binary);
3114                 
3115                 // Read stuff
3116                 is.read((char*)buf, 2);
3117                 u16 len = readU16(buf);
3118                 
3119                 std::wstring message;
3120                 for(u16 i=0; i<len; i++)
3121                 {
3122                         is.read((char*)buf, 2);
3123                         message += (wchar_t)readU16(buf);
3124                 }
3125
3126                 // Get player name of this client
3127                 std::wstring name = narrow_to_wide(player->getName());
3128                 
3129                 // Line to send to players
3130                 std::wstring line;
3131                 // Whether to send to the player that sent the line
3132                 bool send_to_sender = false;
3133                 // Whether to send to other players
3134                 bool send_to_others = false;
3135                 
3136                 // Local player gets all privileges regardless of
3137                 // what's set on their account.
3138                 u64 privs = getPlayerPrivs(player);
3139
3140                 // Parse commands
3141                 if(message[0] == L'/')
3142                 {
3143                         size_t strip_size = 1;
3144                         if (message[1] == L'#') // support old-style commans
3145                                 ++strip_size;
3146                         message = message.substr(strip_size);
3147
3148                         WStrfnd f1(message);
3149                         f1.next(L" "); // Skip over /#whatever
3150                         std::wstring paramstring = f1.next(L"");
3151
3152                         ServerCommandContext *ctx = new ServerCommandContext(
3153                                 str_split(message, L' '),
3154                                 paramstring,
3155                                 this,
3156                                 &m_env,
3157                                 player,
3158                                 privs);
3159
3160                         std::wstring reply(processServerCommand(ctx));
3161                         send_to_sender = ctx->flags & SEND_TO_SENDER;
3162                         send_to_others = ctx->flags & SEND_TO_OTHERS;
3163
3164                         if (ctx->flags & SEND_NO_PREFIX)
3165                                 line += reply;
3166                         else
3167                                 line += L"Server: " + reply;
3168
3169                         delete ctx;
3170
3171                 }
3172                 else
3173                 {
3174                         if(privs & PRIV_SHOUT)
3175                         {
3176                                 line += L"<";
3177                                 line += name;
3178                                 line += L"> ";
3179                                 line += message;
3180                                 send_to_others = true;
3181                         }
3182                         else
3183                         {
3184                                 line += L"Server: You are not allowed to shout";
3185                                 send_to_sender = true;
3186                         }
3187                 }
3188                 
3189                 if(line != L"")
3190                 {
3191                         if(send_to_others)
3192                                 actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
3193
3194                         /*
3195                                 Send the message to clients
3196                         */
3197                         for(core::map<u16, RemoteClient*>::Iterator
3198                                 i = m_clients.getIterator();
3199                                 i.atEnd() == false; i++)
3200                         {
3201                                 // Get client and check that it is valid
3202                                 RemoteClient *client = i.getNode()->getValue();
3203                                 assert(client->peer_id == i.getNode()->getKey());
3204                                 if(client->serialization_version == SER_FMT_VER_INVALID)
3205                                         continue;
3206
3207                                 // Filter recipient
3208                                 bool sender_selected = (peer_id == client->peer_id);
3209                                 if(sender_selected == true && send_to_sender == false)
3210                                         continue;
3211                                 if(sender_selected == false && send_to_others == false)
3212                                         continue;
3213
3214                                 SendChatMessage(client->peer_id, line);
3215                         }
3216                 }
3217         }
3218         else if(command == TOSERVER_DAMAGE)
3219         {
3220                 std::string datastring((char*)&data[2], datasize-2);
3221                 std::istringstream is(datastring, std::ios_base::binary);
3222                 u8 damage = readU8(is);
3223
3224                 if(g_settings->getBool("enable_damage"))
3225                 {
3226                         actionstream<<player->getName()<<" damaged by "
3227                                         <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
3228                                         <<std::endl;
3229                                 
3230                         HandlePlayerHP(player, damage);
3231                 }
3232                 else
3233                 {
3234                         SendPlayerHP(player);
3235                 }
3236         }
3237         else if(command == TOSERVER_PASSWORD)
3238         {
3239                 /*
3240                         [0] u16 TOSERVER_PASSWORD
3241                         [2] u8[28] old password
3242                         [30] u8[28] new password
3243                 */
3244
3245                 if(datasize != 2+PASSWORD_SIZE*2)
3246                         return;
3247                 /*char password[PASSWORD_SIZE];
3248                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3249                         password[i] = data[2+i];
3250                 password[PASSWORD_SIZE-1] = 0;*/
3251                 std::string oldpwd;
3252                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3253                 {
3254                         char c = data[2+i];
3255                         if(c == 0)
3256                                 break;
3257                         oldpwd += c;
3258                 }
3259                 std::string newpwd;
3260                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3261                 {
3262                         char c = data[2+PASSWORD_SIZE+i];
3263                         if(c == 0)
3264                                 break;
3265                         newpwd += c;
3266                 }
3267
3268                 infostream<<"Server: Client requests a password change from "
3269                                 <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
3270
3271                 std::string playername = player->getName();
3272
3273                 if(m_authmanager.exists(playername) == false)
3274                 {
3275                         infostream<<"Server: playername not found in authmanager"<<std::endl;
3276                         // Wrong old password supplied!!
3277                         SendChatMessage(peer_id, L"playername not found in authmanager");
3278                         return;
3279                 }
3280
3281                 std::string checkpwd = m_authmanager.getPassword(playername);
3282
3283                 if(oldpwd != checkpwd)
3284                 {
3285                         infostream<<"Server: invalid old password"<<std::endl;
3286                         // Wrong old password supplied!!
3287                         SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
3288                         return;
3289                 }
3290
3291                 actionstream<<player->getName()<<" changes password"<<std::endl;
3292
3293                 m_authmanager.setPassword(playername, newpwd);
3294                 
3295                 infostream<<"Server: password change successful for "<<playername
3296                                 <<std::endl;
3297                 SendChatMessage(peer_id, L"Password change successful");
3298         }
3299         else if(command == TOSERVER_PLAYERITEM)
3300         {
3301                 if (datasize < 2+2)
3302                         return;
3303
3304                 u16 item = readU16(&data[2]);
3305                 player->wieldItem(item);
3306                 SendWieldedItem(player);
3307         }
3308         else if(command == TOSERVER_RESPAWN)
3309         {
3310                 if(player->hp != 0)
3311                         return;
3312                 
3313                 RespawnPlayer(player);
3314                 
3315                 actionstream<<player->getName()<<" respawns at "
3316                                 <<PP(player->getPosition()/BS)<<std::endl;
3317         }
3318         else
3319         {
3320                 infostream<<"Server::ProcessData(): Ignoring "
3321                                 "unknown command "<<command<<std::endl;
3322         }
3323         
3324         } //try
3325         catch(SendFailedException &e)
3326         {
3327                 errorstream<<"Server::ProcessData(): SendFailedException: "
3328                                 <<"what="<<e.what()
3329                                 <<std::endl;
3330         }
3331 }
3332
3333 void Server::onMapEditEvent(MapEditEvent *event)
3334 {
3335         //infostream<<"Server::onMapEditEvent()"<<std::endl;
3336         if(m_ignore_map_edit_events)
3337                 return;
3338         MapEditEvent *e = event->clone();
3339         m_unsent_map_edit_queue.push_back(e);
3340 }
3341
3342 Inventory* Server::getInventory(InventoryContext *c, std::string id)
3343 {
3344         if(id == "current_player")
3345         {
3346                 assert(c->current_player);
3347                 return &(c->current_player->inventory);
3348         }
3349         
3350         Strfnd fn(id);
3351         std::string id0 = fn.next(":");
3352
3353         if(id0 == "nodemeta")
3354         {
3355                 v3s16 p;
3356                 p.X = stoi(fn.next(","));
3357                 p.Y = stoi(fn.next(","));
3358                 p.Z = stoi(fn.next(","));
3359                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
3360                 if(meta)
3361                         return meta->getInventory();
3362                 infostream<<"nodemeta at ("<<p.X<<","<<p.Y<<","<<p.Z<<"): "
3363                                 <<"no metadata found"<<std::endl;
3364                 return NULL;
3365         }
3366
3367         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3368         return NULL;
3369 }
3370 void Server::inventoryModified(InventoryContext *c, std::string id)
3371 {
3372         if(id == "current_player")
3373         {
3374                 assert(c->current_player);
3375                 // Send inventory
3376                 UpdateCrafting(c->current_player->peer_id);
3377                 SendInventory(c->current_player->peer_id);
3378                 return;
3379         }
3380         
3381         Strfnd fn(id);
3382         std::string id0 = fn.next(":");
3383
3384         if(id0 == "nodemeta")
3385         {
3386                 v3s16 p;
3387                 p.X = stoi(fn.next(","));
3388                 p.Y = stoi(fn.next(","));
3389                 p.Z = stoi(fn.next(","));
3390                 v3s16 blockpos = getNodeBlockPos(p);
3391
3392                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
3393                 if(meta)
3394                         meta->inventoryModified();
3395
3396                 for(core::map<u16, RemoteClient*>::Iterator
3397                         i = m_clients.getIterator();
3398                         i.atEnd()==false; i++)
3399                 {
3400                         RemoteClient *client = i.getNode()->getValue();
3401                         client->SetBlockNotSent(blockpos);
3402                 }
3403
3404                 return;
3405         }
3406
3407         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3408 }
3409
3410 core::list<PlayerInfo> Server::getPlayerInfo()
3411 {
3412         DSTACK(__FUNCTION_NAME);
3413         JMutexAutoLock envlock(m_env_mutex);
3414         JMutexAutoLock conlock(m_con_mutex);
3415         
3416         core::list<PlayerInfo> list;
3417
3418         core::list<Player*> players = m_env.getPlayers();
3419         
3420         core::list<Player*>::Iterator i;
3421         for(i = players.begin();
3422                         i != players.end(); i++)
3423         {
3424                 PlayerInfo info;
3425
3426                 Player *player = *i;
3427
3428                 try{
3429                         // Copy info from connection to info struct
3430                         info.id = player->peer_id;
3431                         info.address = m_con.GetPeerAddress(player->peer_id);
3432                         info.avg_rtt = m_con.GetPeerAvgRTT(player->peer_id);
3433                 }
3434                 catch(con::PeerNotFoundException &e)
3435                 {
3436                         // Set dummy peer info
3437                         info.id = 0;
3438                         info.address = Address(0,0,0,0,0);
3439                         info.avg_rtt = 0.0;
3440                 }
3441
3442                 snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName());
3443                 info.position = player->getPosition();
3444
3445                 list.push_back(info);
3446         }
3447
3448         return list;
3449 }
3450
3451
3452 void Server::peerAdded(con::Peer *peer)
3453 {
3454         DSTACK(__FUNCTION_NAME);
3455         infostream<<"Server::peerAdded(): peer->id="
3456                         <<peer->id<<std::endl;
3457         
3458         PeerChange c;
3459         c.type = PEER_ADDED;
3460         c.peer_id = peer->id;
3461         c.timeout = false;
3462         m_peer_change_queue.push_back(c);
3463 }
3464
3465 void Server::deletingPeer(con::Peer *peer, bool timeout)
3466 {
3467         DSTACK(__FUNCTION_NAME);
3468         infostream<<"Server::deletingPeer(): peer->id="
3469                         <<peer->id<<", timeout="<<timeout<<std::endl;
3470         
3471         PeerChange c;
3472         c.type = PEER_REMOVED;
3473         c.peer_id = peer->id;
3474         c.timeout = timeout;
3475         m_peer_change_queue.push_back(c);
3476 }
3477
3478 /*
3479         Static send methods
3480 */
3481
3482 void Server::SendHP(con::Connection &con, u16 peer_id, u8 hp)
3483 {
3484         DSTACK(__FUNCTION_NAME);
3485         std::ostringstream os(std::ios_base::binary);
3486
3487         writeU16(os, TOCLIENT_HP);
3488         writeU8(os, hp);
3489
3490         // Make data buffer
3491         std::string s = os.str();
3492         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3493         // Send as reliable
3494         con.Send(peer_id, 0, data, true);
3495 }
3496
3497 void Server::SendAccessDenied(con::Connection &con, u16 peer_id,
3498                 const std::wstring &reason)
3499 {
3500         DSTACK(__FUNCTION_NAME);
3501         std::ostringstream os(std::ios_base::binary);
3502
3503         writeU16(os, TOCLIENT_ACCESS_DENIED);
3504         os<<serializeWideString(reason);
3505
3506         // Make data buffer
3507         std::string s = os.str();
3508         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3509         // Send as reliable
3510         con.Send(peer_id, 0, data, true);
3511 }
3512
3513 void Server::SendDeathscreen(con::Connection &con, u16 peer_id,
3514                 bool set_camera_point_target, v3f camera_point_target)
3515 {
3516         DSTACK(__FUNCTION_NAME);
3517         std::ostringstream os(std::ios_base::binary);
3518
3519         writeU16(os, TOCLIENT_DEATHSCREEN);
3520         writeU8(os, set_camera_point_target);
3521         writeV3F1000(os, camera_point_target);
3522
3523         // Make data buffer
3524         std::string s = os.str();
3525         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3526         // Send as reliable
3527         con.Send(peer_id, 0, data, true);
3528 }
3529
3530 /*
3531         Non-static send methods
3532 */
3533
3534 void Server::SendObjectData(float dtime)
3535 {
3536         DSTACK(__FUNCTION_NAME);
3537
3538         core::map<v3s16, bool> stepped_blocks;
3539         
3540         for(core::map<u16, RemoteClient*>::Iterator
3541                 i = m_clients.getIterator();
3542                 i.atEnd() == false; i++)
3543         {
3544                 u16 peer_id = i.getNode()->getKey();
3545                 RemoteClient *client = i.getNode()->getValue();
3546                 assert(client->peer_id == peer_id);
3547                 
3548                 if(client->serialization_version == SER_FMT_VER_INVALID)
3549                         continue;
3550                 
3551                 client->SendObjectData(this, dtime, stepped_blocks);
3552         }
3553 }
3554
3555 void Server::SendPlayerInfos()
3556 {
3557         DSTACK(__FUNCTION_NAME);
3558
3559         //JMutexAutoLock envlock(m_env_mutex);
3560         
3561         // Get connected players
3562         core::list<Player*> players = m_env.getPlayers(true);
3563         
3564         u32 player_count = players.getSize();
3565         u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
3566
3567         SharedBuffer<u8> data(datasize);
3568         writeU16(&data[0], TOCLIENT_PLAYERINFO);
3569         
3570         u32 start = 2;
3571         core::list<Player*>::Iterator i;
3572         for(i = players.begin();
3573                         i != players.end(); i++)
3574         {
3575                 Player *player = *i;
3576
3577                 /*infostream<<"Server sending player info for player with "
3578                                 "peer_id="<<player->peer_id<<std::endl;*/
3579                 
3580                 writeU16(&data[start], player->peer_id);
3581                 memset((char*)&data[start+2], 0, PLAYERNAME_SIZE);
3582                 snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName());
3583                 start += 2+PLAYERNAME_SIZE;
3584         }
3585
3586         //JMutexAutoLock conlock(m_con_mutex);
3587
3588         // Send as reliable
3589         m_con.SendToAll(0, data, true);
3590 }
3591
3592 void Server::SendInventory(u16 peer_id)
3593 {
3594         DSTACK(__FUNCTION_NAME);
3595         
3596         Player* player = m_env.getPlayer(peer_id);
3597         assert(player);
3598
3599         /*
3600                 Serialize it
3601         */
3602
3603         std::ostringstream os;
3604         //os.imbue(std::locale("C"));
3605
3606         player->inventory.serialize(os);
3607
3608         std::string s = os.str();
3609         
3610         SharedBuffer<u8> data(s.size()+2);
3611         writeU16(&data[0], TOCLIENT_INVENTORY);
3612         memcpy(&data[2], s.c_str(), s.size());
3613         
3614         // Send as reliable
3615         m_con.Send(peer_id, 0, data, true);
3616 }
3617
3618 std::string getWieldedItemString(const Player *player)
3619 {
3620         const InventoryItem *item = player->getWieldItem();
3621         if (item == NULL)
3622                 return std::string("");
3623         std::ostringstream os(std::ios_base::binary);
3624         item->serialize(os);
3625         return os.str();
3626 }
3627
3628 void Server::SendWieldedItem(const Player* player)
3629 {
3630         DSTACK(__FUNCTION_NAME);
3631
3632         assert(player);
3633
3634         std::ostringstream os(std::ios_base::binary);
3635
3636         writeU16(os, TOCLIENT_PLAYERITEM);
3637         writeU16(os, 1);
3638         writeU16(os, player->peer_id);
3639         os<<serializeString(getWieldedItemString(player));
3640
3641         // Make data buffer
3642         std::string s = os.str();
3643         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3644
3645         m_con.SendToAll(0, data, true);
3646 }
3647
3648 void Server::SendPlayerItems()
3649 {
3650         DSTACK(__FUNCTION_NAME);
3651
3652         std::ostringstream os(std::ios_base::binary);
3653         core::list<Player *> players = m_env.getPlayers(true);
3654
3655         writeU16(os, TOCLIENT_PLAYERITEM);
3656         writeU16(os, players.size());
3657         core::list<Player *>::Iterator i;
3658         for(i = players.begin(); i != players.end(); ++i)
3659         {
3660                 Player *p = *i;
3661                 writeU16(os, p->peer_id);
3662                 os<<serializeString(getWieldedItemString(p));
3663         }
3664
3665         // Make data buffer
3666         std::string s = os.str();
3667         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3668
3669         m_con.SendToAll(0, data, true);
3670 }
3671
3672 void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
3673 {
3674         DSTACK(__FUNCTION_NAME);
3675         
3676         std::ostringstream os(std::ios_base::binary);
3677         u8 buf[12];
3678         
3679         // Write command
3680         writeU16(buf, TOCLIENT_CHAT_MESSAGE);
3681         os.write((char*)buf, 2);
3682         
3683         // Write length
3684         writeU16(buf, message.size());
3685         os.write((char*)buf, 2);
3686         
3687         // Write string
3688         for(u32 i=0; i<message.size(); i++)
3689         {
3690                 u16 w = message[i];
3691                 writeU16(buf, w);
3692                 os.write((char*)buf, 2);
3693         }
3694         
3695         // Make data buffer
3696         std::string s = os.str();
3697         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3698         // Send as reliable
3699         m_con.Send(peer_id, 0, data, true);
3700 }
3701
3702 void Server::BroadcastChatMessage(const std::wstring &message)
3703 {
3704         for(core::map<u16, RemoteClient*>::Iterator
3705                 i = m_clients.getIterator();
3706                 i.atEnd() == false; i++)
3707         {
3708                 // Get client and check that it is valid
3709                 RemoteClient *client = i.getNode()->getValue();
3710                 assert(client->peer_id == i.getNode()->getKey());
3711                 if(client->serialization_version == SER_FMT_VER_INVALID)
3712                         continue;
3713
3714                 SendChatMessage(client->peer_id, message);
3715         }
3716 }
3717
3718 void Server::SendPlayerHP(Player *player)
3719 {
3720         SendHP(m_con, player->peer_id, player->hp);
3721 }
3722
3723 void Server::SendMovePlayer(Player *player)
3724 {
3725         DSTACK(__FUNCTION_NAME);
3726         std::ostringstream os(std::ios_base::binary);
3727
3728         writeU16(os, TOCLIENT_MOVE_PLAYER);
3729         writeV3F1000(os, player->getPosition());
3730         writeF1000(os, player->getPitch());
3731         writeF1000(os, player->getYaw());
3732         
3733         {
3734                 v3f pos = player->getPosition();
3735                 f32 pitch = player->getPitch();
3736                 f32 yaw = player->getYaw();
3737                 infostream<<"Server sending TOCLIENT_MOVE_PLAYER"
3738                                 <<" pos=("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
3739                                 <<" pitch="<<pitch
3740                                 <<" yaw="<<yaw
3741                                 <<std::endl;
3742         }
3743
3744         // Make data buffer
3745         std::string s = os.str();
3746         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3747         // Send as reliable
3748         m_con.Send(player->peer_id, 0, data, true);
3749 }
3750
3751 void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
3752         core::list<u16> *far_players, float far_d_nodes)
3753 {
3754         float maxd = far_d_nodes*BS;
3755         v3f p_f = intToFloat(p, BS);
3756
3757         // Create packet
3758         u32 replysize = 8;
3759         SharedBuffer<u8> reply(replysize);
3760         writeU16(&reply[0], TOCLIENT_REMOVENODE);
3761         writeS16(&reply[2], p.X);
3762         writeS16(&reply[4], p.Y);
3763         writeS16(&reply[6], p.Z);
3764
3765         for(core::map<u16, RemoteClient*>::Iterator
3766                 i = m_clients.getIterator();
3767                 i.atEnd() == false; i++)
3768         {
3769                 // Get client and check that it is valid
3770                 RemoteClient *client = i.getNode()->getValue();
3771                 assert(client->peer_id == i.getNode()->getKey());
3772                 if(client->serialization_version == SER_FMT_VER_INVALID)
3773                         continue;
3774
3775                 // Don't send if it's the same one
3776                 if(client->peer_id == ignore_id)
3777                         continue;
3778                 
3779                 if(far_players)
3780                 {
3781                         // Get player
3782                         Player *player = m_env.getPlayer(client->peer_id);
3783                         if(player)
3784                         {
3785                                 // If player is far away, only set modified blocks not sent
3786                                 v3f player_pos = player->getPosition();
3787                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3788                                 {
3789                                         far_players->push_back(client->peer_id);
3790                                         continue;
3791                                 }
3792                         }
3793                 }
3794
3795                 // Send as reliable
3796                 m_con.Send(client->peer_id, 0, reply, true);
3797         }
3798 }
3799
3800 void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
3801                 core::list<u16> *far_players, float far_d_nodes)
3802 {
3803         float maxd = far_d_nodes*BS;
3804         v3f p_f = intToFloat(p, BS);
3805
3806         for(core::map<u16, RemoteClient*>::Iterator
3807                 i = m_clients.getIterator();
3808                 i.atEnd() == false; i++)
3809         {
3810                 // Get client and check that it is valid
3811                 RemoteClient *client = i.getNode()->getValue();
3812                 assert(client->peer_id == i.getNode()->getKey());
3813                 if(client->serialization_version == SER_FMT_VER_INVALID)
3814                         continue;
3815
3816                 // Don't send if it's the same one
3817                 if(client->peer_id == ignore_id)
3818                         continue;
3819
3820                 if(far_players)
3821                 {
3822                         // Get player
3823                         Player *player = m_env.getPlayer(client->peer_id);
3824                         if(player)
3825                         {
3826                                 // If player is far away, only set modified blocks not sent
3827                                 v3f player_pos = player->getPosition();
3828                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3829                                 {
3830                                         far_players->push_back(client->peer_id);
3831                                         continue;
3832                                 }
3833                         }
3834                 }
3835
3836                 // Create packet
3837                 u32 replysize = 8 + MapNode::serializedLength(client->serialization_version);
3838                 SharedBuffer<u8> reply(replysize);
3839                 writeU16(&reply[0], TOCLIENT_ADDNODE);
3840                 writeS16(&reply[2], p.X);
3841                 writeS16(&reply[4], p.Y);
3842                 writeS16(&reply[6], p.Z);
3843                 n.serialize(&reply[8], client->serialization_version);
3844
3845                 // Send as reliable
3846                 m_con.Send(client->peer_id, 0, reply, true);
3847         }
3848 }
3849
3850 void Server::setBlockNotSent(v3s16 p)
3851 {
3852         for(core::map<u16, RemoteClient*>::Iterator
3853                 i = m_clients.getIterator();
3854                 i.atEnd()==false; i++)
3855         {
3856                 RemoteClient *client = i.getNode()->getValue();
3857                 client->SetBlockNotSent(p);
3858         }
3859 }
3860
3861 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
3862 {
3863         DSTACK(__FUNCTION_NAME);
3864
3865         v3s16 p = block->getPos();
3866         
3867 #if 0
3868         // Analyze it a bit
3869         bool completely_air = true;
3870         for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
3871         for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
3872         for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
3873         {
3874                 if(block->getNodeNoEx(v3s16(x0,y0,z0)).d != CONTENT_AIR)
3875                 {
3876                         completely_air = false;
3877                         x0 = y0 = z0 = MAP_BLOCKSIZE; // Break out
3878                 }
3879         }
3880
3881         // Print result
3882         infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<"): ";
3883         if(completely_air)
3884                 infostream<<"[completely air] ";
3885         infostream<<std::endl;
3886 #endif
3887
3888         /*
3889                 Create a packet with the block in the right format
3890         */
3891         
3892         std::ostringstream os(std::ios_base::binary);
3893         block->serialize(os, ver);
3894         std::string s = os.str();
3895         SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
3896
3897         u32 replysize = 8 + blockdata.getSize();
3898         SharedBuffer<u8> reply(replysize);
3899         writeU16(&reply[0], TOCLIENT_BLOCKDATA);
3900         writeS16(&reply[2], p.X);
3901         writeS16(&reply[4], p.Y);
3902         writeS16(&reply[6], p.Z);
3903         memcpy(&reply[8], *blockdata, blockdata.getSize());
3904
3905         /*infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<")"
3906                         <<":  \tpacket size: "<<replysize<<std::endl;*/
3907         
3908         /*
3909                 Send packet
3910         */
3911         m_con.Send(peer_id, 1, reply, true);
3912 }
3913
3914 void Server::SendBlocks(float dtime)
3915 {
3916         DSTACK(__FUNCTION_NAME);
3917
3918         JMutexAutoLock envlock(m_env_mutex);
3919         JMutexAutoLock conlock(m_con_mutex);
3920
3921         //TimeTaker timer("Server::SendBlocks");
3922
3923         core::array<PrioritySortedBlockTransfer> queue;
3924
3925         s32 total_sending = 0;
3926         
3927         {
3928                 ScopeProfiler sp(g_profiler, "Server: selecting blocks for sending");
3929
3930                 for(core::map<u16, RemoteClient*>::Iterator
3931                         i = m_clients.getIterator();
3932                         i.atEnd() == false; i++)
3933                 {
3934                         RemoteClient *client = i.getNode()->getValue();
3935                         assert(client->peer_id == i.getNode()->getKey());
3936
3937                         total_sending += client->SendingCount();
3938                         
3939                         if(client->serialization_version == SER_FMT_VER_INVALID)
3940                                 continue;
3941                         
3942                         client->GetNextBlocks(this, dtime, queue);
3943                 }
3944         }
3945
3946         // Sort.
3947         // Lowest priority number comes first.
3948         // Lowest is most important.
3949         queue.sort();
3950
3951         for(u32 i=0; i<queue.size(); i++)
3952         {
3953                 //TODO: Calculate limit dynamically
3954                 if(total_sending >= g_settings->getS32
3955                                 ("max_simultaneous_block_sends_server_total"))
3956                         break;
3957                 
3958                 PrioritySortedBlockTransfer q = queue[i];
3959
3960                 MapBlock *block = NULL;
3961                 try
3962                 {
3963                         block = m_env.getMap().getBlockNoCreate(q.pos);
3964                 }
3965                 catch(InvalidPositionException &e)
3966                 {
3967                         continue;
3968                 }
3969
3970                 RemoteClient *client = getClient(q.peer_id);
3971
3972                 SendBlockNoLock(q.peer_id, block, client->serialization_version);
3973
3974                 client->SentBlock(q.pos);
3975
3976                 total_sending++;
3977         }
3978 }
3979
3980 /*
3981         Something random
3982 */
3983
3984 void Server::HandlePlayerHP(Player *player, s16 damage)
3985 {
3986         if(player->hp > damage)
3987         {
3988                 player->hp -= damage;
3989                 SendPlayerHP(player);
3990         }
3991         else
3992         {
3993                 infostream<<"Server::HandlePlayerHP(): Player "
3994                                 <<player->getName()<<" dies"<<std::endl;
3995                 
3996                 player->hp = 0;
3997                 
3998                 //TODO: Throw items around
3999                 
4000                 // Handle players that are not connected
4001                 if(player->peer_id == PEER_ID_INEXISTENT){
4002                         RespawnPlayer(player);
4003                         return;
4004                 }
4005
4006                 SendPlayerHP(player);
4007                 
4008                 RemoteClient *client = getClient(player->peer_id);
4009                 if(client->net_proto_version >= 3)
4010                 {
4011                         SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
4012                 }
4013                 else
4014                 {
4015                         RespawnPlayer(player);
4016                 }
4017         }
4018 }
4019
4020 void Server::RespawnPlayer(Player *player)
4021 {
4022         v3f pos = findSpawnPos(m_env.getServerMap());
4023         player->setPosition(pos);
4024         player->hp = 20;
4025         SendMovePlayer(player);
4026         SendPlayerHP(player);
4027 }
4028
4029 void Server::UpdateCrafting(u16 peer_id)
4030 {
4031         DSTACK(__FUNCTION_NAME);
4032         
4033         Player* player = m_env.getPlayer(peer_id);
4034         assert(player);
4035
4036         /*
4037                 Calculate crafting stuff
4038         */
4039         if(g_settings->getBool("creative_mode") == false)
4040         {
4041                 InventoryList *clist = player->inventory.getList("craft");
4042                 InventoryList *rlist = player->inventory.getList("craftresult");
4043
4044                 if(rlist && rlist->getUsedSlots() == 0)
4045                         player->craftresult_is_preview = true;
4046
4047                 if(rlist && player->craftresult_is_preview)
4048                 {
4049                         rlist->clearItems();
4050                 }
4051                 if(clist && rlist && player->craftresult_is_preview)
4052                 {
4053                         InventoryItem *items[9];
4054                         for(u16 i=0; i<9; i++)
4055                         {
4056                                 items[i] = clist->getItem(i);
4057                         }
4058                         
4059                         // Get result of crafting grid
4060                         InventoryItem *result = craft_get_result(items);
4061                         if(result)
4062                                 rlist->addItem(result);
4063                 }
4064         
4065         } // if creative_mode == false
4066 }
4067
4068 RemoteClient* Server::getClient(u16 peer_id)
4069 {
4070         DSTACK(__FUNCTION_NAME);
4071         //JMutexAutoLock lock(m_con_mutex);
4072         core::map<u16, RemoteClient*>::Node *n;
4073         n = m_clients.find(peer_id);
4074         // A client should exist for all peers
4075         assert(n != NULL);
4076         return n->getValue();
4077 }
4078
4079 std::wstring Server::getStatusString()
4080 {
4081         std::wostringstream os(std::ios_base::binary);
4082         os<<L"# Server: ";
4083         // Version
4084         os<<L"version="<<narrow_to_wide(VERSION_STRING);
4085         // Uptime
4086         os<<L", uptime="<<m_uptime.get();
4087         // Information about clients
4088         os<<L", clients={";
4089         for(core::map<u16, RemoteClient*>::Iterator
4090                 i = m_clients.getIterator();
4091                 i.atEnd() == false; i++)
4092         {
4093                 // Get client and check that it is valid
4094                 RemoteClient *client = i.getNode()->getValue();
4095                 assert(client->peer_id == i.getNode()->getKey());
4096                 if(client->serialization_version == SER_FMT_VER_INVALID)
4097                         continue;
4098                 // Get player
4099                 Player *player = m_env.getPlayer(client->peer_id);
4100                 // Get name of player
4101                 std::wstring name = L"unknown";
4102                 if(player != NULL)
4103                         name = narrow_to_wide(player->getName());
4104                 // Add name to information string
4105                 os<<name<<L",";
4106         }
4107         os<<L"}";
4108         if(((ServerMap*)(&m_env.getMap()))->isSavingEnabled() == false)
4109                 os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
4110         if(g_settings->get("motd") != "")
4111                 os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
4112         return os.str();
4113 }
4114
4115 // Saves g_settings to configpath given at initialization
4116 void Server::saveConfig()
4117 {
4118         if(m_configpath != "")
4119                 g_settings->updateConfigFile(m_configpath.c_str());
4120 }
4121
4122 void Server::notifyPlayer(const char *name, const std::wstring msg)
4123 {
4124         Player *player = m_env.getPlayer(name);
4125         if(!player)
4126                 return;
4127         SendChatMessage(player->peer_id, std::wstring(L"Server: -!- ")+msg);
4128 }
4129
4130 void Server::notifyPlayers(const std::wstring msg)
4131 {
4132         BroadcastChatMessage(msg);
4133 }
4134
4135 v3f findSpawnPos(ServerMap &map)
4136 {
4137         //return v3f(50,50,50)*BS;
4138
4139         v3s16 nodepos;
4140         
4141 #if 0
4142         nodepos = v2s16(0,0);
4143         groundheight = 20;
4144 #endif
4145
4146 #if 1
4147         // Try to find a good place a few times
4148         for(s32 i=0; i<1000; i++)
4149         {
4150                 s32 range = 1 + i;
4151                 // We're going to try to throw the player to this position
4152                 v2s16 nodepos2d = v2s16(-range + (myrand()%(range*2)),
4153                                 -range + (myrand()%(range*2)));
4154                 //v2s16 sectorpos = getNodeSectorPos(nodepos2d);
4155                 // Get ground height at point (fallbacks to heightmap function)
4156                 s16 groundheight = map.findGroundLevel(nodepos2d);
4157                 // Don't go underwater
4158                 if(groundheight < WATER_LEVEL)
4159                 {
4160                         //infostream<<"-> Underwater"<<std::endl;
4161                         continue;
4162                 }
4163                 // Don't go to high places
4164                 if(groundheight > WATER_LEVEL + 4)
4165                 {
4166                         //infostream<<"-> Underwater"<<std::endl;
4167                         continue;
4168                 }
4169                 
4170                 nodepos = v3s16(nodepos2d.X, groundheight-2, nodepos2d.Y);
4171                 bool is_good = false;
4172                 s32 air_count = 0;
4173                 for(s32 i=0; i<10; i++){
4174                         v3s16 blockpos = getNodeBlockPos(nodepos);
4175                         map.emergeBlock(blockpos, true);
4176                         MapNode n = map.getNodeNoEx(nodepos);
4177                         if(n.getContent() == CONTENT_AIR){
4178                                 air_count++;
4179                                 if(air_count >= 2){
4180                                         is_good = true;
4181                                         nodepos.Y -= 1;
4182                                         break;
4183                                 }
4184                         }
4185                         nodepos.Y++;
4186                 }
4187                 if(is_good){
4188                         // Found a good place
4189                         //infostream<<"Searched through "<<i<<" places."<<std::endl;
4190                         break;
4191                 }
4192         }
4193 #endif
4194         
4195         return intToFloat(nodepos, BS);
4196 }
4197
4198 Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id)
4199 {
4200         /*
4201                 Try to get an existing player
4202         */
4203         Player *player = m_env.getPlayer(name);
4204         if(player != NULL)
4205         {
4206                 // If player is already connected, cancel
4207                 if(player->peer_id != 0)
4208                 {
4209                         infostream<<"emergePlayer(): Player already connected"<<std::endl;
4210                         return NULL;
4211                 }
4212
4213                 // Got one.
4214                 player->peer_id = peer_id;
4215                 
4216                 // Reset inventory to creative if in creative mode
4217                 if(g_settings->getBool("creative_mode"))
4218                 {
4219                         // Warning: double code below
4220                         // Backup actual inventory
4221                         player->inventory_backup = new Inventory();
4222                         *(player->inventory_backup) = player->inventory;
4223                         // Set creative inventory
4224                         craft_set_creative_inventory(player);
4225                 }
4226
4227                 return player;
4228         }
4229
4230         /*
4231                 If player with the wanted peer_id already exists, cancel.
4232         */
4233         if(m_env.getPlayer(peer_id) != NULL)
4234         {
4235                 infostream<<"emergePlayer(): Player with wrong name but same"
4236                                 " peer_id already exists"<<std::endl;
4237                 return NULL;
4238         }
4239         
4240         /*
4241                 Create a new player
4242         */
4243         {
4244                 player = new ServerRemotePlayer();
4245                 //player->peer_id = c.peer_id;
4246                 //player->peer_id = PEER_ID_INEXISTENT;
4247                 player->peer_id = peer_id;
4248                 player->updateName(name);
4249                 m_authmanager.add(name);
4250                 m_authmanager.setPassword(name, password);
4251                 m_authmanager.setPrivs(name,
4252                                 stringToPrivs(g_settings->get("default_privs")));
4253
4254                 /*
4255                         Set player position
4256                 */
4257                 
4258                 infostream<<"Server: Finding spawn place for player \""
4259                                 <<player->getName()<<"\""<<std::endl;
4260
4261                 v3f pos = findSpawnPos(m_env.getServerMap());
4262
4263                 player->setPosition(pos);
4264
4265                 /*
4266                         Add player to environment
4267                 */
4268
4269                 m_env.addPlayer(player);
4270
4271                 /*
4272                         Add stuff to inventory
4273                 */
4274                 
4275                 if(g_settings->getBool("creative_mode"))
4276                 {
4277                         // Warning: double code above
4278                         // Backup actual inventory
4279                         player->inventory_backup = new Inventory();
4280                         *(player->inventory_backup) = player->inventory;
4281                         // Set creative inventory
4282                         craft_set_creative_inventory(player);
4283                 }
4284                 else if(g_settings->getBool("give_initial_stuff"))
4285                 {
4286                         craft_give_initial_stuff(player);
4287                 }
4288
4289                 return player;
4290                 
4291         } // create new player
4292 }
4293
4294 void Server::handlePeerChange(PeerChange &c)
4295 {
4296         JMutexAutoLock envlock(m_env_mutex);
4297         JMutexAutoLock conlock(m_con_mutex);
4298         
4299         if(c.type == PEER_ADDED)
4300         {
4301                 /*
4302                         Add
4303                 */
4304
4305                 // Error check
4306                 core::map<u16, RemoteClient*>::Node *n;
4307                 n = m_clients.find(c.peer_id);
4308                 // The client shouldn't already exist
4309                 assert(n == NULL);
4310
4311                 // Create client
4312                 RemoteClient *client = new RemoteClient();
4313                 client->peer_id = c.peer_id;
4314                 m_clients.insert(client->peer_id, client);
4315
4316         } // PEER_ADDED
4317         else if(c.type == PEER_REMOVED)
4318         {
4319                 /*
4320                         Delete
4321                 */
4322
4323                 // Error check
4324                 core::map<u16, RemoteClient*>::Node *n;
4325                 n = m_clients.find(c.peer_id);
4326                 // The client should exist
4327                 assert(n != NULL);
4328                 
4329                 /*
4330                         Mark objects to be not known by the client
4331                 */
4332                 RemoteClient *client = n->getValue();
4333                 // Handle objects
4334                 for(core::map<u16, bool>::Iterator
4335                                 i = client->m_known_objects.getIterator();
4336                                 i.atEnd()==false; i++)
4337                 {
4338                         // Get object
4339                         u16 id = i.getNode()->getKey();
4340                         ServerActiveObject* obj = m_env.getActiveObject(id);
4341                         
4342                         if(obj && obj->m_known_by_count > 0)
4343                                 obj->m_known_by_count--;
4344                 }
4345
4346                 // Collect information about leaving in chat
4347                 std::wstring message;
4348                 {
4349                         Player *player = m_env.getPlayer(c.peer_id);
4350                         if(player != NULL)
4351                         {
4352                                 std::wstring name = narrow_to_wide(player->getName());
4353                                 message += L"*** ";
4354                                 message += name;
4355                                 message += L" left game";
4356                                 if(c.timeout)
4357                                         message += L" (timed out)";
4358                         }
4359                 }
4360
4361                 /*// Delete player
4362                 {
4363                         m_env.removePlayer(c.peer_id);
4364                 }*/
4365
4366                 // Set player client disconnected
4367                 {
4368                         Player *player = m_env.getPlayer(c.peer_id);
4369                         if(player != NULL)
4370                                 player->peer_id = 0;
4371                         
4372                         /*
4373                                 Print out action
4374                         */
4375                         if(player != NULL)
4376                         {
4377                                 std::ostringstream os(std::ios_base::binary);
4378                                 for(core::map<u16, RemoteClient*>::Iterator
4379                                         i = m_clients.getIterator();
4380                                         i.atEnd() == false; i++)
4381                                 {
4382                                         RemoteClient *client = i.getNode()->getValue();
4383                                         assert(client->peer_id == i.getNode()->getKey());
4384                                         if(client->serialization_version == SER_FMT_VER_INVALID)
4385                                                 continue;
4386                                         // Get player
4387                                         Player *player = m_env.getPlayer(client->peer_id);
4388                                         if(!player)
4389                                                 continue;
4390                                         // Get name of player
4391                                         os<<player->getName()<<" ";
4392                                 }
4393
4394                                 actionstream<<player->getName()<<" "
4395                                                 <<(c.timeout?"times out.":"leaves game.")
4396                                                 <<" List of players: "
4397                                                 <<os.str()<<std::endl;
4398                         }
4399                 }
4400                 
4401                 // Delete client
4402                 delete m_clients[c.peer_id];
4403                 m_clients.remove(c.peer_id);
4404
4405                 // Send player info to all remaining clients
4406                 SendPlayerInfos();
4407                 
4408                 // Send leave chat message to all remaining clients
4409                 BroadcastChatMessage(message);
4410                 
4411         } // PEER_REMOVED
4412         else
4413         {
4414                 assert(0);
4415         }
4416 }
4417
4418 void Server::handlePeerChanges()
4419 {
4420         while(m_peer_change_queue.size() > 0)
4421         {
4422                 PeerChange c = m_peer_change_queue.pop_front();
4423
4424                 infostream<<"Server: Handling peer change: "
4425                                 <<"id="<<c.peer_id<<", timeout="<<c.timeout
4426                                 <<std::endl;
4427
4428                 handlePeerChange(c);
4429         }
4430 }
4431
4432 u64 Server::getPlayerPrivs(Player *player)
4433 {
4434         if(player==NULL)
4435                 return 0;
4436         std::string playername = player->getName();
4437         // Local player gets all privileges regardless of
4438         // what's set on their account.
4439         if(g_settings->get("name") == playername)
4440         {
4441                 return PRIV_ALL;
4442         }
4443         else
4444         {
4445                 return getPlayerAuthPrivs(playername);
4446         }
4447 }
4448
4449 void dedicated_server_loop(Server &server, bool &kill)
4450 {
4451         DSTACK(__FUNCTION_NAME);
4452         
4453         infostream<<DTIME<<std::endl;
4454         infostream<<"========================"<<std::endl;
4455         infostream<<"Running dedicated server"<<std::endl;
4456         infostream<<"========================"<<std::endl;
4457         infostream<<std::endl;
4458
4459         IntervalLimiter m_profiler_interval;
4460
4461         for(;;)
4462         {
4463                 // This is kind of a hack but can be done like this
4464                 // because server.step() is very light
4465                 {
4466                         ScopeProfiler sp(g_profiler, "dedicated server sleep");
4467                         sleep_ms(30);
4468                 }
4469                 server.step(0.030);
4470
4471                 if(server.getShutdownRequested() || kill)
4472                 {
4473                         infostream<<DTIME<<" dedicated_server_loop(): Quitting."<<std::endl;
4474                         break;
4475                 }
4476
4477                 /*
4478                         Profiler
4479                 */
4480                 float profiler_print_interval =
4481                                 g_settings->getFloat("profiler_print_interval");
4482                 if(profiler_print_interval != 0)
4483                 {
4484                         if(m_profiler_interval.step(0.030, profiler_print_interval))
4485                         {
4486                                 infostream<<"Profiler:"<<std::endl;
4487                                 g_profiler->print(infostream);
4488                                 g_profiler->clear();
4489                         }
4490                 }
4491                 
4492                 /*
4493                         Player info
4494                 */
4495                 static int counter = 0;
4496                 counter--;
4497                 if(counter <= 0)
4498                 {
4499                         counter = 10;
4500
4501                         core::list<PlayerInfo> list = server.getPlayerInfo();
4502                         core::list<PlayerInfo>::Iterator i;
4503                         static u32 sum_old = 0;
4504                         u32 sum = PIChecksum(list);
4505                         if(sum != sum_old)
4506                         {
4507                                 infostream<<DTIME<<"Player info:"<<std::endl;
4508                                 for(i=list.begin(); i!=list.end(); i++)
4509                                 {
4510                                         i->PrintLine(&infostream);
4511                                 }
4512                         }
4513                         sum_old = sum;
4514                 }
4515         }
4516 }
4517
4518