[Net] Implement lower level ENet wrappers.

This commit is contained in:
Fabio Alessandrelli 2021-06-14 11:51:53 +02:00
parent 1e8bf86379
commit 42a1777531
10 changed files with 1487 additions and 10 deletions

View File

@ -9,6 +9,8 @@ def configure(env):
def get_doc_classes():
return [
"ENetMultiplayerPeer",
"ENetConnection",
"ENetPacketPeer",
]

View File

@ -0,0 +1,240 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="ENetConnection" inherits="RefCounted" version="4.0">
<brief_description>
A wrapper class for an [url=http://enet.bespin.org/group__host.html]ENetHost[/url].
</brief_description>
<description>
ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol).
</description>
<tutorials>
<link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link>
</tutorials>
<methods>
<method name="bandwidth_limit">
<return type="void">
</return>
<argument index="0" name="in_bandwidth" type="int" default="0">
</argument>
<argument index="1" name="out_bandwidth" type="int" default="0">
</argument>
<description>
Adjusts the bandwidth limits of a host.
</description>
</method>
<method name="broadcast">
<return type="void">
</return>
<argument index="0" name="channel" type="int">
</argument>
<argument index="1" name="packet" type="PackedByteArray">
</argument>
<argument index="2" name="flags" type="int">
</argument>
<description>
Queues a [code]packet[/code] to be sent to all peers associated with the host over the specified [code]channel[/code]. See [ENetPacketPeer] [code]FLAG_*[/code] constants for available packet flags.
</description>
</method>
<method name="channel_limit">
<return type="void">
</return>
<argument index="0" name="limit" type="int">
</argument>
<description>
Limits the maximum allowed channels of future incoming connections.
</description>
</method>
<method name="compress">
<return type="void">
</return>
<argument index="0" name="mode" type="int" enum="ENetConnection.CompressionMode">
</argument>
<description>
Sets the compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all.
[b]Note:[/b] Most games' network design involve sending many small packets frequently (smaller than 4 KB each). If in doubt, it is recommended to keep the default compression algorithm as it works best on these small packets.
</description>
</method>
<method name="connect_to_host">
<return type="ENetPacketPeer">
</return>
<argument index="0" name="address" type="String">
</argument>
<argument index="1" name="port" type="int">
</argument>
<argument index="2" name="channels" type="int" default="0">
</argument>
<argument index="3" name="data" type="int" default="0">
</argument>
<description>
Initiates a connection to a foreign [code]address[/code] using the specified [code]port[/code] and allocting the requested [code]channels[/code]. Optional [code]data[/code] can be passed during connection in the form of a 32 bit integer.
Note: You must call either [method create_host] or [method create_host_bound] before calling this method.
</description>
</method>
<method name="create_host">
<return type="int" enum="Error">
</return>
<argument index="0" name="max_peers" type="int" default="32">
</argument>
<argument index="1" name="max_channels" type="int" default="0">
</argument>
<argument index="2" name="in_bandwidth" type="int" default="0">
</argument>
<argument index="3" name="out_bandwidth" type="int" default="0">
</argument>
<description>
Create an ENetHost that will allow up to [code]max_peers[/code] connected peers, each allocating up to [code]max_channels[/code] channels, optionally limiting bandwith to [code]in_bandwidth[/code] and [code]out_bandwidth[/code].
</description>
</method>
<method name="create_host_bound">
<return type="int" enum="Error">
</return>
<argument index="0" name="bind_address" type="String">
</argument>
<argument index="1" name="bind_port" type="int">
</argument>
<argument index="2" name="max_peers" type="int" default="32">
</argument>
<argument index="3" name="max_channels" type="int" default="0">
</argument>
<argument index="4" name="in_bandwidth" type="int" default="0">
</argument>
<argument index="5" name="out_bandwidth" type="int" default="0">
</argument>
<description>
Create an ENetHost like [method create_host] which is also bound to the given [code]bind_address[/code] and [code]bind_port[/code].
</description>
</method>
<method name="destroy">
<return type="void">
</return>
<description>
Destroys the host and all resources associated with it.
</description>
</method>
<method name="dtls_client_setup">
<return type="int" enum="Error">
</return>
<argument index="0" name="certificate" type="X509Certificate">
</argument>
<argument index="1" name="hostname" type="String">
</argument>
<argument index="2" name="verify" type="bool" default="true">
</argument>
<description>
Configure this ENetHost to use the custom Godot extension allowing DTLS encryption for ENet clients. Call this before [method connect_to_host] to have ENet connect using DTLS with [code]certificate[/code] and [code]hostname[/code] verification. Verification can be optionally turned off via the [code]verify[/code] parameter.
</description>
</method>
<method name="dtls_server_setup">
<return type="int" enum="Error">
</return>
<argument index="0" name="key" type="CryptoKey">
</argument>
<argument index="1" name="certificate" type="X509Certificate">
</argument>
<description>
Configure this ENetHost to use the custom Godot extension allowing DTLS encryption for ENet servers. Call this right after [method create_host_bound] to have ENet expect peers to connect using DTLS.
</description>
</method>
<method name="flush">
<return type="void">
</return>
<description>
Sends any queued packets on the host specified to its designated peers.
</description>
</method>
<method name="get_local_port" qualifiers="const">
<return type="int">
</return>
<description>
Returns the local port to which this peer is bound.
</description>
</method>
<method name="get_max_channels" qualifiers="const">
<return type="int">
</return>
<description>
Returns the maximum number of channels allowed for connected peers.
</description>
</method>
<method name="get_peers">
<return type="Array">
</return>
<description>
Returns the list of peers associated with this host.
Note: This list might include some peers that are not fully connected or are still being disconnected.
</description>
</method>
<method name="pop_statistic">
<return type="float">
</return>
<argument index="0" name="statistic" type="int" enum="ENetConnection.HostStatistic">
</argument>
<description>
Returns and resets host statistics. See [enum HostStatistic] for more info.
</description>
</method>
<method name="refuse_new_connections">
<return type="void">
</return>
<argument index="0" name="refuse" type="bool">
</argument>
<description>
Configures the DTLS server to automatically drop new connections.
Note: This method is only relevant after calling [method dtls_server_setup].
</description>
</method>
<method name="service">
<return type="Array">
</return>
<argument index="0" name="timeout" type="int" default="0">
</argument>
<description>
Waits for events on the host specified and shuttles packets between the host and its peers. The returned [Array] will have 4 elements. An [enum EventType], the [ENetPacketPeer] which generated the event, the event associated data (if any), the event associated channel (if any). If the generated event is [constant EVENT_RECEIVE], the received packet will be queued to the associated [ENetPacketPeer].
Call this function regularly to handle connections, disconnections, and to receive new packets.
</description>
</method>
</methods>
<constants>
<constant name="COMPRESS_NONE" value="0" enum="CompressionMode">
No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources. This option may also be used to make network debugging using tools like Wireshark easier.
</constant>
<constant name="COMPRESS_RANGE_CODER" value="1" enum="CompressionMode">
ENet's built-in range encoding. Works well on small packets, but is not the most efficient algorithm on packets larger than 4 KB.
</constant>
<constant name="COMPRESS_FASTLZ" value="2" enum="CompressionMode">
[url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth.
</constant>
<constant name="COMPRESS_ZLIB" value="3" enum="CompressionMode">
[url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources.
</constant>
<constant name="COMPRESS_ZSTD" value="4" enum="CompressionMode">
[url=https://facebook.github.io/zstd/]Zstandard[/url] compression. Note that this algorithm is not very efficient on packets smaller than 4 KB. Therefore, it's recommended to use other compression algorithms in most cases.
</constant>
<constant name="EVENT_ERROR" value="-1" enum="EventType">
An error occurred during [method service]. You will likely need to [method destroy] the host and recreate it.
</constant>
<constant name="EVENT_NONE" value="0" enum="EventType">
No event occurred within the specified time limit.
</constant>
<constant name="EVENT_CONNECT" value="1" enum="EventType">
A connection request initiated by enet_host_connect has completed. The array will contain the peer which successfully connected.
</constant>
<constant name="EVENT_DISCONNECT" value="2" enum="EventType">
A peer has disconnected. This event is generated on a successful completion of a disconnect initiated by [method ENetPacketPeer.peer_disconnect], if a peer has timed out, or if a connection request intialized by [method connect_to_host] has timed out. The array will contain the peer which disconnected. The data field contains user supplied data describing the disconnection, or 0, if none is available.
</constant>
<constant name="EVENT_RECEIVE" value="3" enum="EventType">
A packet has been received from a peer. The array will contain the peer which sent the packet, the channel number upon which the packet was received, and the received packet.
</constant>
<constant name="HOST_TOTAL_SENT_DATA" value="0" enum="HostStatistic">
Total data sent.
</constant>
<constant name="HOST_TOTAL_SENT_PACKETS" value="1" enum="HostStatistic">
Total UDP packets sent.
</constant>
<constant name="HOST_TOTAL_RECEIVED_DATA" value="2" enum="HostStatistic">
Total data received.
</constant>
<constant name="HOST_TOTAL_RECEIVED_PACKETS" value="3" enum="HostStatistic">
Total UDP packets received.
</constant>
</constants>
</class>

View File

@ -0,0 +1,210 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="ENetPacketPeer" inherits="PacketPeer" version="4.0">
<brief_description>
A wrapper class for an [url=http://enet.bespin.org/group__peer.html]ENetPeer[/url].
</brief_description>
<description>
A PacketPeer implementation representing a peer of an [ENetConnection].
This class cannot be instantiated directly but can be retrieved during [method ENetConnection.service] or via [method ENetConnection.get_peers].
</description>
<tutorials>
<link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link>
</tutorials>
<methods>
<method name="get_channels" qualifiers="const">
<return type="int">
</return>
<description>
Returns the number of channels allocated for communication with peer.
</description>
</method>
<method name="get_state" qualifiers="const">
<return type="int" enum="ENetPacketPeer.PeerState">
</return>
<description>
Returns the current peer state. See [enum PeerState].
</description>
</method>
<method name="get_statistic">
<return type="float">
</return>
<argument index="0" name="statistic" type="int" enum="ENetPacketPeer.PeerStatistic">
</argument>
<description>
Returns the requested [code]statistic[/code] for this peer. See [enum PeerStatistic].
</description>
</method>
<method name="is_active" qualifiers="const">
<return type="bool">
</return>
<description>
Returns [code]true[/code] if the peer is currently active (i.e. the associated [ENetConnection] is still valid).
</description>
</method>
<method name="peer_disconnect">
<return type="void">
</return>
<argument index="0" name="data" type="int" default="0">
</argument>
<description>
Request a disconnection from a peer. An [constant ENetConnection.EVENT_DISCONNECT] will be generated during [method ENetConnection.service] once the disconnection is complete.
</description>
</method>
<method name="peer_disconnect_later">
<return type="void">
</return>
<argument index="0" name="data" type="int" default="0">
</argument>
<description>
Request a disconnection from a peer, but only after all queued outgoing packets are sent. An [constant ENetConnection.EVENT_DISCONNECT] will be generated during [method ENetConnection.service] once the disconnection is complete.
</description>
</method>
<method name="peer_disconnect_now">
<return type="void">
</return>
<argument index="0" name="data" type="int" default="0">
</argument>
<description>
Force an immediate disconnection from a peer. No [constant ENetConnection.EVENT_DISCONNECT] will be generated. The foreign peer is not guaranteed to receive the disconnect notification, and is reset immediately upon return from this function.
</description>
</method>
<method name="ping">
<return type="void">
</return>
<description>
Sends a ping request to a peer. ENet automatically pings all connected peers at regular intervals, however, this function may be called to ensure more frequent ping requests.
</description>
</method>
<method name="ping_interval">
<return type="void">
</return>
<argument index="0" name="ping_interval" type="int">
</argument>
<description>
Sets the [code]ping_interval[/code] in milliseconds at which pings will be sent to a peer. Pings are used both to monitor the liveness of the connection and also to dynamically adjust the throttle during periods of low traffic so that the throttle has reasonable responsiveness during traffic spikes.
</description>
</method>
<method name="reset">
<return type="void">
</return>
<description>
Forcefully disconnects a peer. The foreign host represented by the peer is not notified of the disconnection and will timeout on its connection to the local host.
</description>
</method>
<method name="send">
<return type="int" enum="Error">
</return>
<argument index="0" name="channel" type="int">
</argument>
<argument index="1" name="packet" type="PackedByteArray">
</argument>
<argument index="2" name="flags" type="int">
</argument>
<description>
Queues a [code]packet[/code] to be sent over the specified [code]channel[/code]. See [code]FLAG_*[/code] constants for available packet flags.
</description>
</method>
<method name="set_timeout">
<return type="void">
</return>
<argument index="0" name="timeout" type="int">
</argument>
<argument index="1" name="timeout_min" type="int">
</argument>
<argument index="2" name="timeout_max" type="int">
</argument>
<description>
Sets the timeout parameters for a peer. The timeout parameters control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values are expressed in milliseconds.
The [code]timeout_limit[/code] is a factor that, multiplied by a value based on the average round trip time, will determine the timeout limit for a reliable packet. When that limit is reached, the timeout will be doubled, and the peer will be disconnected if that limit has reached [code]timeout_min[/code]. The [code]timeout_max[/code] parameter, on the other hand, defines a fixed timeout for which any packet must be acknowledged or the peer will be dropped.
</description>
</method>
<method name="throttle_configure">
<return type="void">
</return>
<argument index="0" name="interval" type="int">
</argument>
<argument index="1" name="acceleration" type="int">
</argument>
<argument index="2" name="deceleration" type="int">
</argument>
<description>
Configures throttle parameter for a peer.
Unreliable packets are dropped by ENet in response to the varying conditions of the Internet connection to the peer. The throttle represents a probability that an unreliable packet should not be dropped and thus sent by ENet to the peer. By measuring fluctuations in round trip times of reliable packets over the specified [code]interval[/code], ENet will either increase the probably by the amount specified in the [code]acceleration[/code] parameter, or decrease it by the amount specified in the [code]deceleration[/code] parameter (both are ratios to [constant PACKET_THROTTLE_SCALE]).
When the throttle has a value of [constant PACKET_THROTTLE_SCALE], no unreliable packets are dropped by ENet, and so 100% of all unreliable packets will be sent.
When the throttle has a value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable packets will be sent.
Intermediate values for the throttle represent intermediate probabilities between 0% and 100% of unreliable packets being sent. The bandwidth limits of the local and foreign hosts are taken into account to determine a sensible limit for the throttle probability above which it should not raise even in the best of conditions.
</description>
</method>
</methods>
<constants>
<constant name="STATE_DISCONNECTED" value="0" enum="PeerState">
</constant>
<constant name="STATE_CONNECTING" value="1" enum="PeerState">
</constant>
<constant name="STATE_ACKNOWLEDGING_CONNECT" value="2" enum="PeerState">
</constant>
<constant name="STATE_CONNECTION_PENDING" value="3" enum="PeerState">
</constant>
<constant name="STATE_CONNECTION_SUCCEEDED" value="4" enum="PeerState">
</constant>
<constant name="STATE_CONNECTED" value="5" enum="PeerState">
</constant>
<constant name="STATE_DISCONNECT_LATER" value="6" enum="PeerState">
</constant>
<constant name="STATE_DISCONNECTING" value="7" enum="PeerState">
</constant>
<constant name="STATE_ACKNOWLEDGING_DISCONNECT" value="8" enum="PeerState">
</constant>
<constant name="STATE_ZOMBIE" value="9" enum="PeerState">
</constant>
<constant name="PEER_PACKET_LOSS" value="0" enum="PeerStatistic">
Mean packet loss of reliable packets as a ratio with respect to the [constant PACKET_LOSS_SCALE].
</constant>
<constant name="PEER_PACKET_LOSS_VARIANCE" value="1" enum="PeerStatistic">
Packet loss variance.
</constant>
<constant name="PEER_PACKET_LOSS_EPOCH" value="2" enum="PeerStatistic">
</constant>
<constant name="PEER_ROUND_TRIP_TIME" value="3" enum="PeerStatistic">
Mean packet round trip time for reliable packets.
</constant>
<constant name="PEER_ROUND_TRIP_TIME_VARIANCE" value="4" enum="PeerStatistic">
Variance of the mean round trip time.
</constant>
<constant name="PEER_LAST_ROUND_TRIP_TIME" value="5" enum="PeerStatistic">
Last recorded round trip time for a reliable packet.
</constant>
<constant name="PEER_LAST_ROUND_TRIP_TIME_VARIANCE" value="6" enum="PeerStatistic">
Variance of the last trip time recorded.
</constant>
<constant name="PEER_PACKET_THROTTLE" value="7" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_LIMIT" value="8" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_COUNTER" value="9" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_EPOCH" value="10" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_ACCELERATION" value="11" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_DECELERATION" value="12" enum="PeerStatistic">
</constant>
<constant name="PEER_PACKET_THROTTLE_INTERVAL" value="13" enum="PeerStatistic">
</constant>
<constant name="PACKET_LOSS_SCALE" value="65536">
The reference scale for packet loss. See [method get_statistic] and [constant PEER_PACKET_LOSS].
</constant>
<constant name="PACKET_THROTTLE_SCALE" value="32">
The reference value for throttle configuration. See [method throttle_configure].
</constant>
<constant name="FLAG_RELIABLE" value="1">
Mark the packet to be sent as reliable.
</constant>
<constant name="FLAG_UNSEQUENCED" value="2">
Mark the packet to be sent unsequenced (unreliable).
</constant>
<constant name="FLAG_UNRELIABLE_FRAGMENT" value="8">
Mark the packet to be sent unreliable even if the packet is too big and needs fragmentation (increasing the chance of it being dropped).
</constant>
</constants>
</class>

View File

@ -0,0 +1,470 @@
/*************************************************************************/
/* enet_connection.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "enet_connection.h"
#include "enet_packet_peer.h"
#include "core/io/compression.h"
#include "core/io/ip.h"
void ENetConnection::broadcast(enet_uint8 p_channel, ENetPacket *p_packet) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_MSG(p_channel >= host->channelLimit, vformat("Unable to send packet on channel %d, max channels: %d", p_channel, (int)host->channelLimit));
enet_host_broadcast(host, p_channel, p_packet);
}
Error ENetConnection::create_host_bound(const IPAddress &p_bind_address, int p_port, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
ERR_FAIL_COND_V_MSG(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(), ERR_INVALID_PARAMETER, "Invalid bind IP.");
ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The local port number must be between 0 and 65535 (inclusive).");
ENetAddress address;
memset(&address, 0, sizeof(address));
address.port = p_port;
#ifdef GODOT_ENET
if (p_bind_address.is_wildcard()) {
address.wildcard = 1;
} else {
enet_address_set_ip(&address, p_bind_address.get_ipv6(), 16);
}
#else
if (p_bind_address.is_wildcard()) {
address.host = 0;
} else {
ERR_FAIL_COND_V(!p_bind_address.is_ipv4(), ERR_INVALID_PARAMETER);
address.host = *(uint32_t *)p_bind_address.get_ipv4();
}
#endif
return _create(&address, p_max_peers, p_max_channels, p_in_bandwidth, p_out_bandwidth);
}
Error ENetConnection::create_host(int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
return _create(nullptr, p_max_peers, p_max_channels, p_in_bandwidth, p_out_bandwidth);
}
void ENetConnection::destroy() {
ERR_FAIL_COND_MSG(!host, "Host already destroyed");
for (List<Ref<ENetPacketPeer>>::Element *E = peers.front(); E; E = E->next()) {
E->get()->_on_disconnect();
}
peers.clear();
enet_host_destroy(host);
host = nullptr;
}
Ref<ENetPacketPeer> ENetConnection::connect_to_host(const String &p_address, int p_port, int p_channels, int p_data) {
Ref<ENetPacketPeer> out;
ERR_FAIL_COND_V_MSG(!host, out, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_V_MSG(peers.size(), out, "The ENetConnection is already connected to a peer.");
ERR_FAIL_COND_V_MSG(p_port < 1 || p_port > 65535, out, "The remote port number must be between 1 and 65535 (inclusive).");
IPAddress ip;
if (p_address.is_valid_ip_address()) {
ip = p_address;
} else {
#ifdef GODOT_ENET
ip = IP::get_singleton()->resolve_hostname(p_address);
#else
ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4);
#endif
ERR_FAIL_COND_V_MSG(!ip.is_valid(), out, "Couldn't resolve the server IP address or domain name.");
}
ENetAddress address;
#ifdef GODOT_ENET
enet_address_set_ip(&address, ip.get_ipv6(), 16);
#else
ERR_FAIL_COND_V_MSG(!ip.is_ipv4(), out, "Connecting to an IPv6 server isn't supported when using vanilla ENet. Recompile Godot with the bundled ENet library.");
address.host = *(uint32_t *)ip.get_ipv4();
#endif
address.port = p_port;
// Initiate connection, allocating enough channels
ENetPeer *peer = enet_host_connect(host, &address, p_channels, p_data);
if (peer == nullptr) {
return nullptr;
}
out = Ref<ENetPacketPeer>(memnew(ENetPacketPeer(peer)));
peers.push_back(out);
return out;
}
ENetConnection::EventType ENetConnection::service(int p_timeout, Event &r_event) {
ERR_FAIL_COND_V_MSG(!host, EVENT_ERROR, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_V(r_event.peer.is_valid(), EVENT_ERROR);
// Drop peers that have already been disconnected.
// NOTE: Forcibly disconnected peers (i.e. peers disconnected via
// enet_peer_disconnect*) do not trigger DISCONNECTED events.
List<Ref<ENetPacketPeer>>::Element *E = peers.front();
while (E) {
if (!E->get()->is_active()) {
peers.erase(E->get());
}
E = E->next();
}
ENetEvent event;
int ret = enet_host_service(host, &event, p_timeout);
if (ret < 0) {
return EVENT_ERROR;
} else if (ret == 0) {
return EVENT_NONE;
}
switch (event.type) {
case ENET_EVENT_TYPE_CONNECT: {
if (event.peer->data == nullptr) {
Ref<ENetPacketPeer> pp = memnew(ENetPacketPeer(event.peer));
peers.push_back(pp);
}
r_event.peer = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data);
r_event.data = event.data;
return EVENT_CONNECT;
} break;
case ENET_EVENT_TYPE_DISCONNECT: {
// A peer disconnected.
if (event.peer->data != nullptr) {
Ref<ENetPacketPeer> pp = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data);
pp->_on_disconnect();
peers.erase(pp);
r_event.peer = pp;
r_event.data = event.data;
return EVENT_DISCONNECT;
}
return EVENT_ERROR;
} break;
case ENET_EVENT_TYPE_RECEIVE: {
// Packet reveived.
if (event.peer->data != nullptr) {
Ref<ENetPacketPeer> pp = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data);
r_event.peer = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data);
r_event.channel_id = event.channelID;
r_event.packet = event.packet;
return EVENT_RECEIVE;
}
return EVENT_ERROR;
} break;
case ENET_EVENT_TYPE_NONE:
return EVENT_NONE;
default:
return EVENT_NONE;
}
}
void ENetConnection::flush() {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_flush(host);
}
void ENetConnection::bandwidth_limit(int p_in_bandwidth, int p_out_bandwidth) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_bandwidth_limit(host, p_in_bandwidth, p_out_bandwidth);
}
void ENetConnection::channel_limit(int p_max_channels) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_channel_limit(host, p_max_channels);
}
void ENetConnection::bandwidth_throttle() {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_bandwidth_throttle(host);
}
void ENetConnection::compress(CompressionMode p_mode) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
Compressor::setup(host, p_mode);
}
double ENetConnection::pop_statistic(HostStatistic p_stat) {
ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active.");
uint32_t *ptr = nullptr;
switch (p_stat) {
case HOST_TOTAL_SENT_DATA:
ptr = &(host->totalSentData);
break;
case HOST_TOTAL_SENT_PACKETS:
ptr = &(host->totalSentPackets);
break;
case HOST_TOTAL_RECEIVED_DATA:
ptr = &(host->totalReceivedData);
break;
case HOST_TOTAL_RECEIVED_PACKETS:
ptr = &(host->totalReceivedPackets);
break;
}
ERR_FAIL_COND_V_MSG(ptr == nullptr, 0, "Invalid statistic: " + itos(p_stat));
uint32_t ret = *ptr;
*ptr = 0;
return ret;
}
int ENetConnection::get_max_channels() const {
ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active.");
return host->channelLimit;
}
int ENetConnection::get_local_port() const {
ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_V_MSG(!(host->socket), 0, "The ENetConnection instance isn't currently bound");
ENetAddress address;
ERR_FAIL_COND_V_MSG(enet_socket_get_address(host->socket, &address), 0, "Unable to get socket address");
return address.port;
}
void ENetConnection::get_peers(List<Ref<ENetPacketPeer>> &r_peers) {
for (const Ref<ENetPacketPeer> &I : peers) {
r_peers.push_back(I);
}
}
Array ENetConnection::_get_peers() {
ERR_FAIL_COND_V_MSG(!host, Array(), "The ENetConnection instance isn't currently active.");
Array out;
for (const Ref<ENetPacketPeer> &I : peers) {
out.push_back(I);
}
return out;
}
Error ENetConnection::dtls_server_setup(Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert) {
#ifdef GODOT_ENET
ERR_FAIL_COND_V_MSG(!host, ERR_UNCONFIGURED, "The ENetConnection instance isn't currently active.");
return enet_host_dtls_server_setup(host, p_key.ptr(), p_cert.ptr()) ? FAILED : OK;
#else
ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "ENet DTLS support not available in this build.");
#endif
}
void ENetConnection::refuse_new_connections(bool p_refuse) {
#ifdef GODOT_ENET
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
enet_host_refuse_new_connections(host, p_refuse);
#else
ERR_FAIL_MSG("ENet DTLS support not available in this build.");
#endif
}
Error ENetConnection::dtls_client_setup(Ref<X509Certificate> p_cert, const String &p_hostname, bool p_verify) {
#ifdef GODOT_ENET
ERR_FAIL_COND_V_MSG(!host, ERR_UNCONFIGURED, "The ENetConnection instance isn't currently active.");
return enet_host_dtls_client_setup(host, p_cert.ptr(), p_verify, p_hostname.utf8().get_data()) ? FAILED : OK;
#else
ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "ENet DTLS support not available in this build.");
#endif
}
Error ENetConnection::_create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
ERR_FAIL_COND_V_MSG(host != nullptr, ERR_ALREADY_IN_USE, "The ENetConnection instance is already active.");
ERR_FAIL_COND_V_MSG(p_max_peers < 1 || p_max_peers > 4095, ERR_INVALID_PARAMETER, "The number of clients must be set between 1 and 4095 (inclusive).");
ERR_FAIL_COND_V_MSG(p_max_channels < 0 || p_max_channels > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, ERR_INVALID_PARAMETER, "Invalid channel count. Must be between 0 and 255 (0 means maximum, i.e. 255)");
ERR_FAIL_COND_V_MSG(p_in_bandwidth < 0, ERR_INVALID_PARAMETER, "The incoming bandwidth limit must be greater than or equal to 0 (0 disables the limit).");
ERR_FAIL_COND_V_MSG(p_out_bandwidth < 0, ERR_INVALID_PARAMETER, "The outgoing bandwidth limit must be greater than or equal to 0 (0 disables the limit).");
host = enet_host_create(p_address /* the address to bind the server host to */,
p_max_peers /* allow up to p_max_peers connections */,
p_max_channels /* allow up to p_max_channel to be used */,
p_in_bandwidth /* limit incoming bandwidth if > 0 */,
p_out_bandwidth /* limit outgoing bandwidth if > 0 */);
ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create an ENet host.");
return OK;
}
Array ENetConnection::_service(int p_timeout) {
Array out;
Event event;
Ref<ENetPacketPeer> peer;
EventType ret = service(p_timeout, event);
out.push_back(ret);
out.push_back(event.peer);
out.push_back(event.data);
out.push_back(event.channel_id);
if (event.packet && event.peer.is_valid()) {
event.peer->_queue_packet(event.packet);
}
return out;
}
void ENetConnection::_broadcast(int p_channel, PackedByteArray p_packet, int p_flags) {
ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active.");
ERR_FAIL_COND_MSG(p_channel < 0 || p_channel > (int)host->channelLimit, "Invalid channel");
ERR_FAIL_COND_MSG(p_flags & ~ENetPacketPeer::FLAG_ALLOWED, "Invalid flags");
ENetPacket *pkt = enet_packet_create(p_packet.ptr(), p_packet.size(), p_flags);
broadcast(p_channel, pkt);
}
void ENetConnection::_bind_methods() {
ClassDB::bind_method(D_METHOD("create_host_bound", "bind_address", "bind_port", "max_peers", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetConnection::create_host_bound, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("create_host", "max_peers", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetConnection::create_host, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("destroy"), &ENetConnection::destroy);
ClassDB::bind_method(D_METHOD("connect_to_host", "address", "port", "channels", "data"), &ENetConnection::connect_to_host, DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("service", "timeout"), &ENetConnection::_service, DEFVAL(0));
ClassDB::bind_method(D_METHOD("flush"), &ENetConnection::flush);
ClassDB::bind_method(D_METHOD("bandwidth_limit", "in_bandwidth", "out_bandwidth"), &ENetConnection::bandwidth_limit, DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("channel_limit", "limit"), &ENetConnection::channel_limit);
ClassDB::bind_method(D_METHOD("broadcast", "channel", "packet", "flags"), &ENetConnection::_broadcast);
ClassDB::bind_method(D_METHOD("compress", "mode"), &ENetConnection::compress);
ClassDB::bind_method(D_METHOD("dtls_server_setup", "key", "certificate"), &ENetConnection::dtls_server_setup);
ClassDB::bind_method(D_METHOD("dtls_client_setup", "certificate", "hostname", "verify"), &ENetConnection::dtls_client_setup, DEFVAL(true));
ClassDB::bind_method(D_METHOD("refuse_new_connections", "refuse"), &ENetConnection::refuse_new_connections);
ClassDB::bind_method(D_METHOD("pop_statistic", "statistic"), &ENetConnection::pop_statistic);
ClassDB::bind_method(D_METHOD("get_max_channels"), &ENetConnection::get_max_channels);
ClassDB::bind_method(D_METHOD("get_local_port"), &ENetConnection::get_local_port);
ClassDB::bind_method(D_METHOD("get_peers"), &ENetConnection::_get_peers);
BIND_ENUM_CONSTANT(COMPRESS_NONE);
BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER);
BIND_ENUM_CONSTANT(COMPRESS_FASTLZ);
BIND_ENUM_CONSTANT(COMPRESS_ZLIB);
BIND_ENUM_CONSTANT(COMPRESS_ZSTD);
BIND_ENUM_CONSTANT(EVENT_ERROR);
BIND_ENUM_CONSTANT(EVENT_NONE);
BIND_ENUM_CONSTANT(EVENT_CONNECT);
BIND_ENUM_CONSTANT(EVENT_DISCONNECT);
BIND_ENUM_CONSTANT(EVENT_RECEIVE);
BIND_ENUM_CONSTANT(HOST_TOTAL_SENT_DATA);
BIND_ENUM_CONSTANT(HOST_TOTAL_SENT_PACKETS);
BIND_ENUM_CONSTANT(HOST_TOTAL_RECEIVED_DATA);
BIND_ENUM_CONSTANT(HOST_TOTAL_RECEIVED_PACKETS);
}
ENetConnection::~ENetConnection() {
if (host) {
destroy();
}
}
size_t ENetConnection::Compressor::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
Compressor *compressor = (Compressor *)(context);
if (size_t(compressor->src_mem.size()) < inLimit) {
compressor->src_mem.resize(inLimit);
}
int total = inLimit;
int ofs = 0;
while (total) {
for (size_t i = 0; i < inBufferCount; i++) {
int to_copy = MIN(total, int(inBuffers[i].dataLength));
memcpy(&compressor->src_mem.write[ofs], inBuffers[i].data, to_copy);
ofs += to_copy;
total -= to_copy;
}
}
Compression::Mode mode;
switch (compressor->mode) {
case COMPRESS_FASTLZ: {
mode = Compression::MODE_FASTLZ;
} break;
case COMPRESS_ZLIB: {
mode = Compression::MODE_DEFLATE;
} break;
case COMPRESS_ZSTD: {
mode = Compression::MODE_ZSTD;
} break;
default: {
ERR_FAIL_V_MSG(0, vformat("Invalid ENet compression mode: %d", compressor->mode));
}
}
int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
if (compressor->dst_mem.size() < req_size) {
compressor->dst_mem.resize(req_size);
}
int ret = Compression::compress(compressor->dst_mem.ptrw(), compressor->src_mem.ptr(), ofs, mode);
if (ret < 0) {
return 0;
}
if (ret > int(outLimit)) {
return 0; // Do not bother
}
memcpy(outData, compressor->dst_mem.ptr(), ret);
return ret;
}
size_t ENetConnection::Compressor::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
Compressor *compressor = (Compressor *)(context);
int ret = -1;
switch (compressor->mode) {
case COMPRESS_FASTLZ: {
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ);
} break;
case COMPRESS_ZLIB: {
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
} break;
case COMPRESS_ZSTD: {
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
} break;
default: {
}
}
if (ret < 0) {
return 0;
} else {
return ret;
}
}
void ENetConnection::Compressor::setup(ENetHost *p_host, CompressionMode p_mode) {
ERR_FAIL_COND(!p_host);
switch (p_mode) {
case COMPRESS_NONE: {
enet_host_compress(p_host, nullptr);
} break;
case COMPRESS_RANGE_CODER: {
enet_host_compress_with_range_coder(p_host);
} break;
case COMPRESS_FASTLZ:
case COMPRESS_ZLIB:
case COMPRESS_ZSTD: {
Compressor *compressor = memnew(Compressor(p_mode));
enet_host_compress(p_host, &(compressor->enet_compressor));
} break;
}
}
ENetConnection::Compressor::Compressor(CompressionMode p_mode) {
mode = p_mode;
enet_compressor.context = this;
enet_compressor.compress = enet_compress;
enet_compressor.decompress = enet_decompress;
enet_compressor.destroy = enet_compressor_destroy;
}

View File

@ -0,0 +1,138 @@
/*************************************************************************/
/* enet_connection.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef ENET_CONNECTION_H
#define ENET_CONNECTION_H
#include "core/object/ref_counted.h"
#include "core/crypto/crypto.h"
#include "enet_packet_peer.h"
#include <enet/enet.h>
class ENetConnection : public RefCounted {
GDCLASS(ENetConnection, RefCounted);
public:
enum CompressionMode {
COMPRESS_NONE = 0,
COMPRESS_RANGE_CODER,
COMPRESS_FASTLZ,
COMPRESS_ZLIB,
COMPRESS_ZSTD,
};
enum HostStatistic {
HOST_TOTAL_SENT_DATA,
HOST_TOTAL_SENT_PACKETS,
HOST_TOTAL_RECEIVED_DATA,
HOST_TOTAL_RECEIVED_PACKETS,
};
enum EventType {
EVENT_ERROR = -1,
EVENT_NONE = 0,
EVENT_CONNECT,
EVENT_DISCONNECT,
EVENT_RECEIVE,
};
struct Event {
Ref<ENetPacketPeer> peer;
enet_uint8 channel_id = 0;
enet_uint32 data = 0;
ENetPacket *packet = nullptr;
};
protected:
static void _bind_methods();
private:
ENetHost *host = nullptr;
List<Ref<ENetPacketPeer>> peers;
Error _create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth);
Array _service(int p_timeout = 0);
void _broadcast(int p_channel, PackedByteArray p_packet, int p_flags);
Array _get_peers();
class Compressor {
private:
CompressionMode mode = COMPRESS_NONE;
Vector<uint8_t> src_mem;
Vector<uint8_t> dst_mem;
ENetCompressor enet_compressor;
Compressor(CompressionMode mode);
static size_t enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit);
static size_t enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit);
static void enet_compressor_destroy(void *context) {
memdelete((Compressor *)context);
}
public:
static void setup(ENetHost *p_host, CompressionMode p_mode);
};
public:
void broadcast(enet_uint8 p_channel, ENetPacket *p_packet);
Error create_host_bound(const IPAddress &p_bind_address = IPAddress("*"), int p_port = 0, int p_max_peers = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0);
Error create_host(int p_max_peers = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0);
void destroy();
Ref<ENetPacketPeer> connect_to_host(const String &p_address, int p_port, int p_channels, int p_data = 0);
EventType service(int p_timeout, Event &r_event);
void flush();
void bandwidth_limit(int p_in_bandwidth = 0, int p_out_bandwidth = 0);
void channel_limit(int p_max_channels);
void bandwidth_throttle();
void compress(CompressionMode p_mode);
double pop_statistic(HostStatistic p_stat);
int get_max_channels() const;
// Extras
void get_peers(List<Ref<ENetPacketPeer>> &r_peers);
int get_local_port() const;
// Godot additions
Error dtls_server_setup(Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert);
Error dtls_client_setup(Ref<X509Certificate> p_cert, const String &p_hostname, bool p_verify = true);
void refuse_new_connections(bool p_refuse);
ENetConnection() {}
~ENetConnection();
};
VARIANT_ENUM_CAST(ENetConnection::CompressionMode);
VARIANT_ENUM_CAST(ENetConnection::EventType);
VARIANT_ENUM_CAST(ENetConnection::HostStatistic);
#endif // ENET_CONNECTION_H

View File

@ -0,0 +1,263 @@
/*************************************************************************/
/* enet_packet_peer.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "enet_packet_peer.h"
void ENetPacketPeer::peer_disconnect(int p_data) {
ERR_FAIL_COND(!peer);
enet_peer_disconnect(peer, p_data);
}
void ENetPacketPeer::peer_disconnect_later(int p_data) {
ERR_FAIL_COND(!peer);
enet_peer_disconnect_later(peer, p_data);
}
void ENetPacketPeer::peer_disconnect_now(int p_data) {
ERR_FAIL_COND(!peer);
enet_peer_disconnect_now(peer, p_data);
_on_disconnect();
}
void ENetPacketPeer::ping() {
ERR_FAIL_COND(!peer);
enet_peer_ping(peer);
}
void ENetPacketPeer::ping_interval(int p_interval) {
ERR_FAIL_COND(!peer);
enet_peer_ping_interval(peer, p_interval);
}
int ENetPacketPeer::send(uint8_t p_channel, ENetPacket *p_packet) {
ERR_FAIL_COND_V(peer == nullptr, -1);
ERR_FAIL_COND_V(p_packet == nullptr, -1);
ERR_FAIL_COND_V_MSG(p_channel >= peer->channelCount, -1, vformat("Unable to send packet on channel %d, max channels: %d", p_channel, (int)peer->channelCount));
return enet_peer_send(peer, p_channel, p_packet);
}
void ENetPacketPeer::reset() {
ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected");
enet_peer_reset(peer);
_on_disconnect();
}
void ENetPacketPeer::throttle_configure(int p_interval, int p_acceleration, int p_deceleration) {
ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected");
enet_peer_throttle_configure(peer, p_interval, p_acceleration, p_deceleration);
}
void ENetPacketPeer::set_timeout(int p_timeout, int p_timeout_min, int p_timeout_max) {
ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected");
ERR_FAIL_COND_MSG(p_timeout > p_timeout_min || p_timeout_min > p_timeout_max, "Timeout limit must be less than minimum timeout, which itself must be less then maximum timeout");
enet_peer_timeout(peer, p_timeout, p_timeout_min, p_timeout_max);
}
int ENetPacketPeer::get_max_packet_size() const {
return 1 << 24;
}
int ENetPacketPeer::get_available_packet_count() const {
return packet_queue.size();
}
Error ENetPacketPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
ERR_FAIL_COND_V(!peer, ERR_UNCONFIGURED);
ERR_FAIL_COND_V(!packet_queue.size(), ERR_UNAVAILABLE);
if (last_packet) {
enet_packet_destroy(last_packet);
last_packet = nullptr;
}
last_packet = packet_queue.front()->get();
packet_queue.pop_front();
*r_buffer = (const uint8_t *)(last_packet->data);
r_buffer_size = last_packet->dataLength;
return OK;
}
Error ENetPacketPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
ERR_FAIL_COND_V(!peer, ERR_UNCONFIGURED);
ENetPacket *packet = enet_packet_create(p_buffer, p_buffer_size, ENET_PACKET_FLAG_RELIABLE);
return send(0, packet) < 0 ? FAILED : OK;
}
IPAddress ENetPacketPeer::get_remote_address() const {
ERR_FAIL_COND_V(!peer, IPAddress());
IPAddress out;
#ifdef GODOT_ENET
out.set_ipv6((uint8_t *)&(peer->address.host));
#else
out.set_ipv4((uint8_t *)&(peer->address.host));
#endif
return out;
}
int ENetPacketPeer::get_remote_port() const {
ERR_FAIL_COND_V(!peer, 0);
return peer->address.port;
}
bool ENetPacketPeer::is_active() const {
return peer != nullptr;
}
double ENetPacketPeer::get_statistic(PeerStatistic p_stat) {
ERR_FAIL_COND_V(!peer, 0);
switch (p_stat) {
case PEER_PACKET_LOSS:
return peer->packetLoss;
case PEER_PACKET_LOSS_VARIANCE:
return peer->packetLossVariance;
case PEER_PACKET_LOSS_EPOCH:
return peer->packetLossEpoch;
case PEER_ROUND_TRIP_TIME:
return peer->roundTripTime;
case PEER_ROUND_TRIP_TIME_VARIANCE:
return peer->roundTripTimeVariance;
case PEER_LAST_ROUND_TRIP_TIME:
return peer->lastRoundTripTime;
case PEER_LAST_ROUND_TRIP_TIME_VARIANCE:
return peer->lastRoundTripTimeVariance;
case PEER_PACKET_THROTTLE:
return peer->packetThrottle;
case PEER_PACKET_THROTTLE_LIMIT:
return peer->packetThrottleLimit;
case PEER_PACKET_THROTTLE_COUNTER:
return peer->packetThrottleCounter;
case PEER_PACKET_THROTTLE_EPOCH:
return peer->packetThrottleEpoch;
case PEER_PACKET_THROTTLE_ACCELERATION:
return peer->packetThrottleAcceleration;
case PEER_PACKET_THROTTLE_DECELERATION:
return peer->packetThrottleDeceleration;
case PEER_PACKET_THROTTLE_INTERVAL:
return peer->packetThrottleInterval;
}
ERR_FAIL_V(0);
}
ENetPacketPeer::PeerState ENetPacketPeer::get_state() const {
if (!is_active()) {
return STATE_DISCONNECTED;
}
return (PeerState)peer->state;
}
int ENetPacketPeer::get_channels() const {
ERR_FAIL_COND_V_MSG(!peer, 0, "The ENetConnection instance isn't currently active.");
return peer->channelCount;
}
void ENetPacketPeer::_on_disconnect() {
if (peer) {
peer->data = nullptr;
}
peer = nullptr;
}
void ENetPacketPeer::_queue_packet(ENetPacket *p_packet) {
ERR_FAIL_COND(!peer);
packet_queue.push_back(p_packet);
}
Error ENetPacketPeer::_send(int p_channel, PackedByteArray p_packet, int p_flags) {
ERR_FAIL_COND_V_MSG(peer == nullptr, ERR_UNCONFIGURED, "Peer not connected");
ERR_FAIL_COND_V_MSG(p_channel < 0 || p_channel > (int)peer->channelCount, ERR_INVALID_PARAMETER, "Invalid channel");
ERR_FAIL_COND_V_MSG(p_flags & ~FLAG_ALLOWED, ERR_INVALID_PARAMETER, "Invalid flags");
ENetPacket *packet = enet_packet_create(p_packet.ptr(), p_packet.size(), p_flags);
return send(p_channel, packet) == 0 ? OK : FAILED;
}
void ENetPacketPeer::_bind_methods() {
ClassDB::bind_method(D_METHOD("peer_disconnect", "data"), &ENetPacketPeer::peer_disconnect, DEFVAL(0));
ClassDB::bind_method(D_METHOD("peer_disconnect_later", "data"), &ENetPacketPeer::peer_disconnect_later, DEFVAL(0));
ClassDB::bind_method(D_METHOD("peer_disconnect_now", "data"), &ENetPacketPeer::peer_disconnect_now, DEFVAL(0));
ClassDB::bind_method(D_METHOD("ping"), &ENetPacketPeer::ping);
ClassDB::bind_method(D_METHOD("ping_interval", "ping_interval"), &ENetPacketPeer::ping_interval);
ClassDB::bind_method(D_METHOD("reset"), &ENetPacketPeer::reset);
ClassDB::bind_method(D_METHOD("send", "channel", "packet", "flags"), &ENetPacketPeer::_send);
ClassDB::bind_method(D_METHOD("throttle_configure", "interval", "acceleration", "deceleration"), &ENetPacketPeer::throttle_configure);
ClassDB::bind_method(D_METHOD("set_timeout", "timeout", "timeout_min", "timeout_max"), &ENetPacketPeer::set_timeout);
ClassDB::bind_method(D_METHOD("get_statistic", "statistic"), &ENetPacketPeer::get_statistic);
ClassDB::bind_method(D_METHOD("get_state"), &ENetPacketPeer::get_state);
ClassDB::bind_method(D_METHOD("get_channels"), &ENetPacketPeer::get_channels);
ClassDB::bind_method(D_METHOD("is_active"), &ENetPacketPeer::is_active);
BIND_ENUM_CONSTANT(STATE_DISCONNECTED);
BIND_ENUM_CONSTANT(STATE_CONNECTING);
BIND_ENUM_CONSTANT(STATE_ACKNOWLEDGING_CONNECT);
BIND_ENUM_CONSTANT(STATE_CONNECTION_PENDING);
BIND_ENUM_CONSTANT(STATE_CONNECTION_SUCCEEDED);
BIND_ENUM_CONSTANT(STATE_CONNECTED);
BIND_ENUM_CONSTANT(STATE_DISCONNECT_LATER);
BIND_ENUM_CONSTANT(STATE_DISCONNECTING);
BIND_ENUM_CONSTANT(STATE_ACKNOWLEDGING_DISCONNECT);
BIND_ENUM_CONSTANT(STATE_ZOMBIE);
BIND_ENUM_CONSTANT(PEER_PACKET_LOSS);
BIND_ENUM_CONSTANT(PEER_PACKET_LOSS_VARIANCE);
BIND_ENUM_CONSTANT(PEER_PACKET_LOSS_EPOCH);
BIND_ENUM_CONSTANT(PEER_ROUND_TRIP_TIME);
BIND_ENUM_CONSTANT(PEER_ROUND_TRIP_TIME_VARIANCE);
BIND_ENUM_CONSTANT(PEER_LAST_ROUND_TRIP_TIME);
BIND_ENUM_CONSTANT(PEER_LAST_ROUND_TRIP_TIME_VARIANCE);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_LIMIT);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_COUNTER);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_EPOCH);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_ACCELERATION);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_DECELERATION);
BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_INTERVAL);
BIND_CONSTANT(PACKET_LOSS_SCALE);
BIND_CONSTANT(PACKET_THROTTLE_SCALE);
BIND_CONSTANT(FLAG_RELIABLE);
BIND_CONSTANT(FLAG_UNSEQUENCED);
BIND_CONSTANT(FLAG_UNRELIABLE_FRAGMENT);
}
ENetPacketPeer::ENetPacketPeer(ENetPeer *p_peer) {
peer = p_peer;
peer->data = this;
}
ENetPacketPeer::~ENetPacketPeer() {
_on_disconnect();
if (last_packet) {
enet_packet_destroy(last_packet);
last_packet = nullptr;
}
for (List<ENetPacket *>::Element *E = packet_queue.front(); E; E = E->next()) {
enet_packet_destroy(E->get());
}
packet_queue.clear();
}

View File

@ -0,0 +1,131 @@
/*************************************************************************/
/* enet_packet_peer.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef ENET_PACKET_PEER_H
#define ENET_PACKET_PEER_H
#include "core/io/packet_peer.h"
#include <enet/enet.h>
class ENetPacketPeer : public PacketPeer {
GDCLASS(ENetPacketPeer, PacketPeer);
private:
ENetPeer *peer = nullptr;
List<ENetPacket *> packet_queue;
ENetPacket *last_packet = nullptr;
static void _bind_methods();
Error _send(int p_channel, PackedByteArray p_packet, int p_flags);
protected:
friend class ENetConnection;
// Internally used by ENetConnection during service, destroy, etc.
void _on_disconnect();
void _queue_packet(ENetPacket *p_packet);
public:
enum {
PACKET_THROTTLE_SCALE = ENET_PEER_PACKET_THROTTLE_SCALE,
PACKET_LOSS_SCALE = ENET_PEER_PACKET_LOSS_SCALE,
};
enum {
FLAG_RELIABLE = ENET_PACKET_FLAG_RELIABLE,
FLAG_UNSEQUENCED = ENET_PACKET_FLAG_UNSEQUENCED,
FLAG_UNRELIABLE_FRAGMENT = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT,
FLAG_ALLOWED = ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT,
};
enum PeerState {
STATE_DISCONNECTED = ENET_PEER_STATE_DISCONNECTED,
STATE_CONNECTING = ENET_PEER_STATE_CONNECTING,
STATE_ACKNOWLEDGING_CONNECT = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT,
STATE_CONNECTION_PENDING = ENET_PEER_STATE_CONNECTION_PENDING,
STATE_CONNECTION_SUCCEEDED = ENET_PEER_STATE_CONNECTION_SUCCEEDED,
STATE_CONNECTED = ENET_PEER_STATE_CONNECTED,
STATE_DISCONNECT_LATER = ENET_PEER_STATE_DISCONNECT_LATER,
STATE_DISCONNECTING = ENET_PEER_STATE_DISCONNECTING,
STATE_ACKNOWLEDGING_DISCONNECT = ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT,
STATE_ZOMBIE = ENET_PEER_STATE_ZOMBIE,
};
enum PeerStatistic {
PEER_PACKET_LOSS,
PEER_PACKET_LOSS_VARIANCE,
PEER_PACKET_LOSS_EPOCH,
PEER_ROUND_TRIP_TIME,
PEER_ROUND_TRIP_TIME_VARIANCE,
PEER_LAST_ROUND_TRIP_TIME,
PEER_LAST_ROUND_TRIP_TIME_VARIANCE,
PEER_PACKET_THROTTLE,
PEER_PACKET_THROTTLE_LIMIT,
PEER_PACKET_THROTTLE_COUNTER,
PEER_PACKET_THROTTLE_EPOCH,
PEER_PACKET_THROTTLE_ACCELERATION,
PEER_PACKET_THROTTLE_DECELERATION,
PEER_PACKET_THROTTLE_INTERVAL,
};
int get_max_packet_size() const override;
int get_available_packet_count() const override;
Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet
Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
void peer_disconnect(int p_data = 0);
void peer_disconnect_later(int p_data = 0);
void peer_disconnect_now(int p_data = 0);
void ping();
void ping_interval(int p_interval);
void reset();
int send(uint8_t p_channel, ENetPacket *p_packet);
void throttle_configure(int interval, int acceleration, int deceleration);
void set_timeout(int p_timeout, int p_timeout_min, int p_timeout_max);
double get_statistic(PeerStatistic p_stat);
PeerState get_state() const;
int get_channels() const;
// Extras
IPAddress get_remote_address() const;
int get_remote_port() const;
// Used by ENetMultiplayer (TODO use meta? If only they where StringNames)
bool is_active() const;
ENetPacketPeer(ENetPeer *p_peer);
~ENetPacketPeer();
};
VARIANT_ENUM_CAST(ENetPacketPeer::PeerState);
VARIANT_ENUM_CAST(ENetPacketPeer::PeerStatistic);
#endif // ENET_PACKET_PEER_H

View File

@ -30,7 +30,9 @@
#include "register_types.h"
#include "core/error/error_macros.h"
#include "enet_connection.h"
#include "enet_multiplayer_peer.h"
#include "enet_packet_peer.h"
static bool enet_ok = false;
@ -42,6 +44,8 @@ void register_enet_types() {
}
GDREGISTER_CLASS(ENetMultiplayerPeer);
GDREGISTER_VIRTUAL_CLASS(ENetPacketPeer);
GDREGISTER_CLASS(ENetConnection);
}
void unregister_enet_types() {

View File

@ -11,8 +11,8 @@
*/
ENET_API void enet_address_set_ip(ENetAddress * address, const uint8_t * ip, size_t size);
ENET_API void enet_host_dtls_server_setup (ENetHost *, void *, void *);
ENET_API void enet_host_dtls_client_setup (ENetHost *, void *, uint8_t, const char *);
ENET_API int enet_host_dtls_server_setup (ENetHost *, void *, void *);
ENET_API int enet_host_dtls_client_setup (ENetHost *, void *, uint8_t, const char *);
ENET_API void enet_host_refuse_new_connections (ENetHost *, int);
#endif // __ENET_GODOT_EXT_H__

View File

@ -52,6 +52,7 @@ public:
virtual int set_option(ENetSocketOption p_option, int p_value) = 0;
virtual void close() = 0;
virtual void set_refuse_new_connections(bool p_enable) {} /* Only used by dtls server */
virtual bool can_upgrade() { return false; } /* Only true in ENetUDP */
virtual ~ENetGodotSocket() {}
};
@ -79,6 +80,10 @@ public:
sock->close();
}
bool can_upgrade() {
return true;
}
Error bind(IPAddress p_ip, uint16_t p_port) {
local_address = p_ip;
bound = true;
@ -86,7 +91,11 @@ public:
}
Error get_socket_address(IPAddress *r_ip, uint16_t *r_port) {
return sock->get_socket_address(r_ip, r_port);
Error err = sock->get_socket_address(r_ip, r_port);
if (bound) {
*r_ip = local_address;
}
return err;
}
Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
@ -195,7 +204,9 @@ public:
Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
if (!connected) {
udp->connect_to_host(p_ip, p_port);
dtls->connect_to_peer(udp, verify, for_hostname, cert);
if (dtls->connect_to_peer(udp, verify, for_hostname, cert)) {
return FAILED;
}
connected = true;
}
dtls->poll();
@ -424,16 +435,24 @@ ENetSocket enet_socket_create(ENetSocketType type) {
return socket;
}
void enet_host_dtls_server_setup(ENetHost *host, void *p_key, void *p_cert) {
ENetUDP *sock = (ENetUDP *)host->socket;
host->socket = memnew(ENetDTLSServer(sock, Ref<CryptoKey>((CryptoKey *)p_key), Ref<X509Certificate>((X509Certificate *)p_cert)));
int enet_host_dtls_server_setup(ENetHost *host, void *p_key, void *p_cert) {
ENetGodotSocket *sock = (ENetGodotSocket *)host->socket;
if (!sock->can_upgrade()) {
return -1;
}
host->socket = memnew(ENetDTLSServer((ENetUDP *)sock, Ref<CryptoKey>((CryptoKey *)p_key), Ref<X509Certificate>((X509Certificate *)p_cert)));
memdelete(sock);
return 0;
}
void enet_host_dtls_client_setup(ENetHost *host, void *p_cert, uint8_t p_verify, const char *p_for_hostname) {
ENetUDP *sock = (ENetUDP *)host->socket;
host->socket = memnew(ENetDTLSClient(sock, Ref<X509Certificate>((X509Certificate *)p_cert), p_verify, String(p_for_hostname)));
int enet_host_dtls_client_setup(ENetHost *host, void *p_cert, uint8_t p_verify, const char *p_for_hostname) {
ENetGodotSocket *sock = (ENetGodotSocket *)host->socket;
if (!sock->can_upgrade()) {
return -1;
}
host->socket = memnew(ENetDTLSClient((ENetUDP *)sock, Ref<X509Certificate>((X509Certificate *)p_cert), p_verify, String::utf8(p_for_hostname)));
memdelete(sock);
return 0;
}
void enet_host_refuse_new_connections(ENetHost *host, int p_refuse) {