summaryrefslogtreecommitdiff
path: root/src/network/core/packet.h
blob: 6b5442e0e8ad5a8c993acbdfac4e694a2d232b82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* $Id$ */

/*
 * This file is part of OpenTTD.
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file packet.h Basic functions to create, fill and read packets.
 */

#ifndef NETWORK_CORE_PACKET_H
#define NETWORK_CORE_PACKET_H

#include "config.h"
#include "core.h"

#ifdef ENABLE_NETWORK

typedef uint16 PacketSize; ///< Size of the whole packet.
typedef uint8  PacketType; ///< Identifier for the packet

/**
 * 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 SEND_MTU bytes. 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.
 */
struct Packet {
	/** The next packet. Used for queueing packets before sending. */
	Packet *next;
	/** The size of the whole packet for received packets. For packets
	 * that will be sent, the value is filled in just before the
	 * actual transmission. */
	PacketSize size;
	/** The current read/write position in the packet */
	PacketSize pos;
	/** The buffer of this packet */
	byte buffer[SEND_MTU];
private:
	NetworkSocketHandler *cs;

public:
	Packet(NetworkSocketHandler *cs);
	Packet(PacketType type);

	/* Sending/writing of packets */
	void PrepareToSend();

	void Send_bool  (bool   data);
	void Send_uint8 (uint8  data);
	void Send_uint16(uint16 data);
	void Send_uint32(uint32 data);
	void Send_uint64(uint64 data);
	void Send_string(const char *data);

	/* Reading/receiving of packets */
	void ReadRawPacketSize();
	void PrepareToRead();

	bool   CanReadFromPacket (uint bytes_to_read);
	bool   Recv_bool  ();
	uint8  Recv_uint8 ();
	uint16 Recv_uint16();
	uint32 Recv_uint32();
	uint64 Recv_uint64();
	void   Recv_string(char *buffer, size_t size, bool allow_newlines = false);
};

Packet *NetworkSend_Init(PacketType type);

#endif /* ENABLE_NETWORK */

#endif /* NETWORK_CORE_PACKET_H */