OpenTTD Source  12.0-beta2
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=sizeof(PacketSize))
 Create a packet that is used to read from a network socket. More...
 
 Packet (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 data)
 Package a 8 bits integer in the packet. More...
 
void Send_uint16 (uint16 data)
 Package a 16 bits integer in the packet. More...
 
void Send_uint32 (uint32 data)
 Package a 32 bits integer in the packet. More...
 
void Send_uint64 (uint64 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...
 
size_t Send_bytes (const byte *begin, const byte *end)
 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...
 
void PrepareToRead ()
 Prepares the packet so it can be read.
 
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 Recv_uint8 ()
 Read a 8 bits integer from the packet. More...
 
uint16 Recv_uint16 ()
 Read a 16 bits integer from the packet. More...
 
uint32 Recv_uint32 ()
 Read a 32 bits integer from the packet. More...
 
uint64 Recv_uint64 ()
 Read a 64 bits integer from the packet. 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 void AddToQueue (Packet **queue, Packet *packet)
 Add the given Packet to the end of the queue of packets. More...
 
static PacketPopFromQueue (Packet **queue)
 Pop the packet from the begin of the queue and set the begin of the queue to the second element in the queue. More...
 

Private Attributes

Packetnext
 The next packet. More...
 
PacketSize pos
 The current read/write position in the packet.
 
std::vector< byte > 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 44 of file packet.h.

Constructor & Destructor Documentation

◆ Packet() [1/2]

Packet::Packet ( NetworkSocketHandler cs,
size_t  limit,
size_t  initial_read_size = sizeof(PacketSize) 
)

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 ( PacketType  type,
size_t  limit = COMPAT_MTU 
)

Creates a packet to send.

Parameters
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 47 of file packet.cpp.

References Send_uint16(), and Send_uint8().

Member Function Documentation

◆ AddToQueue()

void Packet::AddToQueue ( Packet **  queue,
Packet packet 
)
static

Add the given Packet to the end of the queue of packets.

Parameters
queueThe pointer to the begin of the queue.
packetThe packet to append to the queue.

Definition at line 59 of file packet.cpp.

References next.

Referenced by PacketWriter::AppendQueue(), PacketWriter::PrependQueue(), and NetworkTCPSocketHandler::SendPacket().

◆ 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 218 of file packet.cpp.

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

Referenced by ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(), Recv_uint16(), 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 99 of file packet.cpp.

References limit, and Size().

Referenced by Send_string(), Send_uint16(), Send_uint32(), Send_uint64(), Send_uint8(), ServerNetworkAdminSocketHandler::SendCmdNames(), and PacketWriter::Write().

◆ GetPacketType()

PacketType Packet::GetPacketType ( ) const

Get the PacketType from this packet.

Returns
The packet type.

Definition at line 287 of file packet.cpp.

References buffer, and Size().

Referenced by PacketWriter::TransferToNetworkQueue().

◆ 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 237 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 258 of file packet.cpp.

References buffer, cs, limit, next, and pos.

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

◆ PopFromQueue()

Packet * Packet::PopFromQueue ( Packet **  queue)
static

Pop the packet from the begin of the queue and set the begin of the queue to the second element in the queue.

Parameters
queueThe pointer to the begin of the queue.
Returns
The Packet that used to be a the begin of the queue.

Definition at line 71 of file packet.cpp.

References next.

Referenced by NetworkTCPSocketHandler::EmptyPacketQueue(), NetworkTCPSocketHandler::SendPackets(), PacketWriter::TransferToNetworkQueue(), and PacketWriter::~PacketWriter().

◆ Recv_bool()

bool Packet::Recv_bool ( )

Read a boolean from the packet.

Returns
The read data.

Definition at line 297 of file packet.cpp.

References Recv_uint8().

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

◆ 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 380 of file packet.cpp.

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

Referenced by DeserializeGRFIdentifierWithName(), DeserializeNetworkGameInfo(), 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(), ClientNetworkContentSocketHandler::Receive_SERVER_INFO(), ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(), ClientNetworkGameSocketHandler::Receive_SERVER_RCON(), ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(), and ClientNetworkTurnSocketHandler::Receive_TURN_CONNECTED().

◆ Recv_uint16()

◆ Recv_uint32()

◆ Recv_uint64()

uint64 Packet::Recv_uint64 ( )

Read a 64 bits integer from the packet.

Returns
The read data.

Definition at line 352 of file packet.cpp.

References CanReadFromPacket().

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 402 of file packet.cpp.

References pos, and Size().

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

◆ Send_bool()

◆ Send_bytes()

size_t Packet::Send_bytes ( const byte *  begin,
const byte *  end 
)

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 amount of bytes that were actually sent.

Parameters
beginThe begin of the buffer to send.
endThe end of the buffer to send.
Returns
The number of bytes that were added to this packet.

Definition at line 196 of file packet.cpp.

References buffer, limit, and Size().

Referenced by PacketWriter::Write().

◆ 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 181 of file packet.cpp.

References buffer, and CanWriteToPacket().

Referenced by ClientNetworkCoordinatorSocketHandler::ConnectFailure(), ClientNetworkCoordinatorSocketHandler::ConnectSuccess(), ClientNetworkCoordinatorSocketHandler::ConnectToServer(), ClientNetworkCoordinatorSocketHandler::GetListing(), ClientNetworkCoordinatorSocketHandler::Register(), ServerNetworkAdminSocketHandler::SendChat(), ClientNetworkGameSocketHandler::SendChat(), ServerNetworkGameSocketHandler::SendChat(), ServerNetworkAdminSocketHandler::SendClientInfo(), ServerNetworkGameSocketHandler::SendClientInfo(), ServerNetworkAdminSocketHandler::SendClientUpdate(), ServerNetworkAdminSocketHandler::SendCmdLogging(), ServerNetworkAdminSocketHandler::SendCmdNames(), NetworkGameSocketHandler::SendCommand(), ServerNetworkAdminSocketHandler::SendCompanyInfo(), ClientNetworkGameSocketHandler::SendCompanyPassword(), ServerNetworkAdminSocketHandler::SendCompanyUpdate(), ServerNetworkGameSocketHandler::SendConfigUpdate(), ServerNetworkAdminSocketHandler::SendConsole(), ServerNetworkGameSocketHandler::SendError(), ClientNetworkGameSocketHandler::SendGamePassword(), ServerNetworkAdminSocketHandler::SendGameScript(), ClientNetworkGameSocketHandler::SendMove(), ServerNetworkGameSocketHandler::SendNeedCompanyPassword(), ServerNetworkAdminSocketHandler::SendRcon(), ClientNetworkGameSocketHandler::SendRCon(), ServerNetworkAdminSocketHandler::SendRconEnd(), ServerNetworkGameSocketHandler::SendRConResult(), ClientNetworkGameSocketHandler::SendSetName(), ClientNetworkGameSocketHandler::SendSetPassword(), ServerNetworkGameSocketHandler::SendWelcome(), ServerNetworkAdminSocketHandler::SendWelcome(), SerializeNetworkGameInfo(), ClientNetworkStunSocketHandler::Stun(), ClientNetworkCoordinatorSocketHandler::StunResult(), and ClientNetworkTurnSocketHandler::Turn().

◆ Send_uint16()

◆ Send_uint32()

◆ Send_uint64()

void Packet::Send_uint64 ( uint64  data)

Package a 64 bits integer in the packet.

Parameters
dataThe data to send.

Definition at line 163 of file packet.cpp.

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

Referenced by ServerNetworkAdminSocketHandler::SendChat(), ClientNetworkGameSocketHandler::SendChat(), ServerNetworkGameSocketHandler::SendChat(), and ServerNetworkAdminSocketHandler::SendCompanyEconomy().

◆ Send_uint8()

void Packet::Send_uint8 ( uint8  data)

Package a 8 bits integer in the packet.

Parameters
dataThe data to send.

Definition at line 129 of file packet.cpp.

References buffer, and CanWriteToPacket().

Referenced by ClientNetworkCoordinatorSocketHandler::ConnectFailure(), ClientNetworkCoordinatorSocketHandler::ConnectSuccess(), ClientNetworkCoordinatorSocketHandler::ConnectToServer(), ClientNetworkCoordinatorSocketHandler::GetListing(), Packet(), ClientNetworkCoordinatorSocketHandler::Register(), ClientNetworkContentSocketHandler::RequestContentList(), Send_bool(), ClientNetworkGameSocketHandler::SendAck(), ServerNetworkAdminSocketHandler::SendChat(), ClientNetworkGameSocketHandler::SendChat(), ServerNetworkGameSocketHandler::SendChat(), ServerNetworkAdminSocketHandler::SendClientError(), ServerNetworkAdminSocketHandler::SendClientInfo(), ServerNetworkGameSocketHandler::SendClientInfo(), ServerNetworkAdminSocketHandler::SendClientUpdate(), ServerNetworkAdminSocketHandler::SendCmdLogging(), NetworkGameSocketHandler::SendCommand(), ServerNetworkAdminSocketHandler::SendCompanyEconomy(), ServerNetworkAdminSocketHandler::SendCompanyInfo(), ServerNetworkAdminSocketHandler::SendCompanyNew(), ServerNetworkAdminSocketHandler::SendCompanyRemove(), ServerNetworkAdminSocketHandler::SendCompanyStats(), ServerNetworkAdminSocketHandler::SendCompanyUpdate(), ServerNetworkGameSocketHandler::SendConfigUpdate(), ServerNetworkAdminSocketHandler::SendError(), ClientNetworkGameSocketHandler::SendError(), ServerNetworkGameSocketHandler::SendError(), ServerNetworkGameSocketHandler::SendErrorQuit(), ServerNetworkGameSocketHandler::SendMove(), ClientNetworkGameSocketHandler::SendMove(), ServerNetworkGameSocketHandler::SendNewGRFCheck(), ServerNetworkAdminSocketHandler::SendProtocol(), ClientNetworkCoordinatorSocketHandler::SendServerUpdate(), ServerNetworkGameSocketHandler::SendWait(), ServerNetworkAdminSocketHandler::SendWelcome(), SerializeGRFIdentifier(), SerializeNetworkGameInfo(), ClientNetworkStunSocketHandler::Stun(), ClientNetworkCoordinatorSocketHandler::StunResult(), and ClientNetworkTurnSocketHandler::Turn().

◆ 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 249 of file packet.cpp.

References buffer.

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

◆ 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 176 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 141 of file packet.h.

Referenced by ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(), 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 111 of file packet.h.

Referenced by PacketReader::AddPacket().

Field Documentation

◆ next

Packet* Packet::next
private

The next packet.

Used for queueing packets before sending.

Definition at line 47 of file packet.h.

Referenced by AddToQueue(), ParsePacketSize(), PopFromQueue(), and PrepareToSend().


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