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