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