Path: blob/master/modules/multiplayer/scene_rpc_interface.cpp
20844 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];86// Default values should match GDScript `@rpc` annotation registration and `rpc_annotation()`.87RPCConfig cfg;88cfg.name = name;89cfg.rpc_mode = ((MultiplayerAPI::RPCMode)dict.get("rpc_mode", MultiplayerAPI::RPC_MODE_AUTHORITY).operator int());90cfg.transfer_mode = ((MultiplayerPeer::TransferMode)dict.get("transfer_mode", MultiplayerPeer::TRANSFER_MODE_RELIABLE).operator int());91cfg.call_local = dict.get("call_local", false).operator bool();92cfg.channel = dict.get("channel", 0).operator int();93uint16_t id = ((uint16_t)i);94if (p_for_node) {95id |= (1 << 15);96}97r_cache.configs[id] = cfg;98r_cache.ids[name] = id;99}100}101102const SceneRPCInterface::RPCConfigCache &SceneRPCInterface::_get_node_config(const Node *p_node) {103const ObjectID oid = p_node->get_instance_id();104if (rpc_cache.has(oid)) {105return rpc_cache[oid];106}107RPCConfigCache cache;108_parse_rpc_config(p_node->get_node_rpc_config(), true, cache);109if (p_node->get_script_instance()) {110_parse_rpc_config(p_node->get_script_instance()->get_rpc_config(), false, cache);111}112rpc_cache[oid] = cache;113return rpc_cache[oid];114}115116String SceneRPCInterface::get_rpc_md5(const Object *p_obj) {117const Node *node = Object::cast_to<Node>(p_obj);118ERR_FAIL_NULL_V(node, "");119const RPCConfigCache cache = _get_node_config(node);120String rpc_list;121for (const KeyValue<uint16_t, RPCConfig> &config : cache.configs) {122rpc_list += String(config.value.name);123}124return rpc_list.md5_text();125}126127Node *SceneRPCInterface::_process_get_node(int p_from, const uint8_t *p_packet, uint32_t p_node_target, int p_packet_len) {128Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());129ERR_FAIL_NULL_V(root_node, nullptr);130Node *node = nullptr;131132if (p_node_target & 0x80000000) {133// Use full path (not cached yet).134int ofs = p_node_target & 0x7FFFFFFF;135136ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, nullptr, "Invalid packet received. Size smaller than declared.");137138String paths = String::utf8((const char *)&p_packet[ofs], p_packet_len - ofs);139140NodePath np = paths;141142node = root_node->get_node(np);143144if (!node) {145ERR_PRINT("Failed to get path from RPC: " + String(np) + ".");146}147return node;148} else {149// Use cached path.150return Object::cast_to<Node>(multiplayer_cache->get_cached_object(p_from, p_node_target));151}152}153154void SceneRPCInterface::process_rpc(int p_from, const uint8_t *p_packet, int p_packet_len) {155// Extract packet meta156int packet_min_size = 1;157int name_id_offset = 1;158ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");159// Compute the meta size, which depends on the compression level.160int node_id_compression = (p_packet[0] & NODE_ID_COMPRESSION_FLAG) >> NODE_ID_COMPRESSION_SHIFT;161int name_id_compression = (p_packet[0] & NAME_ID_COMPRESSION_FLAG) >> NAME_ID_COMPRESSION_SHIFT;162163switch (node_id_compression) {164case NETWORK_NODE_ID_COMPRESSION_8:165packet_min_size += 1;166name_id_offset += 1;167break;168case NETWORK_NODE_ID_COMPRESSION_16:169packet_min_size += 2;170name_id_offset += 2;171break;172case NETWORK_NODE_ID_COMPRESSION_32:173packet_min_size += 4;174name_id_offset += 4;175break;176default:177ERR_FAIL_MSG("Was not possible to extract the node id compression mode.");178}179switch (name_id_compression) {180case NETWORK_NAME_ID_COMPRESSION_8:181packet_min_size += 1;182break;183case NETWORK_NAME_ID_COMPRESSION_16:184packet_min_size += 2;185break;186default:187ERR_FAIL_MSG("Was not possible to extract the name id compression mode.");188}189ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");190191uint32_t node_target = 0;192switch (node_id_compression) {193case NETWORK_NODE_ID_COMPRESSION_8:194node_target = p_packet[1];195break;196case NETWORK_NODE_ID_COMPRESSION_16:197node_target = decode_uint16(p_packet + 1);198break;199case NETWORK_NODE_ID_COMPRESSION_32:200node_target = decode_uint32(p_packet + 1);201break;202default:203// Unreachable, checked before.204CRASH_NOW();205}206207Node *node = _process_get_node(p_from, p_packet, node_target, p_packet_len);208ERR_FAIL_NULL_MSG(node, "Invalid packet received. Requested node was not found.");209210uint16_t name_id = 0;211switch (name_id_compression) {212case NETWORK_NAME_ID_COMPRESSION_8:213name_id = p_packet[name_id_offset];214break;215case NETWORK_NAME_ID_COMPRESSION_16:216name_id = decode_uint16(p_packet + name_id_offset);217break;218default:219// Unreachable, checked before.220CRASH_NOW();221}222223const int packet_len = get_packet_len(node_target, p_packet_len);224_process_rpc(node, name_id, p_from, p_packet, packet_len, packet_min_size);225}226227static String _get_rpc_mode_string(MultiplayerAPI::RPCMode p_mode) {228switch (p_mode) {229case MultiplayerAPI::RPC_MODE_DISABLED:230return "disabled";231case MultiplayerAPI::RPC_MODE_ANY_PEER:232return "any_peer";233case MultiplayerAPI::RPC_MODE_AUTHORITY:234return "authority";235}236ERR_FAIL_V_MSG(String(), "Invalid RPC mode.");237}238239void 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) {240ERR_FAIL_COND_MSG(p_offset > p_packet_len, "Invalid packet received. Size too small.");241242// Check that remote can call the RPC on this node.243const RPCConfigCache &cache_config = _get_node_config(p_node);244ERR_FAIL_COND(!cache_config.configs.has(p_rpc_method_id));245const RPCConfig &config = cache_config.configs[p_rpc_method_id];246247bool can_call = false;248switch (config.rpc_mode) {249case MultiplayerAPI::RPC_MODE_DISABLED: {250can_call = false;251} break;252case MultiplayerAPI::RPC_MODE_ANY_PEER: {253can_call = true;254} break;255case MultiplayerAPI::RPC_MODE_AUTHORITY: {256can_call = p_from == p_node->get_multiplayer_authority();257} break;258}259260ERR_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()) + ".");261262int argc = 0;263264const bool byte_only_or_no_args = p_packet[0] & BYTE_ONLY_OR_NO_ARGS_FLAG;265if (byte_only_or_no_args) {266if (p_offset < p_packet_len) {267// This packet contains only bytes.268argc = 1;269}270} else {271// Normal variant, takes the argument count from the packet.272ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");273argc = p_packet[p_offset];274p_offset += 1;275}276277Vector<Variant> args;278Vector<const Variant *> argp;279args.resize(argc);280argp.resize(argc);281282#ifdef DEBUG_ENABLED283_profile_node_data("rpc_in", p_node->get_instance_id(), p_packet_len);284#endif285286int out;287MultiplayerAPI::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());288for (int i = 0; i < argc; i++) {289argp.write[i] = &args[i];290}291292Callable::CallError ce;293294p_node->callp(config.name, (const Variant **)argp.ptr(), argc, ce);295if (ce.error != Callable::CallError::CALL_OK) {296String error = Variant::get_call_error_text(p_node, config.name, (const Variant **)argp.ptr(), argc, ce);297error = "RPC - " + error;298ERR_PRINT(error);299}300}301302void 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) {303Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();304ERR_FAIL_COND_MSG(peer.is_null(), "Attempt to call RPC without active multiplayer peer.");305306ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_CONNECTING, "Attempt to call RPC while multiplayer peer is not connected yet.");307308ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to call RPC while multiplayer peer is disconnected.");309310ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments (>255).");311312if (p_to != 0 && !multiplayer->get_connected_peers().has(Math::abs(p_to))) {313ERR_FAIL_COND_MSG(p_to == multiplayer->get_unique_id(), "Attempt to call RPC on yourself! Peer unique ID: " + itos(multiplayer->get_unique_id()) + ".");314315ERR_FAIL_MSG("Attempt to call RPC with unknown peer ID: " + itos(p_to) + ".");316}317318// See if all peers have cached path (if so, call can be fast) while building the RPC target list.319HashSet<int> targets;320int psc_id = -1;321bool has_all_peers = true;322const ObjectID oid = p_node->get_instance_id();323if (p_to > 0) {324ERR_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));325targets.insert(p_to);326has_all_peers = multiplayer_cache->send_object_cache(p_node, p_to, psc_id);327} else {328bool restricted = !multiplayer_replicator->is_rpc_visible(oid, 0);329for (const int &P : multiplayer->get_connected_peers()) {330if (p_to < 0 && P == -p_to) {331continue; // Excluded peer.332}333if (restricted && !multiplayer_replicator->is_rpc_visible(oid, P)) {334continue; // Not visible to this peer.335}336targets.insert(P);337bool has_peer = multiplayer_cache->send_object_cache(p_node, P, psc_id);338has_all_peers = has_all_peers && has_peer;339}340}341if (targets.is_empty()) {342return; // No one in sight.343}344345// Create base packet, lots of hardcode because it must be tight.346int ofs = 0;347348#define MAKE_ROOM(m_amount) \349if (packet_cache.size() < m_amount) \350packet_cache.resize(m_amount);351352// Encode meta.353uint8_t command_type = SceneMultiplayer::NETWORK_COMMAND_REMOTE_CALL;354uint8_t node_id_compression = UINT8_MAX;355uint8_t name_id_compression = UINT8_MAX;356bool byte_only_or_no_args = false;357358MAKE_ROOM(1);359// The meta is composed along the way, so just set 0 for now.360packet_cache.write[0] = 0;361ofs += 1;362363// Encode Node ID.364if (has_all_peers) {365// Compress the node ID only if all the target peers already know it.366if (psc_id >= 0 && psc_id <= 255) {367// We can encode the id in 1 byte368node_id_compression = NETWORK_NODE_ID_COMPRESSION_8;369MAKE_ROOM(ofs + 1);370packet_cache.write[ofs] = static_cast<uint8_t>(psc_id);371ofs += 1;372} else if (psc_id >= 0 && psc_id <= 65535) {373// We can encode the id in 2 bytes374node_id_compression = NETWORK_NODE_ID_COMPRESSION_16;375MAKE_ROOM(ofs + 2);376encode_uint16(static_cast<uint16_t>(psc_id), &(packet_cache.write[ofs]));377ofs += 2;378} else {379// Too big, let's use 4 bytes.380node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;381MAKE_ROOM(ofs + 4);382encode_uint32(psc_id, &(packet_cache.write[ofs]));383ofs += 4;384}385} else {386// The targets don't know the node yet, so we need to use 32 bits int.387node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;388MAKE_ROOM(ofs + 4);389encode_uint32(psc_id, &(packet_cache.write[ofs]));390ofs += 4;391}392393// Encode method ID394if (p_rpc_id <= UINT8_MAX) {395// The ID fits in 1 byte396name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;397MAKE_ROOM(ofs + 1);398packet_cache.write[ofs] = static_cast<uint8_t>(p_rpc_id);399ofs += 1;400} else {401// The ID is larger, let's use 2 bytes402name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;403MAKE_ROOM(ofs + 2);404encode_uint16(p_rpc_id, &(packet_cache.write[ofs]));405ofs += 2;406}407408int len;409Error err = MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, nullptr, len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());410ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC arguments. THIS IS LIKELY A BUG IN THE ENGINE!");411if (byte_only_or_no_args) {412MAKE_ROOM(ofs + len);413} else {414MAKE_ROOM(ofs + 1 + len);415packet_cache.write[ofs] = p_argcount;416ofs += 1;417}418if (len) {419MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, &packet_cache.write[ofs], len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());420ofs += len;421}422423ERR_FAIL_COND(command_type > 7);424ERR_FAIL_COND(node_id_compression > 3);425ERR_FAIL_COND(name_id_compression > 1);426427#ifdef DEBUG_ENABLED428_profile_node_data("rpc_out", p_node->get_instance_id(), ofs);429#endif430431// We can now set the meta432packet_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);433434// Take chance and set transfer mode, since all send methods will use it.435peer->set_transfer_channel(p_config.channel);436peer->set_transfer_mode(p_config.transfer_mode);437438if (has_all_peers) {439for (const int P : targets) {440multiplayer->send_command(P, packet_cache.ptr(), ofs);441}442} else {443// Unreachable because the node ID is never compressed if the peers doesn't know it.444CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);445446// Not all verified path, so send one by one.447448// Append path at the end, since we will need it for some packets.449CharString pname = String(multiplayer->get_root_path().rel_path_to(p_node->get_path())).utf8();450int path_len = encode_cstring(pname.get_data(), nullptr);451MAKE_ROOM(ofs + path_len);452encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));453454// Not all verified path, so check which needs the longer packet.455for (const int P : targets) {456bool confirmed = multiplayer_cache->is_cache_confirmed(p_node, P);457if (confirmed) {458// This one confirmed path, so use id.459encode_uint32(psc_id, &(packet_cache.write[1]));460multiplayer->send_command(P, packet_cache.ptr(), ofs);461} else {462// This one did not confirm path yet, so use entire path (sorry!).463encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.464multiplayer->send_command(P, packet_cache.ptr(), ofs + path_len);465}466}467}468}469470Error SceneRPCInterface::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {471Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();472ERR_FAIL_COND_V_MSG(peer.is_null(), ERR_UNCONFIGURED, "Trying to call an RPC while no multiplayer peer is active.");473Node *node = Object::cast_to<Node>(p_obj);474ERR_FAIL_COND_V_MSG(!node || !node->is_inside_tree(), ERR_INVALID_PARAMETER, "The object must be a valid Node inside the SceneTree");475ERR_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.");476477int caller_id = multiplayer->get_unique_id();478bool call_local_native = false;479bool call_local_script = false;480const RPCConfigCache &config_cache = _get_node_config(node);481uint16_t rpc_id = config_cache.ids.has(p_method) ? config_cache.ids[p_method] : UINT16_MAX;482ERR_FAIL_COND_V_MSG(rpc_id == UINT16_MAX, ERR_INVALID_PARAMETER,483vformat("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()));484const RPCConfig &config = config_cache.configs[rpc_id];485486ERR_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.");487488if (p_peer_id == 0 || p_peer_id == caller_id || (p_peer_id < 0 && p_peer_id != -caller_id)) {489if (rpc_id & (1 << 15)) {490call_local_native = config.call_local;491} else {492call_local_script = config.call_local;493}494}495496if (p_peer_id != caller_id) {497_send_rpc(node, p_peer_id, rpc_id, config, p_method, p_arg, p_argcount);498}499500if (call_local_native) {501Callable::CallError ce;502503multiplayer->set_remote_sender_override(multiplayer->get_unique_id());504node->callp(p_method, p_arg, p_argcount, ce);505multiplayer->set_remote_sender_override(0);506507if (ce.error != Callable::CallError::CALL_OK) {508String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);509error = "rpc() aborted in local call: - " + error + ".";510ERR_PRINT(error);511return FAILED;512}513}514515if (call_local_script) {516Callable::CallError ce;517ce.error = Callable::CallError::CALL_OK;518519multiplayer->set_remote_sender_override(multiplayer->get_unique_id());520node->get_script_instance()->callp(p_method, p_arg, p_argcount, ce);521multiplayer->set_remote_sender_override(0);522523if (ce.error != Callable::CallError::CALL_OK) {524String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);525error = "rpc() aborted in script local call: - " + error + ".";526ERR_PRINT(error);527return FAILED;528}529}530return OK;531}532533534