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