]> git.lizzy.rs Git - minetest.git/blob - src/server.cpp
Allow the LUA API to set animations to meshes as well as the animation speed. Also...
[minetest.git] / src / server.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "server.h"
21 #include <iostream>
22 #include <queue>
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 "config.h"
30 #include "filesys.h"
31 #include "mapblock.h"
32 #include "serverobject.h"
33 #include "settings.h"
34 #include "profiler.h"
35 #include "log.h"
36 #include "script.h"
37 #include "scriptapi.h"
38 #include "nodedef.h"
39 #include "itemdef.h"
40 #include "craftdef.h"
41 #include "mapgen.h"
42 #include "content_mapnode.h"
43 #include "content_nodemeta.h"
44 #include "content_abm.h"
45 #include "content_sao.h"
46 #include "mods.h"
47 #include "sha1.h"
48 #include "base64.h"
49 #include "tool.h"
50 #include "sound.h" // dummySoundManager
51 #include "event_manager.h"
52 #include "hex.h"
53 #include "util/string.h"
54 #include "util/pointedthing.h"
55 #include "util/mathconstants.h"
56 #include "rollback.h"
57
58 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
59
60 #define BLOCK_EMERGE_FLAG_FROMDISK (1<<0)
61
62 class MapEditEventIgnorer
63 {
64 public:
65         MapEditEventIgnorer(bool *flag):
66                 m_flag(flag)
67         {
68                 if(*m_flag == false)
69                         *m_flag = true;
70                 else
71                         m_flag = NULL;
72         }
73
74         ~MapEditEventIgnorer()
75         {
76                 if(m_flag)
77                 {
78                         assert(*m_flag);
79                         *m_flag = false;
80                 }
81         }
82         
83 private:
84         bool *m_flag;
85 };
86
87 class MapEditEventAreaIgnorer
88 {
89 public:
90         MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
91                 m_ignorevariable(ignorevariable)
92         {
93                 if(m_ignorevariable->getVolume() == 0)
94                         *m_ignorevariable = a;
95                 else
96                         m_ignorevariable = NULL;
97         }
98
99         ~MapEditEventAreaIgnorer()
100         {
101                 if(m_ignorevariable)
102                 {
103                         assert(m_ignorevariable->getVolume() != 0);
104                         *m_ignorevariable = VoxelArea();
105                 }
106         }
107         
108 private:
109         VoxelArea *m_ignorevariable;
110 };
111
112 void * ServerThread::Thread()
113 {
114         ThreadStarted();
115
116         log_register_thread("ServerThread");
117
118         DSTACK(__FUNCTION_NAME);
119
120         BEGIN_DEBUG_EXCEPTION_HANDLER
121
122         while(getRun())
123         {
124                 try{
125                         //TimeTaker timer("AsyncRunStep() + Receive()");
126
127                         {
128                                 //TimeTaker timer("AsyncRunStep()");
129                                 m_server->AsyncRunStep();
130                         }
131                 
132                         //infostream<<"Running m_server->Receive()"<<std::endl;
133                         m_server->Receive();
134                 }
135                 catch(con::NoIncomingDataException &e)
136                 {
137                 }
138                 catch(con::PeerNotFoundException &e)
139                 {
140                         infostream<<"Server: PeerNotFoundException"<<std::endl;
141                 }
142                 catch(con::ConnectionBindFailed &e)
143                 {
144                         m_server->setAsyncFatalError(e.what());
145                 }
146                 catch(LuaError &e)
147                 {
148                         m_server->setAsyncFatalError(e.what());
149                 }
150         }
151         
152         END_DEBUG_EXCEPTION_HANDLER(errorstream)
153
154         return NULL;
155 }
156
157 void * EmergeThread::Thread()
158 {
159         ThreadStarted();
160
161         log_register_thread("EmergeThread");
162
163         DSTACK(__FUNCTION_NAME);
164
165         BEGIN_DEBUG_EXCEPTION_HANDLER
166
167         bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
168
169         v3s16 last_tried_pos(-32768,-32768,-32768); // For error output
170         
171         /*
172                 Get block info from queue, emerge them and send them
173                 to clients.
174
175                 After queue is empty, exit.
176         */
177         while(getRun())
178         try{
179                 QueuedBlockEmerge *qptr = m_server->m_emerge_queue.pop();
180                 if(qptr == NULL)
181                         break;
182                 
183                 SharedPtr<QueuedBlockEmerge> q(qptr);
184
185                 v3s16 &p = q->pos;
186                 v2s16 p2d(p.X,p.Z);
187                 
188                 last_tried_pos = p;
189
190                 /*
191                         Do not generate over-limit
192                 */
193                 if(blockpos_over_limit(p))
194                         continue;
195                         
196                 //infostream<<"EmergeThread::Thread(): running"<<std::endl;
197
198                 //TimeTaker timer("block emerge");
199                 
200                 /*
201                         Try to emerge it from somewhere.
202
203                         If it is only wanted as optional, only loading from disk
204                         will be allowed.
205                 */
206                 
207                 /*
208                         Check if any peer wants it as non-optional. In that case it
209                         will be generated.
210
211                         Also decrement the emerge queue count in clients.
212                 */
213
214                 bool only_from_disk = true;
215
216                 {
217                         core::map<u16, u8>::Iterator i;
218                         for(i=q->peer_ids.getIterator(); i.atEnd()==false; i++)
219                         {
220                                 //u16 peer_id = i.getNode()->getKey();
221
222                                 // Check flags
223                                 u8 flags = i.getNode()->getValue();
224                                 if((flags & BLOCK_EMERGE_FLAG_FROMDISK) == false)
225                                         only_from_disk = false;
226                                 
227                         }
228                 }
229                 
230                 if(enable_mapgen_debug_info)
231                         infostream<<"EmergeThread: p="
232                                         <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
233                                         <<"only_from_disk="<<only_from_disk<<std::endl;
234                 
235                 ServerMap &map = ((ServerMap&)m_server->m_env->getMap());
236                         
237                 MapBlock *block = NULL;
238                 bool got_block = true;
239                 core::map<v3s16, MapBlock*> modified_blocks;
240
241                 /*
242                         Try to fetch block from memory or disk.
243                         If not found and asked to generate, initialize generator.
244                 */
245                 
246                 bool started_generate = false;
247                 mapgen::BlockMakeData data;
248
249                 {
250                         JMutexAutoLock envlock(m_server->m_env_mutex);
251                         
252                         // Load sector if it isn't loaded
253                         if(map.getSectorNoGenerateNoEx(p2d) == NULL)
254                                 map.loadSectorMeta(p2d);
255                         
256                         // Attempt to load block
257                         block = map.getBlockNoCreateNoEx(p);
258                         if(!block || block->isDummy() || !block->isGenerated())
259                         {
260                                 if(enable_mapgen_debug_info)
261                                         infostream<<"EmergeThread: not in memory, "
262                                                         <<"attempting to load from disk"<<std::endl;
263
264                                 block = map.loadBlock(p);
265                         }
266                         
267                         // If could not load and allowed to generate, start generation
268                         // inside this same envlock
269                         if(only_from_disk == false &&
270                                         (block == NULL || block->isGenerated() == false)){
271                                 if(enable_mapgen_debug_info)
272                                         infostream<<"EmergeThread: generating"<<std::endl;
273                                 started_generate = true;
274
275                                 map.initBlockMake(&data, p);
276                         }
277                 }
278
279                 /*
280                         If generator was initialized, generate now when envlock is free.
281                 */
282                 if(started_generate)
283                 {
284                         {
285                                 ScopeProfiler sp(g_profiler, "EmergeThread: mapgen::make_block",
286                                                 SPT_AVG);
287                                 TimeTaker t("mapgen::make_block()");
288
289                                 mapgen::make_block(&data);
290
291                                 if(enable_mapgen_debug_info == false)
292                                         t.stop(true); // Hide output
293                         }
294                         
295                         do{ // enable break
296                                 // Lock environment again to access the map
297                                 JMutexAutoLock envlock(m_server->m_env_mutex);
298                                 
299                                 ScopeProfiler sp(g_profiler, "EmergeThread: after "
300                                                 "mapgen::make_block (envlock)", SPT_AVG);
301
302                                 // Blit data back on map, update lighting, add mobs and
303                                 // whatever this does
304                                 map.finishBlockMake(&data, modified_blocks);
305
306                                 // Get central block
307                                 block = map.getBlockNoCreateNoEx(p);
308                                 
309                                 // If block doesn't exist, don't try doing anything with it
310                                 // This happens if the block is not in generation boundaries
311                                 if(!block)
312                                         break;
313
314                                 /*
315                                         Do some post-generate stuff
316                                 */
317
318                                 v3s16 minp = data.blockpos_min*MAP_BLOCKSIZE;
319                                 v3s16 maxp = data.blockpos_max*MAP_BLOCKSIZE +
320                                                 v3s16(1,1,1)*(MAP_BLOCKSIZE-1);
321                                 
322                                 /*
323                                         Ignore map edit events, they will not need to be
324                                         sent to anybody because the block hasn't been sent
325                                         to anybody
326                                 */
327                                 //MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
328                                 MapEditEventAreaIgnorer ign(
329                                                 &m_server->m_ignore_map_edit_events_area,
330                                                 VoxelArea(minp, maxp));
331                                 {
332                                         TimeTaker timer("on_generated");
333                                         scriptapi_environment_on_generated(m_server->m_lua,
334                                                         minp, maxp, mapgen::get_blockseed(data.seed, minp));
335                                         /*int t = timer.stop(true);
336                                         dstream<<"on_generated took "<<t<<"ms"<<std::endl;*/
337                                 }
338                                 
339                                 if(enable_mapgen_debug_info)
340                                         infostream<<"EmergeThread: ended up with: "
341                                                         <<analyze_block(block)<<std::endl;
342
343                                 // Activate objects and stuff
344                                 m_server->m_env->activateBlock(block, 0);
345                         }while(false);
346                 }
347
348                 if(block == NULL)
349                         got_block = false;
350                         
351                 /*
352                         Set sent status of modified blocks on clients
353                 */
354         
355                 // NOTE: Server's clients are also behind the connection mutex
356                 JMutexAutoLock lock(m_server->m_con_mutex);
357
358                 /*
359                         Add the originally fetched block to the modified list
360                 */
361                 if(got_block)
362                 {
363                         modified_blocks.insert(p, block);
364                 }
365                 
366                 /*
367                         Set the modified blocks unsent for all the clients
368                 */
369                 
370                 for(core::map<u16, RemoteClient*>::Iterator
371                                 i = m_server->m_clients.getIterator();
372                                 i.atEnd() == false; i++)
373                 {
374                         RemoteClient *client = i.getNode()->getValue();
375                         
376                         if(modified_blocks.size() > 0)
377                         {
378                                 // Remove block from sent history
379                                 client->SetBlocksNotSent(modified_blocks);
380                         }
381                 }
382         }
383         catch(VersionMismatchException &e)
384         {
385                 std::ostringstream err;
386                 err<<"World data version mismatch in MapBlock "<<PP(last_tried_pos)<<std::endl;
387                 err<<"----"<<std::endl;
388                 err<<"\""<<e.what()<<"\""<<std::endl;
389                 err<<"See debug.txt."<<std::endl;
390                 err<<"World probably saved by a newer version of Minetest."<<std::endl;
391                 m_server->setAsyncFatalError(err.str());
392         }
393         catch(SerializationError &e)
394         {
395                 std::ostringstream err;
396                 err<<"Invalid data in MapBlock "<<PP(last_tried_pos)<<std::endl;
397                 err<<"----"<<std::endl;
398                 err<<"\""<<e.what()<<"\""<<std::endl;
399                 err<<"See debug.txt."<<std::endl;
400                 err<<"You can ignore this using [ignore_world_load_errors = true]."<<std::endl;
401                 m_server->setAsyncFatalError(err.str());
402         }
403
404         END_DEBUG_EXCEPTION_HANDLER(errorstream)
405
406         log_deregister_thread();
407
408         return NULL;
409 }
410
411 v3f ServerSoundParams::getPos(ServerEnvironment *env, bool *pos_exists) const
412 {
413         if(pos_exists) *pos_exists = false;
414         switch(type){
415         case SSP_LOCAL:
416                 return v3f(0,0,0);
417         case SSP_POSITIONAL:
418                 if(pos_exists) *pos_exists = true;
419                 return pos;
420         case SSP_OBJECT: {
421                 if(object == 0)
422                         return v3f(0,0,0);
423                 ServerActiveObject *sao = env->getActiveObject(object);
424                 if(!sao)
425                         return v3f(0,0,0);
426                 if(pos_exists) *pos_exists = true;
427                 return sao->getBasePosition(); }
428         }
429         return v3f(0,0,0);
430 }
431
432 void RemoteClient::GetNextBlocks(Server *server, float dtime,
433                 core::array<PrioritySortedBlockTransfer> &dest)
434 {
435         DSTACK(__FUNCTION_NAME);
436         
437         /*u32 timer_result;
438         TimeTaker timer("RemoteClient::GetNextBlocks", &timer_result);*/
439         
440         // Increment timers
441         m_nothing_to_send_pause_timer -= dtime;
442         m_nearest_unsent_reset_timer += dtime;
443         
444         if(m_nothing_to_send_pause_timer >= 0)
445                 return;
446
447         Player *player = server->m_env->getPlayer(peer_id);
448         // This can happen sometimes; clients and players are not in perfect sync.
449         if(player == NULL)
450                 return;
451
452         // Won't send anything if already sending
453         if(m_blocks_sending.size() >= g_settings->getU16
454                         ("max_simultaneous_block_sends_per_client"))
455         {
456                 //infostream<<"Not sending any blocks, Queue full."<<std::endl;
457                 return;
458         }
459
460         //TimeTaker timer("RemoteClient::GetNextBlocks");
461         
462         v3f playerpos = player->getPosition();
463         v3f playerspeed = player->getSpeed();
464         v3f playerspeeddir(0,0,0);
465         if(playerspeed.getLength() > 1.0*BS)
466                 playerspeeddir = playerspeed / playerspeed.getLength();
467         // Predict to next block
468         v3f playerpos_predicted = playerpos + playerspeeddir*MAP_BLOCKSIZE*BS;
469
470         v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);
471
472         v3s16 center = getNodeBlockPos(center_nodepos);
473         
474         // Camera position and direction
475         v3f camera_pos = player->getEyePosition();
476         v3f camera_dir = v3f(0,0,1);
477         camera_dir.rotateYZBy(player->getPitch());
478         camera_dir.rotateXZBy(player->getYaw());
479
480         /*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<","
481                         <<camera_dir.Z<<")"<<std::endl;*/
482
483         /*
484                 Get the starting value of the block finder radius.
485         */
486                 
487         if(m_last_center != center)
488         {
489                 m_nearest_unsent_d = 0;
490                 m_last_center = center;
491         }
492
493         /*infostream<<"m_nearest_unsent_reset_timer="
494                         <<m_nearest_unsent_reset_timer<<std::endl;*/
495                         
496         // Reset periodically to workaround for some bugs or stuff
497         if(m_nearest_unsent_reset_timer > 20.0)
498         {
499                 m_nearest_unsent_reset_timer = 0;
500                 m_nearest_unsent_d = 0;
501                 //infostream<<"Resetting m_nearest_unsent_d for "
502                 //              <<server->getPlayerName(peer_id)<<std::endl;
503         }
504
505         //s16 last_nearest_unsent_d = m_nearest_unsent_d;
506         s16 d_start = m_nearest_unsent_d;
507
508         //infostream<<"d_start="<<d_start<<std::endl;
509
510         u16 max_simul_sends_setting = g_settings->getU16
511                         ("max_simultaneous_block_sends_per_client");
512         u16 max_simul_sends_usually = max_simul_sends_setting;
513
514         /*
515                 Check the time from last addNode/removeNode.
516                 
517                 Decrease send rate if player is building stuff.
518         */
519         m_time_from_building += dtime;
520         if(m_time_from_building < g_settings->getFloat(
521                                 "full_block_send_enable_min_time_from_building"))
522         {
523                 max_simul_sends_usually
524                         = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
525         }
526         
527         /*
528                 Number of blocks sending + number of blocks selected for sending
529         */
530         u32 num_blocks_selected = m_blocks_sending.size();
531         
532         /*
533                 next time d will be continued from the d from which the nearest
534                 unsent block was found this time.
535
536                 This is because not necessarily any of the blocks found this
537                 time are actually sent.
538         */
539         s32 new_nearest_unsent_d = -1;
540
541         s16 d_max = g_settings->getS16("max_block_send_distance");
542         s16 d_max_gen = g_settings->getS16("max_block_generate_distance");
543         
544         // Don't loop very much at a time
545         s16 max_d_increment_at_time = 2;
546         if(d_max > d_start + max_d_increment_at_time)
547                 d_max = d_start + max_d_increment_at_time;
548         /*if(d_max_gen > d_start+2)
549                 d_max_gen = d_start+2;*/
550         
551         //infostream<<"Starting from "<<d_start<<std::endl;
552
553         s32 nearest_emerged_d = -1;
554         s32 nearest_emergefull_d = -1;
555         s32 nearest_sent_d = -1;
556         bool queue_is_full = false;
557         
558         s16 d;
559         for(d = d_start; d <= d_max; d++)
560         {
561                 /*errorstream<<"checking d="<<d<<" for "
562                                 <<server->getPlayerName(peer_id)<<std::endl;*/
563                 //infostream<<"RemoteClient::SendBlocks(): d="<<d<<std::endl;
564                 
565                 /*
566                         If m_nearest_unsent_d was changed by the EmergeThread
567                         (it can change it to 0 through SetBlockNotSent),
568                         update our d to it.
569                         Else update m_nearest_unsent_d
570                 */
571                 /*if(m_nearest_unsent_d != last_nearest_unsent_d)
572                 {
573                         d = m_nearest_unsent_d;
574                         last_nearest_unsent_d = m_nearest_unsent_d;
575                 }*/
576
577                 /*
578                         Get the border/face dot coordinates of a "d-radiused"
579                         box
580                 */
581                 core::list<v3s16> list;
582                 getFacePositions(list, d);
583                 
584                 core::list<v3s16>::Iterator li;
585                 for(li=list.begin(); li!=list.end(); li++)
586                 {
587                         v3s16 p = *li + center;
588                         
589                         /*
590                                 Send throttling
591                                 - Don't allow too many simultaneous transfers
592                                 - EXCEPT when the blocks are very close
593
594                                 Also, don't send blocks that are already flying.
595                         */
596                         
597                         // Start with the usual maximum
598                         u16 max_simul_dynamic = max_simul_sends_usually;
599                         
600                         // If block is very close, allow full maximum
601                         if(d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
602                                 max_simul_dynamic = max_simul_sends_setting;
603
604                         // Don't select too many blocks for sending
605                         if(num_blocks_selected >= max_simul_dynamic)
606                         {
607                                 queue_is_full = true;
608                                 goto queue_full_break;
609                         }
610                         
611                         // Don't send blocks that are currently being transferred
612                         if(m_blocks_sending.find(p) != NULL)
613                                 continue;
614                 
615                         /*
616                                 Do not go over-limit
617                         */
618                         if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
619                         || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
620                         || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
621                         || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
622                         || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
623                         || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
624                                 continue;
625                 
626                         // If this is true, inexistent block will be made from scratch
627                         bool generate = d <= d_max_gen;
628                         
629                         {
630                                 /*// Limit the generating area vertically to 2/3
631                                 if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3)
632                                         generate = false;*/
633
634                                 // Limit the send area vertically to 1/2
635                                 if(abs(p.Y - center.Y) > d_max / 2)
636                                         continue;
637                         }
638
639 #if 0
640                         /*
641                                 If block is far away, don't generate it unless it is
642                                 near ground level.
643                         */
644                         if(d >= 4)
645                         {
646         #if 1
647                                 // Block center y in nodes
648                                 f32 y = (f32)(p.Y * MAP_BLOCKSIZE + MAP_BLOCKSIZE/2);
649                                 // Don't generate if it's very high or very low
650                                 if(y < -64 || y > 64)
651                                         generate = false;
652         #endif
653         #if 0
654                                 v2s16 p2d_nodes_center(
655                                         MAP_BLOCKSIZE*p.X,
656                                         MAP_BLOCKSIZE*p.Z);
657                                 
658                                 // Get ground height in nodes
659                                 s16 gh = server->m_env->getServerMap().findGroundLevel(
660                                                 p2d_nodes_center);
661
662                                 // If differs a lot, don't generate
663                                 if(fabs(gh - y) > MAP_BLOCKSIZE*2)
664                                         generate = false;
665                                         // Actually, don't even send it
666                                         //continue;
667         #endif
668                         }
669 #endif
670
671                         //infostream<<"d="<<d<<std::endl;
672 #if 1
673                         /*
674                                 Don't generate or send if not in sight
675                                 FIXME This only works if the client uses a small enough
676                                 FOV setting. The default of 72 degrees is fine.
677                         */
678
679                         float camera_fov = (72.0*M_PI/180) * 4./3.;
680                         if(isBlockInSight(p, camera_pos, camera_dir, camera_fov, 10000*BS) == false)
681                         {
682                                 continue;
683                         }
684 #endif
685                         /*
686                                 Don't send already sent blocks
687                         */
688                         {
689                                 if(m_blocks_sent.find(p) != NULL)
690                                 {
691                                         continue;
692                                 }
693                         }
694
695                         /*
696                                 Check if map has this block
697                         */
698                         MapBlock *block = server->m_env->getMap().getBlockNoCreateNoEx(p);
699                         
700                         bool surely_not_found_on_disk = false;
701                         bool block_is_invalid = false;
702                         if(block != NULL)
703                         {
704                                 // Reset usage timer, this block will be of use in the future.
705                                 block->resetUsageTimer();
706
707                                 // Block is dummy if data doesn't exist.
708                                 // It means it has been not found from disk and not generated
709                                 if(block->isDummy())
710                                 {
711                                         surely_not_found_on_disk = true;
712                                 }
713                                 
714                                 // Block is valid if lighting is up-to-date and data exists
715                                 if(block->isValid() == false)
716                                 {
717                                         block_is_invalid = true;
718                                 }
719                                 
720                                 /*if(block->isFullyGenerated() == false)
721                                 {
722                                         block_is_invalid = true;
723                                 }*/
724
725 #if 0
726                                 v2s16 p2d(p.X, p.Z);
727                                 ServerMap *map = (ServerMap*)(&server->m_env->getMap());
728                                 v2s16 chunkpos = map->sector_to_chunk(p2d);
729                                 if(map->chunkNonVolatile(chunkpos) == false)
730                                         block_is_invalid = true;
731 #endif
732                                 if(block->isGenerated() == false)
733                                         block_is_invalid = true;
734 #if 1
735                                 /*
736                                         If block is not close, don't send it unless it is near
737                                         ground level.
738
739                                         Block is near ground level if night-time mesh
740                                         differs from day-time mesh.
741                                 */
742                                 if(d >= 4)
743                                 {
744                                         if(block->getDayNightDiff() == false)
745                                                 continue;
746                                 }
747 #endif
748                         }
749
750                         /*
751                                 If block has been marked to not exist on disk (dummy)
752                                 and generating new ones is not wanted, skip block.
753                         */
754                         if(generate == false && surely_not_found_on_disk == true)
755                         {
756                                 // get next one.
757                                 continue;
758                         }
759
760                         /*
761                                 Add inexistent block to emerge queue.
762                         */
763                         if(block == NULL || surely_not_found_on_disk || block_is_invalid)
764                         {
765                                 //TODO: Get value from somewhere
766                                 // Allow only one block in emerge queue
767                                 //if(server->m_emerge_queue.peerItemCount(peer_id) < 1)
768                                 // Allow two blocks in queue per client
769                                 //if(server->m_emerge_queue.peerItemCount(peer_id) < 2)
770                                 u32 max_emerge = 5;
771                                 // Make it more responsive when needing to generate stuff
772                                 if(surely_not_found_on_disk)
773                                         max_emerge = 1;
774                                 if(server->m_emerge_queue.peerItemCount(peer_id) < max_emerge)
775                                 {
776                                         //infostream<<"Adding block to emerge queue"<<std::endl;
777                                         
778                                         // Add it to the emerge queue and trigger the thread
779                                         
780                                         u8 flags = 0;
781                                         if(generate == false)
782                                                 flags |= BLOCK_EMERGE_FLAG_FROMDISK;
783                                         
784                                         server->m_emerge_queue.addBlock(peer_id, p, flags);
785                                         server->m_emergethread.trigger();
786
787                                         if(nearest_emerged_d == -1)
788                                                 nearest_emerged_d = d;
789                                 } else {
790                                         if(nearest_emergefull_d == -1)
791                                                 nearest_emergefull_d = d;
792                                 }
793                                 
794                                 // get next one.
795                                 continue;
796                         }
797
798                         if(nearest_sent_d == -1)
799                                 nearest_sent_d = d;
800
801                         /*
802                                 Add block to send queue
803                         */
804
805                         /*errorstream<<"sending from d="<<d<<" to "
806                                         <<server->getPlayerName(peer_id)<<std::endl;*/
807
808                         PrioritySortedBlockTransfer q((float)d, p, peer_id);
809
810                         dest.push_back(q);
811
812                         num_blocks_selected += 1;
813                 }
814         }
815 queue_full_break:
816
817         //infostream<<"Stopped at "<<d<<std::endl;
818         
819         // If nothing was found for sending and nothing was queued for
820         // emerging, continue next time browsing from here
821         if(nearest_emerged_d != -1){
822                 new_nearest_unsent_d = nearest_emerged_d;
823         } else if(nearest_emergefull_d != -1){
824                 new_nearest_unsent_d = nearest_emergefull_d;
825         } else {
826                 if(d > g_settings->getS16("max_block_send_distance")){
827                         new_nearest_unsent_d = 0;
828                         m_nothing_to_send_pause_timer = 2.0;
829                         /*infostream<<"GetNextBlocks(): d wrapped around for "
830                                         <<server->getPlayerName(peer_id)
831                                         <<"; setting to 0 and pausing"<<std::endl;*/
832                 } else {
833                         if(nearest_sent_d != -1)
834                                 new_nearest_unsent_d = nearest_sent_d;
835                         else
836                                 new_nearest_unsent_d = d;
837                 }
838         }
839
840         if(new_nearest_unsent_d != -1)
841                 m_nearest_unsent_d = new_nearest_unsent_d;
842
843         /*timer_result = timer.stop(true);
844         if(timer_result != 0)
845                 infostream<<"GetNextBlocks timeout: "<<timer_result<<" (!=0)"<<std::endl;*/
846 }
847
848 void RemoteClient::GotBlock(v3s16 p)
849 {
850         if(m_blocks_sending.find(p) != NULL)
851                 m_blocks_sending.remove(p);
852         else
853         {
854                 /*infostream<<"RemoteClient::GotBlock(): Didn't find in"
855                                 " m_blocks_sending"<<std::endl;*/
856                 m_excess_gotblocks++;
857         }
858         m_blocks_sent.insert(p, true);
859 }
860
861 void RemoteClient::SentBlock(v3s16 p)
862 {
863         if(m_blocks_sending.find(p) == NULL)
864                 m_blocks_sending.insert(p, 0.0);
865         else
866                 infostream<<"RemoteClient::SentBlock(): Sent block"
867                                 " already in m_blocks_sending"<<std::endl;
868 }
869
870 void RemoteClient::SetBlockNotSent(v3s16 p)
871 {
872         m_nearest_unsent_d = 0;
873         
874         if(m_blocks_sending.find(p) != NULL)
875                 m_blocks_sending.remove(p);
876         if(m_blocks_sent.find(p) != NULL)
877                 m_blocks_sent.remove(p);
878 }
879
880 void RemoteClient::SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks)
881 {
882         m_nearest_unsent_d = 0;
883         
884         for(core::map<v3s16, MapBlock*>::Iterator
885                         i = blocks.getIterator();
886                         i.atEnd()==false; i++)
887         {
888                 v3s16 p = i.getNode()->getKey();
889
890                 if(m_blocks_sending.find(p) != NULL)
891                         m_blocks_sending.remove(p);
892                 if(m_blocks_sent.find(p) != NULL)
893                         m_blocks_sent.remove(p);
894         }
895 }
896
897 /*
898         PlayerInfo
899 */
900
901 PlayerInfo::PlayerInfo()
902 {
903         name[0] = 0;
904         avg_rtt = 0;
905 }
906
907 void PlayerInfo::PrintLine(std::ostream *s)
908 {
909         (*s)<<id<<": ";
910         (*s)<<"\""<<name<<"\" ("
911                         <<(position.X/10)<<","<<(position.Y/10)
912                         <<","<<(position.Z/10)<<") ";
913         address.print(s);
914         (*s)<<" avg_rtt="<<avg_rtt;
915         (*s)<<std::endl;
916 }
917
918 /*
919         Server
920 */
921
922 Server::Server(
923                 const std::string &path_world,
924                 const std::string &path_config,
925                 const SubgameSpec &gamespec,
926                 bool simple_singleplayer_mode
927         ):
928         m_path_world(path_world),
929         m_path_config(path_config),
930         m_gamespec(gamespec),
931         m_simple_singleplayer_mode(simple_singleplayer_mode),
932         m_async_fatal_error(""),
933         m_env(NULL),
934         m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
935         m_banmanager(path_world+DIR_DELIM+"ipban.txt"),
936         m_rollback(NULL),
937         m_rollback_sink_enabled(true),
938         m_enable_rollback_recording(false),
939         m_lua(NULL),
940         m_itemdef(createItemDefManager()),
941         m_nodedef(createNodeDefManager()),
942         m_craftdef(createCraftDefManager()),
943         m_event(new EventManager()),
944         m_thread(this),
945         m_emergethread(this),
946         m_time_of_day_send_timer(0),
947         m_uptime(0),
948         m_shutdown_requested(false),
949         m_ignore_map_edit_events(false),
950         m_ignore_map_edit_events_peer_id(0)
951 {
952         m_liquid_transform_timer = 0.0;
953         m_print_info_timer = 0.0;
954         m_objectdata_timer = 0.0;
955         m_emergethread_trigger_timer = 0.0;
956         m_savemap_timer = 0.0;
957         
958         m_env_mutex.Init();
959         m_con_mutex.Init();
960         m_step_dtime_mutex.Init();
961         m_step_dtime = 0.0;
962
963         if(path_world == "")
964                 throw ServerError("Supplied empty world path");
965         
966         if(!gamespec.isValid())
967                 throw ServerError("Supplied invalid gamespec");
968         
969         infostream<<"Server created for gameid \""<<m_gamespec.id<<"\"";
970         if(m_simple_singleplayer_mode)
971                 infostream<<" in simple singleplayer mode"<<std::endl;
972         else
973                 infostream<<std::endl;
974         infostream<<"- world:  "<<m_path_world<<std::endl;
975         infostream<<"- config: "<<m_path_config<<std::endl;
976         infostream<<"- game:   "<<m_gamespec.path<<std::endl;
977
978         // Create rollback manager
979         std::string rollback_path = m_path_world+DIR_DELIM+"rollback.txt";
980         m_rollback = createRollbackManager(rollback_path, this);
981
982         // Add world mod search path
983         m_modspaths.push_front(m_path_world + DIR_DELIM + "worldmods");
984         // Add addon mod search path
985         for(std::set<std::string>::const_iterator i = m_gamespec.mods_paths.begin();
986                         i != m_gamespec.mods_paths.end(); i++)
987                 m_modspaths.push_front((*i));
988
989         // Print out mod search paths
990         for(core::list<std::string>::Iterator i = m_modspaths.begin();
991                         i != m_modspaths.end(); i++){
992                 std::string modspath = *i;
993                 infostream<<"- mods:   "<<modspath<<std::endl;
994         }
995         
996         // Path to builtin.lua
997         std::string builtinpath = getBuiltinLuaPath() + DIR_DELIM + "builtin.lua";
998
999         // Create world if it doesn't exist
1000         if(!initializeWorld(m_path_world, m_gamespec.id))
1001                 throw ServerError("Failed to initialize world");
1002
1003         // Lock environment
1004         JMutexAutoLock envlock(m_env_mutex);
1005         JMutexAutoLock conlock(m_con_mutex);
1006
1007         // Initialize scripting
1008         
1009         infostream<<"Server: Initializing Lua"<<std::endl;
1010         m_lua = script_init();
1011         assert(m_lua);
1012         // Export API
1013         scriptapi_export(m_lua, this);
1014         // Load and run builtin.lua
1015         infostream<<"Server: Loading builtin.lua [\""
1016                         <<builtinpath<<"\"]"<<std::endl;
1017         bool success = scriptapi_loadmod(m_lua, builtinpath, "__builtin");
1018         if(!success){
1019                 errorstream<<"Server: Failed to load and run "
1020                                 <<builtinpath<<std::endl;
1021                 throw ModError("Failed to load and run "+builtinpath);
1022         }
1023         // Find mods in mod search paths
1024         m_mods = getMods(m_modspaths);
1025         // Print 'em
1026         infostream<<"Server: Loading mods: ";
1027         for(core::list<ModSpec>::Iterator i = m_mods.begin();
1028                         i != m_mods.end(); i++){
1029                 const ModSpec &mod = *i;
1030                 infostream<<mod.name<<" ";
1031         }
1032         infostream<<std::endl;
1033         // Load and run "mod" scripts
1034         for(core::list<ModSpec>::Iterator i = m_mods.begin();
1035                         i != m_mods.end(); i++){
1036                 const ModSpec &mod = *i;
1037                 std::string scriptpath = mod.path + DIR_DELIM + "init.lua";
1038                 infostream<<"  ["<<padStringRight(mod.name, 12)<<"] [\""
1039                                 <<scriptpath<<"\"]"<<std::endl;
1040                 bool success = scriptapi_loadmod(m_lua, scriptpath, mod.name);
1041                 if(!success){
1042                         errorstream<<"Server: Failed to load and run "
1043                                         <<scriptpath<<std::endl;
1044                         throw ModError("Failed to load and run "+scriptpath);
1045                 }
1046         }
1047         
1048         // Read Textures and calculate sha1 sums
1049         fillMediaCache();
1050
1051         // Apply item aliases in the node definition manager
1052         m_nodedef->updateAliases(m_itemdef);
1053
1054         // Initialize Environment
1055         
1056         m_env = new ServerEnvironment(new ServerMap(path_world, this), m_lua,
1057                         this, this);
1058         
1059         // Give environment reference to scripting api
1060         scriptapi_add_environment(m_lua, m_env);
1061         
1062         // Register us to receive map edit events
1063         m_env->getMap().addEventReceiver(this);
1064
1065         // If file exists, load environment metadata
1066         if(fs::PathExists(m_path_world+DIR_DELIM+"env_meta.txt"))
1067         {
1068                 infostream<<"Server: Loading environment metadata"<<std::endl;
1069                 m_env->loadMeta(m_path_world);
1070         }
1071
1072         // Load players
1073         infostream<<"Server: Loading players"<<std::endl;
1074         m_env->deSerializePlayers(m_path_world);
1075
1076         /*
1077                 Add some test ActiveBlockModifiers to environment
1078         */
1079         add_legacy_abms(m_env, m_nodedef);
1080 }
1081
1082 Server::~Server()
1083 {
1084         infostream<<"Server destructing"<<std::endl;
1085
1086         /*
1087                 Send shutdown message
1088         */
1089         {
1090                 JMutexAutoLock conlock(m_con_mutex);
1091                 
1092                 std::wstring line = L"*** Server shutting down";
1093
1094                 /*
1095                         Send the message to clients
1096                 */
1097                 for(core::map<u16, RemoteClient*>::Iterator
1098                         i = m_clients.getIterator();
1099                         i.atEnd() == false; i++)
1100                 {
1101                         // Get client and check that it is valid
1102                         RemoteClient *client = i.getNode()->getValue();
1103                         assert(client->peer_id == i.getNode()->getKey());
1104                         if(client->serialization_version == SER_FMT_VER_INVALID)
1105                                 continue;
1106
1107                         try{
1108                                 SendChatMessage(client->peer_id, line);
1109                         }
1110                         catch(con::PeerNotFoundException &e)
1111                         {}
1112                 }
1113         }
1114         
1115         {
1116                 JMutexAutoLock envlock(m_env_mutex);
1117
1118                 /*
1119                         Save players
1120                 */
1121                 infostream<<"Server: Saving players"<<std::endl;
1122                 m_env->serializePlayers(m_path_world);
1123
1124                 /*
1125                         Save environment metadata
1126                 */
1127                 infostream<<"Server: Saving environment metadata"<<std::endl;
1128                 m_env->saveMeta(m_path_world);
1129         }
1130                 
1131         /*
1132                 Stop threads
1133         */
1134         stop();
1135         
1136         /*
1137                 Delete clients
1138         */
1139         {
1140                 JMutexAutoLock clientslock(m_con_mutex);
1141
1142                 for(core::map<u16, RemoteClient*>::Iterator
1143                         i = m_clients.getIterator();
1144                         i.atEnd() == false; i++)
1145                 {
1146                         /*// Delete player
1147                         // NOTE: These are removed by env destructor
1148                         {
1149                                 u16 peer_id = i.getNode()->getKey();
1150                                 JMutexAutoLock envlock(m_env_mutex);
1151                                 m_env->removePlayer(peer_id);
1152                         }*/
1153                         
1154                         // Delete client
1155                         delete i.getNode()->getValue();
1156                 }
1157         }
1158         
1159         // Delete things in the reverse order of creation
1160         delete m_env;
1161         delete m_rollback;
1162         delete m_event;
1163         delete m_itemdef;
1164         delete m_nodedef;
1165         delete m_craftdef;
1166         
1167         // Deinitialize scripting
1168         infostream<<"Server: Deinitializing scripting"<<std::endl;
1169         script_deinit(m_lua);
1170
1171         // Delete detached inventories
1172         {
1173                 for(std::map<std::string, Inventory*>::iterator
1174                                 i = m_detached_inventories.begin();
1175                                 i != m_detached_inventories.end(); i++){
1176                         delete i->second;
1177                 }
1178         }
1179 }
1180
1181 void Server::start(unsigned short port)
1182 {
1183         DSTACK(__FUNCTION_NAME);
1184         infostream<<"Starting server on port "<<port<<"..."<<std::endl;
1185
1186         // Stop thread if already running
1187         m_thread.stop();
1188         
1189         // Initialize connection
1190         m_con.SetTimeoutMs(30);
1191         m_con.Serve(port);
1192
1193         // Start thread
1194         m_thread.setRun(true);
1195         m_thread.Start();
1196         
1197         // ASCII art for the win!
1198         actionstream
1199         <<"        .__               __                   __   "<<std::endl
1200         <<"  _____ |__| ____   _____/  |_  ____   _______/  |_ "<<std::endl
1201         <<" /     \\|  |/    \\_/ __ \\   __\\/ __ \\ /  ___/\\   __\\"<<std::endl
1202         <<"|  Y Y  \\  |   |  \\  ___/|  | \\  ___/ \\___ \\  |  |  "<<std::endl
1203         <<"|__|_|  /__|___|  /\\___  >__|  \\___  >____  > |__|  "<<std::endl
1204         <<"      \\/        \\/     \\/          \\/     \\/        "<<std::endl;
1205         actionstream<<"World at ["<<m_path_world<<"]"<<std::endl;
1206         actionstream<<"Server for gameid=\""<<m_gamespec.id
1207                         <<"\" listening on port "<<port<<"."<<std::endl;
1208 }
1209
1210 void Server::stop()
1211 {
1212         DSTACK(__FUNCTION_NAME);
1213         
1214         infostream<<"Server: Stopping and waiting threads"<<std::endl;
1215
1216         // Stop threads (set run=false first so both start stopping)
1217         m_thread.setRun(false);
1218         m_emergethread.setRun(false);
1219         m_thread.stop();
1220         m_emergethread.stop();
1221         
1222         infostream<<"Server: Threads stopped"<<std::endl;
1223 }
1224
1225 void Server::step(float dtime)
1226 {
1227         DSTACK(__FUNCTION_NAME);
1228         // Limit a bit
1229         if(dtime > 2.0)
1230                 dtime = 2.0;
1231         {
1232                 JMutexAutoLock lock(m_step_dtime_mutex);
1233                 m_step_dtime += dtime;
1234         }
1235         // Throw if fatal error occurred in thread
1236         std::string async_err = m_async_fatal_error.get();
1237         if(async_err != ""){
1238                 throw ServerError(async_err);
1239         }
1240 }
1241
1242 void Server::AsyncRunStep()
1243 {
1244         DSTACK(__FUNCTION_NAME);
1245         
1246         g_profiler->add("Server::AsyncRunStep (num)", 1);
1247         
1248         float dtime;
1249         {
1250                 JMutexAutoLock lock1(m_step_dtime_mutex);
1251                 dtime = m_step_dtime;
1252         }
1253         
1254         {
1255                 // Send blocks to clients
1256                 SendBlocks(dtime);
1257         }
1258         
1259         if(dtime < 0.001)
1260                 return;
1261         
1262         g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
1263
1264         //infostream<<"Server steps "<<dtime<<std::endl;
1265         //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
1266         
1267         {
1268                 JMutexAutoLock lock1(m_step_dtime_mutex);
1269                 m_step_dtime -= dtime;
1270         }
1271
1272         /*
1273                 Update uptime
1274         */
1275         {
1276                 m_uptime.set(m_uptime.get() + dtime);
1277         }
1278         
1279         {
1280                 // Process connection's timeouts
1281                 JMutexAutoLock lock2(m_con_mutex);
1282                 ScopeProfiler sp(g_profiler, "Server: connection timeout processing");
1283                 m_con.RunTimeouts(dtime);
1284         }
1285         
1286         {
1287                 // This has to be called so that the client list gets synced
1288                 // with the peer list of the connection
1289                 handlePeerChanges();
1290         }
1291
1292         /*
1293                 Update time of day and overall game time
1294         */
1295         {
1296                 JMutexAutoLock envlock(m_env_mutex);
1297
1298                 m_env->setTimeOfDaySpeed(g_settings->getFloat("time_speed"));
1299
1300                 /*
1301                         Send to clients at constant intervals
1302                 */
1303
1304                 m_time_of_day_send_timer -= dtime;
1305                 if(m_time_of_day_send_timer < 0.0)
1306                 {
1307                         m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
1308
1309                         //JMutexAutoLock envlock(m_env_mutex);
1310                         JMutexAutoLock conlock(m_con_mutex);
1311
1312                         for(core::map<u16, RemoteClient*>::Iterator
1313                                 i = m_clients.getIterator();
1314                                 i.atEnd() == false; i++)
1315                         {
1316                                 RemoteClient *client = i.getNode()->getValue();
1317                                 SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
1318                                                 m_env->getTimeOfDay(), g_settings->getFloat("time_speed"));
1319                                 // Send as reliable
1320                                 m_con.Send(client->peer_id, 0, data, true);
1321                         }
1322                 }
1323         }
1324
1325         {
1326                 JMutexAutoLock lock(m_env_mutex);
1327                 // Step environment
1328                 ScopeProfiler sp(g_profiler, "SEnv step");
1329                 ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG);
1330                 m_env->step(dtime);
1331         }
1332                 
1333         const float map_timer_and_unload_dtime = 2.92;
1334         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
1335         {
1336                 JMutexAutoLock lock(m_env_mutex);
1337                 // Run Map's timers and unload unused data
1338                 ScopeProfiler sp(g_profiler, "Server: map timer and unload");
1339                 m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
1340                                 g_settings->getFloat("server_unload_unused_data_timeout"));
1341         }
1342         
1343         /*
1344                 Do background stuff
1345         */
1346
1347         /*
1348                 Handle players
1349         */
1350         {
1351                 JMutexAutoLock lock(m_env_mutex);
1352                 JMutexAutoLock lock2(m_con_mutex);
1353
1354                 ScopeProfiler sp(g_profiler, "Server: handle players");
1355
1356                 for(core::map<u16, RemoteClient*>::Iterator
1357                         i = m_clients.getIterator();
1358                         i.atEnd() == false; i++)
1359                 {
1360                         RemoteClient *client = i.getNode()->getValue();
1361                         PlayerSAO *playersao = getPlayerSAO(client->peer_id);
1362                         if(playersao == NULL)
1363                                 continue;
1364
1365                         /*
1366                                 Handle player HPs (die if hp=0)
1367                         */
1368                         if(playersao->getHP() == 0 && playersao->m_hp_not_sent)
1369                                 DiePlayer(client->peer_id);
1370
1371                         /*
1372                                 Send player inventories and HPs if necessary
1373                         */
1374                         if(playersao->m_teleported){
1375                                 SendMovePlayer(client->peer_id);
1376                                 playersao->m_teleported = false;
1377                         }
1378                         if(playersao->m_inventory_not_sent){
1379                                 UpdateCrafting(client->peer_id);
1380                                 SendInventory(client->peer_id);
1381                         }
1382                         if(playersao->m_hp_not_sent){
1383                                 SendPlayerHP(client->peer_id);
1384                         }
1385                 }
1386         }
1387         
1388         /* Transform liquids */
1389         m_liquid_transform_timer += dtime;
1390         if(m_liquid_transform_timer >= 1.00)
1391         {
1392                 m_liquid_transform_timer -= 1.00;
1393                 
1394                 JMutexAutoLock lock(m_env_mutex);
1395
1396                 ScopeProfiler sp(g_profiler, "Server: liquid transform");
1397
1398                 core::map<v3s16, MapBlock*> modified_blocks;
1399                 m_env->getMap().transformLiquids(modified_blocks);
1400 #if 0           
1401                 /*
1402                         Update lighting
1403                 */
1404                 core::map<v3s16, MapBlock*> lighting_modified_blocks;
1405                 ServerMap &map = ((ServerMap&)m_env->getMap());
1406                 map.updateLighting(modified_blocks, lighting_modified_blocks);
1407                 
1408                 // Add blocks modified by lighting to modified_blocks
1409                 for(core::map<v3s16, MapBlock*>::Iterator
1410                                 i = lighting_modified_blocks.getIterator();
1411                                 i.atEnd() == false; i++)
1412                 {
1413                         MapBlock *block = i.getNode()->getValue();
1414                         modified_blocks.insert(block->getPos(), block);
1415                 }
1416 #endif
1417                 /*
1418                         Set the modified blocks unsent for all the clients
1419                 */
1420                 
1421                 JMutexAutoLock lock2(m_con_mutex);
1422
1423                 for(core::map<u16, RemoteClient*>::Iterator
1424                                 i = m_clients.getIterator();
1425                                 i.atEnd() == false; i++)
1426                 {
1427                         RemoteClient *client = i.getNode()->getValue();
1428                         
1429                         if(modified_blocks.size() > 0)
1430                         {
1431                                 // Remove block from sent history
1432                                 client->SetBlocksNotSent(modified_blocks);
1433                         }
1434                 }
1435         }
1436
1437         // Periodically print some info
1438         {
1439                 float &counter = m_print_info_timer;
1440                 counter += dtime;
1441                 if(counter >= 30.0)
1442                 {
1443                         counter = 0.0;
1444
1445                         JMutexAutoLock lock2(m_con_mutex);
1446                         
1447                         if(m_clients.size() != 0)
1448                                 infostream<<"Players:"<<std::endl;
1449                         for(core::map<u16, RemoteClient*>::Iterator
1450                                 i = m_clients.getIterator();
1451                                 i.atEnd() == false; i++)
1452                         {
1453                                 //u16 peer_id = i.getNode()->getKey();
1454                                 RemoteClient *client = i.getNode()->getValue();
1455                                 Player *player = m_env->getPlayer(client->peer_id);
1456                                 if(player==NULL)
1457                                         continue;
1458                                 infostream<<"* "<<player->getName()<<"\t";
1459                                 client->PrintInfo(infostream);
1460                         }
1461                 }
1462         }
1463
1464         //if(g_settings->getBool("enable_experimental"))
1465         {
1466
1467         /*
1468                 Check added and deleted active objects
1469         */
1470         {
1471                 //infostream<<"Server: Checking added and deleted active objects"<<std::endl;
1472                 JMutexAutoLock envlock(m_env_mutex);
1473                 JMutexAutoLock conlock(m_con_mutex);
1474
1475                 ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
1476
1477                 // Radius inside which objects are active
1478                 s16 radius = g_settings->getS16("active_object_send_range_blocks");
1479                 radius *= MAP_BLOCKSIZE;
1480
1481                 for(core::map<u16, RemoteClient*>::Iterator
1482                         i = m_clients.getIterator();
1483                         i.atEnd() == false; i++)
1484                 {
1485                         RemoteClient *client = i.getNode()->getValue();
1486
1487                         // If definitions and textures have not been sent, don't
1488                         // send objects either
1489                         if(!client->definitions_sent)
1490                                 continue;
1491
1492                         Player *player = m_env->getPlayer(client->peer_id);
1493                         if(player==NULL)
1494                         {
1495                                 // This can happen if the client timeouts somehow
1496                                 /*infostream<<"WARNING: "<<__FUNCTION_NAME<<": Client "
1497                                                 <<client->peer_id
1498                                                 <<" has no associated player"<<std::endl;*/
1499                                 continue;
1500                         }
1501                         v3s16 pos = floatToInt(player->getPosition(), BS);
1502
1503                         core::map<u16, bool> removed_objects;
1504                         core::map<u16, bool> added_objects;
1505                         m_env->getRemovedActiveObjects(pos, radius,
1506                                         client->m_known_objects, removed_objects);
1507                         m_env->getAddedActiveObjects(pos, radius,
1508                                         client->m_known_objects, added_objects);
1509                         
1510                         // Ignore if nothing happened
1511                         if(removed_objects.size() == 0 && added_objects.size() == 0)
1512                         {
1513                                 //infostream<<"active objects: none changed"<<std::endl;
1514                                 continue;
1515                         }
1516                         
1517                         std::string data_buffer;
1518
1519                         char buf[4];
1520                         
1521                         // Handle removed objects
1522                         writeU16((u8*)buf, removed_objects.size());
1523                         data_buffer.append(buf, 2);
1524                         for(core::map<u16, bool>::Iterator
1525                                         i = removed_objects.getIterator();
1526                                         i.atEnd()==false; i++)
1527                         {
1528                                 // Get object
1529                                 u16 id = i.getNode()->getKey();
1530                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1531
1532                                 // Add to data buffer for sending
1533                                 writeU16((u8*)buf, i.getNode()->getKey());
1534                                 data_buffer.append(buf, 2);
1535                                 
1536                                 // Remove from known objects
1537                                 client->m_known_objects.remove(i.getNode()->getKey());
1538
1539                                 if(obj && obj->m_known_by_count > 0)
1540                                         obj->m_known_by_count--;
1541                         }
1542
1543                         // Handle added objects
1544                         writeU16((u8*)buf, added_objects.size());
1545                         data_buffer.append(buf, 2);
1546                         for(core::map<u16, bool>::Iterator
1547                                         i = added_objects.getIterator();
1548                                         i.atEnd()==false; i++)
1549                         {
1550                                 // Get object
1551                                 u16 id = i.getNode()->getKey();
1552                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1553                                 
1554                                 // Get object type
1555                                 u8 type = ACTIVEOBJECT_TYPE_INVALID;
1556                                 if(obj == NULL)
1557                                         infostream<<"WARNING: "<<__FUNCTION_NAME
1558                                                         <<": NULL object"<<std::endl;
1559                                 else
1560                                         type = obj->getSendType();
1561
1562                                 // Add to data buffer for sending
1563                                 writeU16((u8*)buf, id);
1564                                 data_buffer.append(buf, 2);
1565                                 writeU8((u8*)buf, type);
1566                                 data_buffer.append(buf, 1);
1567                                 
1568                                 if(obj)
1569                                         data_buffer.append(serializeLongString(
1570                                                         obj->getClientInitializationData()));
1571                                 else
1572                                         data_buffer.append(serializeLongString(""));
1573
1574                                 // Add to known objects
1575                                 client->m_known_objects.insert(i.getNode()->getKey(), false);
1576
1577                                 if(obj)
1578                                         obj->m_known_by_count++;
1579                         }
1580
1581                         // Send packet
1582                         SharedBuffer<u8> reply(2 + data_buffer.size());
1583                         writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD);
1584                         memcpy((char*)&reply[2], data_buffer.c_str(),
1585                                         data_buffer.size());
1586                         // Send as reliable
1587                         m_con.Send(client->peer_id, 0, reply, true);
1588
1589                         verbosestream<<"Server: Sent object remove/add: "
1590                                         <<removed_objects.size()<<" removed, "
1591                                         <<added_objects.size()<<" added, "
1592                                         <<"packet size is "<<reply.getSize()<<std::endl;
1593                 }
1594
1595 #if 0
1596                 /*
1597                         Collect a list of all the objects known by the clients
1598                         and report it back to the environment.
1599                 */
1600
1601                 core::map<u16, bool> all_known_objects;
1602
1603                 for(core::map<u16, RemoteClient*>::Iterator
1604                         i = m_clients.getIterator();
1605                         i.atEnd() == false; i++)
1606                 {
1607                         RemoteClient *client = i.getNode()->getValue();
1608                         // Go through all known objects of client
1609                         for(core::map<u16, bool>::Iterator
1610                                         i = client->m_known_objects.getIterator();
1611                                         i.atEnd()==false; i++)
1612                         {
1613                                 u16 id = i.getNode()->getKey();
1614                                 all_known_objects[id] = true;
1615                         }
1616                 }
1617                 
1618                 m_env->setKnownActiveObjects(whatever);
1619 #endif
1620
1621         }
1622
1623         /*
1624                 Send object messages
1625         */
1626         {
1627                 JMutexAutoLock envlock(m_env_mutex);
1628                 JMutexAutoLock conlock(m_con_mutex);
1629
1630                 ScopeProfiler sp(g_profiler, "Server: sending object messages");
1631
1632                 // Key = object id
1633                 // Value = data sent by object
1634                 core::map<u16, core::list<ActiveObjectMessage>* > buffered_messages;
1635
1636                 // Get active object messages from environment
1637                 for(;;)
1638                 {
1639                         ActiveObjectMessage aom = m_env->getActiveObjectMessage();
1640                         if(aom.id == 0)
1641                                 break;
1642                         
1643                         core::list<ActiveObjectMessage>* message_list = NULL;
1644                         core::map<u16, core::list<ActiveObjectMessage>* >::Node *n;
1645                         n = buffered_messages.find(aom.id);
1646                         if(n == NULL)
1647                         {
1648                                 message_list = new core::list<ActiveObjectMessage>;
1649                                 buffered_messages.insert(aom.id, message_list);
1650                         }
1651                         else
1652                         {
1653                                 message_list = n->getValue();
1654                         }
1655                         message_list->push_back(aom);
1656                 }
1657                 
1658                 // Route data to every client
1659                 for(core::map<u16, RemoteClient*>::Iterator
1660                         i = m_clients.getIterator();
1661                         i.atEnd()==false; i++)
1662                 {
1663                         RemoteClient *client = i.getNode()->getValue();
1664                         std::string reliable_data;
1665                         std::string unreliable_data;
1666                         // Go through all objects in message buffer
1667                         for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1668                                         j = buffered_messages.getIterator();
1669                                         j.atEnd()==false; j++)
1670                         {
1671                                 // If object is not known by client, skip it
1672                                 u16 id = j.getNode()->getKey();
1673                                 if(client->m_known_objects.find(id) == NULL)
1674                                         continue;
1675                                 // Get message list of object
1676                                 core::list<ActiveObjectMessage>* list = j.getNode()->getValue();
1677                                 // Go through every message
1678                                 for(core::list<ActiveObjectMessage>::Iterator
1679                                                 k = list->begin(); k != list->end(); k++)
1680                                 {
1681                                         // Compose the full new data with header
1682                                         ActiveObjectMessage aom = *k;
1683                                         std::string new_data;
1684                                         // Add object id
1685                                         char buf[2];
1686                                         writeU16((u8*)&buf[0], aom.id);
1687                                         new_data.append(buf, 2);
1688                                         // Add data
1689                                         new_data += serializeString(aom.datastring);
1690                                         // Add data to buffer
1691                                         if(aom.reliable)
1692                                                 reliable_data += new_data;
1693                                         else
1694                                                 unreliable_data += new_data;
1695                                 }
1696                         }
1697                         /*
1698                                 reliable_data and unreliable_data are now ready.
1699                                 Send them.
1700                         */
1701                         if(reliable_data.size() > 0)
1702                         {
1703                                 SharedBuffer<u8> reply(2 + reliable_data.size());
1704                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1705                                 memcpy((char*)&reply[2], reliable_data.c_str(),
1706                                                 reliable_data.size());
1707                                 // Send as reliable
1708                                 m_con.Send(client->peer_id, 0, reply, true);
1709                         }
1710                         if(unreliable_data.size() > 0)
1711                         {
1712                                 SharedBuffer<u8> reply(2 + unreliable_data.size());
1713                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1714                                 memcpy((char*)&reply[2], unreliable_data.c_str(),
1715                                                 unreliable_data.size());
1716                                 // Send as unreliable
1717                                 m_con.Send(client->peer_id, 0, reply, false);
1718                         }
1719
1720                         /*if(reliable_data.size() > 0 || unreliable_data.size() > 0)
1721                         {
1722                                 infostream<<"Server: Size of object message data: "
1723                                                 <<"reliable: "<<reliable_data.size()
1724                                                 <<", unreliable: "<<unreliable_data.size()
1725                                                 <<std::endl;
1726                         }*/
1727                 }
1728
1729                 // Clear buffered_messages
1730                 for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1731                                 i = buffered_messages.getIterator();
1732                                 i.atEnd()==false; i++)
1733                 {
1734                         delete i.getNode()->getValue();
1735                 }
1736         }
1737
1738         } // enable_experimental
1739
1740         /*
1741                 Send queued-for-sending map edit events.
1742         */
1743         {
1744                 // We will be accessing the environment and the connection
1745                 JMutexAutoLock lock(m_env_mutex);
1746                 JMutexAutoLock conlock(m_con_mutex);
1747
1748                 // Don't send too many at a time
1749                 //u32 count = 0;
1750
1751                 // Single change sending is disabled if queue size is not small
1752                 bool disable_single_change_sending = false;
1753                 if(m_unsent_map_edit_queue.size() >= 4)
1754                         disable_single_change_sending = true;
1755
1756                 int event_count = m_unsent_map_edit_queue.size();
1757
1758                 // We'll log the amount of each
1759                 Profiler prof;
1760
1761                 while(m_unsent_map_edit_queue.size() != 0)
1762                 {
1763                         MapEditEvent* event = m_unsent_map_edit_queue.pop_front();
1764                         
1765                         // Players far away from the change are stored here.
1766                         // Instead of sending the changes, MapBlocks are set not sent
1767                         // for them.
1768                         core::list<u16> far_players;
1769
1770                         if(event->type == MEET_ADDNODE)
1771                         {
1772                                 //infostream<<"Server: MEET_ADDNODE"<<std::endl;
1773                                 prof.add("MEET_ADDNODE", 1);
1774                                 if(disable_single_change_sending)
1775                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1776                                                         &far_players, 5);
1777                                 else
1778                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1779                                                         &far_players, 30);
1780                         }
1781                         else if(event->type == MEET_REMOVENODE)
1782                         {
1783                                 //infostream<<"Server: MEET_REMOVENODE"<<std::endl;
1784                                 prof.add("MEET_REMOVENODE", 1);
1785                                 if(disable_single_change_sending)
1786                                         sendRemoveNode(event->p, event->already_known_by_peer,
1787                                                         &far_players, 5);
1788                                 else
1789                                         sendRemoveNode(event->p, event->already_known_by_peer,
1790                                                         &far_players, 30);
1791                         }
1792                         else if(event->type == MEET_BLOCK_NODE_METADATA_CHANGED)
1793                         {
1794                                 infostream<<"Server: MEET_BLOCK_NODE_METADATA_CHANGED"<<std::endl;
1795                                 prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1);
1796                                 setBlockNotSent(event->p);
1797                         }
1798                         else if(event->type == MEET_OTHER)
1799                         {
1800                                 infostream<<"Server: MEET_OTHER"<<std::endl;
1801                                 prof.add("MEET_OTHER", 1);
1802                                 for(core::map<v3s16, bool>::Iterator
1803                                                 i = event->modified_blocks.getIterator();
1804                                                 i.atEnd()==false; i++)
1805                                 {
1806                                         v3s16 p = i.getNode()->getKey();
1807                                         setBlockNotSent(p);
1808                                 }
1809                         }
1810                         else
1811                         {
1812                                 prof.add("unknown", 1);
1813                                 infostream<<"WARNING: Server: Unknown MapEditEvent "
1814                                                 <<((u32)event->type)<<std::endl;
1815                         }
1816                         
1817                         /*
1818                                 Set blocks not sent to far players
1819                         */
1820                         if(far_players.size() > 0)
1821                         {
1822                                 // Convert list format to that wanted by SetBlocksNotSent
1823                                 core::map<v3s16, MapBlock*> modified_blocks2;
1824                                 for(core::map<v3s16, bool>::Iterator
1825                                                 i = event->modified_blocks.getIterator();
1826                                                 i.atEnd()==false; i++)
1827                                 {
1828                                         v3s16 p = i.getNode()->getKey();
1829                                         modified_blocks2.insert(p,
1830                                                         m_env->getMap().getBlockNoCreateNoEx(p));
1831                                 }
1832                                 // Set blocks not sent
1833                                 for(core::list<u16>::Iterator
1834                                                 i = far_players.begin();
1835                                                 i != far_players.end(); i++)
1836                                 {
1837                                         u16 peer_id = *i;
1838                                         RemoteClient *client = getClient(peer_id);
1839                                         if(client==NULL)
1840                                                 continue;
1841                                         client->SetBlocksNotSent(modified_blocks2);
1842                                 }
1843                         }
1844
1845                         delete event;
1846
1847                         /*// Don't send too many at a time
1848                         count++;
1849                         if(count >= 1 && m_unsent_map_edit_queue.size() < 100)
1850                                 break;*/
1851                 }
1852
1853                 if(event_count >= 5){
1854                         infostream<<"Server: MapEditEvents:"<<std::endl;
1855                         prof.print(infostream);
1856                 } else if(event_count != 0){
1857                         verbosestream<<"Server: MapEditEvents:"<<std::endl;
1858                         prof.print(verbosestream);
1859                 }
1860                 
1861         }
1862
1863         /*
1864                 Trigger emergethread (it somehow gets to a non-triggered but
1865                 bysy state sometimes)
1866         */
1867         {
1868                 float &counter = m_emergethread_trigger_timer;
1869                 counter += dtime;
1870                 if(counter >= 2.0)
1871                 {
1872                         counter = 0.0;
1873                         
1874                         m_emergethread.trigger();
1875
1876                         // Update m_enable_rollback_recording here too
1877                         m_enable_rollback_recording =
1878                                         g_settings->getBool("enable_rollback_recording");
1879                 }
1880         }
1881
1882         // Save map, players and auth stuff
1883         {
1884                 float &counter = m_savemap_timer;
1885                 counter += dtime;
1886                 if(counter >= g_settings->getFloat("server_map_save_interval"))
1887                 {
1888                         counter = 0.0;
1889                         JMutexAutoLock lock(m_env_mutex);
1890
1891                         ScopeProfiler sp(g_profiler, "Server: saving stuff");
1892
1893                         //Ban stuff
1894                         if(m_banmanager.isModified())
1895                                 m_banmanager.save();
1896                         
1897                         // Save changed parts of map
1898                         m_env->getMap().save(MOD_STATE_WRITE_NEEDED);
1899
1900                         // Save players
1901                         m_env->serializePlayers(m_path_world);
1902                         
1903                         // Save environment metadata
1904                         m_env->saveMeta(m_path_world);
1905                 }
1906         }
1907 }
1908
1909 void Server::Receive()
1910 {
1911         DSTACK(__FUNCTION_NAME);
1912         SharedBuffer<u8> data;
1913         u16 peer_id;
1914         u32 datasize;
1915         try{
1916                 {
1917                         JMutexAutoLock conlock(m_con_mutex);
1918                         datasize = m_con.Receive(peer_id, data);
1919                 }
1920
1921                 // This has to be called so that the client list gets synced
1922                 // with the peer list of the connection
1923                 handlePeerChanges();
1924
1925                 ProcessData(*data, datasize, peer_id);
1926         }
1927         catch(con::InvalidIncomingDataException &e)
1928         {
1929                 infostream<<"Server::Receive(): "
1930                                 "InvalidIncomingDataException: what()="
1931                                 <<e.what()<<std::endl;
1932         }
1933         catch(con::PeerNotFoundException &e)
1934         {
1935                 //NOTE: This is not needed anymore
1936                 
1937                 // The peer has been disconnected.
1938                 // Find the associated player and remove it.
1939
1940                 /*JMutexAutoLock envlock(m_env_mutex);
1941
1942                 infostream<<"ServerThread: peer_id="<<peer_id
1943                                 <<" has apparently closed connection. "
1944                                 <<"Removing player."<<std::endl;
1945
1946                 m_env->removePlayer(peer_id);*/
1947         }
1948 }
1949
1950 void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
1951 {
1952         DSTACK(__FUNCTION_NAME);
1953         // Environment is locked first.
1954         JMutexAutoLock envlock(m_env_mutex);
1955         JMutexAutoLock conlock(m_con_mutex);
1956         
1957         ScopeProfiler sp(g_profiler, "Server::ProcessData");
1958         
1959         try{
1960                 Address address = m_con.GetPeerAddress(peer_id);
1961                 std::string addr_s = address.serializeString();
1962
1963                 // drop player if is ip is banned
1964                 if(m_banmanager.isIpBanned(addr_s)){
1965                         infostream<<"Server: A banned client tried to connect from "
1966                                         <<addr_s<<"; banned name was "
1967                                         <<m_banmanager.getBanName(addr_s)<<std::endl;
1968                         // This actually doesn't seem to transfer to the client
1969                         SendAccessDenied(m_con, peer_id,
1970                                         L"Your ip is banned. Banned name was "
1971                                         +narrow_to_wide(m_banmanager.getBanName(addr_s)));
1972                         m_con.DeletePeer(peer_id);
1973                         return;
1974                 }
1975         }
1976         catch(con::PeerNotFoundException &e)
1977         {
1978                 infostream<<"Server::ProcessData(): Cancelling: peer "
1979                                 <<peer_id<<" not found"<<std::endl;
1980                 return;
1981         }
1982         
1983         std::string addr_s = m_con.GetPeerAddress(peer_id).serializeString();
1984
1985         u8 peer_ser_ver = getClient(peer_id)->serialization_version;
1986
1987         try
1988         {
1989
1990         if(datasize < 2)
1991                 return;
1992
1993         ToServerCommand command = (ToServerCommand)readU16(&data[0]);
1994         
1995         if(command == TOSERVER_INIT)
1996         {
1997                 // [0] u16 TOSERVER_INIT
1998                 // [2] u8 SER_FMT_VER_HIGHEST
1999                 // [3] u8[20] player_name
2000                 // [23] u8[28] password <--- can be sent without this, from old versions
2001
2002                 if(datasize < 2+1+PLAYERNAME_SIZE)
2003                         return;
2004
2005                 verbosestream<<"Server: Got TOSERVER_INIT from "
2006                                 <<peer_id<<std::endl;
2007
2008                 // First byte after command is maximum supported
2009                 // serialization version
2010                 u8 client_max = data[2];
2011                 u8 our_max = SER_FMT_VER_HIGHEST;
2012                 // Use the highest version supported by both
2013                 u8 deployed = core::min_(client_max, our_max);
2014                 // If it's lower than the lowest supported, give up.
2015                 if(deployed < SER_FMT_VER_LOWEST)
2016                         deployed = SER_FMT_VER_INVALID;
2017
2018                 //peer->serialization_version = deployed;
2019                 getClient(peer_id)->pending_serialization_version = deployed;
2020                 
2021                 if(deployed == SER_FMT_VER_INVALID)
2022                 {
2023                         actionstream<<"Server: A mismatched client tried to connect from "
2024                                         <<addr_s<<std::endl;
2025                         infostream<<"Server: Cannot negotiate "
2026                                         "serialization version with peer "
2027                                         <<peer_id<<std::endl;
2028                         SendAccessDenied(m_con, peer_id, std::wstring(
2029                                         L"Your client's version is not supported.\n"
2030                                         L"Server version is ")
2031                                         + narrow_to_wide(VERSION_STRING) + L"."
2032                         );
2033                         return;
2034                 }
2035                 
2036                 /*
2037                         Read and check network protocol version
2038                 */
2039
2040                 u16 net_proto_version = 0;
2041                 if(datasize >= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2)
2042                 {
2043                         net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]);
2044                 }
2045
2046                 getClient(peer_id)->net_proto_version = net_proto_version;
2047
2048                 if(net_proto_version == 0)
2049                 {
2050                         actionstream<<"Server: An old tried to connect from "<<addr_s
2051                                         <<std::endl;
2052                         SendAccessDenied(m_con, peer_id, std::wstring(
2053                                         L"Your client's version is not supported.\n"
2054                                         L"Server version is ")
2055                                         + narrow_to_wide(VERSION_STRING) + L"."
2056                         );
2057                         return;
2058                 }
2059                 
2060                 if(g_settings->getBool("strict_protocol_version_checking"))
2061                 {
2062                         if(net_proto_version != PROTOCOL_VERSION)
2063                         {
2064                                 actionstream<<"Server: A mismatched client tried to connect"
2065                                                 <<" from "<<addr_s<<std::endl;
2066                                 SendAccessDenied(m_con, peer_id, std::wstring(
2067                                                 L"Your client's version is not supported.\n"
2068                                                 L"Server version is ")
2069                                                 + narrow_to_wide(VERSION_STRING) + L",\n"
2070                                                 + L"server's PROTOCOL_VERSION is "
2071                                                 + narrow_to_wide(itos(PROTOCOL_VERSION))
2072                                                 + L", client's PROTOCOL_VERSION is "
2073                                                 + narrow_to_wide(itos(net_proto_version))
2074                                 );
2075                                 return;
2076                         }
2077                 }
2078
2079                 /*
2080                         Set up player
2081                 */
2082                 
2083                 // Get player name
2084                 char playername[PLAYERNAME_SIZE];
2085                 for(u32 i=0; i<PLAYERNAME_SIZE-1; i++)
2086                 {
2087                         playername[i] = data[3+i];
2088                 }
2089                 playername[PLAYERNAME_SIZE-1] = 0;
2090                 
2091                 if(playername[0]=='\0')
2092                 {
2093                         actionstream<<"Server: Player with an empty name "
2094                                         <<"tried to connect from "<<addr_s<<std::endl;
2095                         SendAccessDenied(m_con, peer_id,
2096                                         L"Empty name");
2097                         return;
2098                 }
2099
2100                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
2101                 {
2102                         actionstream<<"Server: Player with an invalid name "
2103                                         <<"tried to connect from "<<addr_s<<std::endl;
2104                         SendAccessDenied(m_con, peer_id,
2105                                         L"Name contains unallowed characters");
2106                         return;
2107                 }
2108
2109                 infostream<<"Server: New connection: \""<<playername<<"\" from "
2110                                 <<m_con.GetPeerAddress(peer_id).serializeString()<<std::endl;
2111
2112                 // Get password
2113                 char given_password[PASSWORD_SIZE];
2114                 if(datasize < 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE)
2115                 {
2116                         // old version - assume blank password
2117                         given_password[0] = 0;
2118                 }
2119                 else
2120                 {
2121                         for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2122                         {
2123                                 given_password[i] = data[23+i];
2124                         }
2125                         given_password[PASSWORD_SIZE-1] = 0;
2126                 }
2127
2128                 if(!base64_is_valid(given_password)){
2129                         infostream<<"Server: "<<playername
2130                                         <<" supplied invalid password hash"<<std::endl;
2131                         SendAccessDenied(m_con, peer_id, L"Invalid password hash");
2132                         return;
2133                 }
2134                 
2135                 std::string checkpwd; // Password hash to check against
2136                 bool has_auth = scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
2137                 
2138                 // If no authentication info exists for user, create it
2139                 if(!has_auth){
2140                         if(!isSingleplayer() &&
2141                                         g_settings->getBool("disallow_empty_password") &&
2142                                         std::string(given_password) == ""){
2143                                 SendAccessDenied(m_con, peer_id, L"Empty passwords are "
2144                                                 L"disallowed. Set a password and try again.");
2145                                 return;
2146                         }
2147                         std::wstring raw_default_password =
2148                                 narrow_to_wide(g_settings->get("default_password"));
2149                         std::string initial_password =
2150                                 translatePassword(playername, raw_default_password);
2151
2152                         // If default_password is empty, allow any initial password
2153                         if (raw_default_password.length() == 0)
2154                                 initial_password = given_password;
2155
2156                         scriptapi_create_auth(m_lua, playername, initial_password);
2157                 }
2158                 
2159                 has_auth = scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
2160
2161                 if(!has_auth){
2162                         SendAccessDenied(m_con, peer_id, L"Not allowed to login");
2163                         return;
2164                 }
2165
2166                 if(given_password != checkpwd){
2167                         infostream<<"Server: peer_id="<<peer_id
2168                                         <<": supplied invalid password for "
2169                                         <<playername<<std::endl;
2170                         SendAccessDenied(m_con, peer_id, L"Invalid password");
2171                         return;
2172                 }
2173
2174                 // Do not allow multiple players in simple singleplayer mode.
2175                 // This isn't a perfect way to do it, but will suffice for now.
2176                 if(m_simple_singleplayer_mode && m_clients.size() > 1){
2177                         infostream<<"Server: Not allowing another client to connect in"
2178                                         <<" simple singleplayer mode"<<std::endl;
2179                         SendAccessDenied(m_con, peer_id,
2180                                         L"Running in simple singleplayer mode.");
2181                         return;
2182                 }
2183                 
2184                 // Enforce user limit.
2185                 // Don't enforce for users that have some admin right
2186                 if(m_clients.size() >= g_settings->getU16("max_users") &&
2187                                 !checkPriv(playername, "server") &&
2188                                 !checkPriv(playername, "ban") &&
2189                                 !checkPriv(playername, "privs") &&
2190                                 !checkPriv(playername, "password") &&
2191                                 playername != g_settings->get("name"))
2192                 {
2193                         actionstream<<"Server: "<<playername<<" tried to join, but there"
2194                                         <<" are already max_users="
2195                                         <<g_settings->getU16("max_users")<<" players."<<std::endl;
2196                         SendAccessDenied(m_con, peer_id, L"Too many users.");
2197                         return;
2198                 }
2199
2200                 // Get player
2201                 PlayerSAO *playersao = emergePlayer(playername, peer_id);
2202
2203                 // If failed, cancel
2204                 if(playersao == NULL)
2205                 {
2206                         errorstream<<"Server: peer_id="<<peer_id
2207                                         <<": failed to emerge player"<<std::endl;
2208                         return;
2209                 }
2210
2211                 /*
2212                         Answer with a TOCLIENT_INIT
2213                 */
2214                 {
2215                         SharedBuffer<u8> reply(2+1+6+8);
2216                         writeU16(&reply[0], TOCLIENT_INIT);
2217                         writeU8(&reply[2], deployed);
2218                         writeV3S16(&reply[2+1], floatToInt(playersao->getPlayer()->getPosition()+v3f(0,BS/2,0), BS));
2219                         writeU64(&reply[2+1+6], m_env->getServerMap().getSeed());
2220                         
2221                         // Send as reliable
2222                         m_con.Send(peer_id, 0, reply, true);
2223                 }
2224
2225                 /*
2226                         Send complete position information
2227                 */
2228                 SendMovePlayer(peer_id);
2229
2230                 return;
2231         }
2232
2233         if(command == TOSERVER_INIT2)
2234         {
2235                 verbosestream<<"Server: Got TOSERVER_INIT2 from "
2236                                 <<peer_id<<std::endl;
2237
2238                 Player *player = m_env->getPlayer(peer_id);
2239                 if(!player){
2240                         verbosestream<<"Server: TOSERVER_INIT2: "
2241                                         <<"Player not found; ignoring."<<std::endl;
2242                         return;
2243                 }
2244
2245                 getClient(peer_id)->serialization_version
2246                                 = getClient(peer_id)->pending_serialization_version;
2247
2248                 /*
2249                         Send some initialization data
2250                 */
2251
2252                 infostream<<"Server: Sending content to "
2253                                 <<getPlayerName(peer_id)<<std::endl;
2254
2255                 // Send item definitions
2256                 SendItemDef(m_con, peer_id, m_itemdef);
2257                 
2258                 // Send node definitions
2259                 SendNodeDef(m_con, peer_id, m_nodedef);
2260                 
2261                 // Send media announcement
2262                 sendMediaAnnouncement(peer_id);
2263                 
2264                 // Send privileges
2265                 SendPlayerPrivileges(peer_id);
2266                 
2267                 // Send inventory formspec
2268                 SendPlayerInventoryFormspec(peer_id);
2269
2270                 // Send inventory
2271                 UpdateCrafting(peer_id);
2272                 SendInventory(peer_id);
2273
2274                 // Send HP
2275                 SendPlayerHP(peer_id);
2276                 
2277                 // Send detached inventories
2278                 sendDetachedInventories(peer_id);
2279                 
2280                 // Show death screen if necessary
2281                 if(player->hp == 0)
2282                         SendDeathscreen(m_con, peer_id, false, v3f(0,0,0));
2283
2284                 // Send time of day
2285                 {
2286                         SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
2287                                         m_env->getTimeOfDay(), g_settings->getFloat("time_speed"));
2288                         m_con.Send(peer_id, 0, data, true);
2289                 }
2290                 
2291                 // Note things in chat if not in simple singleplayer mode
2292                 if(!m_simple_singleplayer_mode)
2293                 {
2294                         // Send information about server to player in chat
2295                         SendChatMessage(peer_id, getStatusString());
2296                         
2297                         // Send information about joining in chat
2298                         {
2299                                 std::wstring name = L"unknown";
2300                                 Player *player = m_env->getPlayer(peer_id);
2301                                 if(player != NULL)
2302                                         name = narrow_to_wide(player->getName());
2303                                 
2304                                 std::wstring message;
2305                                 message += L"*** ";
2306                                 message += name;
2307                                 message += L" joined the game.";
2308                                 BroadcastChatMessage(message);
2309                         }
2310                 }
2311                 
2312                 // Warnings about protocol version can be issued here
2313                 if(getClient(peer_id)->net_proto_version < PROTOCOL_VERSION)
2314                 {
2315                         SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER!");
2316                 }
2317
2318                 /*
2319                         Print out action
2320                 */
2321                 {
2322                         std::ostringstream os(std::ios_base::binary);
2323                         for(core::map<u16, RemoteClient*>::Iterator
2324                                 i = m_clients.getIterator();
2325                                 i.atEnd() == false; i++)
2326                         {
2327                                 RemoteClient *client = i.getNode()->getValue();
2328                                 assert(client->peer_id == i.getNode()->getKey());
2329                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2330                                         continue;
2331                                 // Get player
2332                                 Player *player = m_env->getPlayer(client->peer_id);
2333                                 if(!player)
2334                                         continue;
2335                                 // Get name of player
2336                                 os<<player->getName()<<" ";
2337                         }
2338
2339                         actionstream<<player->getName()<<" joins game. List of players: "
2340                                         <<os.str()<<std::endl;
2341                 }
2342
2343                 return;
2344         }
2345
2346         if(peer_ser_ver == SER_FMT_VER_INVALID)
2347         {
2348                 infostream<<"Server::ProcessData(): Cancelling: Peer"
2349                                 " serialization format invalid or not initialized."
2350                                 " Skipping incoming command="<<command<<std::endl;
2351                 return;
2352         }
2353         
2354         Player *player = m_env->getPlayer(peer_id);
2355         if(player == NULL){
2356                 infostream<<"Server::ProcessData(): Cancelling: "
2357                                 "No player for peer_id="<<peer_id
2358                                 <<std::endl;
2359                 return;
2360         }
2361
2362         PlayerSAO *playersao = player->getPlayerSAO();
2363         if(playersao == NULL){
2364                 infostream<<"Server::ProcessData(): Cancelling: "
2365                                 "No player object for peer_id="<<peer_id
2366                                 <<std::endl;
2367                 return;
2368         }
2369
2370         if(command == TOSERVER_PLAYERPOS)
2371         {
2372                 if(datasize < 2+12+12+4+4)
2373                         return;
2374         
2375                 u32 start = 0;
2376                 v3s32 ps = readV3S32(&data[start+2]);
2377                 v3s32 ss = readV3S32(&data[start+2+12]);
2378                 f32 pitch = (f32)readS32(&data[2+12+12]) / 100.0;
2379                 f32 yaw = (f32)readS32(&data[2+12+12+4]) / 100.0;
2380                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
2381                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
2382                 pitch = wrapDegrees(pitch);
2383                 yaw = wrapDegrees(yaw);
2384
2385                 player->setPosition(position);
2386                 player->setSpeed(speed);
2387                 player->setPitch(pitch);
2388                 player->setYaw(yaw);
2389                 
2390                 /*infostream<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
2391                                 <<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
2392                                 <<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
2393         }
2394         else if(command == TOSERVER_GOTBLOCKS)
2395         {
2396                 if(datasize < 2+1)
2397                         return;
2398                 
2399                 /*
2400                         [0] u16 command
2401                         [2] u8 count
2402                         [3] v3s16 pos_0
2403                         [3+6] v3s16 pos_1
2404                         ...
2405                 */
2406
2407                 u16 count = data[2];
2408                 for(u16 i=0; i<count; i++)
2409                 {
2410                         if((s16)datasize < 2+1+(i+1)*6)
2411                                 throw con::InvalidIncomingDataException
2412                                         ("GOTBLOCKS length is too short");
2413                         v3s16 p = readV3S16(&data[2+1+i*6]);
2414                         /*infostream<<"Server: GOTBLOCKS ("
2415                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2416                         RemoteClient *client = getClient(peer_id);
2417                         client->GotBlock(p);
2418                 }
2419         }
2420         else if(command == TOSERVER_DELETEDBLOCKS)
2421         {
2422                 if(datasize < 2+1)
2423                         return;
2424                 
2425                 /*
2426                         [0] u16 command
2427                         [2] u8 count
2428                         [3] v3s16 pos_0
2429                         [3+6] v3s16 pos_1
2430                         ...
2431                 */
2432
2433                 u16 count = data[2];
2434                 for(u16 i=0; i<count; i++)
2435                 {
2436                         if((s16)datasize < 2+1+(i+1)*6)
2437                                 throw con::InvalidIncomingDataException
2438                                         ("DELETEDBLOCKS length is too short");
2439                         v3s16 p = readV3S16(&data[2+1+i*6]);
2440                         /*infostream<<"Server: DELETEDBLOCKS ("
2441                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2442                         RemoteClient *client = getClient(peer_id);
2443                         client->SetBlockNotSent(p);
2444                 }
2445         }
2446         else if(command == TOSERVER_CLICK_OBJECT)
2447         {
2448                 infostream<<"Server: CLICK_OBJECT not supported anymore"<<std::endl;
2449                 return;
2450         }
2451         else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
2452         {
2453                 infostream<<"Server: CLICK_ACTIVEOBJECT not supported anymore"<<std::endl;
2454                 return;
2455         }
2456         else if(command == TOSERVER_GROUND_ACTION)
2457         {
2458                 infostream<<"Server: GROUND_ACTION not supported anymore"<<std::endl;
2459                 return;
2460
2461         }
2462         else if(command == TOSERVER_RELEASE)
2463         {
2464                 infostream<<"Server: RELEASE not supported anymore"<<std::endl;
2465                 return;
2466         }
2467         else if(command == TOSERVER_SIGNTEXT)
2468         {
2469                 infostream<<"Server: SIGNTEXT not supported anymore"
2470                                 <<std::endl;
2471                 return;
2472         }
2473         else if(command == TOSERVER_SIGNNODETEXT)
2474         {
2475                 infostream<<"Server: SIGNNODETEXT not supported anymore"
2476                                 <<std::endl;
2477                 return;
2478         }
2479         else if(command == TOSERVER_INVENTORY_ACTION)
2480         {
2481                 // Strip command and create a stream
2482                 std::string datastring((char*)&data[2], datasize-2);
2483                 verbosestream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
2484                 std::istringstream is(datastring, std::ios_base::binary);
2485                 // Create an action
2486                 InventoryAction *a = InventoryAction::deSerialize(is);
2487                 if(a == NULL)
2488                 {
2489                         infostream<<"TOSERVER_INVENTORY_ACTION: "
2490                                         <<"InventoryAction::deSerialize() returned NULL"
2491                                         <<std::endl;
2492                         return;
2493                 }
2494
2495                 // If something goes wrong, this player is to blame
2496                 RollbackScopeActor rollback_scope(m_rollback,
2497                                 std::string("player:")+player->getName());
2498
2499                 /*
2500                         Note: Always set inventory not sent, to repair cases
2501                         where the client made a bad prediction.
2502                 */
2503
2504                 /*
2505                         Handle restrictions and special cases of the move action
2506                 */
2507                 if(a->getType() == IACTION_MOVE)
2508                 {
2509                         IMoveAction *ma = (IMoveAction*)a;
2510
2511                         ma->from_inv.applyCurrentPlayer(player->getName());
2512                         ma->to_inv.applyCurrentPlayer(player->getName());
2513
2514                         setInventoryModified(ma->from_inv);
2515                         setInventoryModified(ma->to_inv);
2516
2517                         bool from_inv_is_current_player =
2518                                 (ma->from_inv.type == InventoryLocation::PLAYER) &&
2519                                 (ma->from_inv.name == player->getName());
2520
2521                         bool to_inv_is_current_player =
2522                                 (ma->to_inv.type == InventoryLocation::PLAYER) &&
2523                                 (ma->to_inv.name == player->getName());
2524
2525                         /*
2526                                 Disable moving items out of craftpreview
2527                         */
2528                         if(ma->from_list == "craftpreview")
2529                         {
2530                                 infostream<<"Ignoring IMoveAction from "
2531                                                 <<(ma->from_inv.dump())<<":"<<ma->from_list
2532                                                 <<" to "<<(ma->to_inv.dump())<<":"<<ma->to_list
2533                                                 <<" because src is "<<ma->from_list<<std::endl;
2534                                 delete a;
2535                                 return;
2536                         }
2537
2538                         /*
2539                                 Disable moving items into craftresult and craftpreview
2540                         */
2541                         if(ma->to_list == "craftpreview" || ma->to_list == "craftresult")
2542                         {
2543                                 infostream<<"Ignoring IMoveAction from "
2544                                                 <<(ma->from_inv.dump())<<":"<<ma->from_list
2545                                                 <<" to "<<(ma->to_inv.dump())<<":"<<ma->to_list
2546                                                 <<" because dst is "<<ma->to_list<<std::endl;
2547                                 delete a;
2548                                 return;
2549                         }
2550
2551                         // Disallow moving items in elsewhere than player's inventory
2552                         // if not allowed to interact
2553                         if(!checkPriv(player->getName(), "interact") &&
2554                                         (!from_inv_is_current_player ||
2555                                         !to_inv_is_current_player))
2556                         {
2557                                 infostream<<"Cannot move outside of player's inventory: "
2558                                                 <<"No interact privilege"<<std::endl;
2559                                 delete a;
2560                                 return;
2561                         }
2562                 }
2563                 /*
2564                         Handle restrictions and special cases of the drop action
2565                 */
2566                 else if(a->getType() == IACTION_DROP)
2567                 {
2568                         IDropAction *da = (IDropAction*)a;
2569
2570                         da->from_inv.applyCurrentPlayer(player->getName());
2571
2572                         setInventoryModified(da->from_inv);
2573
2574                         // Disallow dropping items if not allowed to interact
2575                         if(!checkPriv(player->getName(), "interact"))
2576                         {
2577                                 delete a;
2578                                 return;
2579                         }
2580                 }
2581                 /*
2582                         Handle restrictions and special cases of the craft action
2583                 */
2584                 else if(a->getType() == IACTION_CRAFT)
2585                 {
2586                         ICraftAction *ca = (ICraftAction*)a;
2587
2588                         ca->craft_inv.applyCurrentPlayer(player->getName());
2589
2590                         setInventoryModified(ca->craft_inv);
2591
2592                         //bool craft_inv_is_current_player =
2593                         //      (ca->craft_inv.type == InventoryLocation::PLAYER) &&
2594                         //      (ca->craft_inv.name == player->getName());
2595
2596                         // Disallow crafting if not allowed to interact
2597                         if(!checkPriv(player->getName(), "interact"))
2598                         {
2599                                 infostream<<"Cannot craft: "
2600                                                 <<"No interact privilege"<<std::endl;
2601                                 delete a;
2602                                 return;
2603                         }
2604                 }
2605                 
2606                 // Do the action
2607                 a->apply(this, playersao, this);
2608                 // Eat the action
2609                 delete a;
2610         }
2611         else if(command == TOSERVER_CHAT_MESSAGE)
2612         {
2613                 /*
2614                         u16 command
2615                         u16 length
2616                         wstring message
2617                 */
2618                 u8 buf[6];
2619                 std::string datastring((char*)&data[2], datasize-2);
2620                 std::istringstream is(datastring, std::ios_base::binary);
2621                 
2622                 // Read stuff
2623                 is.read((char*)buf, 2);
2624                 u16 len = readU16(buf);
2625                 
2626                 std::wstring message;
2627                 for(u16 i=0; i<len; i++)
2628                 {
2629                         is.read((char*)buf, 2);
2630                         message += (wchar_t)readU16(buf);
2631                 }
2632
2633                 // If something goes wrong, this player is to blame
2634                 RollbackScopeActor rollback_scope(m_rollback,
2635                                 std::string("player:")+player->getName());
2636
2637                 // Get player name of this client
2638                 std::wstring name = narrow_to_wide(player->getName());
2639                 
2640                 // Run script hook
2641                 bool ate = scriptapi_on_chat_message(m_lua, player->getName(),
2642                                 wide_to_narrow(message));
2643                 // If script ate the message, don't proceed
2644                 if(ate)
2645                         return;
2646                 
2647                 // Line to send to players
2648                 std::wstring line;
2649                 // Whether to send to the player that sent the line
2650                 bool send_to_sender = false;
2651                 // Whether to send to other players
2652                 bool send_to_others = false;
2653                 
2654                 // Commands are implemented in Lua, so only catch invalid
2655                 // commands that were not "eaten" and send an error back
2656                 if(message[0] == L'/')
2657                 {
2658                         message = message.substr(1);
2659                         send_to_sender = true;
2660                         if(message.length() == 0)
2661                                 line += L"-!- Empty command";
2662                         else
2663                                 line += L"-!- Invalid command: " + str_split(message, L' ')[0];
2664                 }
2665                 else
2666                 {
2667                         if(checkPriv(player->getName(), "shout")){
2668                                 line += L"<";
2669                                 line += name;
2670                                 line += L"> ";
2671                                 line += message;
2672                                 send_to_others = true;
2673                         } else {
2674                                 line += L"-!- You don't have permission to shout.";
2675                                 send_to_sender = true;
2676                         }
2677                 }
2678                 
2679                 if(line != L"")
2680                 {
2681                         if(send_to_others)
2682                                 actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
2683
2684                         /*
2685                                 Send the message to clients
2686                         */
2687                         for(core::map<u16, RemoteClient*>::Iterator
2688                                 i = m_clients.getIterator();
2689                                 i.atEnd() == false; i++)
2690                         {
2691                                 // Get client and check that it is valid
2692                                 RemoteClient *client = i.getNode()->getValue();
2693                                 assert(client->peer_id == i.getNode()->getKey());
2694                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2695                                         continue;
2696
2697                                 // Filter recipient
2698                                 bool sender_selected = (peer_id == client->peer_id);
2699                                 if(sender_selected == true && send_to_sender == false)
2700                                         continue;
2701                                 if(sender_selected == false && send_to_others == false)
2702                                         continue;
2703
2704                                 SendChatMessage(client->peer_id, line);
2705                         }
2706                 }
2707         }
2708         else if(command == TOSERVER_DAMAGE)
2709         {
2710                 std::string datastring((char*)&data[2], datasize-2);
2711                 std::istringstream is(datastring, std::ios_base::binary);
2712                 u8 damage = readU8(is);
2713
2714                 actionstream<<player->getName()<<" damaged by "
2715                                 <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
2716                                 <<std::endl;
2717
2718                 playersao->setHP(playersao->getHP() - damage);
2719
2720                 if(playersao->getHP() == 0 && playersao->m_hp_not_sent)
2721                         DiePlayer(peer_id);
2722
2723                 if(playersao->m_hp_not_sent)
2724                         SendPlayerHP(peer_id);
2725         }
2726         else if(command == TOSERVER_PASSWORD)
2727         {
2728                 /*
2729                         [0] u16 TOSERVER_PASSWORD
2730                         [2] u8[28] old password
2731                         [30] u8[28] new password
2732                 */
2733
2734                 if(datasize != 2+PASSWORD_SIZE*2)
2735                         return;
2736                 /*char password[PASSWORD_SIZE];
2737                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2738                         password[i] = data[2+i];
2739                 password[PASSWORD_SIZE-1] = 0;*/
2740                 std::string oldpwd;
2741                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2742                 {
2743                         char c = data[2+i];
2744                         if(c == 0)
2745                                 break;
2746                         oldpwd += c;
2747                 }
2748                 std::string newpwd;
2749                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2750                 {
2751                         char c = data[2+PASSWORD_SIZE+i];
2752                         if(c == 0)
2753                                 break;
2754                         newpwd += c;
2755                 }
2756
2757                 if(!base64_is_valid(newpwd)){
2758                         infostream<<"Server: "<<player->getName()<<" supplied invalid password hash"<<std::endl;
2759                         // Wrong old password supplied!!
2760                         SendChatMessage(peer_id, L"Invalid new password hash supplied. Password NOT changed.");
2761                         return;
2762                 }
2763
2764                 infostream<<"Server: Client requests a password change from "
2765                                 <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
2766
2767                 std::string playername = player->getName();
2768
2769                 std::string checkpwd;
2770                 scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
2771
2772                 if(oldpwd != checkpwd)
2773                 {
2774                         infostream<<"Server: invalid old password"<<std::endl;
2775                         // Wrong old password supplied!!
2776                         SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
2777                         return;
2778                 }
2779
2780                 bool success = scriptapi_set_password(m_lua, playername, newpwd);
2781                 if(success){
2782                         actionstream<<player->getName()<<" changes password"<<std::endl;
2783                         SendChatMessage(peer_id, L"Password change successful.");
2784                 } else {
2785                         actionstream<<player->getName()<<" tries to change password but "
2786                                         <<"it fails"<<std::endl;
2787                         SendChatMessage(peer_id, L"Password change failed or inavailable.");
2788                 }
2789         }
2790         else if(command == TOSERVER_PLAYERITEM)
2791         {
2792                 if (datasize < 2+2)
2793                         return;
2794
2795                 u16 item = readU16(&data[2]);
2796                 playersao->setWieldIndex(item);
2797         }
2798         else if(command == TOSERVER_RESPAWN)
2799         {
2800                 if(player->hp != 0)
2801                         return;
2802                 
2803                 RespawnPlayer(peer_id);
2804                 
2805                 actionstream<<player->getName()<<" respawns at "
2806                                 <<PP(player->getPosition()/BS)<<std::endl;
2807
2808                 // ActiveObject is added to environment in AsyncRunStep after
2809                 // the previous addition has been succesfully removed
2810         }
2811         else if(command == TOSERVER_REQUEST_MEDIA) {
2812                 std::string datastring((char*)&data[2], datasize-2);
2813                 std::istringstream is(datastring, std::ios_base::binary);
2814                 
2815                 core::list<MediaRequest> tosend;
2816                 u16 numfiles = readU16(is);
2817
2818                 infostream<<"Sending "<<numfiles<<" files to "
2819                                 <<getPlayerName(peer_id)<<std::endl;
2820                 verbosestream<<"TOSERVER_REQUEST_MEDIA: "<<std::endl;
2821
2822                 for(int i = 0; i < numfiles; i++) {
2823                         std::string name = deSerializeString(is);
2824                         tosend.push_back(MediaRequest(name));
2825                         verbosestream<<"TOSERVER_REQUEST_MEDIA: requested file "
2826                                         <<name<<std::endl;
2827                 }
2828
2829                 sendRequestedMedia(peer_id, tosend);
2830
2831                 // Now the client should know about everything
2832                 // (definitions and files)
2833                 getClient(peer_id)->definitions_sent = true;
2834         }
2835         else if(command == TOSERVER_INTERACT)
2836         {
2837                 std::string datastring((char*)&data[2], datasize-2);
2838                 std::istringstream is(datastring, std::ios_base::binary);
2839
2840                 /*
2841                         [0] u16 command
2842                         [2] u8 action
2843                         [3] u16 item
2844                         [5] u32 length of the next item
2845                         [9] serialized PointedThing
2846                         actions:
2847                         0: start digging (from undersurface) or use
2848                         1: stop digging (all parameters ignored)
2849                         2: digging completed
2850                         3: place block or item (to abovesurface)
2851                         4: use item
2852                 */
2853                 u8 action = readU8(is);
2854                 u16 item_i = readU16(is);
2855                 std::istringstream tmp_is(deSerializeLongString(is), std::ios::binary);
2856                 PointedThing pointed;
2857                 pointed.deSerialize(tmp_is);
2858
2859                 verbosestream<<"TOSERVER_INTERACT: action="<<(int)action<<", item="
2860                                 <<item_i<<", pointed="<<pointed.dump()<<std::endl;
2861
2862                 if(player->hp == 0)
2863                 {
2864                         verbosestream<<"TOSERVER_INTERACT: "<<player->getName()
2865                                 <<" tried to interact, but is dead!"<<std::endl;
2866                         return;
2867                 }
2868
2869                 v3f player_pos = playersao->getLastGoodPosition();
2870
2871                 // Update wielded item
2872                 playersao->setWieldIndex(item_i);
2873
2874                 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
2875                 v3s16 p_under = pointed.node_undersurface;
2876                 v3s16 p_above = pointed.node_abovesurface;
2877
2878                 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
2879                 ServerActiveObject *pointed_object = NULL;
2880                 if(pointed.type == POINTEDTHING_OBJECT)
2881                 {
2882                         pointed_object = m_env->getActiveObject(pointed.object_id);
2883                         if(pointed_object == NULL)
2884                         {
2885                                 verbosestream<<"TOSERVER_INTERACT: "
2886                                         "pointed object is NULL"<<std::endl;
2887                                 return;
2888                         }
2889
2890                 }
2891
2892                 v3f pointed_pos_under = player_pos;
2893                 v3f pointed_pos_above = player_pos;
2894                 if(pointed.type == POINTEDTHING_NODE)
2895                 {
2896                         pointed_pos_under = intToFloat(p_under, BS);
2897                         pointed_pos_above = intToFloat(p_above, BS);
2898                 }
2899                 else if(pointed.type == POINTEDTHING_OBJECT)
2900                 {
2901                         pointed_pos_under = pointed_object->getBasePosition();
2902                         pointed_pos_above = pointed_pos_under;
2903                 }
2904
2905                 /*
2906                         Check that target is reasonably close
2907                         (only when digging or placing things)
2908                 */
2909                 if(action == 0 || action == 2 || action == 3)
2910                 {
2911                         float d = player_pos.getDistanceFrom(pointed_pos_under);
2912                         float max_d = BS * 14; // Just some large enough value
2913                         if(d > max_d){
2914                                 actionstream<<"Player "<<player->getName()
2915                                                 <<" tried to access "<<pointed.dump()
2916                                                 <<" from too far: "
2917                                                 <<"d="<<d<<", max_d="<<max_d
2918                                                 <<". ignoring."<<std::endl;
2919                                 // Re-send block to revert change on client-side
2920                                 RemoteClient *client = getClient(peer_id);
2921                                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
2922                                 client->SetBlockNotSent(blockpos);
2923                                 // Do nothing else
2924                                 return;
2925                         }
2926                 }
2927
2928                 /*
2929                         Make sure the player is allowed to do it
2930                 */
2931                 if(!checkPriv(player->getName(), "interact"))
2932                 {
2933                         actionstream<<player->getName()<<" attempted to interact with "
2934                                         <<pointed.dump()<<" without 'interact' privilege"
2935                                         <<std::endl;
2936                         // Re-send block to revert change on client-side
2937                         RemoteClient *client = getClient(peer_id);
2938                         // Digging completed -> under
2939                         if(action == 2){
2940                                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
2941                                 client->SetBlockNotSent(blockpos);
2942                         }
2943                         // Placement -> above
2944                         if(action == 3){
2945                                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
2946                                 client->SetBlockNotSent(blockpos);
2947                         }
2948                         return;
2949                 }
2950
2951                 /*
2952                         If something goes wrong, this player is to blame
2953                 */
2954                 RollbackScopeActor rollback_scope(m_rollback,
2955                                 std::string("player:")+player->getName());
2956
2957                 /*
2958                         0: start digging or punch object
2959                 */
2960                 if(action == 0)
2961                 {
2962                         if(pointed.type == POINTEDTHING_NODE)
2963                         {
2964                                 /*
2965                                         NOTE: This can be used in the future to check if
2966                                         somebody is cheating, by checking the timing.
2967                                 */
2968                                 MapNode n(CONTENT_IGNORE);
2969                                 try
2970                                 {
2971                                         n = m_env->getMap().getNode(p_under);
2972                                 }
2973                                 catch(InvalidPositionException &e)
2974                                 {
2975                                         infostream<<"Server: Not punching: Node not found."
2976                                                         <<" Adding block to emerge queue."
2977                                                         <<std::endl;
2978                                         m_emerge_queue.addBlock(peer_id,
2979                                                         getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
2980                                 }
2981                                 if(n.getContent() != CONTENT_IGNORE)
2982                                         scriptapi_node_on_punch(m_lua, p_under, n, playersao);
2983                                 // Cheat prevention
2984                                 playersao->noCheatDigStart(p_under);
2985                         }
2986                         else if(pointed.type == POINTEDTHING_OBJECT)
2987                         {
2988                                 // Skip if object has been removed
2989                                 if(pointed_object->m_removed)
2990                                         return;
2991
2992                                 actionstream<<player->getName()<<" punches object "
2993                                                 <<pointed.object_id<<": "
2994                                                 <<pointed_object->getDescription()<<std::endl;
2995
2996                                 ItemStack punchitem = playersao->getWieldedItem();
2997                                 ToolCapabilities toolcap =
2998                                                 punchitem.getToolCapabilities(m_itemdef);
2999                                 v3f dir = (pointed_object->getBasePosition() -
3000                                                 (player->getPosition() + player->getEyeOffset())
3001                                                         ).normalize();
3002                                 float time_from_last_punch =
3003                                         playersao->resetTimeFromLastPunch();
3004                                 pointed_object->punch(dir, &toolcap, playersao,
3005                                                 time_from_last_punch);
3006                         }
3007
3008                 } // action == 0
3009
3010                 /*
3011                         1: stop digging
3012                 */
3013                 else if(action == 1)
3014                 {
3015                 } // action == 1
3016
3017                 /*
3018                         2: Digging completed
3019                 */
3020                 else if(action == 2)
3021                 {
3022                         // Only digging of nodes
3023                         if(pointed.type == POINTEDTHING_NODE)
3024                         {
3025                                 MapNode n(CONTENT_IGNORE);
3026                                 try
3027                                 {
3028                                         n = m_env->getMap().getNode(p_under);
3029                                 }
3030                                 catch(InvalidPositionException &e)
3031                                 {
3032                                         infostream<<"Server: Not finishing digging: Node not found."
3033                                                         <<" Adding block to emerge queue."
3034                                                         <<std::endl;
3035                                         m_emerge_queue.addBlock(peer_id,
3036                                                         getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
3037                                 }
3038
3039                                 /* Cheat prevention */
3040                                 bool is_valid_dig = true;
3041                                 if(!isSingleplayer() && !g_settings->getBool("disable_anticheat"))
3042                                 {
3043                                         v3s16 nocheat_p = playersao->getNoCheatDigPos();
3044                                         float nocheat_t = playersao->getNoCheatDigTime();
3045                                         playersao->noCheatDigEnd();
3046                                         // If player didn't start digging this, ignore dig
3047                                         if(nocheat_p != p_under){
3048                                                 infostream<<"Server: NoCheat: "<<player->getName()
3049                                                                 <<" started digging "
3050                                                                 <<PP(nocheat_p)<<" and completed digging "
3051                                                                 <<PP(p_under)<<"; not digging."<<std::endl;
3052                                                 is_valid_dig = false;
3053                                         }
3054                                         // Get player's wielded item
3055                                         ItemStack playeritem;
3056                                         InventoryList *mlist = playersao->getInventory()->getList("main");
3057                                         if(mlist != NULL)
3058                                                 playeritem = mlist->getItem(playersao->getWieldIndex());
3059                                         ToolCapabilities playeritem_toolcap =
3060                                                         playeritem.getToolCapabilities(m_itemdef);
3061                                         // Get diggability and expected digging time
3062                                         DigParams params = getDigParams(m_nodedef->get(n).groups,
3063                                                         &playeritem_toolcap);
3064                                         // If can't dig, try hand
3065                                         if(!params.diggable){
3066                                                 const ItemDefinition &hand = m_itemdef->get("");
3067                                                 const ToolCapabilities *tp = hand.tool_capabilities;
3068                                                 if(tp)
3069                                                         params = getDigParams(m_nodedef->get(n).groups, tp);
3070                                         }
3071                                         // If can't dig, ignore dig
3072                                         if(!params.diggable){
3073                                                 infostream<<"Server: NoCheat: "<<player->getName()
3074                                                                 <<" completed digging "<<PP(p_under)
3075                                                                 <<", which is not diggable with tool. not digging."
3076                                                                 <<std::endl;
3077                                                 is_valid_dig = false;
3078                                         }
3079                                         // If time is considerably too short, ignore dig
3080                                         // Check time only for medium and slow timed digs
3081                                         if(params.diggable && params.time > 0.3 && nocheat_t < 0.5 * params.time){
3082                                                 infostream<<"Server: NoCheat: "<<player->getName()
3083                                                                 <<" completed digging "
3084                                                                 <<PP(p_under)<<" in "<<nocheat_t<<"s; expected "
3085                                                                 <<params.time<<"s; not digging."<<std::endl;
3086                                                 is_valid_dig = false;
3087                                         }
3088                                 }
3089
3090                                 /* Actually dig node */
3091
3092                                 if(is_valid_dig && n.getContent() != CONTENT_IGNORE)
3093                                         scriptapi_node_on_dig(m_lua, p_under, n, playersao);
3094
3095                                 // Send unusual result (that is, node not being removed)
3096                                 if(m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR)
3097                                 {
3098                                         // Re-send block to revert change on client-side
3099                                         RemoteClient *client = getClient(peer_id);
3100                                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
3101                                         client->SetBlockNotSent(blockpos);
3102                                 }
3103                         }
3104                 } // action == 2
3105                 
3106                 /*
3107                         3: place block or right-click object
3108                 */
3109                 else if(action == 3)
3110                 {
3111                         ItemStack item = playersao->getWieldedItem();
3112
3113                         // Reset build time counter
3114                         if(pointed.type == POINTEDTHING_NODE &&
3115                                         item.getDefinition(m_itemdef).type == ITEM_NODE)
3116                                 getClient(peer_id)->m_time_from_building = 0.0;
3117
3118                         if(pointed.type == POINTEDTHING_OBJECT)
3119                         {
3120                                 // Right click object
3121
3122                                 // Skip if object has been removed
3123                                 if(pointed_object->m_removed)
3124                                         return;
3125
3126                                 actionstream<<player->getName()<<" right-clicks object "
3127                                                 <<pointed.object_id<<": "
3128                                                 <<pointed_object->getDescription()<<std::endl;
3129
3130                                 // Do stuff
3131                                 pointed_object->rightClick(playersao);
3132                         }
3133                         else if(scriptapi_item_on_place(m_lua,
3134                                         item, playersao, pointed))
3135                         {
3136                                 // Placement was handled in lua
3137
3138                                 // Apply returned ItemStack
3139                                 playersao->setWieldedItem(item);
3140                         }
3141                         
3142                         // If item has node placement prediction, always send the above
3143                         // node to make sure the client knows what exactly happened
3144                         if(item.getDefinition(m_itemdef).node_placement_prediction != ""){
3145                                 RemoteClient *client = getClient(peer_id);
3146                                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
3147                                 client->SetBlockNotSent(blockpos);
3148                         }
3149                 } // action == 3
3150
3151                 /*
3152                         4: use
3153                 */
3154                 else if(action == 4)
3155                 {
3156                         ItemStack item = playersao->getWieldedItem();
3157
3158                         actionstream<<player->getName()<<" uses "<<item.name
3159                                         <<", pointing at "<<pointed.dump()<<std::endl;
3160
3161                         if(scriptapi_item_on_use(m_lua,
3162                                         item, playersao, pointed))
3163                         {
3164                                 // Apply returned ItemStack
3165                                 playersao->setWieldedItem(item);
3166                         }
3167
3168                 } // action == 4
3169
3170                 /*
3171                         Catch invalid actions
3172                 */
3173                 else
3174                 {
3175                         infostream<<"WARNING: Server: Invalid action "
3176                                         <<action<<std::endl;
3177                 }
3178         }
3179         else if(command == TOSERVER_REMOVED_SOUNDS)
3180         {
3181                 std::string datastring((char*)&data[2], datasize-2);
3182                 std::istringstream is(datastring, std::ios_base::binary);
3183
3184                 int num = readU16(is);
3185                 for(int k=0; k<num; k++){
3186                         s32 id = readS32(is);
3187                         std::map<s32, ServerPlayingSound>::iterator i =
3188                                         m_playing_sounds.find(id);
3189                         if(i == m_playing_sounds.end())
3190                                 continue;
3191                         ServerPlayingSound &psound = i->second;
3192                         psound.clients.erase(peer_id);
3193                         if(psound.clients.size() == 0)
3194                                 m_playing_sounds.erase(i++);
3195                 }
3196         }
3197         else if(command == TOSERVER_NODEMETA_FIELDS)
3198         {
3199                 std::string datastring((char*)&data[2], datasize-2);
3200                 std::istringstream is(datastring, std::ios_base::binary);
3201                 
3202                 v3s16 p = readV3S16(is);
3203                 std::string formname = deSerializeString(is);
3204                 int num = readU16(is);
3205                 std::map<std::string, std::string> fields;
3206                 for(int k=0; k<num; k++){
3207                         std::string fieldname = deSerializeString(is);
3208                         std::string fieldvalue = deSerializeLongString(is);
3209                         fields[fieldname] = fieldvalue;
3210                 }
3211
3212                 // If something goes wrong, this player is to blame
3213                 RollbackScopeActor rollback_scope(m_rollback,
3214                                 std::string("player:")+player->getName());
3215
3216                 // Check the target node for rollback data; leave others unnoticed
3217                 RollbackNode rn_old(&m_env->getMap(), p, this);
3218
3219                 scriptapi_node_on_receive_fields(m_lua, p, formname, fields,
3220                                 playersao);
3221
3222                 // Report rollback data
3223                 RollbackNode rn_new(&m_env->getMap(), p, this);
3224                 if(rollback() && rn_new != rn_old){
3225                         RollbackAction action;
3226                         action.setSetNode(p, rn_old, rn_new);
3227                         rollback()->reportAction(action);
3228                 }
3229         }
3230         else if(command == TOSERVER_INVENTORY_FIELDS)
3231         {
3232                 std::string datastring((char*)&data[2], datasize-2);
3233                 std::istringstream is(datastring, std::ios_base::binary);
3234                 
3235                 std::string formname = deSerializeString(is);
3236                 int num = readU16(is);
3237                 std::map<std::string, std::string> fields;
3238                 for(int k=0; k<num; k++){
3239                         std::string fieldname = deSerializeString(is);
3240                         std::string fieldvalue = deSerializeLongString(is);
3241                         fields[fieldname] = fieldvalue;
3242                 }
3243
3244                 scriptapi_on_player_receive_fields(m_lua, playersao, formname, fields);
3245         }
3246         else
3247         {
3248                 infostream<<"Server::ProcessData(): Ignoring "
3249                                 "unknown command "<<command<<std::endl;
3250         }
3251         
3252         } //try
3253         catch(SendFailedException &e)
3254         {
3255                 errorstream<<"Server::ProcessData(): SendFailedException: "
3256                                 <<"what="<<e.what()
3257                                 <<std::endl;
3258         }
3259 }
3260
3261 void Server::onMapEditEvent(MapEditEvent *event)
3262 {
3263         //infostream<<"Server::onMapEditEvent()"<<std::endl;
3264         if(m_ignore_map_edit_events)
3265                 return;
3266         if(m_ignore_map_edit_events_area.contains(event->getArea()))
3267                 return;
3268         MapEditEvent *e = event->clone();
3269         m_unsent_map_edit_queue.push_back(e);
3270 }
3271
3272 Inventory* Server::getInventory(const InventoryLocation &loc)
3273 {
3274         switch(loc.type){
3275         case InventoryLocation::UNDEFINED:
3276         {}
3277         break;
3278         case InventoryLocation::CURRENT_PLAYER:
3279         {}
3280         break;
3281         case InventoryLocation::PLAYER:
3282         {
3283                 Player *player = m_env->getPlayer(loc.name.c_str());
3284                 if(!player)
3285                         return NULL;
3286                 PlayerSAO *playersao = player->getPlayerSAO();
3287                 if(!playersao)
3288                         return NULL;
3289                 return playersao->getInventory();
3290         }
3291         break;
3292         case InventoryLocation::NODEMETA:
3293         {
3294                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
3295                 if(!meta)
3296                         return NULL;
3297                 return meta->getInventory();
3298         }
3299         break;
3300         case InventoryLocation::DETACHED:
3301         {
3302                 if(m_detached_inventories.count(loc.name) == 0)
3303                         return NULL;
3304                 return m_detached_inventories[loc.name];
3305         }
3306         break;
3307         default:
3308                 assert(0);
3309         }
3310         return NULL;
3311 }
3312 void Server::setInventoryModified(const InventoryLocation &loc)
3313 {
3314         switch(loc.type){
3315         case InventoryLocation::UNDEFINED:
3316         {}
3317         break;
3318         case InventoryLocation::PLAYER:
3319         {
3320                 Player *player = m_env->getPlayer(loc.name.c_str());
3321                 if(!player)
3322                         return;
3323                 PlayerSAO *playersao = player->getPlayerSAO();
3324                 if(!playersao)
3325                         return;
3326                 playersao->m_inventory_not_sent = true;
3327                 playersao->m_wielded_item_not_sent = true;
3328         }
3329         break;
3330         case InventoryLocation::NODEMETA:
3331         {
3332                 v3s16 blockpos = getNodeBlockPos(loc.p);
3333
3334                 MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
3335                 if(block)
3336                         block->raiseModified(MOD_STATE_WRITE_NEEDED);
3337                 
3338                 setBlockNotSent(blockpos);
3339         }
3340         break;
3341         case InventoryLocation::DETACHED:
3342         {
3343                 sendDetachedInventoryToAll(loc.name);
3344         }
3345         break;
3346         default:
3347                 assert(0);
3348         }
3349 }
3350
3351 core::list<PlayerInfo> Server::getPlayerInfo()
3352 {
3353         DSTACK(__FUNCTION_NAME);
3354         JMutexAutoLock envlock(m_env_mutex);
3355         JMutexAutoLock conlock(m_con_mutex);
3356         
3357         core::list<PlayerInfo> list;
3358
3359         core::list<Player*> players = m_env->getPlayers();
3360         
3361         core::list<Player*>::Iterator i;
3362         for(i = players.begin();
3363                         i != players.end(); i++)
3364         {
3365                 PlayerInfo info;
3366
3367                 Player *player = *i;
3368
3369                 try{
3370                         // Copy info from connection to info struct
3371                         info.id = player->peer_id;
3372                         info.address = m_con.GetPeerAddress(player->peer_id);
3373                         info.avg_rtt = m_con.GetPeerAvgRTT(player->peer_id);
3374                 }
3375                 catch(con::PeerNotFoundException &e)
3376                 {
3377                         // Set dummy peer info
3378                         info.id = 0;
3379                         info.address = Address(0,0,0,0,0);
3380                         info.avg_rtt = 0.0;
3381                 }
3382
3383                 snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName());
3384                 info.position = player->getPosition();
3385
3386                 list.push_back(info);
3387         }
3388
3389         return list;
3390 }
3391
3392
3393 void Server::peerAdded(con::Peer *peer)
3394 {
3395         DSTACK(__FUNCTION_NAME);
3396         verbosestream<<"Server::peerAdded(): peer->id="
3397                         <<peer->id<<std::endl;
3398         
3399         PeerChange c;
3400         c.type = PEER_ADDED;
3401         c.peer_id = peer->id;
3402         c.timeout = false;
3403         m_peer_change_queue.push_back(c);
3404 }
3405
3406 void Server::deletingPeer(con::Peer *peer, bool timeout)
3407 {
3408         DSTACK(__FUNCTION_NAME);
3409         verbosestream<<"Server::deletingPeer(): peer->id="
3410                         <<peer->id<<", timeout="<<timeout<<std::endl;
3411         
3412         PeerChange c;
3413         c.type = PEER_REMOVED;
3414         c.peer_id = peer->id;
3415         c.timeout = timeout;
3416         m_peer_change_queue.push_back(c);
3417 }
3418
3419 /*
3420         Static send methods
3421 */
3422
3423 void Server::SendHP(con::Connection &con, u16 peer_id, u8 hp)
3424 {
3425         DSTACK(__FUNCTION_NAME);
3426         std::ostringstream os(std::ios_base::binary);
3427
3428         writeU16(os, TOCLIENT_HP);
3429         writeU8(os, hp);
3430
3431         // Make data buffer
3432         std::string s = os.str();
3433         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3434         // Send as reliable
3435         con.Send(peer_id, 0, data, true);
3436 }
3437
3438 void Server::SendAccessDenied(con::Connection &con, u16 peer_id,
3439                 const std::wstring &reason)
3440 {
3441         DSTACK(__FUNCTION_NAME);
3442         std::ostringstream os(std::ios_base::binary);
3443
3444         writeU16(os, TOCLIENT_ACCESS_DENIED);
3445         os<<serializeWideString(reason);
3446
3447         // Make data buffer
3448         std::string s = os.str();
3449         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3450         // Send as reliable
3451         con.Send(peer_id, 0, data, true);
3452 }
3453
3454 void Server::SendDeathscreen(con::Connection &con, u16 peer_id,
3455                 bool set_camera_point_target, v3f camera_point_target)
3456 {
3457         DSTACK(__FUNCTION_NAME);
3458         std::ostringstream os(std::ios_base::binary);
3459
3460         writeU16(os, TOCLIENT_DEATHSCREEN);
3461         writeU8(os, set_camera_point_target);
3462         writeV3F1000(os, camera_point_target);
3463
3464         // Make data buffer
3465         std::string s = os.str();
3466         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3467         // Send as reliable
3468         con.Send(peer_id, 0, data, true);
3469 }
3470
3471 void Server::SendItemDef(con::Connection &con, u16 peer_id,
3472                 IItemDefManager *itemdef)
3473 {
3474         DSTACK(__FUNCTION_NAME);
3475         std::ostringstream os(std::ios_base::binary);
3476
3477         /*
3478                 u16 command
3479                 u32 length of the next item
3480                 zlib-compressed serialized ItemDefManager
3481         */
3482         writeU16(os, TOCLIENT_ITEMDEF);
3483         std::ostringstream tmp_os(std::ios::binary);
3484         itemdef->serialize(tmp_os);
3485         std::ostringstream tmp_os2(std::ios::binary);
3486         compressZlib(tmp_os.str(), tmp_os2);
3487         os<<serializeLongString(tmp_os2.str());
3488
3489         // Make data buffer
3490         std::string s = os.str();
3491         verbosestream<<"Server: Sending item definitions to id("<<peer_id
3492                         <<"): size="<<s.size()<<std::endl;
3493         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3494         // Send as reliable
3495         con.Send(peer_id, 0, data, true);
3496 }
3497
3498 void Server::SendNodeDef(con::Connection &con, u16 peer_id,
3499                 INodeDefManager *nodedef)
3500 {
3501         DSTACK(__FUNCTION_NAME);
3502         std::ostringstream os(std::ios_base::binary);
3503
3504         /*
3505                 u16 command
3506                 u32 length of the next item
3507                 zlib-compressed serialized NodeDefManager
3508         */
3509         writeU16(os, TOCLIENT_NODEDEF);
3510         std::ostringstream tmp_os(std::ios::binary);
3511         nodedef->serialize(tmp_os);
3512         std::ostringstream tmp_os2(std::ios::binary);
3513         compressZlib(tmp_os.str(), tmp_os2);
3514         os<<serializeLongString(tmp_os2.str());
3515
3516         // Make data buffer
3517         std::string s = os.str();
3518         verbosestream<<"Server: Sending node definitions to id("<<peer_id
3519                         <<"): size="<<s.size()<<std::endl;
3520         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3521         // Send as reliable
3522         con.Send(peer_id, 0, data, true);
3523 }
3524
3525 /*
3526         Non-static send methods
3527 */
3528
3529 void Server::SendInventory(u16 peer_id)
3530 {
3531         DSTACK(__FUNCTION_NAME);
3532         
3533         PlayerSAO *playersao = getPlayerSAO(peer_id);
3534         assert(playersao);
3535
3536         playersao->m_inventory_not_sent = false;
3537
3538         /*
3539                 Serialize it
3540         */
3541
3542         std::ostringstream os;
3543         playersao->getInventory()->serialize(os);
3544
3545         std::string s = os.str();
3546         
3547         SharedBuffer<u8> data(s.size()+2);
3548         writeU16(&data[0], TOCLIENT_INVENTORY);
3549         memcpy(&data[2], s.c_str(), s.size());
3550         
3551         // Send as reliable
3552         m_con.Send(peer_id, 0, data, true);
3553 }
3554
3555 void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
3556 {
3557         DSTACK(__FUNCTION_NAME);
3558         
3559         std::ostringstream os(std::ios_base::binary);
3560         u8 buf[12];
3561         
3562         // Write command
3563         writeU16(buf, TOCLIENT_CHAT_MESSAGE);
3564         os.write((char*)buf, 2);
3565         
3566         // Write length
3567         writeU16(buf, message.size());
3568         os.write((char*)buf, 2);
3569         
3570         // Write string
3571         for(u32 i=0; i<message.size(); i++)
3572         {
3573                 u16 w = message[i];
3574                 writeU16(buf, w);
3575                 os.write((char*)buf, 2);
3576         }
3577         
3578         // Make data buffer
3579         std::string s = os.str();
3580         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3581         // Send as reliable
3582         m_con.Send(peer_id, 0, data, true);
3583 }
3584
3585 void Server::BroadcastChatMessage(const std::wstring &message)
3586 {
3587         for(core::map<u16, RemoteClient*>::Iterator
3588                 i = m_clients.getIterator();
3589                 i.atEnd() == false; i++)
3590         {
3591                 // Get client and check that it is valid
3592                 RemoteClient *client = i.getNode()->getValue();
3593                 assert(client->peer_id == i.getNode()->getKey());
3594                 if(client->serialization_version == SER_FMT_VER_INVALID)
3595                         continue;
3596
3597                 SendChatMessage(client->peer_id, message);
3598         }
3599 }
3600
3601 void Server::SendPlayerHP(u16 peer_id)
3602 {
3603         DSTACK(__FUNCTION_NAME);
3604         PlayerSAO *playersao = getPlayerSAO(peer_id);
3605         assert(playersao);
3606         playersao->m_hp_not_sent = false;
3607         SendHP(m_con, peer_id, playersao->getHP());
3608 }
3609
3610 void Server::SendMovePlayer(u16 peer_id)
3611 {
3612         DSTACK(__FUNCTION_NAME);
3613         Player *player = m_env->getPlayer(peer_id);
3614         assert(player);
3615
3616         std::ostringstream os(std::ios_base::binary);
3617         writeU16(os, TOCLIENT_MOVE_PLAYER);
3618         writeV3F1000(os, player->getPosition());
3619         writeF1000(os, player->getPitch());
3620         writeF1000(os, player->getYaw());
3621         
3622         {
3623                 v3f pos = player->getPosition();
3624                 f32 pitch = player->getPitch();
3625                 f32 yaw = player->getYaw();
3626                 verbosestream<<"Server: Sending TOCLIENT_MOVE_PLAYER"
3627                                 <<" pos=("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
3628                                 <<" pitch="<<pitch
3629                                 <<" yaw="<<yaw
3630                                 <<std::endl;
3631         }
3632
3633         // Make data buffer
3634         std::string s = os.str();
3635         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3636         // Send as reliable
3637         m_con.Send(peer_id, 0, data, true);
3638 }
3639
3640 void Server::SendPlayerPrivileges(u16 peer_id)
3641 {
3642         Player *player = m_env->getPlayer(peer_id);
3643         assert(player);
3644         if(player->peer_id == PEER_ID_INEXISTENT)
3645                 return;
3646
3647         std::set<std::string> privs;
3648         scriptapi_get_auth(m_lua, player->getName(), NULL, &privs);
3649         
3650         std::ostringstream os(std::ios_base::binary);
3651         writeU16(os, TOCLIENT_PRIVILEGES);
3652         writeU16(os, privs.size());
3653         for(std::set<std::string>::const_iterator i = privs.begin();
3654                         i != privs.end(); i++){
3655                 os<<serializeString(*i);
3656         }
3657
3658         // Make data buffer
3659         std::string s = os.str();
3660         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3661         // Send as reliable
3662         m_con.Send(peer_id, 0, data, true);
3663 }
3664
3665 void Server::SendPlayerInventoryFormspec(u16 peer_id)
3666 {
3667         Player *player = m_env->getPlayer(peer_id);
3668         assert(player);
3669         if(player->peer_id == PEER_ID_INEXISTENT)
3670                 return;
3671
3672         std::ostringstream os(std::ios_base::binary);
3673         writeU16(os, TOCLIENT_INVENTORY_FORMSPEC);
3674         os<<serializeLongString(player->inventory_formspec);
3675
3676         // Make data buffer
3677         std::string s = os.str();
3678         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3679         // Send as reliable
3680         m_con.Send(peer_id, 0, data, true);
3681 }
3682
3683 s32 Server::playSound(const SimpleSoundSpec &spec,
3684                 const ServerSoundParams &params)
3685 {
3686         // Find out initial position of sound
3687         bool pos_exists = false;
3688         v3f pos = params.getPos(m_env, &pos_exists);
3689         // If position is not found while it should be, cancel sound
3690         if(pos_exists != (params.type != ServerSoundParams::SSP_LOCAL))
3691                 return -1;
3692         // Filter destination clients
3693         std::set<RemoteClient*> dst_clients;
3694         if(params.to_player != "")
3695         {
3696                 Player *player = m_env->getPlayer(params.to_player.c_str());
3697                 if(!player){
3698                         infostream<<"Server::playSound: Player \""<<params.to_player
3699                                         <<"\" not found"<<std::endl;
3700                         return -1;
3701                 }
3702                 if(player->peer_id == PEER_ID_INEXISTENT){
3703                         infostream<<"Server::playSound: Player \""<<params.to_player
3704                                         <<"\" not connected"<<std::endl;
3705                         return -1;
3706                 }
3707                 RemoteClient *client = getClient(player->peer_id);
3708                 dst_clients.insert(client);
3709         }
3710         else
3711         {
3712                 for(core::map<u16, RemoteClient*>::Iterator
3713                                 i = m_clients.getIterator(); i.atEnd() == false; i++)
3714                 {
3715                         RemoteClient *client = i.getNode()->getValue();
3716                         Player *player = m_env->getPlayer(client->peer_id);
3717                         if(!player)
3718                                 continue;
3719                         if(pos_exists){
3720                                 if(player->getPosition().getDistanceFrom(pos) >
3721                                                 params.max_hear_distance)
3722                                         continue;
3723                         }
3724                         dst_clients.insert(client);
3725                 }
3726         }
3727         if(dst_clients.size() == 0)
3728                 return -1;
3729         // Create the sound
3730         s32 id = m_next_sound_id++;
3731         // The sound will exist as a reference in m_playing_sounds
3732         m_playing_sounds[id] = ServerPlayingSound();
3733         ServerPlayingSound &psound = m_playing_sounds[id];
3734         psound.params = params;
3735         for(std::set<RemoteClient*>::iterator i = dst_clients.begin();
3736                         i != dst_clients.end(); i++)
3737                 psound.clients.insert((*i)->peer_id);
3738         // Create packet
3739         std::ostringstream os(std::ios_base::binary);
3740         writeU16(os, TOCLIENT_PLAY_SOUND);
3741         writeS32(os, id);
3742         os<<serializeString(spec.name);
3743         writeF1000(os, spec.gain * params.gain);
3744         writeU8(os, params.type);
3745         writeV3F1000(os, pos);
3746         writeU16(os, params.object);
3747         writeU8(os, params.loop);
3748         // Make data buffer
3749         std::string s = os.str();
3750         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3751         // Send
3752         for(std::set<RemoteClient*>::iterator i = dst_clients.begin();
3753                         i != dst_clients.end(); i++){
3754                 // Send as reliable
3755                 m_con.Send((*i)->peer_id, 0, data, true);
3756         }
3757         return id;
3758 }
3759 void Server::stopSound(s32 handle)
3760 {
3761         // Get sound reference
3762         std::map<s32, ServerPlayingSound>::iterator i =
3763                         m_playing_sounds.find(handle);
3764         if(i == m_playing_sounds.end())
3765                 return;
3766         ServerPlayingSound &psound = i->second;
3767         // Create packet
3768         std::ostringstream os(std::ios_base::binary);
3769         writeU16(os, TOCLIENT_STOP_SOUND);
3770         writeS32(os, handle);
3771         // Make data buffer
3772         std::string s = os.str();
3773         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3774         // Send
3775         for(std::set<u16>::iterator i = psound.clients.begin();
3776                         i != psound.clients.end(); i++){
3777                 // Send as reliable
3778                 m_con.Send(*i, 0, data, true);
3779         }
3780         // Remove sound reference
3781         m_playing_sounds.erase(i);
3782 }
3783
3784 void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
3785         core::list<u16> *far_players, float far_d_nodes)
3786 {
3787         float maxd = far_d_nodes*BS;
3788         v3f p_f = intToFloat(p, BS);
3789
3790         // Create packet
3791         u32 replysize = 8;
3792         SharedBuffer<u8> reply(replysize);
3793         writeU16(&reply[0], TOCLIENT_REMOVENODE);
3794         writeS16(&reply[2], p.X);
3795         writeS16(&reply[4], p.Y);
3796         writeS16(&reply[6], p.Z);
3797
3798         for(core::map<u16, RemoteClient*>::Iterator
3799                 i = m_clients.getIterator();
3800                 i.atEnd() == false; i++)
3801         {
3802                 // Get client and check that it is valid
3803                 RemoteClient *client = i.getNode()->getValue();
3804                 assert(client->peer_id == i.getNode()->getKey());
3805                 if(client->serialization_version == SER_FMT_VER_INVALID)
3806                         continue;
3807
3808                 // Don't send if it's the same one
3809                 if(client->peer_id == ignore_id)
3810                         continue;
3811                 
3812                 if(far_players)
3813                 {
3814                         // Get player
3815                         Player *player = m_env->getPlayer(client->peer_id);
3816                         if(player)
3817                         {
3818                                 // If player is far away, only set modified blocks not sent
3819                                 v3f player_pos = player->getPosition();
3820                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3821                                 {
3822                                         far_players->push_back(client->peer_id);
3823                                         continue;
3824                                 }
3825                         }
3826                 }
3827
3828                 // Send as reliable
3829                 m_con.Send(client->peer_id, 0, reply, true);
3830         }
3831 }
3832
3833 void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
3834                 core::list<u16> *far_players, float far_d_nodes)
3835 {
3836         float maxd = far_d_nodes*BS;
3837         v3f p_f = intToFloat(p, BS);
3838
3839         for(core::map<u16, RemoteClient*>::Iterator
3840                 i = m_clients.getIterator();
3841                 i.atEnd() == false; i++)
3842         {
3843                 // Get client and check that it is valid
3844                 RemoteClient *client = i.getNode()->getValue();
3845                 assert(client->peer_id == i.getNode()->getKey());
3846                 if(client->serialization_version == SER_FMT_VER_INVALID)
3847                         continue;
3848
3849                 // Don't send if it's the same one
3850                 if(client->peer_id == ignore_id)
3851                         continue;
3852
3853                 if(far_players)
3854                 {
3855                         // Get player
3856                         Player *player = m_env->getPlayer(client->peer_id);
3857                         if(player)
3858                         {
3859                                 // If player is far away, only set modified blocks not sent
3860                                 v3f player_pos = player->getPosition();
3861                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3862                                 {
3863                                         far_players->push_back(client->peer_id);
3864                                         continue;
3865                                 }
3866                         }
3867                 }
3868
3869                 // Create packet
3870                 u32 replysize = 8 + MapNode::serializedLength(client->serialization_version);
3871                 SharedBuffer<u8> reply(replysize);
3872                 writeU16(&reply[0], TOCLIENT_ADDNODE);
3873                 writeS16(&reply[2], p.X);
3874                 writeS16(&reply[4], p.Y);
3875                 writeS16(&reply[6], p.Z);
3876                 n.serialize(&reply[8], client->serialization_version);
3877
3878                 // Send as reliable
3879                 m_con.Send(client->peer_id, 0, reply, true);
3880         }
3881 }
3882
3883 void Server::setBlockNotSent(v3s16 p)
3884 {
3885         for(core::map<u16, RemoteClient*>::Iterator
3886                 i = m_clients.getIterator();
3887                 i.atEnd()==false; i++)
3888         {
3889                 RemoteClient *client = i.getNode()->getValue();
3890                 client->SetBlockNotSent(p);
3891         }
3892 }
3893
3894 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
3895 {
3896         DSTACK(__FUNCTION_NAME);
3897
3898         v3s16 p = block->getPos();
3899         
3900 #if 0
3901         // Analyze it a bit
3902         bool completely_air = true;
3903         for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
3904         for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
3905         for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
3906         {
3907                 if(block->getNodeNoEx(v3s16(x0,y0,z0)).d != CONTENT_AIR)
3908                 {
3909                         completely_air = false;
3910                         x0 = y0 = z0 = MAP_BLOCKSIZE; // Break out
3911                 }
3912         }
3913
3914         // Print result
3915         infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<"): ";
3916         if(completely_air)
3917                 infostream<<"[completely air] ";
3918         infostream<<std::endl;
3919 #endif
3920
3921         /*
3922                 Create a packet with the block in the right format
3923         */
3924         
3925         std::ostringstream os(std::ios_base::binary);
3926         block->serialize(os, ver, false);
3927         std::string s = os.str();
3928         SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
3929
3930         u32 replysize = 8 + blockdata.getSize();
3931         SharedBuffer<u8> reply(replysize);
3932         writeU16(&reply[0], TOCLIENT_BLOCKDATA);
3933         writeS16(&reply[2], p.X);
3934         writeS16(&reply[4], p.Y);
3935         writeS16(&reply[6], p.Z);
3936         memcpy(&reply[8], *blockdata, blockdata.getSize());
3937
3938         /*infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<")"
3939                         <<":  \tpacket size: "<<replysize<<std::endl;*/
3940         
3941         /*
3942                 Send packet
3943         */
3944         m_con.Send(peer_id, 1, reply, true);
3945 }
3946
3947 void Server::SendBlocks(float dtime)
3948 {
3949         DSTACK(__FUNCTION_NAME);
3950
3951         JMutexAutoLock envlock(m_env_mutex);
3952         JMutexAutoLock conlock(m_con_mutex);
3953
3954         ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
3955
3956         core::array<PrioritySortedBlockTransfer> queue;
3957
3958         s32 total_sending = 0;
3959         
3960         {
3961                 ScopeProfiler sp(g_profiler, "Server: selecting blocks for sending");
3962
3963                 for(core::map<u16, RemoteClient*>::Iterator
3964                         i = m_clients.getIterator();
3965                         i.atEnd() == false; i++)
3966                 {
3967                         RemoteClient *client = i.getNode()->getValue();
3968                         assert(client->peer_id == i.getNode()->getKey());
3969
3970                         // If definitions and textures have not been sent, don't
3971                         // send MapBlocks either
3972                         if(!client->definitions_sent)
3973                                 continue;
3974
3975                         total_sending += client->SendingCount();
3976                         
3977                         if(client->serialization_version == SER_FMT_VER_INVALID)
3978                                 continue;
3979                         
3980                         client->GetNextBlocks(this, dtime, queue);
3981                 }
3982         }
3983
3984         // Sort.
3985         // Lowest priority number comes first.
3986         // Lowest is most important.
3987         queue.sort();
3988
3989         for(u32 i=0; i<queue.size(); i++)
3990         {
3991                 //TODO: Calculate limit dynamically
3992                 if(total_sending >= g_settings->getS32
3993                                 ("max_simultaneous_block_sends_server_total"))
3994                         break;
3995                 
3996                 PrioritySortedBlockTransfer q = queue[i];
3997
3998                 MapBlock *block = NULL;
3999                 try
4000                 {
4001                         block = m_env->getMap().getBlockNoCreate(q.pos);
4002                 }
4003                 catch(InvalidPositionException &e)
4004                 {
4005                         continue;
4006                 }
4007
4008                 RemoteClient *client = getClient(q.peer_id);
4009
4010                 SendBlockNoLock(q.peer_id, block, client->serialization_version);
4011
4012                 client->SentBlock(q.pos);
4013
4014                 total_sending++;
4015         }
4016 }
4017
4018 void Server::fillMediaCache()
4019 {
4020         DSTACK(__FUNCTION_NAME);
4021
4022         infostream<<"Server: Calculating media file checksums"<<std::endl;
4023         
4024         // Collect all media file paths
4025         std::list<std::string> paths;
4026         for(core::list<ModSpec>::Iterator i = m_mods.begin();
4027                         i != m_mods.end(); i++){
4028                 const ModSpec &mod = *i;
4029                 paths.push_back(mod.path + DIR_DELIM + "textures");
4030                 paths.push_back(mod.path + DIR_DELIM + "sounds");
4031                 paths.push_back(mod.path + DIR_DELIM + "media");
4032                 paths.push_back(mod.path + DIR_DELIM + "models");
4033         }
4034         std::string path_all = "textures";
4035         paths.push_back(path_all + DIR_DELIM + "all");
4036         
4037         // Collect media file information from paths into cache
4038         for(std::list<std::string>::iterator i = paths.begin();
4039                         i != paths.end(); i++)
4040         {
4041                 std::string mediapath = *i;
4042                 std::vector<fs::DirListNode> dirlist = fs::GetDirListing(mediapath);
4043                 for(u32 j=0; j<dirlist.size(); j++){
4044                         if(dirlist[j].dir) // Ignode dirs
4045                                 continue;
4046                         std::string filename = dirlist[j].name;
4047                         // If name contains illegal characters, ignore the file
4048                         if(!string_allowed(filename, TEXTURENAME_ALLOWED_CHARS)){
4049                                 infostream<<"Server: ignoring illegal file name: \""
4050                                                 <<filename<<"\""<<std::endl;
4051                                 continue;
4052                         }
4053                         // If name is not in a supported format, ignore it
4054                         const char *supported_ext[] = {
4055                                 ".png", ".jpg", ".bmp", ".tga",
4056                                 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
4057                                 ".ogg",
4058                                 ".x", ".b3d", ".md2", ".obj",
4059                                 NULL
4060                         };
4061                         if(removeStringEnd(filename, supported_ext) == ""){
4062                                 infostream<<"Server: ignoring unsupported file extension: \""
4063                                                 <<filename<<"\""<<std::endl;
4064                                 continue;
4065                         }
4066                         // Ok, attempt to load the file and add to cache
4067                         std::string filepath = mediapath + DIR_DELIM + filename;
4068                         // Read data
4069                         std::ifstream fis(filepath.c_str(), std::ios_base::binary);
4070                         if(fis.good() == false){
4071                                 errorstream<<"Server::fillMediaCache(): Could not open \""
4072                                                 <<filename<<"\" for reading"<<std::endl;
4073                                 continue;
4074                         }
4075                         std::ostringstream tmp_os(std::ios_base::binary);
4076                         bool bad = false;
4077                         for(;;){
4078                                 char buf[1024];
4079                                 fis.read(buf, 1024);
4080                                 std::streamsize len = fis.gcount();
4081                                 tmp_os.write(buf, len);
4082                                 if(fis.eof())
4083                                         break;
4084                                 if(!fis.good()){
4085                                         bad = true;
4086                                         break;
4087                                 }
4088                         }
4089                         if(bad){
4090                                 errorstream<<"Server::fillMediaCache(): Failed to read \""
4091                                                 <<filename<<"\""<<std::endl;
4092                                 continue;
4093                         }
4094                         if(tmp_os.str().length() == 0){
4095                                 errorstream<<"Server::fillMediaCache(): Empty file \""
4096                                                 <<filepath<<"\""<<std::endl;
4097                                 continue;
4098                         }
4099
4100                         SHA1 sha1;
4101                         sha1.addBytes(tmp_os.str().c_str(), tmp_os.str().length());
4102
4103                         unsigned char *digest = sha1.getDigest();
4104                         std::string sha1_base64 = base64_encode(digest, 20);
4105                         std::string sha1_hex = hex_encode((char*)digest, 20);
4106                         free(digest);
4107
4108                         // Put in list
4109                         this->m_media[filename] = MediaInfo(filepath, sha1_base64);
4110                         verbosestream<<"Server: "<<sha1_hex<<" is "<<filename<<std::endl;
4111                 }
4112         }
4113 }
4114
4115 struct SendableMediaAnnouncement
4116 {
4117         std::string name;
4118         std::string sha1_digest;
4119
4120         SendableMediaAnnouncement(const std::string name_="",
4121                         const std::string sha1_digest_=""):
4122                 name(name_),
4123                 sha1_digest(sha1_digest_)
4124         {}
4125 };
4126
4127 void Server::sendMediaAnnouncement(u16 peer_id)
4128 {
4129         DSTACK(__FUNCTION_NAME);
4130
4131         verbosestream<<"Server: Announcing files to id("<<peer_id<<")"
4132                         <<std::endl;
4133
4134         core::list<SendableMediaAnnouncement> file_announcements;
4135
4136         for(std::map<std::string, MediaInfo>::iterator i = m_media.begin();
4137                         i != m_media.end(); i++){
4138                 // Put in list
4139                 file_announcements.push_back(
4140                                 SendableMediaAnnouncement(i->first, i->second.sha1_digest));
4141         }
4142
4143         // Make packet
4144         std::ostringstream os(std::ios_base::binary);
4145
4146         /*
4147                 u16 command
4148                 u32 number of files
4149                 for each texture {
4150                         u16 length of name
4151                         string name
4152                         u16 length of sha1_digest
4153                         string sha1_digest
4154                 }
4155         */
4156         
4157         writeU16(os, TOCLIENT_ANNOUNCE_MEDIA);
4158         writeU16(os, file_announcements.size());
4159
4160         for(core::list<SendableMediaAnnouncement>::Iterator
4161                         j = file_announcements.begin();
4162                         j != file_announcements.end(); j++){
4163                 os<<serializeString(j->name);
4164                 os<<serializeString(j->sha1_digest);
4165         }
4166
4167         // Make data buffer
4168         std::string s = os.str();
4169         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
4170
4171         // Send as reliable
4172         m_con.Send(peer_id, 0, data, true);
4173
4174 }
4175
4176 struct SendableMedia
4177 {
4178         std::string name;
4179         std::string path;
4180         std::string data;
4181
4182         SendableMedia(const std::string &name_="", const std::string path_="",
4183                         const std::string &data_=""):
4184                 name(name_),
4185                 path(path_),
4186                 data(data_)
4187         {}
4188 };
4189
4190 void Server::sendRequestedMedia(u16 peer_id,
4191                 const core::list<MediaRequest> &tosend)
4192 {
4193         DSTACK(__FUNCTION_NAME);
4194
4195         verbosestream<<"Server::sendRequestedMedia(): "
4196                         <<"Sending files to client"<<std::endl;
4197
4198         /* Read files */
4199
4200         // Put 5kB in one bunch (this is not accurate)
4201         u32 bytes_per_bunch = 5000;
4202
4203         core::array< core::list<SendableMedia> > file_bunches;
4204         file_bunches.push_back(core::list<SendableMedia>());
4205
4206         u32 file_size_bunch_total = 0;
4207
4208         for(core::list<MediaRequest>::ConstIterator i = tosend.begin();
4209                         i != tosend.end(); i++)
4210         {
4211                 if(m_media.find(i->name) == m_media.end()){
4212                         errorstream<<"Server::sendRequestedMedia(): Client asked for "
4213                                         <<"unknown file \""<<(i->name)<<"\""<<std::endl;
4214                         continue;
4215                 }
4216
4217                 //TODO get path + name
4218                 std::string tpath = m_media[(*i).name].path;
4219
4220                 // Read data
4221                 std::ifstream fis(tpath.c_str(), std::ios_base::binary);
4222                 if(fis.good() == false){
4223                         errorstream<<"Server::sendRequestedMedia(): Could not open \""
4224                                         <<tpath<<"\" for reading"<<std::endl;
4225                         continue;
4226                 }
4227                 std::ostringstream tmp_os(std::ios_base::binary);
4228                 bool bad = false;
4229                 for(;;){
4230                         char buf[1024];
4231                         fis.read(buf, 1024);
4232                         std::streamsize len = fis.gcount();
4233                         tmp_os.write(buf, len);
4234                         file_size_bunch_total += len;
4235                         if(fis.eof())
4236                                 break;
4237                         if(!fis.good()){
4238                                 bad = true;
4239                                 break;
4240                         }
4241                 }
4242                 if(bad){
4243                         errorstream<<"Server::sendRequestedMedia(): Failed to read \""
4244                                         <<(*i).name<<"\""<<std::endl;
4245                         continue;
4246                 }
4247                 /*infostream<<"Server::sendRequestedMedia(): Loaded \""
4248                                 <<tname<<"\""<<std::endl;*/
4249                 // Put in list
4250                 file_bunches[file_bunches.size()-1].push_back(
4251                                 SendableMedia((*i).name, tpath, tmp_os.str()));
4252
4253                 // Start next bunch if got enough data
4254                 if(file_size_bunch_total >= bytes_per_bunch){
4255                         file_bunches.push_back(core::list<SendableMedia>());
4256                         file_size_bunch_total = 0;
4257                 }
4258
4259         }
4260
4261         /* Create and send packets */
4262
4263         u32 num_bunches = file_bunches.size();
4264         for(u32 i=0; i<num_bunches; i++)
4265         {
4266                 std::ostringstream os(std::ios_base::binary);
4267
4268                 /*
4269                         u16 command
4270                         u16 total number of texture bunches
4271                         u16 index of this bunch
4272                         u32 number of files in this bunch
4273                         for each file {
4274                                 u16 length of name
4275                                 string name
4276                                 u32 length of data
4277                                 data
4278                         }
4279                 */
4280
4281                 writeU16(os, TOCLIENT_MEDIA);
4282                 writeU16(os, num_bunches);
4283                 writeU16(os, i);
4284                 writeU32(os, file_bunches[i].size());
4285
4286                 for(core::list<SendableMedia>::Iterator
4287                                 j = file_bunches[i].begin();
4288                                 j != file_bunches[i].end(); j++){
4289                         os<<serializeString(j->name);
4290                         os<<serializeLongString(j->data);
4291                 }
4292
4293                 // Make data buffer
4294                 std::string s = os.str();
4295                 verbosestream<<"Server::sendRequestedMedia(): bunch "
4296                                 <<i<<"/"<<num_bunches
4297                                 <<" files="<<file_bunches[i].size()
4298                                 <<" size=" <<s.size()<<std::endl;
4299                 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
4300                 // Send as reliable
4301                 m_con.Send(peer_id, 0, data, true);
4302         }
4303 }
4304
4305 void Server::sendDetachedInventory(const std::string &name, u16 peer_id)
4306 {
4307         if(m_detached_inventories.count(name) == 0){
4308                 errorstream<<__FUNCTION_NAME<<": \""<<name<<"\" not found"<<std::endl;
4309                 return;
4310         }
4311         Inventory *inv = m_detached_inventories[name];
4312
4313         std::ostringstream os(std::ios_base::binary);
4314         writeU16(os, TOCLIENT_DETACHED_INVENTORY);
4315         os<<serializeString(name);
4316         inv->serialize(os);
4317
4318         // Make data buffer
4319         std::string s = os.str();
4320         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
4321         // Send as reliable
4322         m_con.Send(peer_id, 0, data, true);
4323 }
4324
4325 void Server::sendDetachedInventoryToAll(const std::string &name)
4326 {
4327         DSTACK(__FUNCTION_NAME);
4328
4329         for(core::map<u16, RemoteClient*>::Iterator
4330                         i = m_clients.getIterator();
4331                         i.atEnd() == false; i++){
4332                 RemoteClient *client = i.getNode()->getValue();
4333                 sendDetachedInventory(name, client->peer_id);
4334         }
4335 }
4336
4337 void Server::sendDetachedInventories(u16 peer_id)
4338 {
4339         DSTACK(__FUNCTION_NAME);
4340
4341         for(std::map<std::string, Inventory*>::iterator
4342                         i = m_detached_inventories.begin();
4343                         i != m_detached_inventories.end(); i++){
4344                 const std::string &name = i->first;
4345                 //Inventory *inv = i->second;
4346                 sendDetachedInventory(name, peer_id);
4347         }
4348 }
4349
4350 /*
4351         Something random
4352 */
4353
4354 void Server::DiePlayer(u16 peer_id)
4355 {
4356         DSTACK(__FUNCTION_NAME);
4357         
4358         PlayerSAO *playersao = getPlayerSAO(peer_id);
4359         assert(playersao);
4360
4361         infostream<<"Server::DiePlayer(): Player "
4362                         <<playersao->getPlayer()->getName()
4363                         <<" dies"<<std::endl;
4364
4365         playersao->setHP(0);
4366
4367         // Trigger scripted stuff
4368         scriptapi_on_dieplayer(m_lua, playersao);
4369
4370         SendPlayerHP(peer_id);
4371         SendDeathscreen(m_con, peer_id, false, v3f(0,0,0));
4372 }
4373
4374 void Server::RespawnPlayer(u16 peer_id)
4375 {
4376         DSTACK(__FUNCTION_NAME);
4377
4378         PlayerSAO *playersao = getPlayerSAO(peer_id);
4379         assert(playersao);
4380
4381         infostream<<"Server::RespawnPlayer(): Player "
4382                         <<playersao->getPlayer()->getName()
4383                         <<" respawns"<<std::endl;
4384
4385         playersao->setHP(PLAYER_MAX_HP);
4386
4387         bool repositioned = scriptapi_on_respawnplayer(m_lua, playersao);
4388         if(!repositioned){
4389                 v3f pos = findSpawnPos(m_env->getServerMap());
4390                 playersao->setPos(pos);
4391         }
4392 }
4393
4394 void Server::UpdateCrafting(u16 peer_id)
4395 {
4396         DSTACK(__FUNCTION_NAME);
4397         
4398         Player* player = m_env->getPlayer(peer_id);
4399         assert(player);
4400
4401         // Get a preview for crafting
4402         ItemStack preview;
4403         getCraftingResult(&player->inventory, preview, false, this);
4404
4405         // Put the new preview in
4406         InventoryList *plist = player->inventory.getList("craftpreview");
4407         assert(plist);
4408         assert(plist->getSize() >= 1);
4409         plist->changeItem(0, preview);
4410 }
4411
4412 RemoteClient* Server::getClient(u16 peer_id)
4413 {
4414         DSTACK(__FUNCTION_NAME);
4415         //JMutexAutoLock lock(m_con_mutex);
4416         core::map<u16, RemoteClient*>::Node *n;
4417         n = m_clients.find(peer_id);
4418         // A client should exist for all peers
4419         assert(n != NULL);
4420         return n->getValue();
4421 }
4422
4423 std::wstring Server::getStatusString()
4424 {
4425         std::wostringstream os(std::ios_base::binary);
4426         os<<L"# Server: ";
4427         // Version
4428         os<<L"version="<<narrow_to_wide(VERSION_STRING);
4429         // Uptime
4430         os<<L", uptime="<<m_uptime.get();
4431         // Information about clients
4432         core::map<u16, RemoteClient*>::Iterator i;
4433         bool first;
4434         os<<L", clients={";
4435         for(i = m_clients.getIterator(), first = true;
4436                 i.atEnd() == false; i++)
4437         {
4438                 // Get client and check that it is valid
4439                 RemoteClient *client = i.getNode()->getValue();
4440                 assert(client->peer_id == i.getNode()->getKey());
4441                 if(client->serialization_version == SER_FMT_VER_INVALID)
4442                         continue;
4443                 // Get player
4444                 Player *player = m_env->getPlayer(client->peer_id);
4445                 // Get name of player
4446                 std::wstring name = L"unknown";
4447                 if(player != NULL)
4448                         name = narrow_to_wide(player->getName());
4449                 // Add name to information string
4450                 if(!first)
4451                         os<<L",";
4452                 else
4453                         first = false;
4454                 os<<name;
4455         }
4456         os<<L"}";
4457         if(((ServerMap*)(&m_env->getMap()))->isSavingEnabled() == false)
4458                 os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
4459         if(g_settings->get("motd") != "")
4460                 os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
4461         return os.str();
4462 }
4463
4464 std::set<std::string> Server::getPlayerEffectivePrivs(const std::string &name)
4465 {
4466         std::set<std::string> privs;
4467         scriptapi_get_auth(m_lua, name, NULL, &privs);
4468         return privs;
4469 }
4470
4471 bool Server::checkPriv(const std::string &name, const std::string &priv)
4472 {
4473         std::set<std::string> privs = getPlayerEffectivePrivs(name);
4474         return (privs.count(priv) != 0);
4475 }
4476
4477 void Server::reportPrivsModified(const std::string &name)
4478 {
4479         if(name == ""){
4480                 for(core::map<u16, RemoteClient*>::Iterator
4481                                 i = m_clients.getIterator();
4482                                 i.atEnd() == false; i++){
4483                         RemoteClient *client = i.getNode()->getValue();
4484                         Player *player = m_env->getPlayer(client->peer_id);
4485                         reportPrivsModified(player->getName());
4486                 }
4487         } else {
4488                 Player *player = m_env->getPlayer(name.c_str());
4489                 if(!player)
4490                         return;
4491                 SendPlayerPrivileges(player->peer_id);
4492                 PlayerSAO *sao = player->getPlayerSAO();
4493                 if(!sao)
4494                         return;
4495                 sao->updatePrivileges(
4496                                 getPlayerEffectivePrivs(name),
4497                                 isSingleplayer());
4498         }
4499 }
4500
4501 void Server::reportInventoryFormspecModified(const std::string &name)
4502 {
4503         Player *player = m_env->getPlayer(name.c_str());
4504         if(!player)
4505                 return;
4506         SendPlayerInventoryFormspec(player->peer_id);
4507 }
4508
4509 // Saves g_settings to configpath given at initialization
4510 void Server::saveConfig()
4511 {
4512         if(m_path_config != "")
4513                 g_settings->updateConfigFile(m_path_config.c_str());
4514 }
4515
4516 void Server::notifyPlayer(const char *name, const std::wstring msg)
4517 {
4518         Player *player = m_env->getPlayer(name);
4519         if(!player)
4520                 return;
4521         SendChatMessage(player->peer_id, std::wstring(L"Server: -!- ")+msg);
4522 }
4523
4524 void Server::notifyPlayers(const std::wstring msg)
4525 {
4526         BroadcastChatMessage(msg);
4527 }
4528
4529 void Server::queueBlockEmerge(v3s16 blockpos, bool allow_generate)
4530 {
4531         u8 flags = 0;
4532         if(!allow_generate)
4533                 flags |= BLOCK_EMERGE_FLAG_FROMDISK;
4534         m_emerge_queue.addBlock(PEER_ID_INEXISTENT, blockpos, flags);
4535 }
4536
4537 Inventory* Server::createDetachedInventory(const std::string &name)
4538 {
4539         if(m_detached_inventories.count(name) > 0){
4540                 infostream<<"Server clearing detached inventory \""<<name<<"\""<<std::endl;
4541                 delete m_detached_inventories[name];
4542         } else {
4543                 infostream<<"Server creating detached inventory \""<<name<<"\""<<std::endl;
4544         }
4545         Inventory *inv = new Inventory(m_itemdef);
4546         assert(inv);
4547         m_detached_inventories[name] = inv;
4548         sendDetachedInventoryToAll(name);
4549         return inv;
4550 }
4551
4552 class BoolScopeSet
4553 {
4554 public:
4555         BoolScopeSet(bool *dst, bool val):
4556                 m_dst(dst)
4557         {
4558                 m_orig_state = *m_dst;
4559                 *m_dst = val;
4560         }
4561         ~BoolScopeSet()
4562         {
4563                 *m_dst = m_orig_state;
4564         }
4565 private:
4566         bool *m_dst;
4567         bool m_orig_state;
4568 };
4569
4570 // actions: time-reversed list
4571 // Return value: success/failure
4572 bool Server::rollbackRevertActions(const std::list<RollbackAction> &actions,
4573                 std::list<std::string> *log)
4574 {
4575         infostream<<"Server::rollbackRevertActions(len="<<actions.size()<<")"<<std::endl;
4576         ServerMap *map = (ServerMap*)(&m_env->getMap());
4577         // Disable rollback report sink while reverting
4578         BoolScopeSet rollback_scope_disable(&m_rollback_sink_enabled, false);
4579         
4580         // Fail if no actions to handle
4581         if(actions.empty()){
4582                 log->push_back("Nothing to do.");
4583                 return false;
4584         }
4585
4586         int num_tried = 0;
4587         int num_failed = 0;
4588         
4589         for(std::list<RollbackAction>::const_iterator
4590                         i = actions.begin();
4591                         i != actions.end(); i++)
4592         {
4593                 const RollbackAction &action = *i;
4594                 num_tried++;
4595                 bool success = action.applyRevert(map, this, this);
4596                 if(!success){
4597                         num_failed++;
4598                         std::ostringstream os;
4599                         os<<"Revert of step ("<<num_tried<<") "<<action.toString()<<" failed";
4600                         infostream<<"Map::rollbackRevertActions(): "<<os.str()<<std::endl;
4601                         if(log)
4602                                 log->push_back(os.str());
4603                 }else{
4604                         std::ostringstream os;
4605                         os<<"Succesfully reverted step ("<<num_tried<<") "<<action.toString();
4606                         infostream<<"Map::rollbackRevertActions(): "<<os.str()<<std::endl;
4607                         if(log)
4608                                 log->push_back(os.str());
4609                 }
4610         }
4611         
4612         infostream<<"Map::rollbackRevertActions(): "<<num_failed<<"/"<<num_tried
4613                         <<" failed"<<std::endl;
4614
4615         // Call it done if less than half failed
4616         return num_failed <= num_tried/2;
4617 }
4618
4619 // IGameDef interface
4620 // Under envlock
4621 IItemDefManager* Server::getItemDefManager()
4622 {
4623         return m_itemdef;
4624 }
4625 INodeDefManager* Server::getNodeDefManager()
4626 {
4627         return m_nodedef;
4628 }
4629 ICraftDefManager* Server::getCraftDefManager()
4630 {
4631         return m_craftdef;
4632 }
4633 ITextureSource* Server::getTextureSource()
4634 {
4635         return NULL;
4636 }
4637 u16 Server::allocateUnknownNodeId(const std::string &name)
4638 {
4639         return m_nodedef->allocateDummy(name);
4640 }
4641 ISoundManager* Server::getSoundManager()
4642 {
4643         return &dummySoundManager;
4644 }
4645 MtEventManager* Server::getEventManager()
4646 {
4647         return m_event;
4648 }
4649 IRollbackReportSink* Server::getRollbackReportSink()
4650 {
4651         if(!m_enable_rollback_recording)
4652                 return NULL;
4653         if(!m_rollback_sink_enabled)
4654                 return NULL;
4655         return m_rollback;
4656 }
4657
4658 IWritableItemDefManager* Server::getWritableItemDefManager()
4659 {
4660         return m_itemdef;
4661 }
4662 IWritableNodeDefManager* Server::getWritableNodeDefManager()
4663 {
4664         return m_nodedef;
4665 }
4666 IWritableCraftDefManager* Server::getWritableCraftDefManager()
4667 {
4668         return m_craftdef;
4669 }
4670
4671 const ModSpec* Server::getModSpec(const std::string &modname)
4672 {
4673         for(core::list<ModSpec>::Iterator i = m_mods.begin();
4674                         i != m_mods.end(); i++){
4675                 const ModSpec &mod = *i;
4676                 if(mod.name == modname)
4677                         return &mod;
4678         }
4679         return NULL;
4680 }
4681 void Server::getModNames(core::list<std::string> &modlist)
4682 {
4683         for(core::list<ModSpec>::Iterator i = m_mods.begin(); i != m_mods.end(); i++)
4684         {
4685                 modlist.push_back((*i).name);
4686         }
4687 }
4688 std::string Server::getBuiltinLuaPath()
4689 {
4690         return porting::path_share + DIR_DELIM + "builtin";
4691 }
4692
4693 v3f findSpawnPos(ServerMap &map)
4694 {
4695         //return v3f(50,50,50)*BS;
4696
4697         v3s16 nodepos;
4698         
4699 #if 0
4700         nodepos = v2s16(0,0);
4701         groundheight = 20;
4702 #endif
4703
4704 #if 1
4705         // Try to find a good place a few times
4706         for(s32 i=0; i<1000; i++)
4707         {
4708                 s32 range = 1 + i;
4709                 // We're going to try to throw the player to this position
4710                 v2s16 nodepos2d = v2s16(-range + (myrand()%(range*2)),
4711                                 -range + (myrand()%(range*2)));
4712                 //v2s16 sectorpos = getNodeSectorPos(nodepos2d);
4713                 // Get ground height at point (fallbacks to heightmap function)
4714                 s16 groundheight = map.findGroundLevel(nodepos2d);
4715                 // Don't go underwater
4716                 if(groundheight < WATER_LEVEL)
4717                 {
4718                         //infostream<<"-> Underwater"<<std::endl;
4719                         continue;
4720                 }
4721                 // Don't go to high places
4722                 if(groundheight > WATER_LEVEL + 4)
4723                 {
4724                         //infostream<<"-> Underwater"<<std::endl;
4725                         continue;
4726                 }
4727                 
4728                 nodepos = v3s16(nodepos2d.X, groundheight-2, nodepos2d.Y);
4729                 bool is_good = false;
4730                 s32 air_count = 0;
4731                 for(s32 i=0; i<10; i++){
4732                         v3s16 blockpos = getNodeBlockPos(nodepos);
4733                         map.emergeBlock(blockpos, true);
4734                         MapNode n = map.getNodeNoEx(nodepos);
4735                         if(n.getContent() == CONTENT_AIR){
4736                                 air_count++;
4737                                 if(air_count >= 2){
4738                                         is_good = true;
4739                                         nodepos.Y -= 1;
4740                                         break;
4741                                 }
4742                         }
4743                         nodepos.Y++;
4744                 }
4745                 if(is_good){
4746                         // Found a good place
4747                         //infostream<<"Searched through "<<i<<" places."<<std::endl;
4748                         break;
4749                 }
4750         }
4751 #endif
4752         
4753         return intToFloat(nodepos, BS);
4754 }
4755
4756 PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
4757 {
4758         RemotePlayer *player = NULL;
4759         bool newplayer = false;
4760
4761         /*
4762                 Try to get an existing player
4763         */
4764         player = static_cast<RemotePlayer*>(m_env->getPlayer(name));
4765
4766         // If player is already connected, cancel
4767         if(player != NULL && player->peer_id != 0)
4768         {
4769                 infostream<<"emergePlayer(): Player already connected"<<std::endl;
4770                 return NULL;
4771         }
4772
4773         /*
4774                 If player with the wanted peer_id already exists, cancel.
4775         */
4776         if(m_env->getPlayer(peer_id) != NULL)
4777         {
4778                 infostream<<"emergePlayer(): Player with wrong name but same"
4779                                 " peer_id already exists"<<std::endl;
4780                 return NULL;
4781         }
4782
4783         /*
4784                 Create a new player if it doesn't exist yet
4785         */
4786         if(player == NULL)
4787         {
4788                 newplayer = true;
4789                 player = new RemotePlayer(this);
4790                 player->updateName(name);
4791
4792                 /* Set player position */
4793                 infostream<<"Server: Finding spawn place for player \""
4794                                 <<name<<"\""<<std::endl;
4795                 v3f pos = findSpawnPos(m_env->getServerMap());
4796                 player->setPosition(pos);
4797
4798                 /* Add player to environment */
4799                 m_env->addPlayer(player);
4800         }
4801
4802         /*
4803                 Create a new player active object
4804         */
4805         PlayerSAO *playersao = new PlayerSAO(m_env, player, peer_id,
4806                         getPlayerEffectivePrivs(player->getName()),
4807                         isSingleplayer());
4808
4809         /* Add object to environment */
4810         m_env->addActiveObject(playersao);
4811
4812         /* Run scripts */
4813         if(newplayer)
4814                 scriptapi_on_newplayer(m_lua, playersao);
4815
4816         scriptapi_on_joinplayer(m_lua, playersao);
4817
4818         return playersao;
4819 }
4820
4821 void Server::handlePeerChange(PeerChange &c)
4822 {
4823         JMutexAutoLock envlock(m_env_mutex);
4824         JMutexAutoLock conlock(m_con_mutex);
4825         
4826         if(c.type == PEER_ADDED)
4827         {
4828                 /*
4829                         Add
4830                 */
4831
4832                 // Error check
4833                 core::map<u16, RemoteClient*>::Node *n;
4834                 n = m_clients.find(c.peer_id);
4835                 // The client shouldn't already exist
4836                 assert(n == NULL);
4837
4838                 // Create client
4839                 RemoteClient *client = new RemoteClient();
4840                 client->peer_id = c.peer_id;
4841                 m_clients.insert(client->peer_id, client);
4842
4843         } // PEER_ADDED
4844         else if(c.type == PEER_REMOVED)
4845         {
4846                 /*
4847                         Delete
4848                 */
4849
4850                 // Error check
4851                 core::map<u16, RemoteClient*>::Node *n;
4852                 n = m_clients.find(c.peer_id);
4853                 // The client should exist
4854                 assert(n != NULL);
4855                 
4856                 /*
4857                         Mark objects to be not known by the client
4858                 */
4859                 RemoteClient *client = n->getValue();
4860                 // Handle objects
4861                 for(core::map<u16, bool>::Iterator
4862                                 i = client->m_known_objects.getIterator();
4863                                 i.atEnd()==false; i++)
4864                 {
4865                         // Get object
4866                         u16 id = i.getNode()->getKey();
4867                         ServerActiveObject* obj = m_env->getActiveObject(id);
4868                         
4869                         if(obj && obj->m_known_by_count > 0)
4870                                 obj->m_known_by_count--;
4871                 }
4872
4873                 /*
4874                         Clear references to playing sounds
4875                 */
4876                 for(std::map<s32, ServerPlayingSound>::iterator
4877                                 i = m_playing_sounds.begin();
4878                                 i != m_playing_sounds.end();)
4879                 {
4880                         ServerPlayingSound &psound = i->second;
4881                         psound.clients.erase(c.peer_id);
4882                         if(psound.clients.size() == 0)
4883                                 m_playing_sounds.erase(i++);
4884                         else
4885                                 i++;
4886                 }
4887
4888                 Player *player = m_env->getPlayer(c.peer_id);
4889
4890                 // Collect information about leaving in chat
4891                 std::wstring message;
4892                 {
4893                         if(player != NULL)
4894                         {
4895                                 std::wstring name = narrow_to_wide(player->getName());
4896                                 message += L"*** ";
4897                                 message += name;
4898                                 message += L" left the game.";
4899                                 if(c.timeout)
4900                                         message += L" (timed out)";
4901                         }
4902                 }
4903                 
4904                 /* Run scripts and remove from environment */
4905                 {
4906                         if(player != NULL)
4907                         {
4908                                 PlayerSAO *playersao = player->getPlayerSAO();
4909                                 assert(playersao);
4910
4911                                 scriptapi_on_leaveplayer(m_lua, playersao);
4912
4913                                 playersao->disconnected();
4914                         }
4915                 }
4916
4917                 /*
4918                         Print out action
4919                 */
4920                 {
4921                         if(player != NULL)
4922                         {
4923                                 std::ostringstream os(std::ios_base::binary);
4924                                 for(core::map<u16, RemoteClient*>::Iterator
4925                                         i = m_clients.getIterator();
4926                                         i.atEnd() == false; i++)
4927                                 {
4928                                         RemoteClient *client = i.getNode()->getValue();
4929                                         assert(client->peer_id == i.getNode()->getKey());
4930                                         if(client->serialization_version == SER_FMT_VER_INVALID)
4931                                                 continue;
4932                                         // Get player
4933                                         Player *player = m_env->getPlayer(client->peer_id);
4934                                         if(!player)
4935                                                 continue;
4936                                         // Get name of player
4937                                         os<<player->getName()<<" ";
4938                                 }
4939
4940                                 actionstream<<player->getName()<<" "
4941                                                 <<(c.timeout?"times out.":"leaves game.")
4942                                                 <<" List of players: "
4943                                                 <<os.str()<<std::endl;
4944                         }
4945                 }
4946                 
4947                 // Delete client
4948                 delete m_clients[c.peer_id];
4949                 m_clients.remove(c.peer_id);
4950
4951                 // Send player info to all remaining clients
4952                 //SendPlayerInfos();
4953                 
4954                 // Send leave chat message to all remaining clients
4955                 if(message.length() != 0)
4956                         BroadcastChatMessage(message);
4957                 
4958         } // PEER_REMOVED
4959         else
4960         {
4961                 assert(0);
4962         }
4963 }
4964
4965 void Server::handlePeerChanges()
4966 {
4967         while(m_peer_change_queue.size() > 0)
4968         {
4969                 PeerChange c = m_peer_change_queue.pop_front();
4970
4971                 verbosestream<<"Server: Handling peer change: "
4972                                 <<"id="<<c.peer_id<<", timeout="<<c.timeout
4973                                 <<std::endl;
4974
4975                 handlePeerChange(c);
4976         }
4977 }
4978
4979 void dedicated_server_loop(Server &server, bool &kill)
4980 {
4981         DSTACK(__FUNCTION_NAME);
4982         
4983         verbosestream<<"dedicated_server_loop()"<<std::endl;
4984
4985         IntervalLimiter m_profiler_interval;
4986
4987         for(;;)
4988         {
4989                 float steplen = g_settings->getFloat("dedicated_server_step");
4990                 // This is kind of a hack but can be done like this
4991                 // because server.step() is very light
4992                 {
4993                         ScopeProfiler sp(g_profiler, "dedicated server sleep");
4994                         sleep_ms((int)(steplen*1000.0));
4995                 }
4996                 server.step(steplen);
4997
4998                 if(server.getShutdownRequested() || kill)
4999                 {
5000                         infostream<<"Dedicated server quitting"<<std::endl;
5001                         break;
5002                 }
5003
5004                 /*
5005                         Profiler
5006                 */
5007                 float profiler_print_interval =
5008                                 g_settings->getFloat("profiler_print_interval");
5009                 if(profiler_print_interval != 0)
5010                 {
5011                         if(m_profiler_interval.step(steplen, profiler_print_interval))
5012                         {
5013                                 infostream<<"Profiler:"<<std::endl;
5014                                 g_profiler->print(infostream);
5015                                 g_profiler->clear();
5016                         }
5017                 }
5018         }
5019 }
5020
5021