Path: blob/master/modules/multiplayer/scene_rpc_interface.cpp
11351 views
/**************************************************************************/1/* scene_rpc_interface.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "scene_rpc_interface.h"3132#include "scene_multiplayer.h"3334#include "core/debugger/engine_debugger.h"35#include "core/io/marshalls.h"36#include "scene/main/multiplayer_api.h"37#include "scene/main/node.h"38#include "scene/main/window.h"3940// The RPC meta is composed by a single byte that contains (starting from the least significant bit):41// - `NetworkCommands` in the first four bits.42// - `NetworkNodeIdCompression` in the next 2 bits.43// - `NetworkNameIdCompression` in the next 1 bit.44// - `byte_only_or_no_args` in the next 1 bit.45#define NODE_ID_COMPRESSION_SHIFT SceneMultiplayer::CMD_FLAG_0_SHIFT46#define NAME_ID_COMPRESSION_SHIFT SceneMultiplayer::CMD_FLAG_2_SHIFT47#define BYTE_ONLY_OR_NO_ARGS_SHIFT SceneMultiplayer::CMD_FLAG_3_SHIFT4849#define NODE_ID_COMPRESSION_FLAG ((1 << NODE_ID_COMPRESSION_SHIFT) | (1 << (NODE_ID_COMPRESSION_SHIFT + 1)))50#define NAME_ID_COMPRESSION_FLAG (1 << NAME_ID_COMPRESSION_SHIFT)51#define BYTE_ONLY_OR_NO_ARGS_FLAG (1 << BYTE_ONLY_OR_NO_ARGS_SHIFT)5253#ifdef DEBUG_ENABLED54_FORCE_INLINE_ void SceneRPCInterface::_profile_node_data(const String &p_what, ObjectID p_id, int p_size) {55if (EngineDebugger::is_profiling("multiplayer:rpc")) {56Array values = { p_what, p_id, p_size };57EngineDebugger::profiler_add_frame_data("multiplayer:rpc", values);58}59}60#endif6162// Returns the packet size stripping the node path added when the node is not yet cached.63int get_packet_len(uint32_t p_node_target, int p_packet_len) {64if (p_node_target & 0x80000000) {65int ofs = p_node_target & 0x7FFFFFFF;66return p_packet_len - (p_packet_len - ofs);67} else {68return p_packet_len;69}70}7172void SceneRPCInterface::_parse_rpc_config(const Variant &p_config, bool p_for_node, RPCConfigCache &r_cache) {73if (p_config.get_type() == Variant::NIL) {74return;75}76ERR_FAIL_COND(p_config.get_type() != Variant::DICTIONARY);77const Dictionary config = p_config;78Array names = config.keys();79names.sort_custom(callable_mp_static(&StringLikeVariantOrder::compare)); // Ensure ID order80for (int i = 0; i < names.size(); i++) {81ERR_CONTINUE(!names[i].is_string());82String name = names[i].operator String();83ERR_CONTINUE(config[name].get_type() != Variant::DICTIONARY);84ERR_CONTINUE(!config[name].operator Dictionary().has("rpc_mode"));85Dictionary dict = config[name];86RPCConfig cfg;87cfg.name = name;88cfg.rpc_mode = ((MultiplayerAPI::RPCMode)dict.get("rpc_mode", MultiplayerAPI::RPC_MODE_AUTHORITY).operator int());89cfg.transfer_mode = ((MultiplayerPeer::TransferMode)dict.get("transfer_mode", MultiplayerPeer::TRANSFER_MODE_RELIABLE).operator int());90cfg.call_local = dict.get("call_local", false).operator bool();91cfg.channel = dict.get("channel", 0).operator int();92uint16_t id = ((uint16_t)i);93if (p_for_node) {94id |= (1 << 15);95}96r_cache.configs[id] = cfg;97r_cache.ids[name] = id;98}99}100101const SceneRPCInterface::RPCConfigCache &SceneRPCInterface::_get_node_config(const Node *p_node) {102const ObjectID oid = p_node->get_instance_id();103if (rpc_cache.has(oid)) {104return rpc_cache[oid];105}106RPCConfigCache cache;107_parse_rpc_config(p_node->get_node_rpc_config(), true, cache);108if (p_node->get_script_instance()) {109_parse_rpc_config(p_node->get_script_instance()->get_rpc_config(), false, cache);110}111rpc_cache[oid] = cache;112return rpc_cache[oid];113}114115String SceneRPCInterface::get_rpc_md5(const Object *p_obj) {116const Node *node = Object::cast_to<Node>(p_obj);117ERR_FAIL_NULL_V(node, "");118const RPCConfigCache cache = _get_node_config(node);119String rpc_list;120for (const KeyValue<uint16_t, RPCConfig> &config : cache.configs) {121rpc_list += String(config.value.name);122}123return rpc_list.md5_text();124}125126Node *SceneRPCInterface::_process_get_node(int p_from, const uint8_t *p_packet, uint32_t p_node_target, int p_packet_len) {127Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());128ERR_FAIL_NULL_V(root_node, nullptr);129Node *node = nullptr;130131if (p_node_target & 0x80000000) {132// Use full path (not cached yet).133int ofs = p_node_target & 0x7FFFFFFF;134135ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, nullptr, "Invalid packet received. Size smaller than declared.");136137String paths = String::utf8((const char *)&p_packet[ofs], p_packet_len - ofs);138139NodePath np = paths;140141node = root_node->get_node(np);142143if (!node) {144ERR_PRINT("Failed to get path from RPC: " + String(np) + ".");145}146return node;147} else {148// Use cached path.149return Object::cast_to<Node>(multiplayer_cache->get_cached_object(p_from, p_node_target));150}151}152153void SceneRPCInterface::process_rpc(int p_from, const uint8_t *p_packet, int p_packet_len) {154// Extract packet meta155int packet_min_size = 1;156int name_id_offset = 1;157ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");158// Compute the meta size, which depends on the compression level.159int node_id_compression = (p_packet[0] & NODE_ID_COMPRESSION_FLAG) >> NODE_ID_COMPRESSION_SHIFT;160int name_id_compression = (p_packet[0] & NAME_ID_COMPRESSION_FLAG) >> NAME_ID_COMPRESSION_SHIFT;161162switch (node_id_compression) {163case NETWORK_NODE_ID_COMPRESSION_8:164packet_min_size += 1;165name_id_offset += 1;166break;167case NETWORK_NODE_ID_COMPRESSION_16:168packet_min_size += 2;169name_id_offset += 2;170break;171case NETWORK_NODE_ID_COMPRESSION_32:172packet_min_size += 4;173name_id_offset += 4;174break;175default:176ERR_FAIL_MSG("Was not possible to extract the node id compression mode.");177}178switch (name_id_compression) {179case NETWORK_NAME_ID_COMPRESSION_8:180packet_min_size += 1;181break;182case NETWORK_NAME_ID_COMPRESSION_16:183packet_min_size += 2;184break;185default:186ERR_FAIL_MSG("Was not possible to extract the name id compression mode.");187}188ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");189190uint32_t node_target = 0;191switch (node_id_compression) {192case NETWORK_NODE_ID_COMPRESSION_8:193node_target = p_packet[1];194break;195case NETWORK_NODE_ID_COMPRESSION_16:196node_target = decode_uint16(p_packet + 1);197break;198case NETWORK_NODE_ID_COMPRESSION_32:199node_target = decode_uint32(p_packet + 1);200break;201default:202// Unreachable, checked before.203CRASH_NOW();204}205206Node *node = _process_get_node(p_from, p_packet, node_target, p_packet_len);207ERR_FAIL_NULL_MSG(node, "Invalid packet received. Requested node was not found.");208209uint16_t name_id = 0;210switch (name_id_compression) {211case NETWORK_NAME_ID_COMPRESSION_8:212name_id = p_packet[name_id_offset];213break;214case NETWORK_NAME_ID_COMPRESSION_16:215name_id = decode_uint16(p_packet + name_id_offset);216break;217default:218// Unreachable, checked before.219CRASH_NOW();220}221222const int packet_len = get_packet_len(node_target, p_packet_len);223_process_rpc(node, name_id, p_from, p_packet, packet_len, packet_min_size);224}225226static String _get_rpc_mode_string(MultiplayerAPI::RPCMode p_mode) {227switch (p_mode) {228case MultiplayerAPI::RPC_MODE_DISABLED:229return "disabled";230case MultiplayerAPI::RPC_MODE_ANY_PEER:231return "any_peer";232case MultiplayerAPI::RPC_MODE_AUTHORITY:233return "authority";234}235ERR_FAIL_V_MSG(String(), "Invalid RPC mode.");236}237238void SceneRPCInterface::_process_rpc(Node *p_node, const uint16_t p_rpc_method_id, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {239ERR_FAIL_COND_MSG(p_offset > p_packet_len, "Invalid packet received. Size too small.");240241// Check that remote can call the RPC on this node.242const RPCConfigCache &cache_config = _get_node_config(p_node);243ERR_FAIL_COND(!cache_config.configs.has(p_rpc_method_id));244const RPCConfig &config = cache_config.configs[p_rpc_method_id];245246bool can_call = false;247switch (config.rpc_mode) {248case MultiplayerAPI::RPC_MODE_DISABLED: {249can_call = false;250} break;251case MultiplayerAPI::RPC_MODE_ANY_PEER: {252can_call = true;253} break;254case MultiplayerAPI::RPC_MODE_AUTHORITY: {255can_call = p_from == p_node->get_multiplayer_authority();256} break;257}258259ERR_FAIL_COND_MSG(!can_call, "RPC '" + String(config.name) + "' is not allowed on node " + String(p_node->get_path()) + " from: " + itos(p_from) + ". Mode is \"" + _get_rpc_mode_string(config.rpc_mode) + "\", authority is " + itos(p_node->get_multiplayer_authority()) + ".");260261int argc = 0;262263const bool byte_only_or_no_args = p_packet[0] & BYTE_ONLY_OR_NO_ARGS_FLAG;264if (byte_only_or_no_args) {265if (p_offset < p_packet_len) {266// This packet contains only bytes.267argc = 1;268}269} else {270// Normal variant, takes the argument count from the packet.271ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");272argc = p_packet[p_offset];273p_offset += 1;274}275276Vector<Variant> args;277Vector<const Variant *> argp;278args.resize(argc);279argp.resize(argc);280281#ifdef DEBUG_ENABLED282_profile_node_data("rpc_in", p_node->get_instance_id(), p_packet_len);283#endif284285int out;286MultiplayerAPI::decode_and_decompress_variants(args, &p_packet[p_offset], p_packet_len - p_offset, out, byte_only_or_no_args, multiplayer->is_object_decoding_allowed());287for (int i = 0; i < argc; i++) {288argp.write[i] = &args[i];289}290291Callable::CallError ce;292293p_node->callp(config.name, (const Variant **)argp.ptr(), argc, ce);294if (ce.error != Callable::CallError::CALL_OK) {295String error = Variant::get_call_error_text(p_node, config.name, (const Variant **)argp.ptr(), argc, ce);296error = "RPC - " + error;297ERR_PRINT(error);298}299}300301void SceneRPCInterface::_send_rpc(Node *p_node, int p_to, uint16_t p_rpc_id, const RPCConfig &p_config, const StringName &p_name, const Variant **p_arg, int p_argcount) {302Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();303ERR_FAIL_COND_MSG(peer.is_null(), "Attempt to call RPC without active multiplayer peer.");304305ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_CONNECTING, "Attempt to call RPC while multiplayer peer is not connected yet.");306307ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to call RPC while multiplayer peer is disconnected.");308309ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments (>255).");310311if (p_to != 0 && !multiplayer->get_connected_peers().has(Math::abs(p_to))) {312ERR_FAIL_COND_MSG(p_to == multiplayer->get_unique_id(), "Attempt to call RPC on yourself! Peer unique ID: " + itos(multiplayer->get_unique_id()) + ".");313314ERR_FAIL_MSG("Attempt to call RPC with unknown peer ID: " + itos(p_to) + ".");315}316317// See if all peers have cached path (if so, call can be fast) while building the RPC target list.318HashSet<int> targets;319int psc_id = -1;320bool has_all_peers = true;321const ObjectID oid = p_node->get_instance_id();322if (p_to > 0) {323ERR_FAIL_COND_MSG(!multiplayer_replicator->is_rpc_visible(oid, p_to), "Attempt to call an RPC to a peer that cannot see this node. Peer ID: " + itos(p_to));324targets.insert(p_to);325has_all_peers = multiplayer_cache->send_object_cache(p_node, p_to, psc_id);326} else {327bool restricted = !multiplayer_replicator->is_rpc_visible(oid, 0);328for (const int &P : multiplayer->get_connected_peers()) {329if (p_to < 0 && P == -p_to) {330continue; // Excluded peer.331}332if (restricted && !multiplayer_replicator->is_rpc_visible(oid, P)) {333continue; // Not visible to this peer.334}335targets.insert(P);336bool has_peer = multiplayer_cache->send_object_cache(p_node, P, psc_id);337has_all_peers = has_all_peers && has_peer;338}339}340if (targets.is_empty()) {341return; // No one in sight.342}343344// Create base packet, lots of hardcode because it must be tight.345int ofs = 0;346347#define MAKE_ROOM(m_amount) \348if (packet_cache.size() < m_amount) \349packet_cache.resize(m_amount);350351// Encode meta.352uint8_t command_type = SceneMultiplayer::NETWORK_COMMAND_REMOTE_CALL;353uint8_t node_id_compression = UINT8_MAX;354uint8_t name_id_compression = UINT8_MAX;355bool byte_only_or_no_args = false;356357MAKE_ROOM(1);358// The meta is composed along the way, so just set 0 for now.359packet_cache.write[0] = 0;360ofs += 1;361362// Encode Node ID.363if (has_all_peers) {364// Compress the node ID only if all the target peers already know it.365if (psc_id >= 0 && psc_id <= 255) {366// We can encode the id in 1 byte367node_id_compression = NETWORK_NODE_ID_COMPRESSION_8;368MAKE_ROOM(ofs + 1);369packet_cache.write[ofs] = static_cast<uint8_t>(psc_id);370ofs += 1;371} else if (psc_id >= 0 && psc_id <= 65535) {372// We can encode the id in 2 bytes373node_id_compression = NETWORK_NODE_ID_COMPRESSION_16;374MAKE_ROOM(ofs + 2);375encode_uint16(static_cast<uint16_t>(psc_id), &(packet_cache.write[ofs]));376ofs += 2;377} else {378// Too big, let's use 4 bytes.379node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;380MAKE_ROOM(ofs + 4);381encode_uint32(psc_id, &(packet_cache.write[ofs]));382ofs += 4;383}384} else {385// The targets don't know the node yet, so we need to use 32 bits int.386node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;387MAKE_ROOM(ofs + 4);388encode_uint32(psc_id, &(packet_cache.write[ofs]));389ofs += 4;390}391392// Encode method ID393if (p_rpc_id <= UINT8_MAX) {394// The ID fits in 1 byte395name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;396MAKE_ROOM(ofs + 1);397packet_cache.write[ofs] = static_cast<uint8_t>(p_rpc_id);398ofs += 1;399} else {400// The ID is larger, let's use 2 bytes401name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;402MAKE_ROOM(ofs + 2);403encode_uint16(p_rpc_id, &(packet_cache.write[ofs]));404ofs += 2;405}406407int len;408Error err = MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, nullptr, len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());409ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC arguments. THIS IS LIKELY A BUG IN THE ENGINE!");410if (byte_only_or_no_args) {411MAKE_ROOM(ofs + len);412} else {413MAKE_ROOM(ofs + 1 + len);414packet_cache.write[ofs] = p_argcount;415ofs += 1;416}417if (len) {418MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, &packet_cache.write[ofs], len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());419ofs += len;420}421422ERR_FAIL_COND(command_type > 7);423ERR_FAIL_COND(node_id_compression > 3);424ERR_FAIL_COND(name_id_compression > 1);425426#ifdef DEBUG_ENABLED427_profile_node_data("rpc_out", p_node->get_instance_id(), ofs);428#endif429430// We can now set the meta431packet_cache.write[0] = command_type + (node_id_compression << NODE_ID_COMPRESSION_SHIFT) + (name_id_compression << NAME_ID_COMPRESSION_SHIFT) + (byte_only_or_no_args ? BYTE_ONLY_OR_NO_ARGS_FLAG : 0);432433// Take chance and set transfer mode, since all send methods will use it.434peer->set_transfer_channel(p_config.channel);435peer->set_transfer_mode(p_config.transfer_mode);436437if (has_all_peers) {438for (const int P : targets) {439multiplayer->send_command(P, packet_cache.ptr(), ofs);440}441} else {442// Unreachable because the node ID is never compressed if the peers doesn't know it.443CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);444445// Not all verified path, so send one by one.446447// Append path at the end, since we will need it for some packets.448CharString pname = String(multiplayer->get_root_path().rel_path_to(p_node->get_path())).utf8();449int path_len = encode_cstring(pname.get_data(), nullptr);450MAKE_ROOM(ofs + path_len);451encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));452453// Not all verified path, so check which needs the longer packet.454for (const int P : targets) {455bool confirmed = multiplayer_cache->is_cache_confirmed(p_node, P);456if (confirmed) {457// This one confirmed path, so use id.458encode_uint32(psc_id, &(packet_cache.write[1]));459multiplayer->send_command(P, packet_cache.ptr(), ofs);460} else {461// This one did not confirm path yet, so use entire path (sorry!).462encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.463multiplayer->send_command(P, packet_cache.ptr(), ofs + path_len);464}465}466}467}468469Error SceneRPCInterface::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {470Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();471ERR_FAIL_COND_V_MSG(peer.is_null(), ERR_UNCONFIGURED, "Trying to call an RPC while no multiplayer peer is active.");472Node *node = Object::cast_to<Node>(p_obj);473ERR_FAIL_COND_V_MSG(!node || !node->is_inside_tree(), ERR_INVALID_PARAMETER, "The object must be a valid Node inside the SceneTree");474ERR_FAIL_COND_V_MSG(peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_CONNECTION_ERROR, "Trying to call an RPC via a multiplayer peer which is not connected.");475476int caller_id = multiplayer->get_unique_id();477bool call_local_native = false;478bool call_local_script = false;479const RPCConfigCache &config_cache = _get_node_config(node);480uint16_t rpc_id = config_cache.ids.has(p_method) ? config_cache.ids[p_method] : UINT16_MAX;481ERR_FAIL_COND_V_MSG(rpc_id == UINT16_MAX, ERR_INVALID_PARAMETER,482vformat("Unable to get the RPC configuration for the function \"%s\" at path: \"%s\". This happens when the method is missing or not marked for RPCs in the local script.", p_method, node->get_path()));483const RPCConfig &config = config_cache.configs[rpc_id];484485ERR_FAIL_COND_V_MSG(p_peer_id == caller_id && !config.call_local, ERR_INVALID_PARAMETER, "RPC '" + p_method + "' on yourself is not allowed by selected mode.");486487if (p_peer_id == 0 || p_peer_id == caller_id || (p_peer_id < 0 && p_peer_id != -caller_id)) {488if (rpc_id & (1 << 15)) {489call_local_native = config.call_local;490} else {491call_local_script = config.call_local;492}493}494495if (p_peer_id != caller_id) {496_send_rpc(node, p_peer_id, rpc_id, config, p_method, p_arg, p_argcount);497}498499if (call_local_native) {500Callable::CallError ce;501502multiplayer->set_remote_sender_override(multiplayer->get_unique_id());503node->callp(p_method, p_arg, p_argcount, ce);504multiplayer->set_remote_sender_override(0);505506if (ce.error != Callable::CallError::CALL_OK) {507String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);508error = "rpc() aborted in local call: - " + error + ".";509ERR_PRINT(error);510return FAILED;511}512}513514if (call_local_script) {515Callable::CallError ce;516ce.error = Callable::CallError::CALL_OK;517518multiplayer->set_remote_sender_override(multiplayer->get_unique_id());519node->get_script_instance()->callp(p_method, p_arg, p_argcount, ce);520multiplayer->set_remote_sender_override(0);521522if (ce.error != Callable::CallError::CALL_OK) {523String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);524error = "rpc() aborted in script local call: - " + error + ".";525ERR_PRINT(error);526return FAILED;527}528}529return OK;530}531532533