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