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