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