OpenTTD Source  20240919-master-gdf0233f4c2
Packet Struct Reference

Internal entity of a packet. More...

#include <packet.h>

Public Member Functions

 Packet (NetworkSocketHandler *cs, size_t limit, size_t initial_read_size=EncodedLengthOfPacketSize())
 Create a packet that is used to read from a network socket. More...
 
 Packet (NetworkSocketHandler *cs, PacketType type, size_t limit=COMPAT_MTU)
 Creates a packet to send. More...
 
void PrepareToSend ()
 Writes the packet size from the raw packet from packet->size.
 
bool CanWriteToPacket (size_t bytes_to_write)
 Is it safe to write to the packet, i.e. More...
 
void Send_bool (bool data)
 Package a boolean in the packet. More...
 
void Send_uint8 (uint8_t data)
 Package a 8 bits integer in the packet. More...
 
void Send_uint16 (uint16_t data)
 Package a 16 bits integer in the packet. More...
 
void Send_uint32 (uint32_t data)
 Package a 32 bits integer in the packet. More...
 
void Send_uint64 (uint64_t data)
 Package a 64 bits integer in the packet. More...
 
void Send_string (const std::string_view data)
 Sends a string over the network. More...
 
void Send_buffer (const std::vector< uint8_t > &data)
 Copy a sized byte buffer into the packet. More...
 
std::span< const uint8_t > Send_bytes (const std::span< const uint8_t > span)
 Send as many of the bytes as possible in the packet. More...
 
bool HasPacketSizeData () const
 Check whether the packet, given the position of the "write" pointer, has read enough of the packet to contain its size. More...
 
bool ParsePacketSize ()
 Reads the packet size from the raw packet and stores it in the packet->size. More...
 
size_t Size () const
 Get the number of bytes in the packet. More...
 
bool PrepareToRead ()
 Prepares the packet so it can be read. More...
 
PacketType GetPacketType () const
 Get the PacketType from this packet. More...
 
bool CanReadFromPacket (size_t bytes_to_read, bool close_connection=false)
 Is it safe to read from the packet, i.e. More...
 
bool Recv_bool ()
 Read a boolean from the packet. More...
 
uint8_t Recv_uint8 ()
 Read a 8 bits integer from the packet. More...
 
uint16_t Recv_uint16 ()
 Read a 16 bits integer from the packet. More...
 
uint32_t Recv_uint32 ()
 Read a 32 bits integer from the packet. More...
 
uint64_t Recv_uint64 ()
 Read a 64 bits integer from the packet. More...
 
std::vector< uint8_t > Recv_buffer ()
 Extract a sized byte buffer from the packet. More...
 
size_t Recv_bytes (std::span< uint8_t > span)
 Extract at most the length of the span bytes from the packet into the span. More...
 
std::string Recv_string (size_t length, StringValidationSettings settings=SVS_REPLACE_WITH_QUESTION_MARK)
 Reads characters (bytes) from the packet until it finds a '\0', or reaches a maximum of length characters. More...
 
size_t RemainingBytesToTransfer () const
 Get the amount of bytes that are still available for the Transfer functions. More...
 
template<typename A = size_t, typename F , typename D , typename ... Args>
ssize_t TransferOutWithLimit (F transfer_function, size_t limit, D destination, Args &&... args)
 Transfer data from the packet to the given function. More...
 
template<typename A = size_t, typename F , typename D , typename ... Args>
ssize_t TransferOut (F transfer_function, D destination, Args &&... args)
 Transfer data from the packet to the given function. More...
 
template<typename A = size_t, typename F , typename S , typename ... Args>
ssize_t TransferIn (F transfer_function, S source, Args &&... args)
 Transfer data from the given function into the packet. More...
 

Static Public Member Functions

static constexpr size_t EncodedLengthOfPacketSize ()
 
static constexpr size_t EncodedLengthOfPacketType ()
 

Private Attributes

PacketSize pos
 The current read/write position in the packet.
 
std::vector< uint8_t > buffer
 The buffer of this packet.
 
size_t limit
 The limit for the packet size.
 
NetworkSocketHandlercs
 Socket we're associated with.
 

Detailed Description

Internal entity of a packet.

As everything is sent as a packet, all network communication will need to call the functions that populate the packet. Every packet can be at most a limited number bytes set in the constructor. Overflowing this limit will give an assertion when sending (i.e. writing) the packet. Reading past the size of the packet when receiving will return all 0 values and "" in case of the string.

— Points of attention —

  • all > 1 byte integral values are written in little endian, unless specified otherwise. Thus, 0x01234567 would be sent as {0x67, 0x45, 0x23, 0x01}.
  • all sent strings are of variable length and terminated by a '\0'. Thus, the length of the strings is not sent.
  • years that are leap years in the 'days since X' to 'date' calculations: (year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))

Definition at line 42 of file packet.h.

Constructor & Destructor Documentation

◆ Packet() [1/2]

Packet::Packet ( NetworkSocketHandler cs,
size_t  limit,
size_t  initial_read_size = EncodedLengthOfPacketSize() 
)

Create a packet that is used to read from a network socket.

Parameters
csThe socket handler associated with the socket we are reading from.
limitThe maximum size of packets to accept.
initial_read_sizeThe initial amount of data to transfer from the socket into the packet. This defaults to just the required bytes to determine the packet's size. That default is the wanted for streams such as TCP as you do not want to read data of the next packet yet. For UDP you need to read the whole packet at once otherwise you might loose some the data of the packet, so there you pass the maximum size for the packet you expect from the network.

Definition at line 31 of file packet.cpp.

References buffer, and cs.

◆ Packet() [2/2]

Packet::Packet ( NetworkSocketHandler cs,
PacketType  type,
size_t  limit = COMPAT_MTU 
)

Creates a packet to send.

Parameters
csThe socket handler associated with the socket we are writing to; could be nullptr.
typeThe type of the packet to send
limitThe maximum number of bytes the packet may have. Default is COMPAT_MTU. Be careful of compatibility with older clients/servers when changing the limit as it might break things if the other side is not expecting much larger packets than what they support.

Definition at line 48 of file packet.cpp.

References buffer, CanWriteToPacket(), cs, NetworkSocketHandler::send_encryption_handler, and Send_uint8().

Member Function Documentation

◆ CanReadFromPacket()

bool Packet::CanReadFromPacket ( size_t  bytes_to_read,
bool  close_connection = false 
)

Is it safe to read from the packet, i.e.

didn't we run over the buffer? In case close_connection is true, the connection will be closed when one would overrun the buffer. When it is false, the connection remains untouched.

Parameters
bytes_to_readThe amount of bytes we want to try to read.
close_connectionWhether to close the connection if one cannot read that amount.
Returns
True if that is safe, otherwise false.

Definition at line 219 of file packet.cpp.

References cs, NetworkSocketHandler::HasClientQuit(), pos, and Size().

Referenced by ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(), Recv_uint32(), Recv_uint64(), and Recv_uint8().

◆ CanWriteToPacket()

bool Packet::CanWriteToPacket ( size_t  bytes_to_write)

Is it safe to write to the packet, i.e.

didn't we run over the buffer?

Parameters
bytes_to_writeThe amount of bytes we want to try to write.
Returns
True iff the given amount of bytes can be written to the packet.

Definition at line 90 of file packet.cpp.

References limit, and Size().

Referenced by Packet(), Send_buffer(), Send_string(), Send_uint32(), Send_uint64(), and Send_uint8().

◆ GetPacketType()

PacketType Packet::GetPacketType ( ) const

Get the PacketType from this packet.

Returns
The packet type.

Definition at line 297 of file packet.cpp.

References buffer, cs, NetworkSocketHandler::send_encryption_handler, and Size().

◆ HasPacketSizeData()

bool Packet::HasPacketSizeData ( ) const

Check whether the packet, given the position of the "write" pointer, has read enough of the packet to contain its size.

Returns
True iff there is enough data in the packet to contain the packet's size.

Definition at line 238 of file packet.cpp.

References pos.

Referenced by NetworkTCPSocketHandler::ReceivePacket().

◆ ParsePacketSize()

bool Packet::ParsePacketSize ( )

Reads the packet size from the raw packet and stores it in the packet->size.

Returns
True iff the packet size seems plausible.

Definition at line 259 of file packet.cpp.

References buffer, limit, and pos.

Referenced by NetworkTCPSocketHandler::ReceivePacket(), and NetworkUDPSocketHandler::ReceivePackets().

◆ PrepareToRead()

bool Packet::PrepareToRead ( )

Prepares the packet so it can be read.

Returns
True when the packet was valid, otherwise false.

Definition at line 278 of file packet.cpp.

References buffer, cs, pos, NetworkSocketHandler::receive_encryption_handler, and valid.

Referenced by NetworkTCPSocketHandler::ReceivePacket(), and NetworkUDPSocketHandler::ReceivePackets().

◆ Recv_bool()

bool Packet::Recv_bool ( )

Read a boolean from the packet.

Returns
The read data.

Definition at line 309 of file packet.cpp.

References Recv_uint8().

Referenced by ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(), and ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND().

◆ Recv_buffer()

std::vector< uint8_t > Packet::Recv_buffer ( )

Extract a sized byte buffer from the packet.

Returns
The extracted buffer.

Definition at line 385 of file packet.cpp.

◆ Recv_bytes()

size_t Packet::Recv_bytes ( std::span< uint8_t >  span)

Extract at most the length of the span bytes from the packet into the span.

Parameters
spanThe span to write the bytes to.
Returns
The number of bytes that were actually read.

Definition at line 403 of file packet.cpp.

References TransferOut().

Referenced by ClientNetworkContentSocketHandler::Receive_SERVER_INFO(), X25519AuthenticationHandler::ReceiveEnableEncryption(), X25519AuthenticationHandler::ReceiveRequest(), and X25519AuthenticationHandler::ReceiveResponse().

◆ Recv_string()

std::string Packet::Recv_string ( size_t  length,
StringValidationSettings  settings = SVS_REPLACE_WITH_QUESTION_MARK 
)

Reads characters (bytes) from the packet until it finds a '\0', or reaches a maximum of length characters.

When the '\0' has not been reached in the first length read characters, more characters are read from the packet until '\0' has been reached. However, these characters will not end up in the returned string. The length of the returned string will be at most length - 1 characters.

Parameters
lengthThe maximum length of the string including '\0'.
settingsThe string validation settings.
Returns
The validated string.

Definition at line 425 of file packet.cpp.

References Recv_uint8(), settings, and StrMakeValid().

Referenced by ClientNetworkCoordinatorSocketHandler::Receive_GC_CONNECT_FAILED(), ClientNetworkCoordinatorSocketHandler::Receive_GC_CONNECTING(), ClientNetworkCoordinatorSocketHandler::Receive_GC_DIRECT_CONNECT(), ClientNetworkCoordinatorSocketHandler::Receive_GC_ERROR(), ClientNetworkCoordinatorSocketHandler::Receive_GC_LISTING(), ClientNetworkCoordinatorSocketHandler::Receive_GC_REGISTER_ACK(), ClientNetworkCoordinatorSocketHandler::Receive_GC_STUN_CONNECT(), ClientNetworkCoordinatorSocketHandler::Receive_GC_STUN_REQUEST(), ClientNetworkCoordinatorSocketHandler::Receive_GC_TURN_CONNECT(), ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(), ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(), ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(), ClientNetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT(), ClientNetworkContentSocketHandler::Receive_SERVER_INFO(), ClientNetworkGameSocketHandler::Receive_SERVER_RCON(), and ClientNetworkTurnSocketHandler::Receive_TURN_CONNECTED().

◆ Recv_uint16()

uint16_t Packet::Recv_uint16 ( )

◆ Recv_uint32()

◆ Recv_uint64()

uint64_t Packet::Recv_uint64 ( )

Read a 64 bits integer from the packet.

Returns
The read data.

Definition at line 364 of file packet.cpp.

References buffer, CanReadFromPacket(), and pos.

Referenced by ClientNetworkGameSocketHandler::Receive_SERVER_CHAT().

◆ Recv_uint8()

◆ RemainingBytesToTransfer()

size_t Packet::RemainingBytesToTransfer ( ) const

Get the amount of bytes that are still available for the Transfer functions.

Returns
The number of bytes that still have to be transfered.

Definition at line 447 of file packet.cpp.

References pos, and Size().

Referenced by PacketReader::AddPacket(), ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(), NetworkTCPSocketHandler::ReceivePacket(), X25519AuthenticationHandler::ReceiveRequest(), X25519AuthenticationHandler::ReceiveResponse(), and NetworkTCPSocketHandler::SendPackets().

◆ Send_bool()

void Packet::Send_bool ( bool  data)

Package a boolean in the packet.

Parameters
dataThe data to send.

Definition at line 111 of file packet.cpp.

References Send_uint8().

◆ Send_buffer()

void Packet::Send_buffer ( const std::vector< uint8_t > &  data)

Copy a sized byte buffer into the packet.

Parameters
dataThe data to send.

Definition at line 183 of file packet.cpp.

References CanWriteToPacket().

Referenced by NetworkGameSocketHandler::SendCommand().

◆ Send_bytes()

std::span< const uint8_t > Packet::Send_bytes ( const std::span< const uint8_t >  span)

Send as many of the bytes as possible in the packet.

This can mean that it is possible that not all bytes are sent. To cope with this the function returns the span of bytes that were not sent.

Parameters
spanThe span describing the range of bytes to send.
Returns
The span of bytes that were not written.

Definition at line 197 of file packet.cpp.

References buffer.

Referenced by X25519AuthenticationHandler::SendEnableEncryption(), and X25519AuthenticationHandler::SendResponse().

◆ Send_string()

void Packet::Send_string ( const std::string_view  data)

Sends a string over the network.

It sends out the string + '\0'. No size-byte or something.

Parameters
dataThe string to send

Definition at line 172 of file packet.cpp.

References buffer, and CanWriteToPacket().

◆ Send_uint16()

void Packet::Send_uint16 ( uint16_t  data)

Package a 16 bits integer in the packet.

Parameters
dataThe data to send.

Definition at line 130 of file packet.cpp.

Referenced by NetworkGameSocketHandler::SendCommand().

◆ Send_uint32()

void Packet::Send_uint32 ( uint32_t  data)

Package a 32 bits integer in the packet.

Parameters
dataThe data to send.

Definition at line 141 of file packet.cpp.

References buffer, CanWriteToPacket(), and GB().

◆ Send_uint64()

void Packet::Send_uint64 ( uint64_t  data)

Package a 64 bits integer in the packet.

Parameters
dataThe data to send.

Definition at line 154 of file packet.cpp.

References buffer, CanWriteToPacket(), and GB().

◆ Send_uint8()

void Packet::Send_uint8 ( uint8_t  data)

Package a 8 bits integer in the packet.

Parameters
dataThe data to send.

Definition at line 120 of file packet.cpp.

References buffer, and CanWriteToPacket().

Referenced by Packet(), Send_bool(), NetworkGameSocketHandler::SendCommand(), and CombinedAuthenticationServerHandler::SendRequest().

◆ Size()

size_t Packet::Size ( ) const

Get the number of bytes in the packet.

When sending a packet this is the size of the data up to that moment. When receiving a packet (before PrepareToRead) this is the allocated size for the data to be read. When reading a packet (after PrepareToRead) this is the full size of the packet.

Returns
The packet's size.

Definition at line 250 of file packet.cpp.

References buffer.

Referenced by CanReadFromPacket(), CanWriteToPacket(), GetPacketType(), PrepareToSend(), NetworkUDPSocketHandler::ReceivePackets(), and RemainingBytesToTransfer().

◆ TransferIn()

template<typename A = size_t, typename F , typename S , typename ... Args>
ssize_t Packet::TransferIn ( transfer_function,
source,
Args &&...  args 
)
inline

Transfer data from the given function into the packet.

It starts writing at the position the last transfer stopped.

Examples of functions that can be used to transfer data into a packet are TCP's recv and UDP's recvfrom functions. They will directly write their data into the packet without an intermediate buffer. Examples of functions that can be used to transfer data from a packet are TCP's send and UDP's sendto functions. They will directly read the data from the packet's buffer without an intermediate buffer. These are functions are special in a sense as even though the packet can send or receive an amount of data, those functions can say they only processed a smaller amount, so special handling is required to keep the position pointers correct. Most of these transfer functions are in the form function(source, buffer, amount, ...), so the template of this function will assume that as the base parameter order.

This will attempt to write all the remaining bytes into the packet. It updates the position based on how many bytes were actually written by the called transfer_function.

Parameters
transfer_functionThe function to pass the buffer as second parameter and the amount to read as third parameter. It returns the amount that was read or -1 upon errors.
sourceThe first parameter of the transfer function.
argsThe fourth and further parameters to the transfer function, if any.
Template Parameters
AThe type for the amount to be passed, so it can be cast to the right type.
FThe type of the transfer_function.
SThe type of the source.
ArgsThe types of the remaining arguments to the function.
Returns
The return value of the transfer_function.

Definition at line 174 of file packet.h.

Referenced by NetworkTCPSocketHandler::ReceivePacket(), and NetworkUDPSocketHandler::ReceivePackets().

◆ TransferOut()

template<typename A = size_t, typename F , typename D , typename ... Args>
ssize_t Packet::TransferOut ( transfer_function,
destination,
Args &&...  args 
)
inline

Transfer data from the packet to the given function.

It starts reading at the position the last transfer stopped. See Packet::TransferIn for more information about transferring data to functions.

Parameters
transfer_functionThe function to pass the buffer as second parameter and the amount to write as third parameter. It returns the amount that was written or -1 upon errors.
destinationThe first parameter of the transfer function.
argsThe fourth and further parameters to the transfer function, if any.
Template Parameters
AThe type for the amount to be passed, so it can be cast to the right type.
FThe type of the transfer_function.
DThe type of the destination.
ArgsThe types of the remaining arguments to the function.
Returns
The return value of the transfer_function.

Definition at line 139 of file packet.h.

Referenced by ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(), Recv_bytes(), NetworkUDPSocketHandler::SendPacket(), and NetworkTCPSocketHandler::SendPackets().

◆ TransferOutWithLimit()

template<typename A = size_t, typename F , typename D , typename ... Args>
ssize_t Packet::TransferOutWithLimit ( transfer_function,
size_t  limit,
destination,
Args &&...  args 
)
inline

Transfer data from the packet to the given function.

It starts reading at the position the last transfer stopped. See Packet::TransferIn for more information about transferring data to functions.

Parameters
transfer_functionThe function to pass the buffer as second parameter and the amount to write as third parameter. It returns the amount that was written or -1 upon errors.
limitThe maximum amount of bytes to transfer.
destinationThe first parameter of the transfer function.
argsThe fourth and further parameters to the transfer function, if any.
Returns
The return value of the transfer_function. < The types of the remaining arguments to the function.

Definition at line 109 of file packet.h.

Referenced by PacketReader::AddPacket().


The documentation for this struct was generated from the following files: