]> git.lizzy.rs Git - dragonfireclient.git/blob - src/server.cpp
Slightly improved version of mystrtok_r
[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         // Initialize Environment
1101         ServerMap *servermap = new ServerMap(path_world, this);
1102         m_env = new ServerEnvironment(servermap, m_lua, this, this);
1103
1104         // Create emerge manager
1105         m_emerge = new EmergeManager(this, m_biomedef, servermap->getMapgenParams());
1106
1107         // Give map pointer to the emerge manager
1108         servermap->setEmerge(m_emerge);
1109
1110         // Give environment reference to scripting api
1111         scriptapi_add_environment(m_lua, m_env);
1112
1113         // Register us to receive map edit events
1114         servermap->addEventReceiver(this);
1115
1116         // If file exists, load environment metadata
1117         if(fs::PathExists(m_path_world+DIR_DELIM+"env_meta.txt"))
1118         {
1119                 infostream<<"Server: Loading environment metadata"<<std::endl;
1120                 m_env->loadMeta(m_path_world);
1121         }
1122
1123         // Load players
1124         infostream<<"Server: Loading players"<<std::endl;
1125         m_env->deSerializePlayers(m_path_world);
1126
1127         /*
1128                 Add some test ActiveBlockModifiers to environment
1129         */
1130         add_legacy_abms(m_env, m_nodedef);
1131 }
1132
1133 Server::~Server()
1134 {
1135         infostream<<"Server destructing"<<std::endl;
1136
1137         /*
1138                 Send shutdown message
1139         */
1140         {
1141                 JMutexAutoLock conlock(m_con_mutex);
1142
1143                 std::wstring line = L"*** Server shutting down";
1144
1145                 /*
1146                         Send the message to clients
1147                 */
1148                 for(core::map<u16, RemoteClient*>::Iterator
1149                         i = m_clients.getIterator();
1150                         i.atEnd() == false; i++)
1151                 {
1152                         // Get client and check that it is valid
1153                         RemoteClient *client = i.getNode()->getValue();
1154                         assert(client->peer_id == i.getNode()->getKey());
1155                         if(client->serialization_version == SER_FMT_VER_INVALID)
1156                                 continue;
1157
1158                         try{
1159                                 SendChatMessage(client->peer_id, line);
1160                         }
1161                         catch(con::PeerNotFoundException &e)
1162                         {}
1163                 }
1164         }
1165
1166         {
1167                 JMutexAutoLock envlock(m_env_mutex);
1168                 JMutexAutoLock conlock(m_con_mutex);
1169
1170                 /*
1171                         Execute script shutdown hooks
1172                 */
1173                 scriptapi_on_shutdown(m_lua);
1174         }
1175
1176         {
1177                 JMutexAutoLock envlock(m_env_mutex);
1178
1179                 /*
1180                         Save players
1181                 */
1182                 infostream<<"Server: Saving players"<<std::endl;
1183                 m_env->serializePlayers(m_path_world);
1184
1185                 /*
1186                         Save environment metadata
1187                 */
1188                 infostream<<"Server: Saving environment metadata"<<std::endl;
1189                 m_env->saveMeta(m_path_world);
1190         }
1191
1192         /*
1193                 Stop threads
1194         */
1195         stop();
1196
1197         /*
1198                 Delete clients
1199         */
1200         {
1201                 JMutexAutoLock clientslock(m_con_mutex);
1202
1203                 for(core::map<u16, RemoteClient*>::Iterator
1204                         i = m_clients.getIterator();
1205                         i.atEnd() == false; i++)
1206                 {
1207
1208                         // Delete client
1209                         delete i.getNode()->getValue();
1210                 }
1211         }
1212
1213         // Delete things in the reverse order of creation
1214         delete m_env;
1215         delete m_rollback;
1216         delete m_emerge;
1217         delete m_event;
1218         delete m_itemdef;
1219         delete m_nodedef;
1220         delete m_craftdef;
1221
1222         // Deinitialize scripting
1223         infostream<<"Server: Deinitializing scripting"<<std::endl;
1224         script_deinit(m_lua);
1225
1226         // Delete detached inventories
1227         {
1228                 for(std::map<std::string, Inventory*>::iterator
1229                                 i = m_detached_inventories.begin();
1230                                 i != m_detached_inventories.end(); i++){
1231                         delete i->second;
1232                 }
1233         }
1234 }
1235
1236 void Server::start(unsigned short port)
1237 {
1238         DSTACK(__FUNCTION_NAME);
1239         infostream<<"Starting server on port "<<port<<"..."<<std::endl;
1240
1241         // Stop thread if already running
1242         m_thread.stop();
1243
1244         // Initialize connection
1245         m_con.SetTimeoutMs(30);
1246         m_con.Serve(port);
1247
1248         // Start thread
1249         m_thread.setRun(true);
1250         m_thread.Start();
1251
1252         // ASCII art for the win!
1253         actionstream
1254         <<"        .__               __                   __   "<<std::endl
1255         <<"  _____ |__| ____   _____/  |_  ____   _______/  |_ "<<std::endl
1256         <<" /     \\|  |/    \\_/ __ \\   __\\/ __ \\ /  ___/\\   __\\"<<std::endl
1257         <<"|  Y Y  \\  |   |  \\  ___/|  | \\  ___/ \\___ \\  |  |  "<<std::endl
1258         <<"|__|_|  /__|___|  /\\___  >__|  \\___  >____  > |__|  "<<std::endl
1259         <<"      \\/        \\/     \\/          \\/     \\/        "<<std::endl;
1260         actionstream<<"World at ["<<m_path_world<<"]"<<std::endl;
1261         actionstream<<"Server for gameid=\""<<m_gamespec.id
1262                         <<"\" listening on port "<<port<<"."<<std::endl;
1263 }
1264
1265 void Server::stop()
1266 {
1267         DSTACK(__FUNCTION_NAME);
1268
1269         infostream<<"Server: Stopping and waiting threads"<<std::endl;
1270
1271         // Stop threads (set run=false first so both start stopping)
1272         m_thread.setRun(false);
1273         m_emergethread.setRun(false);
1274         m_thread.stop();
1275         m_emergethread.stop();
1276
1277         infostream<<"Server: Threads stopped"<<std::endl;
1278 }
1279
1280 void Server::step(float dtime)
1281 {
1282         DSTACK(__FUNCTION_NAME);
1283         // Limit a bit
1284         if(dtime > 2.0)
1285                 dtime = 2.0;
1286         {
1287                 JMutexAutoLock lock(m_step_dtime_mutex);
1288                 m_step_dtime += dtime;
1289         }
1290         // Throw if fatal error occurred in thread
1291         std::string async_err = m_async_fatal_error.get();
1292         if(async_err != ""){
1293                 throw ServerError(async_err);
1294         }
1295 }
1296
1297 void Server::AsyncRunStep()
1298 {
1299         DSTACK(__FUNCTION_NAME);
1300
1301         g_profiler->add("Server::AsyncRunStep (num)", 1);
1302
1303         float dtime;
1304         {
1305                 JMutexAutoLock lock1(m_step_dtime_mutex);
1306                 dtime = m_step_dtime;
1307         }
1308
1309         {
1310                 // Send blocks to clients
1311                 SendBlocks(dtime);
1312         }
1313
1314         if(dtime < 0.001)
1315                 return;
1316
1317         g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
1318
1319         //infostream<<"Server steps "<<dtime<<std::endl;
1320         //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
1321
1322         {
1323                 JMutexAutoLock lock1(m_step_dtime_mutex);
1324                 m_step_dtime -= dtime;
1325         }
1326
1327         /*
1328                 Update uptime
1329         */
1330         {
1331                 m_uptime.set(m_uptime.get() + dtime);
1332         }
1333
1334         {
1335                 // Process connection's timeouts
1336                 JMutexAutoLock lock2(m_con_mutex);
1337                 ScopeProfiler sp(g_profiler, "Server: connection timeout processing");
1338                 m_con.RunTimeouts(dtime);
1339         }
1340
1341         {
1342                 // This has to be called so that the client list gets synced
1343                 // with the peer list of the connection
1344                 handlePeerChanges();
1345         }
1346
1347         /*
1348                 Update time of day and overall game time
1349         */
1350         {
1351                 JMutexAutoLock envlock(m_env_mutex);
1352
1353                 m_env->setTimeOfDaySpeed(g_settings->getFloat("time_speed"));
1354
1355                 /*
1356                         Send to clients at constant intervals
1357                 */
1358
1359                 m_time_of_day_send_timer -= dtime;
1360                 if(m_time_of_day_send_timer < 0.0)
1361                 {
1362                         m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
1363
1364                         //JMutexAutoLock envlock(m_env_mutex);
1365                         JMutexAutoLock conlock(m_con_mutex);
1366
1367                         for(core::map<u16, RemoteClient*>::Iterator
1368                                 i = m_clients.getIterator();
1369                                 i.atEnd() == false; i++)
1370                         {
1371                                 RemoteClient *client = i.getNode()->getValue();
1372                                 SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
1373                                                 m_env->getTimeOfDay(), g_settings->getFloat("time_speed"));
1374                                 // Send as reliable
1375                                 m_con.Send(client->peer_id, 0, data, true);
1376                         }
1377                 }
1378         }
1379
1380         {
1381                 JMutexAutoLock lock(m_env_mutex);
1382                 // Step environment
1383                 ScopeProfiler sp(g_profiler, "SEnv step");
1384                 ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG);
1385                 m_env->step(dtime);
1386         }
1387
1388         const float map_timer_and_unload_dtime = 2.92;
1389         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
1390         {
1391                 JMutexAutoLock lock(m_env_mutex);
1392                 // Run Map's timers and unload unused data
1393                 ScopeProfiler sp(g_profiler, "Server: map timer and unload");
1394                 m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
1395                                 g_settings->getFloat("server_unload_unused_data_timeout"));
1396         }
1397
1398         /*
1399                 Do background stuff
1400         */
1401
1402         /*
1403                 Handle players
1404         */
1405         {
1406                 JMutexAutoLock lock(m_env_mutex);
1407                 JMutexAutoLock lock2(m_con_mutex);
1408
1409                 ScopeProfiler sp(g_profiler, "Server: handle players");
1410
1411                 for(core::map<u16, RemoteClient*>::Iterator
1412                         i = m_clients.getIterator();
1413                         i.atEnd() == false; i++)
1414                 {
1415                         RemoteClient *client = i.getNode()->getValue();
1416                         PlayerSAO *playersao = getPlayerSAO(client->peer_id);
1417                         if(playersao == NULL)
1418                                 continue;
1419
1420                         /*
1421                                 Handle player HPs (die if hp=0)
1422                         */
1423                         if(playersao->m_hp_not_sent && g_settings->getBool("enable_damage"))
1424                         {
1425                                 if(playersao->getHP() == 0)
1426                                         DiePlayer(client->peer_id);
1427                                 else
1428                                         SendPlayerHP(client->peer_id);
1429                         }
1430
1431                         /*
1432                                 Send player inventories if necessary
1433                         */
1434                         if(playersao->m_moved){
1435                                 SendMovePlayer(client->peer_id);
1436                                 playersao->m_moved = false;
1437                         }
1438                         if(playersao->m_inventory_not_sent){
1439                                 UpdateCrafting(client->peer_id);
1440                                 SendInventory(client->peer_id);
1441                         }
1442                 }
1443         }
1444
1445         /* Transform liquids */
1446         m_liquid_transform_timer += dtime;
1447         if(m_liquid_transform_timer >= 1.00)
1448         {
1449                 m_liquid_transform_timer -= 1.00;
1450
1451                 JMutexAutoLock lock(m_env_mutex);
1452
1453                 ScopeProfiler sp(g_profiler, "Server: liquid transform");
1454
1455                 core::map<v3s16, MapBlock*> modified_blocks;
1456                 m_env->getMap().transformLiquids(modified_blocks);
1457 #if 0
1458                 /*
1459                         Update lighting
1460                 */
1461                 core::map<v3s16, MapBlock*> lighting_modified_blocks;
1462                 ServerMap &map = ((ServerMap&)m_env->getMap());
1463                 map.updateLighting(modified_blocks, lighting_modified_blocks);
1464
1465                 // Add blocks modified by lighting to modified_blocks
1466                 for(core::map<v3s16, MapBlock*>::Iterator
1467                                 i = lighting_modified_blocks.getIterator();
1468                                 i.atEnd() == false; i++)
1469                 {
1470                         MapBlock *block = i.getNode()->getValue();
1471                         modified_blocks.insert(block->getPos(), block);
1472                 }
1473 #endif
1474                 /*
1475                         Set the modified blocks unsent for all the clients
1476                 */
1477
1478                 JMutexAutoLock lock2(m_con_mutex);
1479
1480                 for(core::map<u16, RemoteClient*>::Iterator
1481                                 i = m_clients.getIterator();
1482                                 i.atEnd() == false; i++)
1483                 {
1484                         RemoteClient *client = i.getNode()->getValue();
1485
1486                         if(modified_blocks.size() > 0)
1487                         {
1488                                 // Remove block from sent history
1489                                 client->SetBlocksNotSent(modified_blocks);
1490                         }
1491                 }
1492         }
1493
1494         // Periodically print some info
1495         {
1496                 float &counter = m_print_info_timer;
1497                 counter += dtime;
1498                 if(counter >= 30.0)
1499                 {
1500                         counter = 0.0;
1501
1502                         JMutexAutoLock lock2(m_con_mutex);
1503
1504                         if(m_clients.size() != 0)
1505                                 infostream<<"Players:"<<std::endl;
1506                         for(core::map<u16, RemoteClient*>::Iterator
1507                                 i = m_clients.getIterator();
1508                                 i.atEnd() == false; i++)
1509                         {
1510                                 //u16 peer_id = i.getNode()->getKey();
1511                                 RemoteClient *client = i.getNode()->getValue();
1512                                 Player *player = m_env->getPlayer(client->peer_id);
1513                                 if(player==NULL)
1514                                         continue;
1515                                 infostream<<"* "<<player->getName()<<"\t";
1516                                 client->PrintInfo(infostream);
1517                         }
1518                 }
1519         }
1520
1521         //if(g_settings->getBool("enable_experimental"))
1522         {
1523
1524         /*
1525                 Check added and deleted active objects
1526         */
1527         {
1528                 //infostream<<"Server: Checking added and deleted active objects"<<std::endl;
1529                 JMutexAutoLock envlock(m_env_mutex);
1530                 JMutexAutoLock conlock(m_con_mutex);
1531
1532                 ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
1533
1534                 // Radius inside which objects are active
1535                 s16 radius = g_settings->getS16("active_object_send_range_blocks");
1536                 radius *= MAP_BLOCKSIZE;
1537
1538                 for(core::map<u16, RemoteClient*>::Iterator
1539                         i = m_clients.getIterator();
1540                         i.atEnd() == false; i++)
1541                 {
1542                         RemoteClient *client = i.getNode()->getValue();
1543
1544                         // If definitions and textures have not been sent, don't
1545                         // send objects either
1546                         if(!client->definitions_sent)
1547                                 continue;
1548
1549                         Player *player = m_env->getPlayer(client->peer_id);
1550                         if(player==NULL)
1551                         {
1552                                 // This can happen if the client timeouts somehow
1553                                 /*infostream<<"WARNING: "<<__FUNCTION_NAME<<": Client "
1554                                                 <<client->peer_id
1555                                                 <<" has no associated player"<<std::endl;*/
1556                                 continue;
1557                         }
1558                         v3s16 pos = floatToInt(player->getPosition(), BS);
1559
1560                         core::map<u16, bool> removed_objects;
1561                         core::map<u16, bool> added_objects;
1562                         m_env->getRemovedActiveObjects(pos, radius,
1563                                         client->m_known_objects, removed_objects);
1564                         m_env->getAddedActiveObjects(pos, radius,
1565                                         client->m_known_objects, added_objects);
1566
1567                         // Ignore if nothing happened
1568                         if(removed_objects.size() == 0 && added_objects.size() == 0)
1569                         {
1570                                 //infostream<<"active objects: none changed"<<std::endl;
1571                                 continue;
1572                         }
1573
1574                         std::string data_buffer;
1575
1576                         char buf[4];
1577
1578                         // Handle removed objects
1579                         writeU16((u8*)buf, removed_objects.size());
1580                         data_buffer.append(buf, 2);
1581                         for(core::map<u16, bool>::Iterator
1582                                         i = removed_objects.getIterator();
1583                                         i.atEnd()==false; i++)
1584                         {
1585                                 // Get object
1586                                 u16 id = i.getNode()->getKey();
1587                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1588
1589                                 // Add to data buffer for sending
1590                                 writeU16((u8*)buf, i.getNode()->getKey());
1591                                 data_buffer.append(buf, 2);
1592
1593                                 // Remove from known objects
1594                                 client->m_known_objects.remove(i.getNode()->getKey());
1595
1596                                 if(obj && obj->m_known_by_count > 0)
1597                                         obj->m_known_by_count--;
1598                         }
1599
1600                         // Handle added objects
1601                         writeU16((u8*)buf, added_objects.size());
1602                         data_buffer.append(buf, 2);
1603                         for(core::map<u16, bool>::Iterator
1604                                         i = added_objects.getIterator();
1605                                         i.atEnd()==false; i++)
1606                         {
1607                                 // Get object
1608                                 u16 id = i.getNode()->getKey();
1609                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1610
1611                                 // Get object type
1612                                 u8 type = ACTIVEOBJECT_TYPE_INVALID;
1613                                 if(obj == NULL)
1614                                         infostream<<"WARNING: "<<__FUNCTION_NAME
1615                                                         <<": NULL object"<<std::endl;
1616                                 else
1617                                         type = obj->getSendType();
1618
1619                                 // Add to data buffer for sending
1620                                 writeU16((u8*)buf, id);
1621                                 data_buffer.append(buf, 2);
1622                                 writeU8((u8*)buf, type);
1623                                 data_buffer.append(buf, 1);
1624
1625                                 if(obj)
1626                                         data_buffer.append(serializeLongString(
1627                                                         obj->getClientInitializationData(client->net_proto_version)));
1628                                 else
1629                                         data_buffer.append(serializeLongString(""));
1630
1631                                 // Add to known objects
1632                                 client->m_known_objects.insert(i.getNode()->getKey(), false);
1633
1634                                 if(obj)
1635                                         obj->m_known_by_count++;
1636                         }
1637
1638                         // Send packet
1639                         SharedBuffer<u8> reply(2 + data_buffer.size());
1640                         writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD);
1641                         memcpy((char*)&reply[2], data_buffer.c_str(),
1642                                         data_buffer.size());
1643                         // Send as reliable
1644                         m_con.Send(client->peer_id, 0, reply, true);
1645
1646                         verbosestream<<"Server: Sent object remove/add: "
1647                                         <<removed_objects.size()<<" removed, "
1648                                         <<added_objects.size()<<" added, "
1649                                         <<"packet size is "<<reply.getSize()<<std::endl;
1650                 }
1651
1652 #if 0
1653                 /*
1654                         Collect a list of all the objects known by the clients
1655                         and report it back to the environment.
1656                 */
1657
1658                 core::map<u16, bool> all_known_objects;
1659
1660                 for(core::map<u16, RemoteClient*>::Iterator
1661                         i = m_clients.getIterator();
1662                         i.atEnd() == false; i++)
1663                 {
1664                         RemoteClient *client = i.getNode()->getValue();
1665                         // Go through all known objects of client
1666                         for(core::map<u16, bool>::Iterator
1667                                         i = client->m_known_objects.getIterator();
1668                                         i.atEnd()==false; i++)
1669                         {
1670                                 u16 id = i.getNode()->getKey();
1671                                 all_known_objects[id] = true;
1672                         }
1673                 }
1674
1675                 m_env->setKnownActiveObjects(whatever);
1676 #endif
1677
1678         }
1679
1680         /*
1681                 Send object messages
1682         */
1683         {
1684                 JMutexAutoLock envlock(m_env_mutex);
1685                 JMutexAutoLock conlock(m_con_mutex);
1686
1687                 ScopeProfiler sp(g_profiler, "Server: sending object messages");
1688
1689                 // Key = object id
1690                 // Value = data sent by object
1691                 core::map<u16, core::list<ActiveObjectMessage>* > buffered_messages;
1692
1693                 // Get active object messages from environment
1694                 for(;;)
1695                 {
1696                         ActiveObjectMessage aom = m_env->getActiveObjectMessage();
1697                         if(aom.id == 0)
1698                                 break;
1699
1700                         core::list<ActiveObjectMessage>* message_list = NULL;
1701                         core::map<u16, core::list<ActiveObjectMessage>* >::Node *n;
1702                         n = buffered_messages.find(aom.id);
1703                         if(n == NULL)
1704                         {
1705                                 message_list = new core::list<ActiveObjectMessage>;
1706                                 buffered_messages.insert(aom.id, message_list);
1707                         }
1708                         else
1709                         {
1710                                 message_list = n->getValue();
1711                         }
1712                         message_list->push_back(aom);
1713                 }
1714
1715                 // Route data to every client
1716                 for(core::map<u16, RemoteClient*>::Iterator
1717                         i = m_clients.getIterator();
1718                         i.atEnd()==false; i++)
1719                 {
1720                         RemoteClient *client = i.getNode()->getValue();
1721                         std::string reliable_data;
1722                         std::string unreliable_data;
1723                         // Go through all objects in message buffer
1724                         for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1725                                         j = buffered_messages.getIterator();
1726                                         j.atEnd()==false; j++)
1727                         {
1728                                 // If object is not known by client, skip it
1729                                 u16 id = j.getNode()->getKey();
1730                                 if(client->m_known_objects.find(id) == NULL)
1731                                         continue;
1732                                 // Get message list of object
1733                                 core::list<ActiveObjectMessage>* list = j.getNode()->getValue();
1734                                 // Go through every message
1735                                 for(core::list<ActiveObjectMessage>::Iterator
1736                                                 k = list->begin(); k != list->end(); k++)
1737                                 {
1738                                         // Compose the full new data with header
1739                                         ActiveObjectMessage aom = *k;
1740                                         std::string new_data;
1741                                         // Add object id
1742                                         char buf[2];
1743                                         writeU16((u8*)&buf[0], aom.id);
1744                                         new_data.append(buf, 2);
1745                                         // Add data
1746                                         new_data += serializeString(aom.datastring);
1747                                         // Add data to buffer
1748                                         if(aom.reliable)
1749                                                 reliable_data += new_data;
1750                                         else
1751                                                 unreliable_data += new_data;
1752                                 }
1753                         }
1754                         /*
1755                                 reliable_data and unreliable_data are now ready.
1756                                 Send them.
1757                         */
1758                         if(reliable_data.size() > 0)
1759                         {
1760                                 SharedBuffer<u8> reply(2 + reliable_data.size());
1761                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1762                                 memcpy((char*)&reply[2], reliable_data.c_str(),
1763                                                 reliable_data.size());
1764                                 // Send as reliable
1765                                 m_con.Send(client->peer_id, 0, reply, true);
1766                         }
1767                         if(unreliable_data.size() > 0)
1768                         {
1769                                 SharedBuffer<u8> reply(2 + unreliable_data.size());
1770                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1771                                 memcpy((char*)&reply[2], unreliable_data.c_str(),
1772                                                 unreliable_data.size());
1773                                 // Send as unreliable
1774                                 m_con.Send(client->peer_id, 0, reply, false);
1775                         }
1776
1777                         /*if(reliable_data.size() > 0 || unreliable_data.size() > 0)
1778                         {
1779                                 infostream<<"Server: Size of object message data: "
1780                                                 <<"reliable: "<<reliable_data.size()
1781                                                 <<", unreliable: "<<unreliable_data.size()
1782                                                 <<std::endl;
1783                         }*/
1784                 }
1785
1786                 // Clear buffered_messages
1787                 for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1788                                 i = buffered_messages.getIterator();
1789                                 i.atEnd()==false; i++)
1790                 {
1791                         delete i.getNode()->getValue();
1792                 }
1793         }
1794
1795         } // enable_experimental
1796
1797         /*
1798                 Send queued-for-sending map edit events.
1799         */
1800         {
1801                 // We will be accessing the environment and the connection
1802                 JMutexAutoLock lock(m_env_mutex);
1803                 JMutexAutoLock conlock(m_con_mutex);
1804
1805                 // Don't send too many at a time
1806                 //u32 count = 0;
1807
1808                 // Single change sending is disabled if queue size is not small
1809                 bool disable_single_change_sending = false;
1810                 if(m_unsent_map_edit_queue.size() >= 4)
1811                         disable_single_change_sending = true;
1812
1813                 int event_count = m_unsent_map_edit_queue.size();
1814
1815                 // We'll log the amount of each
1816                 Profiler prof;
1817
1818                 while(m_unsent_map_edit_queue.size() != 0)
1819                 {
1820                         MapEditEvent* event = m_unsent_map_edit_queue.pop_front();
1821
1822                         // Players far away from the change are stored here.
1823                         // Instead of sending the changes, MapBlocks are set not sent
1824                         // for them.
1825                         core::list<u16> far_players;
1826
1827                         if(event->type == MEET_ADDNODE)
1828                         {
1829                                 //infostream<<"Server: MEET_ADDNODE"<<std::endl;
1830                                 prof.add("MEET_ADDNODE", 1);
1831                                 if(disable_single_change_sending)
1832                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1833                                                         &far_players, 5);
1834                                 else
1835                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1836                                                         &far_players, 30);
1837                         }
1838                         else if(event->type == MEET_REMOVENODE)
1839                         {
1840                                 //infostream<<"Server: MEET_REMOVENODE"<<std::endl;
1841                                 prof.add("MEET_REMOVENODE", 1);
1842                                 if(disable_single_change_sending)
1843                                         sendRemoveNode(event->p, event->already_known_by_peer,
1844                                                         &far_players, 5);
1845                                 else
1846                                         sendRemoveNode(event->p, event->already_known_by_peer,
1847                                                         &far_players, 30);
1848                         }
1849                         else if(event->type == MEET_BLOCK_NODE_METADATA_CHANGED)
1850                         {
1851                                 infostream<<"Server: MEET_BLOCK_NODE_METADATA_CHANGED"<<std::endl;
1852                                 prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1);
1853                                 setBlockNotSent(event->p);
1854                         }
1855                         else if(event->type == MEET_OTHER)
1856                         {
1857                                 infostream<<"Server: MEET_OTHER"<<std::endl;
1858                                 prof.add("MEET_OTHER", 1);
1859                                 for(core::map<v3s16, bool>::Iterator
1860                                                 i = event->modified_blocks.getIterator();
1861                                                 i.atEnd()==false; i++)
1862                                 {
1863                                         v3s16 p = i.getNode()->getKey();
1864                                         setBlockNotSent(p);
1865                                 }
1866                         }
1867                         else
1868                         {
1869                                 prof.add("unknown", 1);
1870                                 infostream<<"WARNING: Server: Unknown MapEditEvent "
1871                                                 <<((u32)event->type)<<std::endl;
1872                         }
1873
1874                         /*
1875                                 Set blocks not sent to far players
1876                         */
1877                         if(far_players.size() > 0)
1878                         {
1879                                 // Convert list format to that wanted by SetBlocksNotSent
1880                                 core::map<v3s16, MapBlock*> modified_blocks2;
1881                                 for(core::map<v3s16, bool>::Iterator
1882                                                 i = event->modified_blocks.getIterator();
1883                                                 i.atEnd()==false; i++)
1884                                 {
1885                                         v3s16 p = i.getNode()->getKey();
1886                                         modified_blocks2.insert(p,
1887                                                         m_env->getMap().getBlockNoCreateNoEx(p));
1888                                 }
1889                                 // Set blocks not sent
1890                                 for(core::list<u16>::Iterator
1891                                                 i = far_players.begin();
1892                                                 i != far_players.end(); i++)
1893                                 {
1894                                         u16 peer_id = *i;
1895                                         RemoteClient *client = getClient(peer_id);
1896                                         if(client==NULL)
1897                                                 continue;
1898                                         client->SetBlocksNotSent(modified_blocks2);
1899                                 }
1900                         }
1901
1902                         delete event;
1903
1904                         /*// Don't send too many at a time
1905                         count++;
1906                         if(count >= 1 && m_unsent_map_edit_queue.size() < 100)
1907                                 break;*/
1908                 }
1909
1910                 if(event_count >= 5){
1911                         infostream<<"Server: MapEditEvents:"<<std::endl;
1912                         prof.print(infostream);
1913                 } else if(event_count != 0){
1914                         verbosestream<<"Server: MapEditEvents:"<<std::endl;
1915                         prof.print(verbosestream);
1916                 }
1917
1918         }
1919
1920         /*
1921                 Trigger emergethread (it somehow gets to a non-triggered but
1922                 bysy state sometimes)
1923         */
1924         {
1925                 float &counter = m_emergethread_trigger_timer;
1926                 counter += dtime;
1927                 if(counter >= 2.0)
1928                 {
1929                         counter = 0.0;
1930
1931                         m_emergethread.trigger();
1932
1933                         // Update m_enable_rollback_recording here too
1934                         m_enable_rollback_recording =
1935                                         g_settings->getBool("enable_rollback_recording");
1936                 }
1937         }
1938
1939         // Save map, players and auth stuff
1940         {
1941                 float &counter = m_savemap_timer;
1942                 counter += dtime;
1943                 if(counter >= g_settings->getFloat("server_map_save_interval"))
1944                 {
1945                         counter = 0.0;
1946                         JMutexAutoLock lock(m_env_mutex);
1947
1948                         ScopeProfiler sp(g_profiler, "Server: saving stuff");
1949
1950                         //Ban stuff
1951                         if(m_banmanager.isModified())
1952                                 m_banmanager.save();
1953
1954                         // Save changed parts of map
1955                         m_env->getMap().save(MOD_STATE_WRITE_NEEDED);
1956
1957                         // Save players
1958                         m_env->serializePlayers(m_path_world);
1959
1960                         // Save environment metadata
1961                         m_env->saveMeta(m_path_world);
1962                 }
1963         }
1964 }
1965
1966 void Server::Receive()
1967 {
1968         DSTACK(__FUNCTION_NAME);
1969         SharedBuffer<u8> data;
1970         u16 peer_id;
1971         u32 datasize;
1972         try{
1973                 {
1974                         JMutexAutoLock conlock(m_con_mutex);
1975                         datasize = m_con.Receive(peer_id, data);
1976                 }
1977
1978                 // This has to be called so that the client list gets synced
1979                 // with the peer list of the connection
1980                 handlePeerChanges();
1981
1982                 ProcessData(*data, datasize, peer_id);
1983         }
1984         catch(con::InvalidIncomingDataException &e)
1985         {
1986                 infostream<<"Server::Receive(): "
1987                                 "InvalidIncomingDataException: what()="
1988                                 <<e.what()<<std::endl;
1989         }
1990         catch(con::PeerNotFoundException &e)
1991         {
1992                 //NOTE: This is not needed anymore
1993
1994                 // The peer has been disconnected.
1995                 // Find the associated player and remove it.
1996
1997                 /*JMutexAutoLock envlock(m_env_mutex);
1998
1999                 infostream<<"ServerThread: peer_id="<<peer_id
2000                                 <<" has apparently closed connection. "
2001                                 <<"Removing player."<<std::endl;
2002
2003                 m_env->removePlayer(peer_id);*/
2004         }
2005 }
2006
2007 void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
2008 {
2009         DSTACK(__FUNCTION_NAME);
2010         // Environment is locked first.
2011         JMutexAutoLock envlock(m_env_mutex);
2012         JMutexAutoLock conlock(m_con_mutex);
2013
2014         ScopeProfiler sp(g_profiler, "Server::ProcessData");
2015
2016         try{
2017                 Address address = m_con.GetPeerAddress(peer_id);
2018                 std::string addr_s = address.serializeString();
2019
2020                 // drop player if is ip is banned
2021                 if(m_banmanager.isIpBanned(addr_s)){
2022                         infostream<<"Server: A banned client tried to connect from "
2023                                         <<addr_s<<"; banned name was "
2024                                         <<m_banmanager.getBanName(addr_s)<<std::endl;
2025                         // This actually doesn't seem to transfer to the client
2026                         SendAccessDenied(m_con, peer_id,
2027                                         L"Your ip is banned. Banned name was "
2028                                         +narrow_to_wide(m_banmanager.getBanName(addr_s)));
2029                         m_con.DeletePeer(peer_id);
2030                         return;
2031                 }
2032         }
2033         catch(con::PeerNotFoundException &e)
2034         {
2035                 infostream<<"Server::ProcessData(): Cancelling: peer "
2036                                 <<peer_id<<" not found"<<std::endl;
2037                 return;
2038         }
2039
2040         std::string addr_s = m_con.GetPeerAddress(peer_id).serializeString();
2041
2042         u8 peer_ser_ver = getClient(peer_id)->serialization_version;
2043
2044         try
2045         {
2046
2047         if(datasize < 2)
2048                 return;
2049
2050         ToServerCommand command = (ToServerCommand)readU16(&data[0]);
2051
2052         if(command == TOSERVER_INIT)
2053         {
2054                 // [0] u16 TOSERVER_INIT
2055                 // [2] u8 SER_FMT_VER_HIGHEST
2056                 // [3] u8[20] player_name
2057                 // [23] u8[28] password <--- can be sent without this, from old versions
2058
2059                 if(datasize < 2+1+PLAYERNAME_SIZE)
2060                         return;
2061
2062                 verbosestream<<"Server: Got TOSERVER_INIT from "
2063                                 <<peer_id<<std::endl;
2064
2065                 // First byte after command is maximum supported
2066                 // serialization version
2067                 u8 client_max = data[2];
2068                 u8 our_max = SER_FMT_VER_HIGHEST;
2069                 // Use the highest version supported by both
2070                 u8 deployed = core::min_(client_max, our_max);
2071                 // If it's lower than the lowest supported, give up.
2072                 if(deployed < SER_FMT_VER_LOWEST)
2073                         deployed = SER_FMT_VER_INVALID;
2074
2075                 //peer->serialization_version = deployed;
2076                 getClient(peer_id)->pending_serialization_version = deployed;
2077
2078                 if(deployed == SER_FMT_VER_INVALID)
2079                 {
2080                         actionstream<<"Server: A mismatched client tried to connect from "
2081                                         <<addr_s<<std::endl;
2082                         infostream<<"Server: Cannot negotiate "
2083                                         "serialization version with peer "
2084                                         <<peer_id<<std::endl;
2085                         SendAccessDenied(m_con, peer_id, std::wstring(
2086                                         L"Your client's version is not supported.\n"
2087                                         L"Server version is ")
2088                                         + narrow_to_wide(VERSION_STRING) + L"."
2089                         );
2090                         return;
2091                 }
2092
2093                 /*
2094                         Read and check network protocol version
2095                 */
2096
2097                 u16 min_net_proto_version = 0;
2098                 if(datasize >= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2)
2099                         min_net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]);
2100
2101                 // Use same version as minimum and maximum if maximum version field
2102                 // doesn't exist (backwards compatibility)
2103                 u16 max_net_proto_version = min_net_proto_version;
2104                 if(datasize >= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2+2)
2105                         max_net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2]);
2106
2107                 // Start with client's maximum version
2108                 u16 net_proto_version = max_net_proto_version;
2109
2110                 // Figure out a working version if it is possible at all
2111                 if(max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
2112                                 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX)
2113                 {
2114                         // If maximum is larger than our maximum, go with our maximum
2115                         if(max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
2116                                 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
2117                         // Else go with client's maximum
2118                         else
2119                                 net_proto_version = max_net_proto_version;
2120                 }
2121
2122                 verbosestream<<"Server: "<<peer_id<<" Protocol version: min: "
2123                                 <<min_net_proto_version<<", max: "<<max_net_proto_version
2124                                 <<", chosen: "<<net_proto_version<<std::endl;
2125
2126                 getClient(peer_id)->net_proto_version = net_proto_version;
2127
2128                 if(net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
2129                                 net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
2130                 {
2131                         actionstream<<"Server: A mismatched client tried to connect from "<<addr_s
2132                                         <<std::endl;
2133                         SendAccessDenied(m_con, peer_id, std::wstring(
2134                                         L"Your client's version is not supported.\n"
2135                                         L"Server version is ")
2136                                         + narrow_to_wide(VERSION_STRING) + L",\n"
2137                                         + L"server's PROTOCOL_VERSION is "
2138                                         + narrow_to_wide(itos(SERVER_PROTOCOL_VERSION_MIN))
2139                                         + L"..."
2140                                         + narrow_to_wide(itos(SERVER_PROTOCOL_VERSION_MAX))
2141                                         + L", client's PROTOCOL_VERSION is "
2142                                         + narrow_to_wide(itos(min_net_proto_version))
2143                                         + L"..."
2144                                         + narrow_to_wide(itos(max_net_proto_version))
2145                         );
2146                         return;
2147                 }
2148
2149                 if(g_settings->getBool("strict_protocol_version_checking"))
2150                 {
2151                         if(net_proto_version != LATEST_PROTOCOL_VERSION)
2152                         {
2153                                 actionstream<<"Server: A mismatched (strict) client tried to "
2154                                                 <<"connect from "<<addr_s<<std::endl;
2155                                 SendAccessDenied(m_con, peer_id, std::wstring(
2156                                                 L"Your client's version is not supported.\n"
2157                                                 L"Server version is ")
2158                                                 + narrow_to_wide(VERSION_STRING) + L",\n"
2159                                                 + L"server's PROTOCOL_VERSION (strict) is "
2160                                                 + narrow_to_wide(itos(LATEST_PROTOCOL_VERSION))
2161                                                 + L", client's PROTOCOL_VERSION is "
2162                                                 + narrow_to_wide(itos(min_net_proto_version))
2163                                                 + L"..."
2164                                                 + narrow_to_wide(itos(max_net_proto_version))
2165                                 );
2166                                 return;
2167                         }
2168                 }
2169
2170                 /*
2171                         Set up player
2172                 */
2173
2174                 // Get player name
2175                 char playername[PLAYERNAME_SIZE];
2176                 for(u32 i=0; i<PLAYERNAME_SIZE-1; i++)
2177                 {
2178                         playername[i] = data[3+i];
2179                 }
2180                 playername[PLAYERNAME_SIZE-1] = 0;
2181
2182                 if(playername[0]=='\0')
2183                 {
2184                         actionstream<<"Server: Player with an empty name "
2185                                         <<"tried to connect from "<<addr_s<<std::endl;
2186                         SendAccessDenied(m_con, peer_id,
2187                                         L"Empty name");
2188                         return;
2189                 }
2190
2191                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
2192                 {
2193                         actionstream<<"Server: Player with an invalid name "
2194                                         <<"tried to connect from "<<addr_s<<std::endl;
2195                         SendAccessDenied(m_con, peer_id,
2196                                         L"Name contains unallowed characters");
2197                         return;
2198                 }
2199
2200                 infostream<<"Server: New connection: \""<<playername<<"\" from "
2201                                 <<m_con.GetPeerAddress(peer_id).serializeString()<<std::endl;
2202
2203                 // Get password
2204                 char given_password[PASSWORD_SIZE];
2205                 if(datasize < 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE)
2206                 {
2207                         // old version - assume blank password
2208                         given_password[0] = 0;
2209                 }
2210                 else
2211                 {
2212                         for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2213                         {
2214                                 given_password[i] = data[23+i];
2215                         }
2216                         given_password[PASSWORD_SIZE-1] = 0;
2217                 }
2218
2219                 if(!base64_is_valid(given_password)){
2220                         infostream<<"Server: "<<playername
2221                                         <<" supplied invalid password hash"<<std::endl;
2222                         SendAccessDenied(m_con, peer_id, L"Invalid password hash");
2223                         return;
2224                 }
2225
2226                 std::string checkpwd; // Password hash to check against
2227                 bool has_auth = scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
2228
2229                 // If no authentication info exists for user, create it
2230                 if(!has_auth){
2231                         if(!isSingleplayer() &&
2232                                         g_settings->getBool("disallow_empty_password") &&
2233                                         std::string(given_password) == ""){
2234                                 SendAccessDenied(m_con, peer_id, L"Empty passwords are "
2235                                                 L"disallowed. Set a password and try again.");
2236                                 return;
2237                         }
2238                         std::wstring raw_default_password =
2239                                 narrow_to_wide(g_settings->get("default_password"));
2240                         std::string initial_password =
2241                                 translatePassword(playername, raw_default_password);
2242
2243                         // If default_password is empty, allow any initial password
2244                         if (raw_default_password.length() == 0)
2245                                 initial_password = given_password;
2246
2247                         scriptapi_create_auth(m_lua, playername, initial_password);
2248                 }
2249
2250                 has_auth = scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
2251
2252                 if(!has_auth){
2253                         SendAccessDenied(m_con, peer_id, L"Not allowed to login");
2254                         return;
2255                 }
2256
2257                 if(given_password != checkpwd){
2258                         infostream<<"Server: peer_id="<<peer_id
2259                                         <<": supplied invalid password for "
2260                                         <<playername<<std::endl;
2261                         SendAccessDenied(m_con, peer_id, L"Invalid password");
2262                         return;
2263                 }
2264
2265                 // Do not allow multiple players in simple singleplayer mode.
2266                 // This isn't a perfect way to do it, but will suffice for now.
2267                 if(m_simple_singleplayer_mode && m_clients.size() > 1){
2268                         infostream<<"Server: Not allowing another client to connect in"
2269                                         <<" simple singleplayer mode"<<std::endl;
2270                         SendAccessDenied(m_con, peer_id,
2271                                         L"Running in simple singleplayer mode.");
2272                         return;
2273                 }
2274
2275                 // Enforce user limit.
2276                 // Don't enforce for users that have some admin right
2277                 if(m_clients.size() >= g_settings->getU16("max_users") &&
2278                                 !checkPriv(playername, "server") &&
2279                                 !checkPriv(playername, "ban") &&
2280                                 !checkPriv(playername, "privs") &&
2281                                 !checkPriv(playername, "password") &&
2282                                 playername != g_settings->get("name"))
2283                 {
2284                         actionstream<<"Server: "<<playername<<" tried to join, but there"
2285                                         <<" are already max_users="
2286                                         <<g_settings->getU16("max_users")<<" players."<<std::endl;
2287                         SendAccessDenied(m_con, peer_id, L"Too many users.");
2288                         return;
2289                 }
2290
2291                 // Get player
2292                 PlayerSAO *playersao = emergePlayer(playername, peer_id);
2293
2294                 // If failed, cancel
2295                 if(playersao == NULL)
2296                 {
2297                         errorstream<<"Server: peer_id="<<peer_id
2298                                         <<": failed to emerge player"<<std::endl;
2299                         return;
2300                 }
2301
2302                 /*
2303                         Answer with a TOCLIENT_INIT
2304                 */
2305                 {
2306                         SharedBuffer<u8> reply(2+1+6+8+4);
2307                         writeU16(&reply[0], TOCLIENT_INIT);
2308                         writeU8(&reply[2], deployed);
2309                         writeV3S16(&reply[2+1], floatToInt(playersao->getPlayer()->getPosition()+v3f(0,BS/2,0), BS));
2310                         writeU64(&reply[2+1+6], m_env->getServerMap().getSeed());
2311                         writeF1000(&reply[2+1+6+8], g_settings->getFloat("dedicated_server_step"));
2312
2313                         // Send as reliable
2314                         m_con.Send(peer_id, 0, reply, true);
2315                 }
2316
2317                 /*
2318                         Send complete position information
2319                 */
2320                 SendMovePlayer(peer_id);
2321
2322                 return;
2323         }
2324
2325         if(command == TOSERVER_INIT2)
2326         {
2327                 verbosestream<<"Server: Got TOSERVER_INIT2 from "
2328                                 <<peer_id<<std::endl;
2329
2330                 Player *player = m_env->getPlayer(peer_id);
2331                 if(!player){
2332                         verbosestream<<"Server: TOSERVER_INIT2: "
2333                                         <<"Player not found; ignoring."<<std::endl;
2334                         return;
2335                 }
2336
2337                 RemoteClient *client = getClient(peer_id);
2338                 client->serialization_version =
2339                                 getClient(peer_id)->pending_serialization_version;
2340
2341                 /*
2342                         Send some initialization data
2343                 */
2344
2345                 infostream<<"Server: Sending content to "
2346                                 <<getPlayerName(peer_id)<<std::endl;
2347
2348                 // Send item definitions
2349                 SendItemDef(m_con, peer_id, m_itemdef);
2350
2351                 // Send node definitions
2352                 SendNodeDef(m_con, peer_id, m_nodedef, client->net_proto_version);
2353
2354                 // Send media announcement
2355                 sendMediaAnnouncement(peer_id);
2356
2357                 // Send privileges
2358                 SendPlayerPrivileges(peer_id);
2359
2360                 // Send inventory formspec
2361                 SendPlayerInventoryFormspec(peer_id);
2362
2363                 // Send inventory
2364                 UpdateCrafting(peer_id);
2365                 SendInventory(peer_id);
2366
2367                 // Send HP
2368                 if(g_settings->getBool("enable_damage"))
2369                         SendPlayerHP(peer_id);
2370
2371                 // Send detached inventories
2372                 sendDetachedInventories(peer_id);
2373
2374                 // Show death screen if necessary
2375                 if(player->hp == 0)
2376                         SendDeathscreen(m_con, peer_id, false, v3f(0,0,0));
2377
2378                 // Send time of day
2379                 {
2380                         SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
2381                                         m_env->getTimeOfDay(), g_settings->getFloat("time_speed"));
2382                         m_con.Send(peer_id, 0, data, true);
2383                 }
2384
2385                 // Note things in chat if not in simple singleplayer mode
2386                 if(!m_simple_singleplayer_mode)
2387                 {
2388                         // Send information about server to player in chat
2389                         SendChatMessage(peer_id, getStatusString());
2390
2391                         // Send information about joining in chat
2392                         {
2393                                 std::wstring name = L"unknown";
2394                                 Player *player = m_env->getPlayer(peer_id);
2395                                 if(player != NULL)
2396                                         name = narrow_to_wide(player->getName());
2397
2398                                 std::wstring message;
2399                                 message += L"*** ";
2400                                 message += name;
2401                                 message += L" joined the game.";
2402                                 BroadcastChatMessage(message);
2403                         }
2404                 }
2405
2406                 // Warnings about protocol version can be issued here
2407                 if(getClient(peer_id)->net_proto_version < LATEST_PROTOCOL_VERSION)
2408                 {
2409                         SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT'S "
2410                                         L"VERSION MAY NOT BE FULLY COMPATIBLE WITH THIS SERVER!");
2411                 }
2412
2413                 /*
2414                         Print out action
2415                 */
2416                 {
2417                         std::ostringstream os(std::ios_base::binary);
2418                         for(core::map<u16, RemoteClient*>::Iterator
2419                                 i = m_clients.getIterator();
2420                                 i.atEnd() == false; i++)
2421                         {
2422                                 RemoteClient *client = i.getNode()->getValue();
2423                                 assert(client->peer_id == i.getNode()->getKey());
2424                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2425                                         continue;
2426                                 // Get player
2427                                 Player *player = m_env->getPlayer(client->peer_id);
2428                                 if(!player)
2429                                         continue;
2430                                 // Get name of player
2431                                 os<<player->getName()<<" ";
2432                         }
2433
2434                         actionstream<<player->getName()<<" joins game. List of players: "
2435                                         <<os.str()<<std::endl;
2436                 }
2437
2438                 return;
2439         }
2440
2441         if(peer_ser_ver == SER_FMT_VER_INVALID)
2442         {
2443                 infostream<<"Server::ProcessData(): Cancelling: Peer"
2444                                 " serialization format invalid or not initialized."
2445                                 " Skipping incoming command="<<command<<std::endl;
2446                 return;
2447         }
2448
2449         Player *player = m_env->getPlayer(peer_id);
2450         if(player == NULL){
2451                 infostream<<"Server::ProcessData(): Cancelling: "
2452                                 "No player for peer_id="<<peer_id
2453                                 <<std::endl;
2454                 return;
2455         }
2456
2457         PlayerSAO *playersao = player->getPlayerSAO();
2458         if(playersao == NULL){
2459                 infostream<<"Server::ProcessData(): Cancelling: "
2460                                 "No player object for peer_id="<<peer_id
2461                                 <<std::endl;
2462                 return;
2463         }
2464
2465         if(command == TOSERVER_PLAYERPOS)
2466         {
2467                 if(datasize < 2+12+12+4+4)
2468                         return;
2469
2470                 u32 start = 0;
2471                 v3s32 ps = readV3S32(&data[start+2]);
2472                 v3s32 ss = readV3S32(&data[start+2+12]);
2473                 f32 pitch = (f32)readS32(&data[2+12+12]) / 100.0;
2474                 f32 yaw = (f32)readS32(&data[2+12+12+4]) / 100.0;
2475                 u32 keyPressed = 0;
2476                 if(datasize >= 2+12+12+4+4+4)
2477                         keyPressed = (u32)readU32(&data[2+12+12+4+4]);
2478                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
2479                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
2480                 pitch = wrapDegrees(pitch);
2481                 yaw = wrapDegrees(yaw);
2482
2483                 player->setPosition(position);
2484                 player->setSpeed(speed);
2485                 player->setPitch(pitch);
2486                 player->setYaw(yaw);
2487                 player->keyPressed=keyPressed;
2488                 player->control.up = (bool)(keyPressed&1);
2489                 player->control.down = (bool)(keyPressed&2);
2490                 player->control.left = (bool)(keyPressed&4);
2491                 player->control.right = (bool)(keyPressed&8);
2492                 player->control.jump = (bool)(keyPressed&16);
2493                 player->control.aux1 = (bool)(keyPressed&32);
2494                 player->control.sneak = (bool)(keyPressed&64);
2495                 player->control.LMB = (bool)(keyPressed&128);
2496                 player->control.RMB = (bool)(keyPressed&256);
2497
2498                 /*infostream<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
2499                                 <<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
2500                                 <<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
2501         }
2502         else if(command == TOSERVER_GOTBLOCKS)
2503         {
2504                 if(datasize < 2+1)
2505                         return;
2506
2507                 /*
2508                         [0] u16 command
2509                         [2] u8 count
2510                         [3] v3s16 pos_0
2511                         [3+6] v3s16 pos_1
2512                         ...
2513                 */
2514
2515                 u16 count = data[2];
2516                 for(u16 i=0; i<count; i++)
2517                 {
2518                         if((s16)datasize < 2+1+(i+1)*6)
2519                                 throw con::InvalidIncomingDataException
2520                                         ("GOTBLOCKS length is too short");
2521                         v3s16 p = readV3S16(&data[2+1+i*6]);
2522                         /*infostream<<"Server: GOTBLOCKS ("
2523                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2524                         RemoteClient *client = getClient(peer_id);
2525                         client->GotBlock(p);
2526                 }
2527         }
2528         else if(command == TOSERVER_DELETEDBLOCKS)
2529         {
2530                 if(datasize < 2+1)
2531                         return;
2532
2533                 /*
2534                         [0] u16 command
2535                         [2] u8 count
2536                         [3] v3s16 pos_0
2537                         [3+6] v3s16 pos_1
2538                         ...
2539                 */
2540
2541                 u16 count = data[2];
2542                 for(u16 i=0; i<count; i++)
2543                 {
2544                         if((s16)datasize < 2+1+(i+1)*6)
2545                                 throw con::InvalidIncomingDataException
2546                                         ("DELETEDBLOCKS length is too short");
2547                         v3s16 p = readV3S16(&data[2+1+i*6]);
2548                         /*infostream<<"Server: DELETEDBLOCKS ("
2549                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2550                         RemoteClient *client = getClient(peer_id);
2551                         client->SetBlockNotSent(p);
2552                 }
2553         }
2554         else if(command == TOSERVER_CLICK_OBJECT)
2555         {
2556                 infostream<<"Server: CLICK_OBJECT not supported anymore"<<std::endl;
2557                 return;
2558         }
2559         else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
2560         {
2561                 infostream<<"Server: CLICK_ACTIVEOBJECT not supported anymore"<<std::endl;
2562                 return;
2563         }
2564         else if(command == TOSERVER_GROUND_ACTION)
2565         {
2566                 infostream<<"Server: GROUND_ACTION not supported anymore"<<std::endl;
2567                 return;
2568
2569         }
2570         else if(command == TOSERVER_RELEASE)
2571         {
2572                 infostream<<"Server: RELEASE not supported anymore"<<std::endl;
2573                 return;
2574         }
2575         else if(command == TOSERVER_SIGNTEXT)
2576         {
2577                 infostream<<"Server: SIGNTEXT not supported anymore"
2578                                 <<std::endl;
2579                 return;
2580         }
2581         else if(command == TOSERVER_SIGNNODETEXT)
2582         {
2583                 infostream<<"Server: SIGNNODETEXT not supported anymore"
2584                                 <<std::endl;
2585                 return;
2586         }
2587         else if(command == TOSERVER_INVENTORY_ACTION)
2588         {
2589                 // Strip command and create a stream
2590                 std::string datastring((char*)&data[2], datasize-2);
2591                 verbosestream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
2592                 std::istringstream is(datastring, std::ios_base::binary);
2593                 // Create an action
2594                 InventoryAction *a = InventoryAction::deSerialize(is);
2595                 if(a == NULL)
2596                 {
2597                         infostream<<"TOSERVER_INVENTORY_ACTION: "
2598                                         <<"InventoryAction::deSerialize() returned NULL"
2599                                         <<std::endl;
2600                         return;
2601                 }
2602
2603                 // If something goes wrong, this player is to blame
2604                 RollbackScopeActor rollback_scope(m_rollback,
2605                                 std::string("player:")+player->getName());
2606
2607                 /*
2608                         Note: Always set inventory not sent, to repair cases
2609                         where the client made a bad prediction.
2610                 */
2611
2612                 /*
2613                         Handle restrictions and special cases of the move action
2614                 */
2615                 if(a->getType() == IACTION_MOVE)
2616                 {
2617                         IMoveAction *ma = (IMoveAction*)a;
2618
2619                         ma->from_inv.applyCurrentPlayer(player->getName());
2620                         ma->to_inv.applyCurrentPlayer(player->getName());
2621
2622                         setInventoryModified(ma->from_inv);
2623                         setInventoryModified(ma->to_inv);
2624
2625                         bool from_inv_is_current_player =
2626                                 (ma->from_inv.type == InventoryLocation::PLAYER) &&
2627                                 (ma->from_inv.name == player->getName());
2628
2629                         bool to_inv_is_current_player =
2630                                 (ma->to_inv.type == InventoryLocation::PLAYER) &&
2631                                 (ma->to_inv.name == player->getName());
2632
2633                         /*
2634                                 Disable moving items out of craftpreview
2635                         */
2636                         if(ma->from_list == "craftpreview")
2637                         {
2638                                 infostream<<"Ignoring IMoveAction from "
2639                                                 <<(ma->from_inv.dump())<<":"<<ma->from_list
2640                                                 <<" to "<<(ma->to_inv.dump())<<":"<<ma->to_list
2641                                                 <<" because src is "<<ma->from_list<<std::endl;
2642                                 delete a;
2643                                 return;
2644                         }
2645
2646                         /*
2647                                 Disable moving items into craftresult and craftpreview
2648                         */
2649                         if(ma->to_list == "craftpreview" || ma->to_list == "craftresult")
2650                         {
2651                                 infostream<<"Ignoring IMoveAction from "
2652                                                 <<(ma->from_inv.dump())<<":"<<ma->from_list
2653                                                 <<" to "<<(ma->to_inv.dump())<<":"<<ma->to_list
2654                                                 <<" because dst is "<<ma->to_list<<std::endl;
2655                                 delete a;
2656                                 return;
2657                         }
2658
2659                         // Disallow moving items in elsewhere than player's inventory
2660                         // if not allowed to interact
2661                         if(!checkPriv(player->getName(), "interact") &&
2662                                         (!from_inv_is_current_player ||
2663                                         !to_inv_is_current_player))
2664                         {
2665                                 infostream<<"Cannot move outside of player's inventory: "
2666                                                 <<"No interact privilege"<<std::endl;
2667                                 delete a;
2668                                 return;
2669                         }
2670                 }
2671                 /*
2672                         Handle restrictions and special cases of the drop action
2673                 */
2674                 else if(a->getType() == IACTION_DROP)
2675                 {
2676                         IDropAction *da = (IDropAction*)a;
2677
2678                         da->from_inv.applyCurrentPlayer(player->getName());
2679
2680                         setInventoryModified(da->from_inv);
2681
2682                         // Disallow dropping items if not allowed to interact
2683                         if(!checkPriv(player->getName(), "interact"))
2684                         {
2685                                 delete a;
2686                                 return;
2687                         }
2688                 }
2689                 /*
2690                         Handle restrictions and special cases of the craft action
2691                 */
2692                 else if(a->getType() == IACTION_CRAFT)
2693                 {
2694                         ICraftAction *ca = (ICraftAction*)a;
2695
2696                         ca->craft_inv.applyCurrentPlayer(player->getName());
2697
2698                         setInventoryModified(ca->craft_inv);
2699
2700                         //bool craft_inv_is_current_player =
2701                         //      (ca->craft_inv.type == InventoryLocation::PLAYER) &&
2702                         //      (ca->craft_inv.name == player->getName());
2703
2704                         // Disallow crafting if not allowed to interact
2705                         if(!checkPriv(player->getName(), "interact"))
2706                         {
2707                                 infostream<<"Cannot craft: "
2708                                                 <<"No interact privilege"<<std::endl;
2709                                 delete a;
2710                                 return;
2711                         }
2712                 }
2713
2714                 // Do the action
2715                 a->apply(this, playersao, this);
2716                 // Eat the action
2717                 delete a;
2718         }
2719         else if(command == TOSERVER_CHAT_MESSAGE)
2720         {
2721                 /*
2722                         u16 command
2723                         u16 length
2724                         wstring message
2725                 */
2726                 u8 buf[6];
2727                 std::string datastring((char*)&data[2], datasize-2);
2728                 std::istringstream is(datastring, std::ios_base::binary);
2729
2730                 // Read stuff
2731                 is.read((char*)buf, 2);
2732                 u16 len = readU16(buf);
2733
2734                 std::wstring message;
2735                 for(u16 i=0; i<len; i++)
2736                 {
2737                         is.read((char*)buf, 2);
2738                         message += (wchar_t)readU16(buf);
2739                 }
2740
2741                 // If something goes wrong, this player is to blame
2742                 RollbackScopeActor rollback_scope(m_rollback,
2743                                 std::string("player:")+player->getName());
2744
2745                 // Get player name of this client
2746                 std::wstring name = narrow_to_wide(player->getName());
2747
2748                 // Run script hook
2749                 bool ate = scriptapi_on_chat_message(m_lua, player->getName(),
2750                                 wide_to_narrow(message));
2751                 // If script ate the message, don't proceed
2752                 if(ate)
2753                         return;
2754
2755                 // Line to send to players
2756                 std::wstring line;
2757                 // Whether to send to the player that sent the line
2758                 bool send_to_sender = false;
2759                 // Whether to send to other players
2760                 bool send_to_others = false;
2761
2762                 // Commands are implemented in Lua, so only catch invalid
2763                 // commands that were not "eaten" and send an error back
2764                 if(message[0] == L'/')
2765                 {
2766                         message = message.substr(1);
2767                         send_to_sender = true;
2768                         if(message.length() == 0)
2769                                 line += L"-!- Empty command";
2770                         else
2771                                 line += L"-!- Invalid command: " + str_split(message, L' ')[0];
2772                 }
2773                 else
2774                 {
2775                         if(checkPriv(player->getName(), "shout")){
2776                                 line += L"<";
2777                                 line += name;
2778                                 line += L"> ";
2779                                 line += message;
2780                                 send_to_others = true;
2781                         } else {
2782                                 line += L"-!- You don't have permission to shout.";
2783                                 send_to_sender = true;
2784                         }
2785                 }
2786
2787                 if(line != L"")
2788                 {
2789                         if(send_to_others)
2790                                 actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
2791
2792                         /*
2793                                 Send the message to clients
2794                         */
2795                         for(core::map<u16, RemoteClient*>::Iterator
2796                                 i = m_clients.getIterator();
2797                                 i.atEnd() == false; i++)
2798                         {
2799                                 // Get client and check that it is valid
2800                                 RemoteClient *client = i.getNode()->getValue();
2801                                 assert(client->peer_id == i.getNode()->getKey());
2802                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2803                                         continue;
2804
2805                                 // Filter recipient
2806                                 bool sender_selected = (peer_id == client->peer_id);
2807                                 if(sender_selected == true && send_to_sender == false)
2808                                         continue;
2809                                 if(sender_selected == false && send_to_others == false)
2810                                         continue;
2811
2812                                 SendChatMessage(client->peer_id, line);
2813                         }
2814                 }
2815         }
2816         else if(command == TOSERVER_DAMAGE)
2817         {
2818                 std::string datastring((char*)&data[2], datasize-2);
2819                 std::istringstream is(datastring, std::ios_base::binary);
2820                 u8 damage = readU8(is);
2821
2822                 if(g_settings->getBool("enable_damage"))
2823                 {
2824                         actionstream<<player->getName()<<" damaged by "
2825                                         <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
2826                                         <<std::endl;
2827
2828                         playersao->setHP(playersao->getHP() - damage);
2829
2830                         if(playersao->getHP() == 0 && playersao->m_hp_not_sent)
2831                                 DiePlayer(peer_id);
2832
2833                         if(playersao->m_hp_not_sent)
2834                                 SendPlayerHP(peer_id);
2835                 }
2836         }
2837         else if(command == TOSERVER_PASSWORD)
2838         {
2839                 /*
2840                         [0] u16 TOSERVER_PASSWORD
2841                         [2] u8[28] old password
2842                         [30] u8[28] new password
2843                 */
2844
2845                 if(datasize != 2+PASSWORD_SIZE*2)
2846                         return;
2847                 /*char password[PASSWORD_SIZE];
2848                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2849                         password[i] = data[2+i];
2850                 password[PASSWORD_SIZE-1] = 0;*/
2851                 std::string oldpwd;
2852                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2853                 {
2854                         char c = data[2+i];
2855                         if(c == 0)
2856                                 break;
2857                         oldpwd += c;
2858                 }
2859                 std::string newpwd;
2860                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2861                 {
2862                         char c = data[2+PASSWORD_SIZE+i];
2863                         if(c == 0)
2864                                 break;
2865                         newpwd += c;
2866                 }
2867
2868                 if(!base64_is_valid(newpwd)){
2869                         infostream<<"Server: "<<player->getName()<<" supplied invalid password hash"<<std::endl;
2870                         // Wrong old password supplied!!
2871                         SendChatMessage(peer_id, L"Invalid new password hash supplied. Password NOT changed.");
2872                         return;
2873                 }
2874
2875                 infostream<<"Server: Client requests a password change from "
2876                                 <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
2877
2878                 std::string playername = player->getName();
2879
2880                 std::string checkpwd;
2881                 scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
2882
2883                 if(oldpwd != checkpwd)
2884                 {
2885                         infostream<<"Server: invalid old password"<<std::endl;
2886                         // Wrong old password supplied!!
2887                         SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
2888                         return;
2889                 }
2890
2891                 bool success = scriptapi_set_password(m_lua, playername, newpwd);
2892                 if(success){
2893                         actionstream<<player->getName()<<" changes password"<<std::endl;
2894                         SendChatMessage(peer_id, L"Password change successful.");
2895                 } else {
2896                         actionstream<<player->getName()<<" tries to change password but "
2897                                         <<"it fails"<<std::endl;
2898                         SendChatMessage(peer_id, L"Password change failed or inavailable.");
2899                 }
2900         }
2901         else if(command == TOSERVER_PLAYERITEM)
2902         {
2903                 if (datasize < 2+2)
2904                         return;
2905
2906                 u16 item = readU16(&data[2]);
2907                 playersao->setWieldIndex(item);
2908         }
2909         else if(command == TOSERVER_RESPAWN)
2910         {
2911                 if(player->hp != 0 || !g_settings->getBool("enable_damage"))
2912                         return;
2913
2914                 RespawnPlayer(peer_id);
2915
2916                 actionstream<<player->getName()<<" respawns at "
2917                                 <<PP(player->getPosition()/BS)<<std::endl;
2918
2919                 // ActiveObject is added to environment in AsyncRunStep after
2920                 // the previous addition has been succesfully removed
2921         }
2922         else if(command == TOSERVER_REQUEST_MEDIA) {
2923                 std::string datastring((char*)&data[2], datasize-2);
2924                 std::istringstream is(datastring, std::ios_base::binary);
2925
2926                 core::list<MediaRequest> tosend;
2927                 u16 numfiles = readU16(is);
2928
2929                 infostream<<"Sending "<<numfiles<<" files to "
2930                                 <<getPlayerName(peer_id)<<std::endl;
2931                 verbosestream<<"TOSERVER_REQUEST_MEDIA: "<<std::endl;
2932
2933                 for(int i = 0; i < numfiles; i++) {
2934                         std::string name = deSerializeString(is);
2935                         tosend.push_back(MediaRequest(name));
2936                         verbosestream<<"TOSERVER_REQUEST_MEDIA: requested file "
2937                                         <<name<<std::endl;
2938                 }
2939
2940                 sendRequestedMedia(peer_id, tosend);
2941
2942                 // Now the client should know about everything
2943                 // (definitions and files)
2944                 getClient(peer_id)->definitions_sent = true;
2945         }
2946         else if(command == TOSERVER_RECEIVED_MEDIA) {
2947                 getClient(peer_id)->definitions_sent = true;
2948         }
2949         else if(command == TOSERVER_INTERACT)
2950         {
2951                 std::string datastring((char*)&data[2], datasize-2);
2952                 std::istringstream is(datastring, std::ios_base::binary);
2953
2954                 /*
2955                         [0] u16 command
2956                         [2] u8 action
2957                         [3] u16 item
2958                         [5] u32 length of the next item
2959                         [9] serialized PointedThing
2960                         actions:
2961                         0: start digging (from undersurface) or use
2962                         1: stop digging (all parameters ignored)
2963                         2: digging completed
2964                         3: place block or item (to abovesurface)
2965                         4: use item
2966                 */
2967                 u8 action = readU8(is);
2968                 u16 item_i = readU16(is);
2969                 std::istringstream tmp_is(deSerializeLongString(is), std::ios::binary);
2970                 PointedThing pointed;
2971                 pointed.deSerialize(tmp_is);
2972
2973                 verbosestream<<"TOSERVER_INTERACT: action="<<(int)action<<", item="
2974                                 <<item_i<<", pointed="<<pointed.dump()<<std::endl;
2975
2976                 if(player->hp == 0)
2977                 {
2978                         verbosestream<<"TOSERVER_INTERACT: "<<player->getName()
2979                                 <<" tried to interact, but is dead!"<<std::endl;
2980                         return;
2981                 }
2982
2983                 v3f player_pos = playersao->getLastGoodPosition();
2984
2985                 // Update wielded item
2986                 playersao->setWieldIndex(item_i);
2987
2988                 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
2989                 v3s16 p_under = pointed.node_undersurface;
2990                 v3s16 p_above = pointed.node_abovesurface;
2991
2992                 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
2993                 ServerActiveObject *pointed_object = NULL;
2994                 if(pointed.type == POINTEDTHING_OBJECT)
2995                 {
2996                         pointed_object = m_env->getActiveObject(pointed.object_id);
2997                         if(pointed_object == NULL)
2998                         {
2999                                 verbosestream<<"TOSERVER_INTERACT: "
3000                                         "pointed object is NULL"<<std::endl;
3001                                 return;
3002                         }
3003
3004                 }
3005
3006                 v3f pointed_pos_under = player_pos;
3007                 v3f pointed_pos_above = player_pos;
3008                 if(pointed.type == POINTEDTHING_NODE)
3009                 {
3010                         pointed_pos_under = intToFloat(p_under, BS);
3011                         pointed_pos_above = intToFloat(p_above, BS);
3012                 }
3013                 else if(pointed.type == POINTEDTHING_OBJECT)
3014                 {
3015                         pointed_pos_under = pointed_object->getBasePosition();
3016                         pointed_pos_above = pointed_pos_under;
3017                 }
3018
3019                 /*
3020                         Check that target is reasonably close
3021                         (only when digging or placing things)
3022                 */
3023                 if(action == 0 || action == 2 || action == 3)
3024                 {
3025                         float d = player_pos.getDistanceFrom(pointed_pos_under);
3026                         float max_d = BS * 14; // Just some large enough value
3027                         if(d > max_d){
3028                                 actionstream<<"Player "<<player->getName()
3029                                                 <<" tried to access "<<pointed.dump()
3030                                                 <<" from too far: "
3031                                                 <<"d="<<d<<", max_d="<<max_d
3032                                                 <<". ignoring."<<std::endl;
3033                                 // Re-send block to revert change on client-side
3034                                 RemoteClient *client = getClient(peer_id);
3035                                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
3036                                 client->SetBlockNotSent(blockpos);
3037                                 // Do nothing else
3038                                 return;
3039                         }
3040                 }
3041
3042                 /*
3043                         Make sure the player is allowed to do it
3044                 */
3045                 if(!checkPriv(player->getName(), "interact"))
3046                 {
3047                         actionstream<<player->getName()<<" attempted to interact with "
3048                                         <<pointed.dump()<<" without 'interact' privilege"
3049                                         <<std::endl;
3050                         // Re-send block to revert change on client-side
3051                         RemoteClient *client = getClient(peer_id);
3052                         // Digging completed -> under
3053                         if(action == 2){
3054                                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
3055                                 client->SetBlockNotSent(blockpos);
3056                         }
3057                         // Placement -> above
3058                         if(action == 3){
3059                                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
3060                                 client->SetBlockNotSent(blockpos);
3061                         }
3062                         return;
3063                 }
3064
3065                 /*
3066                         If something goes wrong, this player is to blame
3067                 */
3068                 RollbackScopeActor rollback_scope(m_rollback,
3069                                 std::string("player:")+player->getName());
3070
3071                 /*
3072                         0: start digging or punch object
3073                 */
3074                 if(action == 0)
3075                 {
3076                         if(pointed.type == POINTEDTHING_NODE)
3077                         {
3078                                 /*
3079                                         NOTE: This can be used in the future to check if
3080                                         somebody is cheating, by checking the timing.
3081                                 */
3082                                 MapNode n(CONTENT_IGNORE);
3083                                 try
3084                                 {
3085                                         n = m_env->getMap().getNode(p_under);
3086                                 }
3087                                 catch(InvalidPositionException &e)
3088                                 {
3089                                         infostream<<"Server: Not punching: Node not found."
3090                                                         <<" Adding block to emerge queue."
3091                                                         <<std::endl;
3092                                         m_emerge_queue.addBlock(peer_id,
3093                                                         getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
3094                                 }
3095                                 if(n.getContent() != CONTENT_IGNORE)
3096                                         scriptapi_node_on_punch(m_lua, p_under, n, playersao);
3097                                 // Cheat prevention
3098                                 playersao->noCheatDigStart(p_under);
3099                         }
3100                         else if(pointed.type == POINTEDTHING_OBJECT)
3101                         {
3102                                 // Skip if object has been removed
3103                                 if(pointed_object->m_removed)
3104                                         return;
3105
3106                                 actionstream<<player->getName()<<" punches object "
3107                                                 <<pointed.object_id<<": "
3108                                                 <<pointed_object->getDescription()<<std::endl;
3109
3110                                 ItemStack punchitem = playersao->getWieldedItem();
3111                                 ToolCapabilities toolcap =
3112                                                 punchitem.getToolCapabilities(m_itemdef);
3113                                 v3f dir = (pointed_object->getBasePosition() -
3114                                                 (player->getPosition() + player->getEyeOffset())
3115                                                         ).normalize();
3116                                 float time_from_last_punch =
3117                                         playersao->resetTimeFromLastPunch();
3118                                 pointed_object->punch(dir, &toolcap, playersao,
3119                                                 time_from_last_punch);
3120                         }
3121
3122                 } // action == 0
3123
3124                 /*
3125                         1: stop digging
3126                 */
3127                 else if(action == 1)
3128                 {
3129                 } // action == 1
3130
3131                 /*
3132                         2: Digging completed
3133                 */
3134                 else if(action == 2)
3135                 {
3136                         // Only digging of nodes
3137                         if(pointed.type == POINTEDTHING_NODE)
3138                         {
3139                                 MapNode n(CONTENT_IGNORE);
3140                                 try
3141                                 {
3142                                         n = m_env->getMap().getNode(p_under);
3143                                 }
3144                                 catch(InvalidPositionException &e)
3145                                 {
3146                                         infostream<<"Server: Not finishing digging: Node not found."
3147                                                         <<" Adding block to emerge queue."
3148                                                         <<std::endl;
3149                                         m_emerge_queue.addBlock(peer_id,
3150                                                         getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
3151                                 }
3152
3153                                 /* Cheat prevention */
3154                                 bool is_valid_dig = true;
3155                                 if(!isSingleplayer() && !g_settings->getBool("disable_anticheat"))
3156                                 {
3157                                         v3s16 nocheat_p = playersao->getNoCheatDigPos();
3158                                         float nocheat_t = playersao->getNoCheatDigTime();
3159                                         playersao->noCheatDigEnd();
3160                                         // If player didn't start digging this, ignore dig
3161                                         if(nocheat_p != p_under){
3162                                                 infostream<<"Server: NoCheat: "<<player->getName()
3163                                                                 <<" started digging "
3164                                                                 <<PP(nocheat_p)<<" and completed digging "
3165                                                                 <<PP(p_under)<<"; not digging."<<std::endl;
3166                                                 is_valid_dig = false;
3167                                         }
3168                                         // Get player's wielded item
3169                                         ItemStack playeritem;
3170                                         InventoryList *mlist = playersao->getInventory()->getList("main");
3171                                         if(mlist != NULL)
3172                                                 playeritem = mlist->getItem(playersao->getWieldIndex());
3173                                         ToolCapabilities playeritem_toolcap =
3174                                                         playeritem.getToolCapabilities(m_itemdef);
3175                                         // Get diggability and expected digging time
3176                                         DigParams params = getDigParams(m_nodedef->get(n).groups,
3177                                                         &playeritem_toolcap);
3178                                         // If can't dig, try hand
3179                                         if(!params.diggable){
3180                                                 const ItemDefinition &hand = m_itemdef->get("");
3181                                                 const ToolCapabilities *tp = hand.tool_capabilities;
3182                                                 if(tp)
3183                                                         params = getDigParams(m_nodedef->get(n).groups, tp);
3184                                         }
3185                                         // If can't dig, ignore dig
3186                                         if(!params.diggable){
3187                                                 infostream<<"Server: NoCheat: "<<player->getName()
3188                                                                 <<" completed digging "<<PP(p_under)
3189                                                                 <<", which is not diggable with tool. not digging."
3190                                                                 <<std::endl;
3191                                                 is_valid_dig = false;
3192                                         }
3193                                         // If time is considerably too short, ignore dig
3194                                         // Check time only for medium and slow timed digs
3195                                         if(params.diggable && params.time > 0.3 && nocheat_t < 0.5 * params.time){
3196                                                 infostream<<"Server: NoCheat: "<<player->getName()
3197                                                                 <<" completed digging "
3198                                                                 <<PP(p_under)<<" in "<<nocheat_t<<"s; expected "
3199                                                                 <<params.time<<"s; not digging."<<std::endl;
3200                                                 is_valid_dig = false;
3201                                         }
3202                                 }
3203
3204                                 /* Actually dig node */
3205
3206                                 if(is_valid_dig && n.getContent() != CONTENT_IGNORE)
3207                                         scriptapi_node_on_dig(m_lua, p_under, n, playersao);
3208
3209                                 // Send unusual result (that is, node not being removed)
3210                                 if(m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR)
3211                                 {
3212                                         // Re-send block to revert change on client-side
3213                                         RemoteClient *client = getClient(peer_id);
3214                                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
3215                                         client->SetBlockNotSent(blockpos);
3216                                 }
3217                         }
3218                 } // action == 2
3219
3220                 /*
3221                         3: place block or right-click object
3222                 */
3223                 else if(action == 3)
3224                 {
3225                         ItemStack item = playersao->getWieldedItem();
3226
3227                         // Reset build time counter
3228                         if(pointed.type == POINTEDTHING_NODE &&
3229                                         item.getDefinition(m_itemdef).type == ITEM_NODE)
3230                                 getClient(peer_id)->m_time_from_building = 0.0;
3231
3232                         if(pointed.type == POINTEDTHING_OBJECT)
3233                         {
3234                                 // Right click object
3235
3236                                 // Skip if object has been removed
3237                                 if(pointed_object->m_removed)
3238                                         return;
3239
3240                                 actionstream<<player->getName()<<" right-clicks object "
3241                                                 <<pointed.object_id<<": "
3242                                                 <<pointed_object->getDescription()<<std::endl;
3243
3244                                 // Do stuff
3245                                 pointed_object->rightClick(playersao);
3246                         }
3247                         else if(scriptapi_item_on_place(m_lua,
3248                                         item, playersao, pointed))
3249                         {
3250                                 // Placement was handled in lua
3251
3252                                 // Apply returned ItemStack
3253                                 playersao->setWieldedItem(item);
3254                         }
3255
3256                         // If item has node placement prediction, always send the above
3257                         // node to make sure the client knows what exactly happened
3258                         if(item.getDefinition(m_itemdef).node_placement_prediction != ""){
3259                                 RemoteClient *client = getClient(peer_id);
3260                                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
3261                                 client->SetBlockNotSent(blockpos);
3262                         }
3263                 } // action == 3
3264
3265                 /*
3266                         4: use
3267                 */
3268                 else if(action == 4)
3269                 {
3270                         ItemStack item = playersao->getWieldedItem();
3271
3272                         actionstream<<player->getName()<<" uses "<<item.name
3273                                         <<", pointing at "<<pointed.dump()<<std::endl;
3274
3275                         if(scriptapi_item_on_use(m_lua,
3276                                         item, playersao, pointed))
3277                         {
3278                                 // Apply returned ItemStack
3279                                 playersao->setWieldedItem(item);
3280                         }
3281
3282                 } // action == 4
3283                 
3284
3285                 /*
3286                         Catch invalid actions
3287                 */
3288                 else
3289                 {
3290                         infostream<<"WARNING: Server: Invalid action "
3291                                         <<action<<std::endl;
3292                 }
3293         }
3294         else if(command == TOSERVER_REMOVED_SOUNDS)
3295         {
3296                 std::string datastring((char*)&data[2], datasize-2);
3297                 std::istringstream is(datastring, std::ios_base::binary);
3298
3299                 int num = readU16(is);
3300                 for(int k=0; k<num; k++){
3301                         s32 id = readS32(is);
3302                         std::map<s32, ServerPlayingSound>::iterator i =
3303                                         m_playing_sounds.find(id);
3304                         if(i == m_playing_sounds.end())
3305                                 continue;
3306                         ServerPlayingSound &psound = i->second;
3307                         psound.clients.erase(peer_id);
3308                         if(psound.clients.size() == 0)
3309                                 m_playing_sounds.erase(i++);
3310                 }
3311         }
3312         else if(command == TOSERVER_NODEMETA_FIELDS)
3313         {
3314                 std::string datastring((char*)&data[2], datasize-2);
3315                 std::istringstream is(datastring, std::ios_base::binary);
3316
3317                 v3s16 p = readV3S16(is);
3318                 std::string formname = deSerializeString(is);
3319                 int num = readU16(is);
3320                 std::map<std::string, std::string> fields;
3321                 for(int k=0; k<num; k++){
3322                         std::string fieldname = deSerializeString(is);
3323                         std::string fieldvalue = deSerializeLongString(is);
3324                         fields[fieldname] = fieldvalue;
3325                 }
3326
3327                 // If something goes wrong, this player is to blame
3328                 RollbackScopeActor rollback_scope(m_rollback,
3329                                 std::string("player:")+player->getName());
3330
3331                 // Check the target node for rollback data; leave others unnoticed
3332                 RollbackNode rn_old(&m_env->getMap(), p, this);
3333
3334                 scriptapi_node_on_receive_fields(m_lua, p, formname, fields,
3335                                 playersao);
3336
3337                 // Report rollback data
3338                 RollbackNode rn_new(&m_env->getMap(), p, this);
3339                 if(rollback() && rn_new != rn_old){
3340                         RollbackAction action;
3341                         action.setSetNode(p, rn_old, rn_new);
3342                         rollback()->reportAction(action);
3343                 }
3344         }
3345         else if(command == TOSERVER_INVENTORY_FIELDS)
3346         {
3347                 std::string datastring((char*)&data[2], datasize-2);
3348                 std::istringstream is(datastring, std::ios_base::binary);
3349
3350                 std::string formname = deSerializeString(is);
3351                 int num = readU16(is);
3352                 std::map<std::string, std::string> fields;
3353                 for(int k=0; k<num; k++){
3354                         std::string fieldname = deSerializeString(is);
3355                         std::string fieldvalue = deSerializeLongString(is);
3356                         fields[fieldname] = fieldvalue;
3357                 }
3358
3359                 scriptapi_on_player_receive_fields(m_lua, playersao, formname, fields);
3360         }
3361         else
3362         {
3363                 infostream<<"Server::ProcessData(): Ignoring "
3364                                 "unknown command "<<command<<std::endl;
3365         }
3366
3367         } //try
3368         catch(SendFailedException &e)
3369         {
3370                 errorstream<<"Server::ProcessData(): SendFailedException: "
3371                                 <<"what="<<e.what()
3372                                 <<std::endl;
3373         }
3374 }
3375
3376 void Server::onMapEditEvent(MapEditEvent *event)
3377 {
3378         //infostream<<"Server::onMapEditEvent()"<<std::endl;
3379         if(m_ignore_map_edit_events)
3380                 return;
3381         if(m_ignore_map_edit_events_area.contains(event->getArea()))
3382                 return;
3383         MapEditEvent *e = event->clone();
3384         m_unsent_map_edit_queue.push_back(e);
3385 }
3386
3387 Inventory* Server::getInventory(const InventoryLocation &loc)
3388 {
3389         switch(loc.type){
3390         case InventoryLocation::UNDEFINED:
3391         {}
3392         break;
3393         case InventoryLocation::CURRENT_PLAYER:
3394         {}
3395         break;
3396         case InventoryLocation::PLAYER:
3397         {
3398                 Player *player = m_env->getPlayer(loc.name.c_str());
3399                 if(!player)
3400                         return NULL;
3401                 PlayerSAO *playersao = player->getPlayerSAO();
3402                 if(!playersao)
3403                         return NULL;
3404                 return playersao->getInventory();
3405         }
3406         break;
3407         case InventoryLocation::NODEMETA:
3408         {
3409                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
3410                 if(!meta)
3411                         return NULL;
3412                 return meta->getInventory();
3413         }
3414         break;
3415         case InventoryLocation::DETACHED:
3416         {
3417                 if(m_detached_inventories.count(loc.name) == 0)
3418                         return NULL;
3419                 return m_detached_inventories[loc.name];
3420         }
3421         break;
3422         default:
3423                 assert(0);
3424         }
3425         return NULL;
3426 }
3427 void Server::setInventoryModified(const InventoryLocation &loc)
3428 {
3429         switch(loc.type){
3430         case InventoryLocation::UNDEFINED:
3431         {}
3432         break;
3433         case InventoryLocation::PLAYER:
3434         {
3435                 Player *player = m_env->getPlayer(loc.name.c_str());
3436                 if(!player)
3437                         return;
3438                 PlayerSAO *playersao = player->getPlayerSAO();
3439                 if(!playersao)
3440                         return;
3441                 playersao->m_inventory_not_sent = true;
3442                 playersao->m_wielded_item_not_sent = true;
3443         }
3444         break;
3445         case InventoryLocation::NODEMETA:
3446         {
3447                 v3s16 blockpos = getNodeBlockPos(loc.p);
3448
3449                 MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
3450                 if(block)
3451                         block->raiseModified(MOD_STATE_WRITE_NEEDED);
3452
3453                 setBlockNotSent(blockpos);
3454         }
3455         break;
3456         case InventoryLocation::DETACHED:
3457         {
3458                 sendDetachedInventoryToAll(loc.name);
3459         }
3460         break;
3461         default:
3462                 assert(0);
3463         }
3464 }
3465
3466 core::list<PlayerInfo> Server::getPlayerInfo()
3467 {
3468         DSTACK(__FUNCTION_NAME);
3469         JMutexAutoLock envlock(m_env_mutex);
3470         JMutexAutoLock conlock(m_con_mutex);
3471
3472         core::list<PlayerInfo> list;
3473
3474         core::list<Player*> players = m_env->getPlayers();
3475
3476         core::list<Player*>::Iterator i;
3477         for(i = players.begin();
3478                         i != players.end(); i++)
3479         {
3480                 PlayerInfo info;
3481
3482                 Player *player = *i;
3483
3484                 try{
3485                         // Copy info from connection to info struct
3486                         info.id = player->peer_id;
3487                         info.address = m_con.GetPeerAddress(player->peer_id);
3488                         info.avg_rtt = m_con.GetPeerAvgRTT(player->peer_id);
3489                 }
3490                 catch(con::PeerNotFoundException &e)
3491                 {
3492                         // Set dummy peer info
3493                         info.id = 0;
3494                         info.address = Address(0,0,0,0,0);
3495                         info.avg_rtt = 0.0;
3496                 }
3497
3498                 snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName());
3499                 info.position = player->getPosition();
3500
3501                 list.push_back(info);
3502         }
3503
3504         return list;
3505 }
3506
3507
3508 void Server::peerAdded(con::Peer *peer)
3509 {
3510         DSTACK(__FUNCTION_NAME);
3511         verbosestream<<"Server::peerAdded(): peer->id="
3512                         <<peer->id<<std::endl;
3513
3514         PeerChange c;
3515         c.type = PEER_ADDED;
3516         c.peer_id = peer->id;
3517         c.timeout = false;
3518         m_peer_change_queue.push_back(c);
3519 }
3520
3521 void Server::deletingPeer(con::Peer *peer, bool timeout)
3522 {
3523         DSTACK(__FUNCTION_NAME);
3524         verbosestream<<"Server::deletingPeer(): peer->id="
3525                         <<peer->id<<", timeout="<<timeout<<std::endl;
3526
3527         PeerChange c;
3528         c.type = PEER_REMOVED;
3529         c.peer_id = peer->id;
3530         c.timeout = timeout;
3531         m_peer_change_queue.push_back(c);
3532 }
3533
3534 /*
3535         Static send methods
3536 */
3537
3538 void Server::SendHP(con::Connection &con, u16 peer_id, u8 hp)
3539 {
3540         DSTACK(__FUNCTION_NAME);
3541         std::ostringstream os(std::ios_base::binary);
3542
3543         writeU16(os, TOCLIENT_HP);
3544         writeU8(os, hp);
3545
3546         // Make data buffer
3547         std::string s = os.str();
3548         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3549         // Send as reliable
3550         con.Send(peer_id, 0, data, true);
3551 }
3552
3553 void Server::SendAccessDenied(con::Connection &con, u16 peer_id,
3554                 const std::wstring &reason)
3555 {
3556         DSTACK(__FUNCTION_NAME);
3557         std::ostringstream os(std::ios_base::binary);
3558
3559         writeU16(os, TOCLIENT_ACCESS_DENIED);
3560         os<<serializeWideString(reason);
3561
3562         // Make data buffer
3563         std::string s = os.str();
3564         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3565         // Send as reliable
3566         con.Send(peer_id, 0, data, true);
3567 }
3568
3569 void Server::SendDeathscreen(con::Connection &con, u16 peer_id,
3570                 bool set_camera_point_target, v3f camera_point_target)
3571 {
3572         DSTACK(__FUNCTION_NAME);
3573         std::ostringstream os(std::ios_base::binary);
3574
3575         writeU16(os, TOCLIENT_DEATHSCREEN);
3576         writeU8(os, set_camera_point_target);
3577         writeV3F1000(os, camera_point_target);
3578
3579         // Make data buffer
3580         std::string s = os.str();
3581         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3582         // Send as reliable
3583         con.Send(peer_id, 0, data, true);
3584 }
3585
3586 void Server::SendItemDef(con::Connection &con, u16 peer_id,
3587                 IItemDefManager *itemdef)
3588 {
3589         DSTACK(__FUNCTION_NAME);
3590         std::ostringstream os(std::ios_base::binary);
3591
3592         /*
3593                 u16 command
3594                 u32 length of the next item
3595                 zlib-compressed serialized ItemDefManager
3596         */
3597         writeU16(os, TOCLIENT_ITEMDEF);
3598         std::ostringstream tmp_os(std::ios::binary);
3599         itemdef->serialize(tmp_os);
3600         std::ostringstream tmp_os2(std::ios::binary);
3601         compressZlib(tmp_os.str(), tmp_os2);
3602         os<<serializeLongString(tmp_os2.str());
3603
3604         // Make data buffer
3605         std::string s = os.str();
3606         verbosestream<<"Server: Sending item definitions to id("<<peer_id
3607                         <<"): size="<<s.size()<<std::endl;
3608         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3609         // Send as reliable
3610         con.Send(peer_id, 0, data, true);
3611 }
3612
3613 void Server::SendNodeDef(con::Connection &con, u16 peer_id,
3614                 INodeDefManager *nodedef, u16 protocol_version)
3615 {
3616         DSTACK(__FUNCTION_NAME);
3617         std::ostringstream os(std::ios_base::binary);
3618
3619         /*
3620                 u16 command
3621                 u32 length of the next item
3622                 zlib-compressed serialized NodeDefManager
3623         */
3624         writeU16(os, TOCLIENT_NODEDEF);
3625         std::ostringstream tmp_os(std::ios::binary);
3626         nodedef->serialize(tmp_os, protocol_version);
3627         std::ostringstream tmp_os2(std::ios::binary);
3628         compressZlib(tmp_os.str(), tmp_os2);
3629         os<<serializeLongString(tmp_os2.str());
3630
3631         // Make data buffer
3632         std::string s = os.str();
3633         verbosestream<<"Server: Sending node definitions to id("<<peer_id
3634                         <<"): size="<<s.size()<<std::endl;
3635         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3636         // Send as reliable
3637         con.Send(peer_id, 0, data, true);
3638 }
3639
3640 /*
3641         Non-static send methods
3642 */
3643
3644 void Server::SendInventory(u16 peer_id)
3645 {
3646         DSTACK(__FUNCTION_NAME);
3647
3648         PlayerSAO *playersao = getPlayerSAO(peer_id);
3649         assert(playersao);
3650
3651         playersao->m_inventory_not_sent = false;
3652
3653         /*
3654                 Serialize it
3655         */
3656
3657         std::ostringstream os;
3658         playersao->getInventory()->serialize(os);
3659
3660         std::string s = os.str();
3661
3662         SharedBuffer<u8> data(s.size()+2);
3663         writeU16(&data[0], TOCLIENT_INVENTORY);
3664         memcpy(&data[2], s.c_str(), s.size());
3665
3666         // Send as reliable
3667         m_con.Send(peer_id, 0, data, true);
3668 }
3669
3670 void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
3671 {
3672         DSTACK(__FUNCTION_NAME);
3673
3674         std::ostringstream os(std::ios_base::binary);
3675         u8 buf[12];
3676
3677         // Write command
3678         writeU16(buf, TOCLIENT_CHAT_MESSAGE);
3679         os.write((char*)buf, 2);
3680
3681         // Write length
3682         writeU16(buf, message.size());
3683         os.write((char*)buf, 2);
3684
3685         // Write string
3686         for(u32 i=0; i<message.size(); i++)
3687         {
3688                 u16 w = message[i];
3689                 writeU16(buf, w);
3690                 os.write((char*)buf, 2);
3691         }
3692
3693         // Make data buffer
3694         std::string s = os.str();
3695         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3696         // Send as reliable
3697         m_con.Send(peer_id, 0, data, true);
3698 }
3699 void Server::SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname)
3700 {
3701         DSTACK(__FUNCTION_NAME);
3702
3703         std::ostringstream os(std::ios_base::binary);
3704         u8 buf[12];
3705
3706         // Write command
3707         writeU16(buf, TOCLIENT_SHOW_FORMSPEC);
3708         os.write((char*)buf, 2);
3709         os<<serializeLongString(formspec);
3710         os<<serializeString(formname);
3711
3712         // Make data buffer
3713         std::string s = os.str();
3714         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3715         // Send as reliable
3716         m_con.Send(peer_id, 0, data, true);
3717 }
3718
3719 void Server::BroadcastChatMessage(const std::wstring &message)
3720 {
3721         for(core::map<u16, RemoteClient*>::Iterator
3722                 i = m_clients.getIterator();
3723                 i.atEnd() == false; i++)
3724         {
3725                 // Get client and check that it is valid
3726                 RemoteClient *client = i.getNode()->getValue();
3727                 assert(client->peer_id == i.getNode()->getKey());
3728                 if(client->serialization_version == SER_FMT_VER_INVALID)
3729                         continue;
3730
3731                 SendChatMessage(client->peer_id, message);
3732         }
3733 }
3734
3735 void Server::SendPlayerHP(u16 peer_id)
3736 {
3737         DSTACK(__FUNCTION_NAME);
3738         PlayerSAO *playersao = getPlayerSAO(peer_id);
3739         assert(playersao);
3740         playersao->m_hp_not_sent = false;
3741         SendHP(m_con, peer_id, playersao->getHP());
3742 }
3743
3744 void Server::SendMovePlayer(u16 peer_id)
3745 {
3746         DSTACK(__FUNCTION_NAME);
3747         Player *player = m_env->getPlayer(peer_id);
3748         assert(player);
3749
3750         std::ostringstream os(std::ios_base::binary);
3751         writeU16(os, TOCLIENT_MOVE_PLAYER);
3752         writeV3F1000(os, player->getPosition());
3753         writeF1000(os, player->getPitch());
3754         writeF1000(os, player->getYaw());
3755
3756         {
3757                 v3f pos = player->getPosition();
3758                 f32 pitch = player->getPitch();
3759                 f32 yaw = player->getYaw();
3760                 verbosestream<<"Server: Sending TOCLIENT_MOVE_PLAYER"
3761                                 <<" pos=("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
3762                                 <<" pitch="<<pitch
3763                                 <<" yaw="<<yaw
3764                                 <<std::endl;
3765         }
3766
3767         // Make data buffer
3768         std::string s = os.str();
3769         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3770         // Send as reliable
3771         m_con.Send(peer_id, 0, data, true);
3772 }
3773
3774 void Server::SendPlayerPrivileges(u16 peer_id)
3775 {
3776         Player *player = m_env->getPlayer(peer_id);
3777         assert(player);
3778         if(player->peer_id == PEER_ID_INEXISTENT)
3779                 return;
3780
3781         std::set<std::string> privs;
3782         scriptapi_get_auth(m_lua, player->getName(), NULL, &privs);
3783
3784         std::ostringstream os(std::ios_base::binary);
3785         writeU16(os, TOCLIENT_PRIVILEGES);
3786         writeU16(os, privs.size());
3787         for(std::set<std::string>::const_iterator i = privs.begin();
3788                         i != privs.end(); i++){
3789                 os<<serializeString(*i);
3790         }
3791
3792         // Make data buffer
3793         std::string s = os.str();
3794         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3795         // Send as reliable
3796         m_con.Send(peer_id, 0, data, true);
3797 }
3798
3799 void Server::SendPlayerInventoryFormspec(u16 peer_id)
3800 {
3801         Player *player = m_env->getPlayer(peer_id);
3802         assert(player);
3803         if(player->peer_id == PEER_ID_INEXISTENT)
3804                 return;
3805
3806         std::ostringstream os(std::ios_base::binary);
3807         writeU16(os, TOCLIENT_INVENTORY_FORMSPEC);
3808         os<<serializeLongString(player->inventory_formspec);
3809
3810         // Make data buffer
3811         std::string s = os.str();
3812         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3813         // Send as reliable
3814         m_con.Send(peer_id, 0, data, true);
3815 }
3816
3817 s32 Server::playSound(const SimpleSoundSpec &spec,
3818                 const ServerSoundParams &params)
3819 {
3820         // Find out initial position of sound
3821         bool pos_exists = false;
3822         v3f pos = params.getPos(m_env, &pos_exists);
3823         // If position is not found while it should be, cancel sound
3824         if(pos_exists != (params.type != ServerSoundParams::SSP_LOCAL))
3825                 return -1;
3826         // Filter destination clients
3827         std::set<RemoteClient*> dst_clients;
3828         if(params.to_player != "")
3829         {
3830                 Player *player = m_env->getPlayer(params.to_player.c_str());
3831                 if(!player){
3832                         infostream<<"Server::playSound: Player \""<<params.to_player
3833                                         <<"\" not found"<<std::endl;
3834                         return -1;
3835                 }
3836                 if(player->peer_id == PEER_ID_INEXISTENT){
3837                         infostream<<"Server::playSound: Player \""<<params.to_player
3838                                         <<"\" not connected"<<std::endl;
3839                         return -1;
3840                 }
3841                 RemoteClient *client = getClient(player->peer_id);
3842                 dst_clients.insert(client);
3843         }
3844         else
3845         {
3846                 for(core::map<u16, RemoteClient*>::Iterator
3847                                 i = m_clients.getIterator(); i.atEnd() == false; i++)
3848                 {
3849                         RemoteClient *client = i.getNode()->getValue();
3850                         Player *player = m_env->getPlayer(client->peer_id);
3851                         if(!player)
3852                                 continue;
3853                         if(pos_exists){
3854                                 if(player->getPosition().getDistanceFrom(pos) >
3855                                                 params.max_hear_distance)
3856                                         continue;
3857                         }
3858                         dst_clients.insert(client);
3859                 }
3860         }
3861         if(dst_clients.size() == 0)
3862                 return -1;
3863         // Create the sound
3864         s32 id = m_next_sound_id++;
3865         // The sound will exist as a reference in m_playing_sounds
3866         m_playing_sounds[id] = ServerPlayingSound();
3867         ServerPlayingSound &psound = m_playing_sounds[id];
3868         psound.params = params;
3869         for(std::set<RemoteClient*>::iterator i = dst_clients.begin();
3870                         i != dst_clients.end(); i++)
3871                 psound.clients.insert((*i)->peer_id);
3872         // Create packet
3873         std::ostringstream os(std::ios_base::binary);
3874         writeU16(os, TOCLIENT_PLAY_SOUND);
3875         writeS32(os, id);
3876         os<<serializeString(spec.name);
3877         writeF1000(os, spec.gain * params.gain);
3878         writeU8(os, params.type);
3879         writeV3F1000(os, pos);
3880         writeU16(os, params.object);
3881         writeU8(os, params.loop);
3882         // Make data buffer
3883         std::string s = os.str();
3884         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3885         // Send
3886         for(std::set<RemoteClient*>::iterator i = dst_clients.begin();
3887                         i != dst_clients.end(); i++){
3888                 // Send as reliable
3889                 m_con.Send((*i)->peer_id, 0, data, true);
3890         }
3891         return id;
3892 }
3893 void Server::stopSound(s32 handle)
3894 {
3895         // Get sound reference
3896         std::map<s32, ServerPlayingSound>::iterator i =
3897                         m_playing_sounds.find(handle);
3898         if(i == m_playing_sounds.end())
3899                 return;
3900         ServerPlayingSound &psound = i->second;
3901         // Create packet
3902         std::ostringstream os(std::ios_base::binary);
3903         writeU16(os, TOCLIENT_STOP_SOUND);
3904         writeS32(os, handle);
3905         // Make data buffer
3906         std::string s = os.str();
3907         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3908         // Send
3909         for(std::set<u16>::iterator i = psound.clients.begin();
3910                         i != psound.clients.end(); i++){
3911                 // Send as reliable
3912                 m_con.Send(*i, 0, data, true);
3913         }
3914         // Remove sound reference
3915         m_playing_sounds.erase(i);
3916 }
3917
3918 void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
3919         core::list<u16> *far_players, float far_d_nodes)
3920 {
3921         float maxd = far_d_nodes*BS;
3922         v3f p_f = intToFloat(p, BS);
3923
3924         // Create packet
3925         u32 replysize = 8;
3926         SharedBuffer<u8> reply(replysize);
3927         writeU16(&reply[0], TOCLIENT_REMOVENODE);
3928         writeS16(&reply[2], p.X);
3929         writeS16(&reply[4], p.Y);
3930         writeS16(&reply[6], p.Z);
3931
3932         for(core::map<u16, RemoteClient*>::Iterator
3933                 i = m_clients.getIterator();
3934                 i.atEnd() == false; i++)
3935         {
3936                 // Get client and check that it is valid
3937                 RemoteClient *client = i.getNode()->getValue();
3938                 assert(client->peer_id == i.getNode()->getKey());
3939                 if(client->serialization_version == SER_FMT_VER_INVALID)
3940                         continue;
3941
3942                 // Don't send if it's the same one
3943                 if(client->peer_id == ignore_id)
3944                         continue;
3945
3946                 if(far_players)
3947                 {
3948                         // Get player
3949                         Player *player = m_env->getPlayer(client->peer_id);
3950                         if(player)
3951                         {
3952                                 // If player is far away, only set modified blocks not sent
3953                                 v3f player_pos = player->getPosition();
3954                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3955                                 {
3956                                         far_players->push_back(client->peer_id);
3957                                         continue;
3958                                 }
3959                         }
3960                 }
3961
3962                 // Send as reliable
3963                 m_con.Send(client->peer_id, 0, reply, true);
3964         }
3965 }
3966
3967 void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
3968                 core::list<u16> *far_players, float far_d_nodes)
3969 {
3970         float maxd = far_d_nodes*BS;
3971         v3f p_f = intToFloat(p, BS);
3972
3973         for(core::map<u16, RemoteClient*>::Iterator
3974                 i = m_clients.getIterator();
3975                 i.atEnd() == false; i++)
3976         {
3977                 // Get client and check that it is valid
3978                 RemoteClient *client = i.getNode()->getValue();
3979                 assert(client->peer_id == i.getNode()->getKey());
3980                 if(client->serialization_version == SER_FMT_VER_INVALID)
3981                         continue;
3982
3983                 // Don't send if it's the same one
3984                 if(client->peer_id == ignore_id)
3985                         continue;
3986
3987                 if(far_players)
3988                 {
3989                         // Get player
3990                         Player *player = m_env->getPlayer(client->peer_id);
3991                         if(player)
3992                         {
3993                                 // If player is far away, only set modified blocks not sent
3994                                 v3f player_pos = player->getPosition();
3995                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3996                                 {
3997                                         far_players->push_back(client->peer_id);
3998                                         continue;
3999                                 }
4000                         }
4001                 }
4002
4003                 // Create packet
4004                 u32 replysize = 8 + MapNode::serializedLength(client->serialization_version);
4005                 SharedBuffer<u8> reply(replysize);
4006                 writeU16(&reply[0], TOCLIENT_ADDNODE);
4007                 writeS16(&reply[2], p.X);
4008                 writeS16(&reply[4], p.Y);
4009                 writeS16(&reply[6], p.Z);
4010                 n.serialize(&reply[8], client->serialization_version);
4011
4012                 // Send as reliable
4013                 m_con.Send(client->peer_id, 0, reply, true);
4014         }
4015 }
4016
4017 void Server::setBlockNotSent(v3s16 p)
4018 {
4019         for(core::map<u16, RemoteClient*>::Iterator
4020                 i = m_clients.getIterator();
4021                 i.atEnd()==false; i++)
4022         {
4023                 RemoteClient *client = i.getNode()->getValue();
4024                 client->SetBlockNotSent(p);
4025         }
4026 }
4027
4028 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
4029 {
4030         DSTACK(__FUNCTION_NAME);
4031
4032         v3s16 p = block->getPos();
4033
4034 #if 0
4035         // Analyze it a bit
4036         bool completely_air = true;
4037         for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
4038         for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
4039         for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
4040         {
4041                 if(block->getNodeNoEx(v3s16(x0,y0,z0)).d != CONTENT_AIR)
4042                 {
4043                         completely_air = false;
4044                         x0 = y0 = z0 = MAP_BLOCKSIZE; // Break out
4045                 }
4046         }
4047
4048         // Print result
4049         infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<"): ";
4050         if(completely_air)
4051                 infostream<<"[completely air] ";
4052         infostream<<std::endl;
4053 #endif
4054
4055         /*
4056                 Create a packet with the block in the right format
4057         */
4058
4059         std::ostringstream os(std::ios_base::binary);
4060         block->serialize(os, ver, false);
4061         std::string s = os.str();
4062         SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
4063
4064         u32 replysize = 8 + blockdata.getSize();
4065         SharedBuffer<u8> reply(replysize);
4066         writeU16(&reply[0], TOCLIENT_BLOCKDATA);
4067         writeS16(&reply[2], p.X);
4068         writeS16(&reply[4], p.Y);
4069         writeS16(&reply[6], p.Z);
4070         memcpy(&reply[8], *blockdata, blockdata.getSize());
4071
4072         /*infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<")"
4073                         <<":  \tpacket size: "<<replysize<<std::endl;*/
4074
4075         /*
4076                 Send packet
4077         */
4078         m_con.Send(peer_id, 1, reply, true);
4079 }
4080
4081 void Server::SendBlocks(float dtime)
4082 {
4083         DSTACK(__FUNCTION_NAME);
4084
4085         JMutexAutoLock envlock(m_env_mutex);
4086         JMutexAutoLock conlock(m_con_mutex);
4087
4088         ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
4089
4090         core::array<PrioritySortedBlockTransfer> queue;
4091
4092         s32 total_sending = 0;
4093
4094         {
4095                 ScopeProfiler sp(g_profiler, "Server: selecting blocks for sending");
4096
4097                 for(core::map<u16, RemoteClient*>::Iterator
4098                         i = m_clients.getIterator();
4099                         i.atEnd() == false; i++)
4100                 {
4101                         RemoteClient *client = i.getNode()->getValue();
4102                         assert(client->peer_id == i.getNode()->getKey());
4103
4104                         // If definitions and textures have not been sent, don't
4105                         // send MapBlocks either
4106                         if(!client->definitions_sent)
4107                                 continue;
4108
4109                         total_sending += client->SendingCount();
4110
4111                         if(client->serialization_version == SER_FMT_VER_INVALID)
4112                                 continue;
4113
4114                         client->GetNextBlocks(this, dtime, queue);
4115                 }
4116         }
4117
4118         // Sort.
4119         // Lowest priority number comes first.
4120         // Lowest is most important.
4121         queue.sort();
4122
4123         for(u32 i=0; i<queue.size(); i++)
4124         {
4125                 //TODO: Calculate limit dynamically
4126                 if(total_sending >= g_settings->getS32
4127                                 ("max_simultaneous_block_sends_server_total"))
4128                         break;
4129
4130                 PrioritySortedBlockTransfer q = queue[i];
4131
4132                 MapBlock *block = NULL;
4133                 try
4134                 {
4135                         block = m_env->getMap().getBlockNoCreate(q.pos);
4136                 }
4137                 catch(InvalidPositionException &e)
4138                 {
4139                         continue;
4140                 }
4141
4142                 RemoteClient *client = getClient(q.peer_id);
4143
4144                 SendBlockNoLock(q.peer_id, block, client->serialization_version);
4145
4146                 client->SentBlock(q.pos);
4147
4148                 total_sending++;
4149         }
4150 }
4151
4152 void Server::fillMediaCache()
4153 {
4154         DSTACK(__FUNCTION_NAME);
4155
4156         infostream<<"Server: Calculating media file checksums"<<std::endl;
4157
4158         // Collect all media file paths
4159         std::list<std::string> paths;
4160         for(std::vector<ModSpec>::iterator i = m_mods.begin();
4161                         i != m_mods.end(); i++){
4162                 const ModSpec &mod = *i;
4163                 paths.push_back(mod.path + DIR_DELIM + "textures");
4164                 paths.push_back(mod.path + DIR_DELIM + "sounds");
4165                 paths.push_back(mod.path + DIR_DELIM + "media");
4166                 paths.push_back(mod.path + DIR_DELIM + "models");
4167         }
4168         std::string path_all = "textures";
4169         paths.push_back(path_all + DIR_DELIM + "all");
4170
4171         // Collect media file information from paths into cache
4172         for(std::list<std::string>::iterator i = paths.begin();
4173                         i != paths.end(); i++)
4174         {
4175                 std::string mediapath = *i;
4176                 std::vector<fs::DirListNode> dirlist = fs::GetDirListing(mediapath);
4177                 for(u32 j=0; j<dirlist.size(); j++){
4178                         if(dirlist[j].dir) // Ignode dirs
4179                                 continue;
4180                         std::string filename = dirlist[j].name;
4181                         // If name contains illegal characters, ignore the file
4182                         if(!string_allowed(filename, TEXTURENAME_ALLOWED_CHARS)){
4183                                 infostream<<"Server: ignoring illegal file name: \""
4184                                                 <<filename<<"\""<<std::endl;
4185                                 continue;
4186                         }
4187                         // If name is not in a supported format, ignore it
4188                         const char *supported_ext[] = {
4189                                 ".png", ".jpg", ".bmp", ".tga",
4190                                 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
4191                                 ".ogg",
4192                                 ".x", ".b3d", ".md2", ".obj",
4193                                 NULL
4194                         };
4195                         if(removeStringEnd(filename, supported_ext) == ""){
4196                                 infostream<<"Server: ignoring unsupported file extension: \""
4197                                                 <<filename<<"\""<<std::endl;
4198                                 continue;
4199                         }
4200                         // Ok, attempt to load the file and add to cache
4201                         std::string filepath = mediapath + DIR_DELIM + filename;
4202                         // Read data
4203                         std::ifstream fis(filepath.c_str(), std::ios_base::binary);
4204                         if(fis.good() == false){
4205                                 errorstream<<"Server::fillMediaCache(): Could not open \""
4206                                                 <<filename<<"\" for reading"<<std::endl;
4207                                 continue;
4208                         }
4209                         std::ostringstream tmp_os(std::ios_base::binary);
4210                         bool bad = false;
4211                         for(;;){
4212                                 char buf[1024];
4213                                 fis.read(buf, 1024);
4214                                 std::streamsize len = fis.gcount();
4215                                 tmp_os.write(buf, len);
4216                                 if(fis.eof())
4217                                         break;
4218                                 if(!fis.good()){
4219                                         bad = true;
4220                                         break;
4221                                 }
4222                         }
4223                         if(bad){
4224                                 errorstream<<"Server::fillMediaCache(): Failed to read \""
4225                                                 <<filename<<"\""<<std::endl;
4226                                 continue;
4227                         }
4228                         if(tmp_os.str().length() == 0){
4229                                 errorstream<<"Server::fillMediaCache(): Empty file \""
4230                                                 <<filepath<<"\""<<std::endl;
4231                                 continue;
4232                         }
4233
4234                         SHA1 sha1;
4235                         sha1.addBytes(tmp_os.str().c_str(), tmp_os.str().length());
4236
4237                         unsigned char *digest = sha1.getDigest();
4238                         std::string sha1_base64 = base64_encode(digest, 20);
4239                         std::string sha1_hex = hex_encode((char*)digest, 20);
4240                         free(digest);
4241
4242                         // Put in list
4243                         this->m_media[filename] = MediaInfo(filepath, sha1_base64);
4244                         verbosestream<<"Server: "<<sha1_hex<<" is "<<filename<<std::endl;
4245                 }
4246         }
4247 }
4248
4249 struct SendableMediaAnnouncement
4250 {
4251         std::string name;
4252         std::string sha1_digest;
4253
4254         SendableMediaAnnouncement(const std::string name_="",
4255                         const std::string sha1_digest_=""):
4256                 name(name_),
4257                 sha1_digest(sha1_digest_)
4258         {}
4259 };
4260
4261 void Server::sendMediaAnnouncement(u16 peer_id)
4262 {
4263         DSTACK(__FUNCTION_NAME);
4264
4265         verbosestream<<"Server: Announcing files to id("<<peer_id<<")"
4266                         <<std::endl;
4267
4268         core::list<SendableMediaAnnouncement> file_announcements;
4269
4270         for(std::map<std::string, MediaInfo>::iterator i = m_media.begin();
4271                         i != m_media.end(); i++){
4272                 // Put in list
4273                 file_announcements.push_back(
4274                                 SendableMediaAnnouncement(i->first, i->second.sha1_digest));
4275         }
4276
4277         // Make packet
4278         std::ostringstream os(std::ios_base::binary);
4279
4280         /*
4281                 u16 command
4282                 u32 number of files
4283                 for each texture {
4284                         u16 length of name
4285                         string name
4286                         u16 length of sha1_digest
4287                         string sha1_digest
4288                 }
4289         */
4290
4291         writeU16(os, TOCLIENT_ANNOUNCE_MEDIA);
4292         writeU16(os, file_announcements.size());
4293
4294         for(core::list<SendableMediaAnnouncement>::Iterator
4295                         j = file_announcements.begin();
4296                         j != file_announcements.end(); j++){
4297                 os<<serializeString(j->name);
4298                 os<<serializeString(j->sha1_digest);
4299         }
4300         os<<serializeString(g_settings->get("remote_media"));
4301
4302         // Make data buffer
4303         std::string s = os.str();
4304         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
4305
4306         // Send as reliable
4307         m_con.Send(peer_id, 0, data, true);
4308 }
4309
4310 struct SendableMedia
4311 {
4312         std::string name;
4313         std::string path;
4314         std::string data;
4315
4316         SendableMedia(const std::string &name_="", const std::string path_="",
4317                         const std::string &data_=""):
4318                 name(name_),
4319                 path(path_),
4320                 data(data_)
4321         {}
4322 };
4323
4324 void Server::sendRequestedMedia(u16 peer_id,
4325                 const core::list<MediaRequest> &tosend)
4326 {
4327         DSTACK(__FUNCTION_NAME);
4328
4329         verbosestream<<"Server::sendRequestedMedia(): "
4330                         <<"Sending files to client"<<std::endl;
4331
4332         /* Read files */
4333
4334         // Put 5kB in one bunch (this is not accurate)
4335         u32 bytes_per_bunch = 5000;
4336
4337         core::array< core::list<SendableMedia> > file_bunches;
4338         file_bunches.push_back(core::list<SendableMedia>());
4339
4340         u32 file_size_bunch_total = 0;
4341
4342         for(core::list<MediaRequest>::ConstIterator i = tosend.begin();
4343                         i != tosend.end(); i++)
4344         {
4345                 if(m_media.find(i->name) == m_media.end()){
4346                         errorstream<<"Server::sendRequestedMedia(): Client asked for "
4347                                         <<"unknown file \""<<(i->name)<<"\""<<std::endl;
4348                         continue;
4349                 }
4350
4351                 //TODO get path + name
4352                 std::string tpath = m_media[(*i).name].path;
4353
4354                 // Read data
4355                 std::ifstream fis(tpath.c_str(), std::ios_base::binary);
4356                 if(fis.good() == false){
4357                         errorstream<<"Server::sendRequestedMedia(): Could not open \""
4358                                         <<tpath<<"\" for reading"<<std::endl;
4359                         continue;
4360                 }
4361                 std::ostringstream tmp_os(std::ios_base::binary);
4362                 bool bad = false;
4363                 for(;;){
4364                         char buf[1024];
4365                         fis.read(buf, 1024);
4366                         std::streamsize len = fis.gcount();
4367                         tmp_os.write(buf, len);
4368                         file_size_bunch_total += len;
4369                         if(fis.eof())
4370                                 break;
4371                         if(!fis.good()){
4372                                 bad = true;
4373                                 break;
4374                         }
4375                 }
4376                 if(bad){
4377                         errorstream<<"Server::sendRequestedMedia(): Failed to read \""
4378                                         <<(*i).name<<"\""<<std::endl;
4379                         continue;
4380                 }
4381                 /*infostream<<"Server::sendRequestedMedia(): Loaded \""
4382                                 <<tname<<"\""<<std::endl;*/
4383                 // Put in list
4384                 file_bunches[file_bunches.size()-1].push_back(
4385                                 SendableMedia((*i).name, tpath, tmp_os.str()));
4386
4387                 // Start next bunch if got enough data
4388                 if(file_size_bunch_total >= bytes_per_bunch){
4389                         file_bunches.push_back(core::list<SendableMedia>());
4390                         file_size_bunch_total = 0;
4391                 }
4392
4393         }
4394
4395         /* Create and send packets */
4396
4397         u32 num_bunches = file_bunches.size();
4398         for(u32 i=0; i<num_bunches; i++)
4399         {
4400                 std::ostringstream os(std::ios_base::binary);
4401
4402                 /*
4403                         u16 command
4404                         u16 total number of texture bunches
4405                         u16 index of this bunch
4406                         u32 number of files in this bunch
4407                         for each file {
4408                                 u16 length of name
4409                                 string name
4410                                 u32 length of data
4411                                 data
4412                         }
4413                 */
4414
4415                 writeU16(os, TOCLIENT_MEDIA);
4416                 writeU16(os, num_bunches);
4417                 writeU16(os, i);
4418                 writeU32(os, file_bunches[i].size());
4419
4420                 for(core::list<SendableMedia>::Iterator
4421                                 j = file_bunches[i].begin();
4422                                 j != file_bunches[i].end(); j++){
4423                         os<<serializeString(j->name);
4424                         os<<serializeLongString(j->data);
4425                 }
4426
4427                 // Make data buffer
4428                 std::string s = os.str();
4429                 verbosestream<<"Server::sendRequestedMedia(): bunch "
4430                                 <<i<<"/"<<num_bunches
4431                                 <<" files="<<file_bunches[i].size()
4432                                 <<" size=" <<s.size()<<std::endl;
4433                 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
4434                 // Send as reliable
4435                 m_con.Send(peer_id, 0, data, true);
4436         }
4437 }
4438
4439 void Server::sendDetachedInventory(const std::string &name, u16 peer_id)
4440 {
4441         if(m_detached_inventories.count(name) == 0){
4442                 errorstream<<__FUNCTION_NAME<<": \""<<name<<"\" not found"<<std::endl;
4443                 return;
4444         }
4445         Inventory *inv = m_detached_inventories[name];
4446
4447         std::ostringstream os(std::ios_base::binary);
4448         writeU16(os, TOCLIENT_DETACHED_INVENTORY);
4449         os<<serializeString(name);
4450         inv->serialize(os);
4451
4452         // Make data buffer
4453         std::string s = os.str();
4454         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
4455         // Send as reliable
4456         m_con.Send(peer_id, 0, data, true);
4457 }
4458
4459 void Server::sendDetachedInventoryToAll(const std::string &name)
4460 {
4461         DSTACK(__FUNCTION_NAME);
4462
4463         for(core::map<u16, RemoteClient*>::Iterator
4464                         i = m_clients.getIterator();
4465                         i.atEnd() == false; i++){
4466                 RemoteClient *client = i.getNode()->getValue();
4467                 sendDetachedInventory(name, client->peer_id);
4468         }
4469 }
4470
4471 void Server::sendDetachedInventories(u16 peer_id)
4472 {
4473         DSTACK(__FUNCTION_NAME);
4474
4475         for(std::map<std::string, Inventory*>::iterator
4476                         i = m_detached_inventories.begin();
4477                         i != m_detached_inventories.end(); i++){
4478                 const std::string &name = i->first;
4479                 //Inventory *inv = i->second;
4480                 sendDetachedInventory(name, peer_id);
4481         }
4482 }
4483
4484 /*
4485         Something random
4486 */
4487
4488 void Server::DiePlayer(u16 peer_id)
4489 {
4490         DSTACK(__FUNCTION_NAME);
4491
4492         PlayerSAO *playersao = getPlayerSAO(peer_id);
4493         assert(playersao);
4494
4495         infostream<<"Server::DiePlayer(): Player "
4496                         <<playersao->getPlayer()->getName()
4497                         <<" dies"<<std::endl;
4498
4499         playersao->setHP(0);
4500
4501         // Trigger scripted stuff
4502         scriptapi_on_dieplayer(m_lua, playersao);
4503
4504         SendPlayerHP(peer_id);
4505         SendDeathscreen(m_con, peer_id, false, v3f(0,0,0));
4506 }
4507
4508 void Server::RespawnPlayer(u16 peer_id)
4509 {
4510         DSTACK(__FUNCTION_NAME);
4511
4512         PlayerSAO *playersao = getPlayerSAO(peer_id);
4513         assert(playersao);
4514
4515         infostream<<"Server::RespawnPlayer(): Player "
4516                         <<playersao->getPlayer()->getName()
4517                         <<" respawns"<<std::endl;
4518
4519         playersao->setHP(PLAYER_MAX_HP);
4520
4521         bool repositioned = scriptapi_on_respawnplayer(m_lua, playersao);
4522         if(!repositioned){
4523                 v3f pos = findSpawnPos(m_env->getServerMap());
4524                 playersao->setPos(pos);
4525         }
4526 }
4527
4528 void Server::UpdateCrafting(u16 peer_id)
4529 {
4530         DSTACK(__FUNCTION_NAME);
4531
4532         Player* player = m_env->getPlayer(peer_id);
4533         assert(player);
4534
4535         // Get a preview for crafting
4536         ItemStack preview;
4537         getCraftingResult(&player->inventory, preview, false, this);
4538
4539         // Put the new preview in
4540         InventoryList *plist = player->inventory.getList("craftpreview");
4541         assert(plist);
4542         assert(plist->getSize() >= 1);
4543         plist->changeItem(0, preview);
4544 }
4545
4546 RemoteClient* Server::getClient(u16 peer_id)
4547 {
4548         DSTACK(__FUNCTION_NAME);
4549         //JMutexAutoLock lock(m_con_mutex);
4550         core::map<u16, RemoteClient*>::Node *n;
4551         n = m_clients.find(peer_id);
4552         // A client should exist for all peers
4553         assert(n != NULL);
4554         return n->getValue();
4555 }
4556
4557 std::wstring Server::getStatusString()
4558 {
4559         std::wostringstream os(std::ios_base::binary);
4560         os<<L"# Server: ";
4561         // Version
4562         os<<L"version="<<narrow_to_wide(VERSION_STRING);
4563         // Uptime
4564         os<<L", uptime="<<m_uptime.get();
4565         // Information about clients
4566         core::map<u16, RemoteClient*>::Iterator i;
4567         bool first;
4568         os<<L", clients={";
4569         for(i = m_clients.getIterator(), first = true;
4570                 i.atEnd() == false; i++)
4571         {
4572                 // Get client and check that it is valid
4573                 RemoteClient *client = i.getNode()->getValue();
4574                 assert(client->peer_id == i.getNode()->getKey());
4575                 if(client->serialization_version == SER_FMT_VER_INVALID)
4576                         continue;
4577                 // Get player
4578                 Player *player = m_env->getPlayer(client->peer_id);
4579                 // Get name of player
4580                 std::wstring name = L"unknown";
4581                 if(player != NULL)
4582                         name = narrow_to_wide(player->getName());
4583                 // Add name to information string
4584                 if(!first)
4585                         os<<L",";
4586                 else
4587                         first = false;
4588                 os<<name;
4589         }
4590         os<<L"}";
4591         if(((ServerMap*)(&m_env->getMap()))->isSavingEnabled() == false)
4592                 os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
4593         if(g_settings->get("motd") != "")
4594                 os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
4595         return os.str();
4596 }
4597
4598 std::set<std::string> Server::getPlayerEffectivePrivs(const std::string &name)
4599 {
4600         std::set<std::string> privs;
4601         scriptapi_get_auth(m_lua, name, NULL, &privs);
4602         return privs;
4603 }
4604
4605 bool Server::checkPriv(const std::string &name, const std::string &priv)
4606 {
4607         std::set<std::string> privs = getPlayerEffectivePrivs(name);
4608         return (privs.count(priv) != 0);
4609 }
4610
4611 void Server::reportPrivsModified(const std::string &name)
4612 {
4613         if(name == ""){
4614                 for(core::map<u16, RemoteClient*>::Iterator
4615                                 i = m_clients.getIterator();
4616                                 i.atEnd() == false; i++){
4617                         RemoteClient *client = i.getNode()->getValue();
4618                         Player *player = m_env->getPlayer(client->peer_id);
4619                         reportPrivsModified(player->getName());
4620                 }
4621         } else {
4622                 Player *player = m_env->getPlayer(name.c_str());
4623                 if(!player)
4624                         return;
4625                 SendPlayerPrivileges(player->peer_id);
4626                 PlayerSAO *sao = player->getPlayerSAO();
4627                 if(!sao)
4628                         return;
4629                 sao->updatePrivileges(
4630                                 getPlayerEffectivePrivs(name),
4631                                 isSingleplayer());
4632         }
4633 }
4634
4635 void Server::reportInventoryFormspecModified(const std::string &name)
4636 {
4637         Player *player = m_env->getPlayer(name.c_str());
4638         if(!player)
4639                 return;
4640         SendPlayerInventoryFormspec(player->peer_id);
4641 }
4642
4643 // Saves g_settings to configpath given at initialization
4644 void Server::saveConfig()
4645 {
4646         if(m_path_config != "")
4647                 g_settings->updateConfigFile(m_path_config.c_str());
4648 }
4649
4650 void Server::notifyPlayer(const char *name, const std::wstring msg)
4651 {
4652         Player *player = m_env->getPlayer(name);
4653         if(!player)
4654                 return;
4655         SendChatMessage(player->peer_id, std::wstring(L"Server: -!- ")+msg);
4656 }
4657
4658 bool Server::showFormspec(const char *playername, const std::string &formspec, const std::string &formname)
4659 {
4660         Player *player = m_env->getPlayer(playername);
4661
4662         if(!player)
4663         {
4664                 infostream<<"showFormspec: couldn't find player:"<<playername<<std::endl;
4665                 return false;
4666         }
4667
4668         SendShowFormspecMessage(player->peer_id, formspec, formname);
4669         return true;
4670 }
4671
4672 void Server::notifyPlayers(const std::wstring msg)
4673 {
4674         BroadcastChatMessage(msg);
4675 }
4676
4677 void Server::queueBlockEmerge(v3s16 blockpos, bool allow_generate)
4678 {
4679         u8 flags = 0;
4680         if(!allow_generate)
4681                 flags |= BLOCK_EMERGE_FLAG_FROMDISK;
4682         m_emerge_queue.addBlock(PEER_ID_INEXISTENT, blockpos, flags);
4683 }
4684
4685 Inventory* Server::createDetachedInventory(const std::string &name)
4686 {
4687         if(m_detached_inventories.count(name) > 0){
4688                 infostream<<"Server clearing detached inventory \""<<name<<"\""<<std::endl;
4689                 delete m_detached_inventories[name];
4690         } else {
4691                 infostream<<"Server creating detached inventory \""<<name<<"\""<<std::endl;
4692         }
4693         Inventory *inv = new Inventory(m_itemdef);
4694         assert(inv);
4695         m_detached_inventories[name] = inv;
4696         sendDetachedInventoryToAll(name);
4697         return inv;
4698 }
4699
4700 class BoolScopeSet
4701 {
4702 public:
4703         BoolScopeSet(bool *dst, bool val):
4704                 m_dst(dst)
4705         {
4706                 m_orig_state = *m_dst;
4707                 *m_dst = val;
4708         }
4709         ~BoolScopeSet()
4710         {
4711                 *m_dst = m_orig_state;
4712         }
4713 private:
4714         bool *m_dst;
4715         bool m_orig_state;
4716 };
4717
4718 // actions: time-reversed list
4719 // Return value: success/failure
4720 bool Server::rollbackRevertActions(const std::list<RollbackAction> &actions,
4721                 std::list<std::string> *log)
4722 {
4723         infostream<<"Server::rollbackRevertActions(len="<<actions.size()<<")"<<std::endl;
4724         ServerMap *map = (ServerMap*)(&m_env->getMap());
4725         // Disable rollback report sink while reverting
4726         BoolScopeSet rollback_scope_disable(&m_rollback_sink_enabled, false);
4727
4728         // Fail if no actions to handle
4729         if(actions.empty()){
4730                 log->push_back("Nothing to do.");
4731                 return false;
4732         }
4733
4734         int num_tried = 0;
4735         int num_failed = 0;
4736
4737         for(std::list<RollbackAction>::const_iterator
4738                         i = actions.begin();
4739                         i != actions.end(); i++)
4740         {
4741                 const RollbackAction &action = *i;
4742                 num_tried++;
4743                 bool success = action.applyRevert(map, this, this);
4744                 if(!success){
4745                         num_failed++;
4746                         std::ostringstream os;
4747                         os<<"Revert of step ("<<num_tried<<") "<<action.toString()<<" failed";
4748                         infostream<<"Map::rollbackRevertActions(): "<<os.str()<<std::endl;
4749                         if(log)
4750                                 log->push_back(os.str());
4751                 }else{
4752                         std::ostringstream os;
4753                         os<<"Successfully reverted step ("<<num_tried<<") "<<action.toString();
4754                         infostream<<"Map::rollbackRevertActions(): "<<os.str()<<std::endl;
4755                         if(log)
4756                                 log->push_back(os.str());
4757                 }
4758         }
4759
4760         infostream<<"Map::rollbackRevertActions(): "<<num_failed<<"/"<<num_tried
4761                         <<" failed"<<std::endl;
4762
4763         // Call it done if less than half failed
4764         return num_failed <= num_tried/2;
4765 }
4766
4767 // IGameDef interface
4768 // Under envlock
4769 IItemDefManager* Server::getItemDefManager()
4770 {
4771         return m_itemdef;
4772 }
4773 INodeDefManager* Server::getNodeDefManager()
4774 {
4775         return m_nodedef;
4776 }
4777 ICraftDefManager* Server::getCraftDefManager()
4778 {
4779         return m_craftdef;
4780 }
4781 ITextureSource* Server::getTextureSource()
4782 {
4783         return NULL;
4784 }
4785 IShaderSource* Server::getShaderSource()
4786 {
4787         return NULL;
4788 }
4789 u16 Server::allocateUnknownNodeId(const std::string &name)
4790 {
4791         return m_nodedef->allocateDummy(name);
4792 }
4793 ISoundManager* Server::getSoundManager()
4794 {
4795         return &dummySoundManager;
4796 }
4797 MtEventManager* Server::getEventManager()
4798 {
4799         return m_event;
4800 }
4801 IRollbackReportSink* Server::getRollbackReportSink()
4802 {
4803         if(!m_enable_rollback_recording)
4804                 return NULL;
4805         if(!m_rollback_sink_enabled)
4806                 return NULL;
4807         return m_rollback;
4808 }
4809
4810 IWritableItemDefManager* Server::getWritableItemDefManager()
4811 {
4812         return m_itemdef;
4813 }
4814 IWritableNodeDefManager* Server::getWritableNodeDefManager()
4815 {
4816         return m_nodedef;
4817 }
4818 IWritableCraftDefManager* Server::getWritableCraftDefManager()
4819 {
4820         return m_craftdef;
4821 }
4822
4823 const ModSpec* Server::getModSpec(const std::string &modname)
4824 {
4825         for(std::vector<ModSpec>::iterator i = m_mods.begin();
4826                         i != m_mods.end(); i++){
4827                 const ModSpec &mod = *i;
4828                 if(mod.name == modname)
4829                         return &mod;
4830         }
4831         return NULL;
4832 }
4833 void Server::getModNames(core::list<std::string> &modlist)
4834 {
4835         for(std::vector<ModSpec>::iterator i = m_mods.begin(); i != m_mods.end(); i++)
4836         {
4837                 modlist.push_back((*i).name);
4838         }
4839 }
4840 std::string Server::getBuiltinLuaPath()
4841 {
4842         return porting::path_share + DIR_DELIM + "builtin";
4843 }
4844
4845 v3f findSpawnPos(ServerMap &map)
4846 {
4847         //return v3f(50,50,50)*BS;
4848
4849         v3s16 nodepos;
4850
4851 #if 0
4852         nodepos = v2s16(0,0);
4853         groundheight = 20;
4854 #endif
4855
4856 #if 1
4857         s16 water_level = map.m_mgparams->water_level;
4858
4859         // Try to find a good place a few times
4860         for(s32 i=0; i<1000; i++)
4861         {
4862                 s32 range = 1 + i;
4863                 // We're going to try to throw the player to this position
4864                 v2s16 nodepos2d = v2s16(-range + (myrand()%(range*2)),
4865                                 -range + (myrand()%(range*2)));
4866                 //v2s16 sectorpos = getNodeSectorPos(nodepos2d);
4867                 // Get ground height at point (fallbacks to heightmap function)
4868                 s16 groundheight = map.findGroundLevel(nodepos2d);
4869                 // Don't go underwater
4870                 if(groundheight <= water_level)
4871                 {
4872                         //infostream<<"-> Underwater"<<std::endl;
4873                         continue;
4874                 }
4875                 // Don't go to high places
4876                 if(groundheight > water_level + 6)
4877                 {
4878                         //infostream<<"-> Underwater"<<std::endl;
4879                         continue;
4880                 }
4881
4882                 nodepos = v3s16(nodepos2d.X, groundheight-2, nodepos2d.Y);
4883                 bool is_good = false;
4884                 s32 air_count = 0;
4885                 for(s32 i=0; i<10; i++){
4886                         v3s16 blockpos = getNodeBlockPos(nodepos);
4887                         map.emergeBlock(blockpos, true);
4888                         MapNode n = map.getNodeNoEx(nodepos);
4889                         if(n.getContent() == CONTENT_AIR){
4890                                 air_count++;
4891                                 if(air_count >= 2){
4892                                         is_good = true;
4893                                         nodepos.Y -= 1;
4894                                         break;
4895                                 }
4896                         }
4897                         nodepos.Y++;
4898                 }
4899                 if(is_good){
4900                         // Found a good place
4901                         //infostream<<"Searched through "<<i<<" places."<<std::endl;
4902                         break;
4903                 }
4904         }
4905 #endif
4906
4907         return intToFloat(nodepos, BS);
4908 }
4909
4910 PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
4911 {
4912         RemotePlayer *player = NULL;
4913         bool newplayer = false;
4914
4915         /*
4916                 Try to get an existing player
4917         */
4918         player = static_cast<RemotePlayer*>(m_env->getPlayer(name));
4919
4920         // If player is already connected, cancel
4921         if(player != NULL && player->peer_id != 0)
4922         {
4923                 infostream<<"emergePlayer(): Player already connected"<<std::endl;
4924                 return NULL;
4925         }
4926
4927         /*
4928                 If player with the wanted peer_id already exists, cancel.
4929         */
4930         if(m_env->getPlayer(peer_id) != NULL)
4931         {
4932                 infostream<<"emergePlayer(): Player with wrong name but same"
4933                                 " peer_id already exists"<<std::endl;
4934                 return NULL;
4935         }
4936
4937         /*
4938                 Create a new player if it doesn't exist yet
4939         */
4940         if(player == NULL)
4941         {
4942                 newplayer = true;
4943                 player = new RemotePlayer(this);
4944                 player->updateName(name);
4945
4946                 /* Set player position */
4947                 infostream<<"Server: Finding spawn place for player \""
4948                                 <<name<<"\""<<std::endl;
4949                 v3f pos = findSpawnPos(m_env->getServerMap());
4950                 player->setPosition(pos);
4951
4952                 /* Add player to environment */
4953                 m_env->addPlayer(player);
4954         }
4955
4956         /*
4957                 Create a new player active object
4958         */
4959         PlayerSAO *playersao = new PlayerSAO(m_env, player, peer_id,
4960                         getPlayerEffectivePrivs(player->getName()),
4961                         isSingleplayer());
4962
4963         /* Add object to environment */
4964         m_env->addActiveObject(playersao);
4965
4966         /* Run scripts */
4967         if(newplayer)
4968                 scriptapi_on_newplayer(m_lua, playersao);
4969
4970         scriptapi_on_joinplayer(m_lua, playersao);
4971
4972         return playersao;
4973 }
4974
4975 void Server::handlePeerChange(PeerChange &c)
4976 {
4977         JMutexAutoLock envlock(m_env_mutex);
4978         JMutexAutoLock conlock(m_con_mutex);
4979
4980         if(c.type == PEER_ADDED)
4981         {
4982                 /*
4983                         Add
4984                 */
4985
4986                 // Error check
4987                 core::map<u16, RemoteClient*>::Node *n;
4988                 n = m_clients.find(c.peer_id);
4989                 // The client shouldn't already exist
4990                 assert(n == NULL);
4991
4992                 // Create client
4993                 RemoteClient *client = new RemoteClient();
4994                 client->peer_id = c.peer_id;
4995                 m_clients.insert(client->peer_id, client);
4996
4997         } // PEER_ADDED
4998         else if(c.type == PEER_REMOVED)
4999         {
5000                 /*
5001                         Delete
5002                 */
5003
5004                 // Error check
5005                 core::map<u16, RemoteClient*>::Node *n;
5006                 n = m_clients.find(c.peer_id);
5007                 // The client should exist
5008                 assert(n != NULL);
5009
5010                 /*
5011                         Mark objects to be not known by the client
5012                 */
5013                 RemoteClient *client = n->getValue();
5014                 // Handle objects
5015                 for(core::map<u16, bool>::Iterator
5016                                 i = client->m_known_objects.getIterator();
5017                                 i.atEnd()==false; i++)
5018                 {
5019                         // Get object
5020                         u16 id = i.getNode()->getKey();
5021                         ServerActiveObject* obj = m_env->getActiveObject(id);
5022
5023                         if(obj && obj->m_known_by_count > 0)
5024                                 obj->m_known_by_count--;
5025                 }
5026
5027                 /*
5028                         Clear references to playing sounds
5029                 */
5030                 for(std::map<s32, ServerPlayingSound>::iterator
5031                                 i = m_playing_sounds.begin();
5032                                 i != m_playing_sounds.end();)
5033                 {
5034                         ServerPlayingSound &psound = i->second;
5035                         psound.clients.erase(c.peer_id);
5036                         if(psound.clients.size() == 0)
5037                                 m_playing_sounds.erase(i++);
5038                         else
5039                                 i++;
5040                 }
5041
5042                 Player *player = m_env->getPlayer(c.peer_id);
5043
5044                 // Collect information about leaving in chat
5045                 std::wstring message;
5046                 {
5047                         if(player != NULL)
5048                         {
5049                                 std::wstring name = narrow_to_wide(player->getName());
5050                                 message += L"*** ";
5051                                 message += name;
5052                                 message += L" left the game.";
5053                                 if(c.timeout)
5054                                         message += L" (timed out)";
5055                         }
5056                 }
5057
5058                 /* Run scripts and remove from environment */
5059                 {
5060                         if(player != NULL)
5061                         {
5062                                 PlayerSAO *playersao = player->getPlayerSAO();
5063                                 assert(playersao);
5064
5065                                 scriptapi_on_leaveplayer(m_lua, playersao);
5066
5067                                 playersao->disconnected();
5068                         }
5069                 }
5070
5071                 /*
5072                         Print out action
5073                 */
5074                 {
5075                         if(player != NULL)
5076                         {
5077                                 std::ostringstream os(std::ios_base::binary);
5078                                 for(core::map<u16, RemoteClient*>::Iterator
5079                                         i = m_clients.getIterator();
5080                                         i.atEnd() == false; i++)
5081                                 {
5082                                         RemoteClient *client = i.getNode()->getValue();
5083                                         assert(client->peer_id == i.getNode()->getKey());
5084                                         if(client->serialization_version == SER_FMT_VER_INVALID)
5085                                                 continue;
5086                                         // Get player
5087                                         Player *player = m_env->getPlayer(client->peer_id);
5088                                         if(!player)
5089                                                 continue;
5090                                         // Get name of player
5091                                         os<<player->getName()<<" ";
5092                                 }
5093
5094                                 actionstream<<player->getName()<<" "
5095                                                 <<(c.timeout?"times out.":"leaves game.")
5096                                                 <<" List of players: "
5097                                                 <<os.str()<<std::endl;
5098                         }
5099                 }
5100
5101                 // Delete client
5102                 delete m_clients[c.peer_id];
5103                 m_clients.remove(c.peer_id);
5104
5105                 // Send player info to all remaining clients
5106                 //SendPlayerInfos();
5107
5108                 // Send leave chat message to all remaining clients
5109                 if(message.length() != 0)
5110                         BroadcastChatMessage(message);
5111
5112         } // PEER_REMOVED
5113         else
5114         {
5115                 assert(0);
5116         }
5117 }
5118
5119 void Server::handlePeerChanges()
5120 {
5121         while(m_peer_change_queue.size() > 0)
5122         {
5123                 PeerChange c = m_peer_change_queue.pop_front();
5124
5125                 verbosestream<<"Server: Handling peer change: "
5126                                 <<"id="<<c.peer_id<<", timeout="<<c.timeout
5127                                 <<std::endl;
5128
5129                 handlePeerChange(c);
5130         }
5131 }
5132
5133 void dedicated_server_loop(Server &server, bool &kill)
5134 {
5135         DSTACK(__FUNCTION_NAME);
5136
5137         verbosestream<<"dedicated_server_loop()"<<std::endl;
5138
5139         IntervalLimiter m_profiler_interval;
5140
5141         for(;;)
5142         {
5143                 float steplen = g_settings->getFloat("dedicated_server_step");
5144                 // This is kind of a hack but can be done like this
5145                 // because server.step() is very light
5146                 {
5147                         ScopeProfiler sp(g_profiler, "dedicated server sleep");
5148                         sleep_ms((int)(steplen*1000.0));
5149                 }
5150                 server.step(steplen);
5151
5152                 if(server.getShutdownRequested() || kill)
5153                 {
5154                         infostream<<"Dedicated server quitting"<<std::endl;
5155                         break;
5156                 }
5157
5158                 /*
5159                         Profiler
5160                 */
5161                 float profiler_print_interval =
5162                                 g_settings->getFloat("profiler_print_interval");
5163                 if(profiler_print_interval != 0)
5164                 {
5165                         if(m_profiler_interval.step(steplen, profiler_print_interval))
5166                         {
5167                                 infostream<<"Profiler:"<<std::endl;
5168                                 g_profiler->print(infostream);
5169                                 g_profiler->clear();
5170                         }
5171                 }
5172         }
5173 }
5174
5175