]> git.lizzy.rs Git - minetest.git/blob - src/clientiface.h
3d84944ea448e062268642d36956b082b273aa1c
[minetest.git] / src / clientiface.h
1 /*
2 Minetest
3 Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #pragma once
21
22 #include "irr_v3d.h"                   // for irrlicht datatypes
23
24 #include "constants.h"
25 #include "serialization.h"             // for SER_FMT_VER_INVALID
26 #include "network/networkpacket.h"
27 #include "network/networkprotocol.h"
28 #include "network/address.h"
29 #include "porting.h"
30 #include "threading/mutex_auto_lock.h"
31
32 #include <list>
33 #include <vector>
34 #include <set>
35 #include <memory>
36 #include <mutex>
37
38 class MapBlock;
39 class ServerEnvironment;
40 class EmergeManager;
41
42 /*
43  * State Transitions
44
45       Start
46   (peer connect)
47         |
48         v
49       /-----------------\
50       |                 |
51       |    Created      |
52       |                 |
53       \-----------------/
54                |                  depending of the incoming packet
55                ----------------------------------------
56                                                       v
57                                        +-----------------------------+
58                                        |IN:                          |
59                                        | TOSERVER_INIT               |
60                                        +-----------------------------+
61                                                       | invalid playername
62                                                       | or denied by mod
63                                                       v
64                                        +-----------------------------+
65                                        |OUT:                         |
66                                        | TOCLIENT_HELLO              |
67                                        +-----------------------------+
68                                                       |
69                                                       |
70                                                       v
71       /-----------------\                    /-----------------\
72       |                 |                    |                 |
73       |  AwaitingInit2  |<---------          |    HelloSent    |
74       |                 |         |          |                 |
75       \-----------------/         |          \-----------------/
76                |                  |                   |
77 +-----------------------------+   |    *-----------------------------*     Auth fails
78 |IN:                          |   |    |Authentication, depending on |------------------
79 | TOSERVER_INIT2              |   |    | packet sent by client       |                 |
80 +-----------------------------+   |    *-----------------------------*                 |
81                |                  |                   |                                |
82                |                  |                   | Authentication                 |
83                v                  |                   |  successful                    |
84       /-----------------\         |                   v                                |
85       |                 |         |    +-----------------------------+                 |
86       |    InitDone     |         |    |OUT:                         |                 |
87       |                 |         |    | TOCLIENT_AUTH_ACCEPT        |                 |
88       \-----------------/         |    +-----------------------------+                 |
89                |                  |                   |                                |
90 +-----------------------------+   ---------------------                                |
91 |OUT:                         |                                                        |
92 | TOCLIENT_MOVEMENT           |                                                        |
93 | TOCLIENT_ITEMDEF            |                                                        |
94 | TOCLIENT_NODEDEF            |                                                        |
95 | TOCLIENT_ANNOUNCE_MEDIA     |                                                        |
96 | TOCLIENT_DETACHED_INVENTORY |                                                        |
97 | TOCLIENT_TIME_OF_DAY        |                                                        |
98 +-----------------------------+                                                        |
99                |                                                                       |
100                |                                                                       |
101                |      -----------------------------                                    |
102                v      |                           |                                    |
103       /-----------------\                         v                                    |
104       |                 |             +-----------------------------+                  |
105       | DefinitionsSent |             |IN:                          |                  |
106       |                 |             | TOSERVER_REQUEST_MEDIA      |                  |
107       \-----------------/             |                             |                  |
108                |                      +-----------------------------+                  |
109                |      ^                           |                                    |
110                |      -----------------------------                                    |
111                v                                                                       v
112 +-----------------------------+                        --------------------------------+
113 |IN:                          |                        |                               ^
114 | TOSERVER_CLIENT_READY       |                        v                               |
115 +-----------------------------+            +------------------------+                  |
116                |                           |OUT:                    |                  |
117                v                           | TOCLIENT_ACCESS_DENIED |                  |
118 +-----------------------------+            +------------------------+                  |
119 |OUT:                         |                        |                               |
120 | TOCLIENT_MOVE_PLAYER        |                        v                               |
121 | TOCLIENT_PRIVILEGES         |                /-----------------\                     |
122 | TOCLIENT_INVENTORY_FORMSPEC |                |                 |                     |
123 | UpdateCrafting              |                |     Denied      |                     |
124 | TOCLIENT_INVENTORY          |                |                 |                     |
125 | TOCLIENT_HP (opt)           |                \-----------------/                     |
126 | TOCLIENT_BREATH             |                                                        |
127 | TOCLIENT_DEATHSCREEN        |                                                        |
128 +-----------------------------+                                                        |
129               |                                                                        |
130               v                                                                        |
131       /-----------------\      async mod action (ban, kick)                            |
132       |                 |---------------------------------------------------------------
133  ---->|     Active      |
134  |    |                 |----------------------------------------------
135  |    \-----------------/      timeout                                v
136  |       |           |                                  +-----------------------------+
137  |       |           |                                  |OUT:                         |
138  |       |           |                                  | TOCLIENT_DISCONNECT         |
139  |       |           |                                  +-----------------------------+
140  |       |           |                                                |
141  |       |           v                                                v
142  |       |  +-----------------------------+                    /-----------------\
143  |       |  |IN:                          |                    |                 |
144  |       |  | TOSERVER_DISCONNECT         |------------------->|  Disconnecting  |
145  |       |  +-----------------------------+                    |                 |
146  |       |                                                     \-----------------/
147  |       | any auth packet which was
148  |       | allowed in TOCLIENT_AUTH_ACCEPT
149  |       v
150  |    *-----------------------------* Auth      +-------------------------------+
151  |    |Authentication, depending on | succeeds  |OUT:                           |
152  |    | packet sent by client       |---------->| TOCLIENT_ACCEPT_SUDO_MODE     |
153  |    *-----------------------------*           +-------------------------------+
154  |                  |                                            |
155  |                  | Auth fails                        /-----------------\
156  |                  v                                   |                 |
157  |    +-------------------------------+                 |    SudoMode     |
158  |    |OUT:                           |                 |                 |
159  |    | TOCLIENT_DENY_SUDO_MODE       |                 \-----------------/
160  |    +-------------------------------+                          |
161  |                  |                                            v
162  |                  |                               +-----------------------------+
163  |                  |    sets password accordingly  |IN:                          |
164  -------------------+-------------------------------| TOSERVER_FIRST_SRP          |
165                                                     +-----------------------------+
166
167 */
168 namespace con {
169         class Connection;
170 }
171
172
173 // Also make sure to update the ClientInterface::statenames
174 // array when modifying these enums
175
176 enum ClientState
177 {
178         CS_Invalid,
179         CS_Disconnecting,
180         CS_Denied,
181         CS_Created,
182         CS_AwaitingInit2,
183         CS_HelloSent,
184         CS_InitDone,
185         CS_DefinitionsSent,
186         CS_Active,
187         CS_SudoMode
188 };
189
190 enum ClientStateEvent
191 {
192         CSE_Hello,
193         CSE_AuthAccept,
194         CSE_GotInit2,
195         CSE_SetDenied,
196         CSE_SetDefinitionsSent,
197         CSE_SetClientReady,
198         CSE_SudoSuccess,
199         CSE_SudoLeave,
200         CSE_Disconnect
201 };
202
203 /*
204         Used for queueing and sorting block transfers in containers
205
206         Lower priority number means higher priority.
207 */
208 struct PrioritySortedBlockTransfer
209 {
210         PrioritySortedBlockTransfer(float a_priority, const v3s16 &a_pos, session_t a_peer_id)
211         {
212                 priority = a_priority;
213                 pos = a_pos;
214                 peer_id = a_peer_id;
215         }
216         bool operator < (const PrioritySortedBlockTransfer &other) const
217         {
218                 return priority < other.priority;
219         }
220         float priority;
221         v3s16 pos;
222         session_t peer_id;
223 };
224
225 class RemoteClient
226 {
227 public:
228         // peer_id=0 means this client has no associated peer
229         // NOTE: If client is made allowed to exist while peer doesn't,
230         //       this has to be set to 0 when there is no peer.
231         //       Also, the client must be moved to some other container.
232         session_t peer_id = PEER_ID_INEXISTENT;
233         // The serialization version to use with the client
234         u8 serialization_version = SER_FMT_VER_INVALID;
235         //
236         u16 net_proto_version = 0;
237
238         /* Authentication information */
239         std::string enc_pwd = "";
240         bool create_player_on_auth_success = false;
241         AuthMechanism chosen_mech  = AUTH_MECHANISM_NONE;
242         void *auth_data = nullptr;
243         u32 allowed_auth_mechs = 0;
244         u32 allowed_sudo_mechs = 0;
245
246         void resetChosenMech();
247
248         bool isSudoMechAllowed(AuthMechanism mech)
249         { return allowed_sudo_mechs & mech; }
250         bool isMechAllowed(AuthMechanism mech)
251         { return allowed_auth_mechs & mech; }
252
253         RemoteClient();
254         ~RemoteClient() = default;
255
256         /*
257                 Finds block that should be sent next to the client.
258                 Environment should be locked when this is called.
259                 dtime is used for resetting send radius at slow interval
260         */
261         void GetNextBlocks(ServerEnvironment *env, EmergeManager* emerge,
262                         float dtime, std::vector<PrioritySortedBlockTransfer> &dest);
263
264         void GotBlock(v3s16 p);
265
266         void SentBlock(v3s16 p);
267
268         void SetBlockNotSent(v3s16 p);
269         void SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks);
270
271         /**
272          * tell client about this block being modified right now.
273          * this information is required to requeue the block in case it's "on wire"
274          * while modification is processed by server
275          * @param p position of modified block
276          */
277         void ResendBlockIfOnWire(v3s16 p);
278
279         u32 getSendingCount() const { return m_blocks_sending.size(); }
280
281         bool isBlockSent(v3s16 p) const
282         {
283                 return m_blocks_sent.find(p) != m_blocks_sent.end();
284         }
285
286         // Increments timeouts and removes timed-out blocks from list
287         // NOTE: This doesn't fix the server-not-sending-block bug
288         //       because it is related to emerging, not sending.
289         //void RunSendingTimeouts(float dtime, float timeout);
290
291         void PrintInfo(std::ostream &o)
292         {
293                 o<<"RemoteClient "<<peer_id<<": "
294                                 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
295                                 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
296                                 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
297                                 <<", m_excess_gotblocks="<<m_excess_gotblocks
298                                 <<std::endl;
299                 m_excess_gotblocks = 0;
300         }
301
302         // Time from last placing or removing blocks
303         float m_time_from_building = 9999;
304
305         /*
306                 List of active objects that the client knows of.
307         */
308         std::set<u16> m_known_objects;
309
310         ClientState getState() const { return m_state; }
311
312         std::string getName() const { return m_name; }
313
314         void setName(const std::string &name) { m_name = name; }
315
316         /* update internal client state */
317         void notifyEvent(ClientStateEvent event);
318
319         /* set expected serialization version */
320         void setPendingSerializationVersion(u8 version)
321                 { m_pending_serialization_version = version; }
322
323         void setDeployedCompressionMode(u16 byteFlag)
324                 { m_deployed_compression = byteFlag; }
325
326         void confirmSerializationVersion()
327                 { serialization_version = m_pending_serialization_version; }
328
329         /* get uptime */
330         u64 uptime() const;
331
332         /* set version information */
333         void setVersionInfo(u8 major, u8 minor, u8 patch, const std::string &full)
334         {
335                 m_version_major = major;
336                 m_version_minor = minor;
337                 m_version_patch = patch;
338                 m_full_version = full;
339         }
340
341         /* read version information */
342         u8 getMajor() const { return m_version_major; }
343         u8 getMinor() const { return m_version_minor; }
344         u8 getPatch() const { return m_version_patch; }
345         const std::string &getFullVer() const { return m_full_version; }
346
347         void setLangCode(const std::string &code) { m_lang_code = code; }
348         const std::string &getLangCode() const { return m_lang_code; }
349
350         void setCachedAddress(const Address &addr) { m_addr = addr; }
351         const Address &getAddress() const { return m_addr; }
352
353 private:
354         // Version is stored in here after INIT before INIT2
355         u8 m_pending_serialization_version = SER_FMT_VER_INVALID;
356
357         /* current state of client */
358         ClientState m_state = CS_Created;
359
360         // Cached here so retrieval doesn't have to go to connection API
361         Address m_addr;
362
363         // Client sent language code
364         std::string m_lang_code;
365
366         /*
367                 Blocks that have been sent to client.
368                 - These don't have to be sent again.
369                 - A block is cleared from here when client says it has
370                   deleted it from it's memory
371
372                 List of block positions.
373                 No MapBlock* is stored here because the blocks can get deleted.
374         */
375         std::set<v3s16> m_blocks_sent;
376         s16 m_nearest_unsent_d = 0;
377         v3s16 m_last_center;
378         v3f m_last_camera_dir;
379
380         const u16 m_max_simul_sends;
381         const float m_min_time_from_building;
382         const s16 m_max_send_distance;
383         const s16 m_block_optimize_distance;
384         const s16 m_max_gen_distance;
385         const bool m_occ_cull;
386
387         /*
388                 Blocks that are currently on the line.
389                 This is used for throttling the sending of blocks.
390                 - The size of this list is limited to some value
391                 Block is added when it is sent with BLOCKDATA.
392                 Block is removed when GOTBLOCKS is received.
393                 Value is time from sending. (not used at the moment)
394         */
395         std::map<v3s16, float> m_blocks_sending;
396
397         /*
398                 Blocks that have been modified since blocks were
399                 sent to the client last (getNextBlocks()).
400                 This is used to reset the unsent distance, so that
401                 modified blocks are resent to the client.
402
403                 List of block positions.
404         */
405         std::set<v3s16> m_blocks_modified;
406
407         /*
408                 Count of excess GotBlocks().
409                 There is an excess amount because the client sometimes
410                 gets a block so late that the server sends it again,
411                 and the client then sends two GOTBLOCKs.
412                 This is reset by PrintInfo()
413         */
414         u32 m_excess_gotblocks = 0;
415
416         // CPU usage optimization
417         float m_nothing_to_send_pause_timer = 0.0f;
418
419         /*
420                 name of player using this client
421         */
422         std::string m_name = "";
423
424         /*
425                 client information
426         */
427         u8 m_version_major = 0;
428         u8 m_version_minor = 0;
429         u8 m_version_patch = 0;
430
431         std::string m_full_version = "unknown";
432
433         u16 m_deployed_compression = 0;
434
435         /*
436                 time this client was created
437          */
438         const u64 m_connection_time = porting::getTimeS();
439 };
440
441 typedef std::unordered_map<u16, RemoteClient*> RemoteClientMap;
442
443 class ClientInterface {
444 public:
445
446         friend class Server;
447
448         ClientInterface(const std::shared_ptr<con::Connection> &con);
449         ~ClientInterface();
450
451         /* run sync step */
452         void step(float dtime);
453
454         /* get list of active client id's */
455         std::vector<session_t> getClientIDs(ClientState min_state=CS_Active);
456
457         /* mark block as not sent to active client sessions */
458         void markBlockposAsNotSent(const v3s16 &pos);
459
460         /* verify is server user limit was reached */
461         bool isUserLimitReached();
462
463         /* get list of client player names */
464         const std::vector<std::string> &getPlayerNames() const { return m_clients_names; }
465
466         /* send message to client */
467         void send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable);
468
469         /* send to all clients */
470         void sendToAll(NetworkPacket *pkt);
471
472         /* delete a client */
473         void DeleteClient(session_t peer_id);
474
475         /* create client */
476         void CreateClient(session_t peer_id);
477
478         /* get a client by peer_id */
479         RemoteClient *getClientNoEx(session_t peer_id,  ClientState state_min = CS_Active);
480
481         /* get client by peer_id (make sure you have list lock before!*/
482         RemoteClient *lockedGetClientNoEx(session_t peer_id,  ClientState state_min = CS_Active);
483
484         /* get state of client by id*/
485         ClientState getClientState(session_t peer_id);
486
487         /* set client playername */
488         void setPlayerName(session_t peer_id, const std::string &name);
489
490         /* get protocol version of client */
491         u16 getProtocolVersion(session_t peer_id);
492
493         /* set client version */
494         void setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch,
495                         const std::string &full);
496
497         /* event to update client state */
498         void event(session_t peer_id, ClientStateEvent event);
499
500         /* Set environment. Do not call this function if environment is already set */
501         void setEnv(ServerEnvironment *env)
502         {
503                 assert(m_env == NULL); // pre-condition
504                 m_env = env;
505         }
506
507         static std::string state2Name(ClientState state);
508 protected:
509         class AutoLock {
510         public:
511                 AutoLock(ClientInterface &iface): m_lock(iface.m_clients_mutex) {}
512
513         private:
514                 RecursiveMutexAutoLock m_lock;
515         };
516
517         RemoteClientMap& getClientList() { return m_clients; }
518
519 private:
520         /* update internal player list */
521         void UpdatePlayerList();
522
523         // Connection
524         std::shared_ptr<con::Connection> m_con;
525         std::recursive_mutex m_clients_mutex;
526         // Connected clients (behind the con mutex)
527         RemoteClientMap m_clients;
528         std::vector<std::string> m_clients_names; //for announcing masterserver
529
530         // Environment
531         ServerEnvironment *m_env;
532
533         float m_print_info_timer;
534
535         static const char *statenames[];
536 };