Path: blob/master/modules/multiplayer/scene_rpc_interface.cpp
10277 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}225226void 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) {227ERR_FAIL_COND_MSG(p_offset > p_packet_len, "Invalid packet received. Size too small.");228229// Check that remote can call the RPC on this node.230const RPCConfigCache &cache_config = _get_node_config(p_node);231ERR_FAIL_COND(!cache_config.configs.has(p_rpc_method_id));232const RPCConfig &config = cache_config.configs[p_rpc_method_id];233234bool can_call = false;235switch (config.rpc_mode) {236case MultiplayerAPI::RPC_MODE_DISABLED: {237can_call = false;238} break;239case MultiplayerAPI::RPC_MODE_ANY_PEER: {240can_call = true;241} break;242case MultiplayerAPI::RPC_MODE_AUTHORITY: {243can_call = p_from == p_node->get_multiplayer_authority();244} break;245}246247ERR_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 " + itos((int)config.rpc_mode) + ", authority is " + itos(p_node->get_multiplayer_authority()) + ".");248249int argc = 0;250251const bool byte_only_or_no_args = p_packet[0] & BYTE_ONLY_OR_NO_ARGS_FLAG;252if (byte_only_or_no_args) {253if (p_offset < p_packet_len) {254// This packet contains only bytes.255argc = 1;256}257} else {258// Normal variant, takes the argument count from the packet.259ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");260argc = p_packet[p_offset];261p_offset += 1;262}263264Vector<Variant> args;265Vector<const Variant *> argp;266args.resize(argc);267argp.resize(argc);268269#ifdef DEBUG_ENABLED270_profile_node_data("rpc_in", p_node->get_instance_id(), p_packet_len);271#endif272273int out;274MultiplayerAPI::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());275for (int i = 0; i < argc; i++) {276argp.write[i] = &args[i];277}278279Callable::CallError ce;280281p_node->callp(config.name, (const Variant **)argp.ptr(), argc, ce);282if (ce.error != Callable::CallError::CALL_OK) {283String error = Variant::get_call_error_text(p_node, config.name, (const Variant **)argp.ptr(), argc, ce);284error = "RPC - " + error;285ERR_PRINT(error);286}287}288289void 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) {290Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();291ERR_FAIL_COND_MSG(peer.is_null(), "Attempt to call RPC without active multiplayer peer.");292293ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_CONNECTING, "Attempt to call RPC while multiplayer peer is not connected yet.");294295ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to call RPC while multiplayer peer is disconnected.");296297ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments (>255).");298299if (p_to != 0 && !multiplayer->get_connected_peers().has(Math::abs(p_to))) {300ERR_FAIL_COND_MSG(p_to == multiplayer->get_unique_id(), "Attempt to call RPC on yourself! Peer unique ID: " + itos(multiplayer->get_unique_id()) + ".");301302ERR_FAIL_MSG("Attempt to call RPC with unknown peer ID: " + itos(p_to) + ".");303}304305// See if all peers have cached path (if so, call can be fast) while building the RPC target list.306HashSet<int> targets;307int psc_id = -1;308bool has_all_peers = true;309const ObjectID oid = p_node->get_instance_id();310if (p_to > 0) {311ERR_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));312targets.insert(p_to);313has_all_peers = multiplayer_cache->send_object_cache(p_node, p_to, psc_id);314} else {315bool restricted = !multiplayer_replicator->is_rpc_visible(oid, 0);316for (const int &P : multiplayer->get_connected_peers()) {317if (p_to < 0 && P == -p_to) {318continue; // Excluded peer.319}320if (restricted && !multiplayer_replicator->is_rpc_visible(oid, P)) {321continue; // Not visible to this peer.322}323targets.insert(P);324bool has_peer = multiplayer_cache->send_object_cache(p_node, P, psc_id);325has_all_peers = has_all_peers && has_peer;326}327}328if (targets.is_empty()) {329return; // No one in sight.330}331332// Create base packet, lots of hardcode because it must be tight.333int ofs = 0;334335#define MAKE_ROOM(m_amount) \336if (packet_cache.size() < m_amount) \337packet_cache.resize(m_amount);338339// Encode meta.340uint8_t command_type = SceneMultiplayer::NETWORK_COMMAND_REMOTE_CALL;341uint8_t node_id_compression = UINT8_MAX;342uint8_t name_id_compression = UINT8_MAX;343bool byte_only_or_no_args = false;344345MAKE_ROOM(1);346// The meta is composed along the way, so just set 0 for now.347packet_cache.write[0] = 0;348ofs += 1;349350// Encode Node ID.351if (has_all_peers) {352// Compress the node ID only if all the target peers already know it.353if (psc_id >= 0 && psc_id <= 255) {354// We can encode the id in 1 byte355node_id_compression = NETWORK_NODE_ID_COMPRESSION_8;356MAKE_ROOM(ofs + 1);357packet_cache.write[ofs] = static_cast<uint8_t>(psc_id);358ofs += 1;359} else if (psc_id >= 0 && psc_id <= 65535) {360// We can encode the id in 2 bytes361node_id_compression = NETWORK_NODE_ID_COMPRESSION_16;362MAKE_ROOM(ofs + 2);363encode_uint16(static_cast<uint16_t>(psc_id), &(packet_cache.write[ofs]));364ofs += 2;365} else {366// Too big, let's use 4 bytes.367node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;368MAKE_ROOM(ofs + 4);369encode_uint32(psc_id, &(packet_cache.write[ofs]));370ofs += 4;371}372} else {373// The targets don't know the node yet, so we need to use 32 bits int.374node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;375MAKE_ROOM(ofs + 4);376encode_uint32(psc_id, &(packet_cache.write[ofs]));377ofs += 4;378}379380// Encode method ID381if (p_rpc_id <= UINT8_MAX) {382// The ID fits in 1 byte383name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;384MAKE_ROOM(ofs + 1);385packet_cache.write[ofs] = static_cast<uint8_t>(p_rpc_id);386ofs += 1;387} else {388// The ID is larger, let's use 2 bytes389name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;390MAKE_ROOM(ofs + 2);391encode_uint16(p_rpc_id, &(packet_cache.write[ofs]));392ofs += 2;393}394395int len;396Error err = MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, nullptr, len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());397ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC arguments. THIS IS LIKELY A BUG IN THE ENGINE!");398if (byte_only_or_no_args) {399MAKE_ROOM(ofs + len);400} else {401MAKE_ROOM(ofs + 1 + len);402packet_cache.write[ofs] = p_argcount;403ofs += 1;404}405if (len) {406MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, &packet_cache.write[ofs], len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());407ofs += len;408}409410ERR_FAIL_COND(command_type > 7);411ERR_FAIL_COND(node_id_compression > 3);412ERR_FAIL_COND(name_id_compression > 1);413414#ifdef DEBUG_ENABLED415_profile_node_data("rpc_out", p_node->get_instance_id(), ofs);416#endif417418// We can now set the meta419packet_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);420421// Take chance and set transfer mode, since all send methods will use it.422peer->set_transfer_channel(p_config.channel);423peer->set_transfer_mode(p_config.transfer_mode);424425if (has_all_peers) {426for (const int P : targets) {427multiplayer->send_command(P, packet_cache.ptr(), ofs);428}429} else {430// Unreachable because the node ID is never compressed if the peers doesn't know it.431CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);432433// Not all verified path, so send one by one.434435// Append path at the end, since we will need it for some packets.436CharString pname = String(multiplayer->get_root_path().rel_path_to(p_node->get_path())).utf8();437int path_len = encode_cstring(pname.get_data(), nullptr);438MAKE_ROOM(ofs + path_len);439encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));440441// Not all verified path, so check which needs the longer packet.442for (const int P : targets) {443bool confirmed = multiplayer_cache->is_cache_confirmed(p_node, P);444if (confirmed) {445// This one confirmed path, so use id.446encode_uint32(psc_id, &(packet_cache.write[1]));447multiplayer->send_command(P, packet_cache.ptr(), ofs);448} else {449// This one did not confirm path yet, so use entire path (sorry!).450encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.451multiplayer->send_command(P, packet_cache.ptr(), ofs + path_len);452}453}454}455}456457Error SceneRPCInterface::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {458Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();459ERR_FAIL_COND_V_MSG(peer.is_null(), ERR_UNCONFIGURED, "Trying to call an RPC while no multiplayer peer is active.");460Node *node = Object::cast_to<Node>(p_obj);461ERR_FAIL_COND_V_MSG(!node || !node->is_inside_tree(), ERR_INVALID_PARAMETER, "The object must be a valid Node inside the SceneTree");462ERR_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.");463464int caller_id = multiplayer->get_unique_id();465bool call_local_native = false;466bool call_local_script = false;467const RPCConfigCache &config_cache = _get_node_config(node);468uint16_t rpc_id = config_cache.ids.has(p_method) ? config_cache.ids[p_method] : UINT16_MAX;469ERR_FAIL_COND_V_MSG(rpc_id == UINT16_MAX, ERR_INVALID_PARAMETER,470vformat("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()));471const RPCConfig &config = config_cache.configs[rpc_id];472473ERR_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.");474475if (p_peer_id == 0 || p_peer_id == caller_id || (p_peer_id < 0 && p_peer_id != -caller_id)) {476if (rpc_id & (1 << 15)) {477call_local_native = config.call_local;478} else {479call_local_script = config.call_local;480}481}482483if (p_peer_id != caller_id) {484_send_rpc(node, p_peer_id, rpc_id, config, p_method, p_arg, p_argcount);485}486487if (call_local_native) {488Callable::CallError ce;489490multiplayer->set_remote_sender_override(multiplayer->get_unique_id());491node->callp(p_method, p_arg, p_argcount, ce);492multiplayer->set_remote_sender_override(0);493494if (ce.error != Callable::CallError::CALL_OK) {495String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);496error = "rpc() aborted in local call: - " + error + ".";497ERR_PRINT(error);498return FAILED;499}500}501502if (call_local_script) {503Callable::CallError ce;504ce.error = Callable::CallError::CALL_OK;505506multiplayer->set_remote_sender_override(multiplayer->get_unique_id());507node->get_script_instance()->callp(p_method, p_arg, p_argcount, ce);508multiplayer->set_remote_sender_override(0);509510if (ce.error != Callable::CallError::CALL_OK) {511String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);512error = "rpc() aborted in script local call: - " + error + ".";513ERR_PRINT(error);514return FAILED;515}516}517return OK;518}519520521