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