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