aboutsummaryrefslogtreecommitdiff
path: root/src/inventory.h
blob: f36bc57cf64e3ffc11443c4c21201ce849326a65 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#pragma once

#include "itemdef.h"
#include "irrlichttypes.h"
#include "itemstackmetadata.h"
#include <istream>
#include <ostream>
#include <string>
#include <vector>
#include <cassert>

struct ToolCapabilities;

struct ItemStack
{
	ItemStack() = default;

	ItemStack(const std::string &name_, u16 count_,
			u16 wear, IItemDefManager *itemdef);

	~ItemStack() = default;

	// Serialization
	void serialize(std::ostream &os, bool serialize_meta = true) const;
	// Deserialization. Pass itemdef unless you don't want aliases resolved.
	void deSerialize(std::istream &is, IItemDefManager *itemdef = NULL);
	void deSerialize(const std::string &s, IItemDefManager *itemdef = NULL);

	// Returns the string used for inventory
	std::string getItemString(bool include_meta = true) const;
	// Returns the tooltip
	std::string getDescription(IItemDefManager *itemdef) const;
	std::string getShortDescription(IItemDefManager *itemdef) const;

	/*
		Quantity methods
	*/

	bool empty() const
	{
		return count == 0;
	}

	void clear()
	{
		name = "";
		count = 0;
		wear = 0;
		metadata.clear();
	}

	void add(u16 n)
	{
		count += n;
	}

	void remove(u16 n)
	{
		assert(count >= n); // Pre-condition
		count -= n;
		if(count == 0)
			clear(); // reset name, wear and metadata too
	}

	// Maximum size of a stack
	u16 getStackMax(IItemDefManager *itemdef) const
	{
		return itemdef->get(name).stack_max;
	}

	// Number of items that can be added to this stack
	u16 freeSpace(IItemDefManager *itemdef) const
	{
		u16 max = getStackMax(itemdef);
		if (count >= max)
			return 0;
		return max - count;
	}

	// Returns false if item is not known and cannot be used
	bool isKnown(IItemDefManager *itemdef) const
	{
		return itemdef->isKnown(name);
	}

	// Returns a pointer to the item definition struct,
	// or a fallback one (name="unknown") if the item is unknown.
	const ItemDefinition& getDefinition(
			IItemDefManager *itemdef) const
	{
		return itemdef->get(name);
	}

	// Get tool digging properties, or those of the hand if not a tool
	const ToolCapabilities& getToolCapabilities(
			IItemDefManager *itemdef) const
	{
		const ToolCapabilities *item_cap =
			itemdef->get(name).tool_capabilities;

		if (item_cap == NULL)
			// Fall back to the hand's tool capabilities
			item_cap = itemdef->get("").tool_capabilities;

		assert(item_cap != NULL);
		return metadata.getToolCapabilities(*item_cap); // Check for override
	}

	// Wear out (only tools)
	// Returns true if the item is (was) a tool
	bool addWear(s32 amount, IItemDefManager *itemdef)
	{
		if(getDefinition(itemdef).type == ITEM_TOOL)
		{
			if(amount > 65535 - wear)
				clear();
			else if(amount < -wear)
				wear = 0;
			else
				wear += amount;
			return true;
		}

		return false;
	}

	// If possible, adds newitem to this item.
	// If cannot be added at all, returns the item back.
	// If can be added partly, decremented item is returned back.
	// If can be added fully, empty item is returned.
	ItemStack addItem(ItemStack newitem, IItemDefManager *itemdef);

	// Checks whether newitem could be added.
	// If restitem is non-NULL, it receives the part of newitem that
	// would be left over after adding.
	bool itemFits(ItemStack newitem,
			ItemStack *restitem,  // may be NULL
			IItemDefManager *itemdef) const;

	// Takes some items.
	// If there are not enough, takes as many as it can.
	// Returns empty item if couldn't take any.
	ItemStack takeItem(u32 takecount);

	// Similar to takeItem, but keeps this ItemStack intact.
	ItemStack peekItem(u32 peekcount) const;

	bool operator ==(const ItemStack &s) const
	{
		return (this->name     == s.name &&
				this->count    == s.count &&
				this->wear     == s.wear &&
				this->metadata == s.metadata);
	}

	bool operator !=(const ItemStack &s) const
	{
		return !(*this == s);
	}

	/*
		Properties
	*/
	std::string name = "";
	u16 count = 0;
	u16 wear = 0;
	ItemStackMetadata metadata;
};

class InventoryList
{
public:
	InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef);
	~InventoryList() = default;
	void clearItems();
	void setSize(u32 newsize);
	void setWidth(u32 newWidth);
	void setName(const std::string &name);
	void serialize(std::ostream &os, bool incremental) const;
	void deSerialize(std::istream &is);

	InventoryList(const InventoryList &other);
	InventoryList & operator = (const InventoryList &other);
	bool operator == (const InventoryList &other) const;
	bool operator != (const InventoryList &other) const
	{
		return !(*this == other);
	}

	const std::string &getName() const;
	u32 getSize() const;
	u32 getWidth() const;
	// Count used slots
	u32 getUsedSlots() const;
	u32 getFreeSlots() const;

	// Get reference to item
	const ItemStack& getItem(u32 i) const;
	ItemStack& getItem(u32 i);
	// Returns old item. Parameter can be an empty item.
	ItemStack changeItem(u32 i, const ItemStack &newitem);
	// Delete item
	void deleteItem(u32 i);

	// Adds an item to a suitable place. Returns leftover item (possibly empty).
	ItemStack addItem(const ItemStack &newitem);

	// If possible, adds item to given slot.
	// If cannot be added at all, returns the item back.
	// If can be added partly, decremented item is returned back.
	// If can be added fully, empty item is returned.
	ItemStack addItem(u32 i, const ItemStack &newitem);

	// Checks whether the item could be added to the given slot
	// If restitem is non-NULL, it receives the part of newitem that
	// would be left over after adding.
	bool itemFits(const u32 i, const ItemStack &newitem,
			ItemStack *restitem = NULL) const;

	// Checks whether there is room for a given item
	bool roomForItem(const ItemStack &item) const;

	// Checks whether the given count of the given item
	// exists in this inventory list.
	// If match_meta is false, only the items' names are compared.
	bool containsItem(const ItemStack &item, bool match_meta) const;

	// Removes the given count of the given item name from
	// this inventory list. Walks the list in reverse order.
	// If not as many items exist as requested, removes as
	// many as possible.
	// Returns the items that were actually removed.
	ItemStack removeItem(const ItemStack &item);

	// Takes some items from a slot.
	// If there are not enough, takes as many as it can.
	// Returns empty item if couldn't take any.
	ItemStack takeItem(u32 i, u32 takecount);

	// Move an item to a different list (or a different stack in the same list)
	// count is the maximum number of items to move (0 for everything)
	// returns number of moved items
	u32 moveItem(u32 i, InventoryList *dest, u32 dest_i,
		u32 count = 0, bool swap_if_needed = true, bool *did_swap = NULL);

	// like moveItem, but without a fixed destination index
	// also with optional rollback recording
	void moveItemSomewhere(u32 i, InventoryList *dest, u32 count);

	inline bool checkModified() const { return m_dirty; }
	inline void setModified(bool dirty = true) { m_dirty = dirty; }

private:
	std::vector<ItemStack> m_items;
	std::string m_name;
	u32 m_size;
	u32 m_width = 0;
	IItemDefManager *m_itemdef;
	bool m_dirty = true;
};

class Inventory
{
public:
	~Inventory();

	void clear();

	Inventory(IItemDefManager *itemdef);
	Inventory(const Inventory &other);
	Inventory & operator = (const Inventory &other);
	bool operator == (const Inventory &other) const;
	bool operator != (const Inventory &other) const
	{
		return !(*this == other);
	}

	// Never ever serialize to disk using "incremental"!
	void serialize(std::ostream &os, bool incremental = false) const;
	void deSerialize(std::istream &is);

	InventoryList * addList(const std::string &name, u32 size);
	InventoryList * getList(const std::string &name);
	const InventoryList * getList(const std::string &name) const;
	std::vector<const InventoryList*> getLists();
	bool deleteList(const std::string &name);
	// A shorthand for adding items. Returns leftover item (possibly empty).
	ItemStack addItem(const std::string &listname, const ItemStack &newitem)
	{
		InventoryList *list = getList(listname);
		if(list == NULL)
			return newitem;
		return list->addItem(newitem);
	}

	inline bool checkModified() const
	{
		if (m_dirty)
			return true;

		for (const auto &list : m_lists)
			if (list->checkModified())
				return true;

		return false;
	}

	inline void setModified(bool dirty = true)
	{
		m_dirty = dirty;
		// Set all as handled
		if (!dirty) {
			for (const auto &list : m_lists)
				list->setModified(dirty);
		}
	}
private:
	// -1 if not found
	const s32 getListIndex(const std::string &name) const;

	std::vector<InventoryList*> m_lists;
	IItemDefManager *m_itemdef;
	bool m_dirty = true;
};
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
/*
Minetest
Copyright (C) 2013-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2017 celeron55, Loic Blot <loic.blot@unix-experience.fr>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "connectionthreads.h"
#include "log.h"
#include "profiler.h"
#include "settings.h"
#include "network/networkpacket.h"
#include "util/serialize.h"

namespace con
{

/******************************************************************************/
/* defines used for debugging and profiling                                   */
/******************************************************************************/
#ifdef NDEBUG
#define LOG(a) a
#define PROFILE(a)
#undef DEBUG_CONNECTION_KBPS
#else
/* this mutex is used to achieve log message consistency */
std::mutex log_conthread_mutex;
#define LOG(a)                                                                \
	{                                                                         \
	MutexAutoLock loglock(log_conthread_mutex);                                 \
	a;                                                                        \
	}
#define PROFILE(a) a
//#define DEBUG_CONNECTION_KBPS
#undef DEBUG_CONNECTION_KBPS
#endif

/* maximum number of retries for reliable packets */
#define MAX_RELIABLE_RETRY 5

#define WINDOW_SIZE 5

static session_t readPeerId(u8 *packetdata)
{
	return readU16(&packetdata[4]);
}
static u8 readChannel(u8 *packetdata)
{
	return readU8(&packetdata[6]);
}

/******************************************************************************/
/* Connection Threads                                                         */
/******************************************************************************/

ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
	float timeout) :
	Thread("ConnectionSend"),
	m_max_packet_size(max_packet_size),
	m_timeout(timeout),
	m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration"))
{
}

void *ConnectionSendThread::run()
{
	assert(m_connection);

	LOG(dout_con << m_connection->getDesc()
		<< "ConnectionSend thread started" << std::endl);

	u64 curtime = porting::getTimeMs();
	u64 lasttime = curtime;

	PROFILE(std::stringstream ThreadIdentifier);
	PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");

	/* if stop is requested don't stop immediately but try to send all        */
	/* packets first */
	while (!stopRequested() || packetsQueued()) {
		BEGIN_DEBUG_EXCEPTION_HANDLER
		PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));

		m_iteration_packets_avaialble = m_max_data_packets_per_iteration;

		/* wait for trigger or timeout */
		m_send_sleep_semaphore.wait(50);

		/* remove all triggers */
		while (m_send_sleep_semaphore.wait(0)) {
		}

		lasttime = curtime;
		curtime = porting::getTimeMs();
		float dtime = CALC_DTIME(lasttime, curtime);

		/* first do all the reliable stuff */
		runTimeouts(dtime);

		/* translate commands to packets */
		ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
		while (c.type != CONNCMD_NONE) {
			if (c.reliable)
				processReliableCommand(c);
			else
				processNonReliableCommand(c);

			c = m_connection->m_command_queue.pop_frontNoEx(0);
		}

		/* send non reliable packets */
		sendPackets(dtime);

		END_DEBUG_EXCEPTION_HANDLER
	}

	PROFILE(g_profiler->remove(ThreadIdentifier.str()));
	return NULL;
}

void ConnectionSendThread::Trigger()
{
	m_send_sleep_semaphore.post();
}

bool ConnectionSendThread::packetsQueued()
{
	std::list<session_t> peerIds = m_connection->getPeerIDs();

	if (!m_outgoing_queue.empty() && !peerIds.empty())
		return true;

	for (session_t peerId : peerIds) {
		PeerHelper peer = m_connection->getPeerNoEx(peerId);

		if (!peer)
			continue;

		if (dynamic_cast<UDPPeer *>(&peer) == 0)
			continue;

		for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
			if (!channel.queued_commands.empty()) {
				return true;
			}
		}
	}


	return false;
}

void ConnectionSendThread::runTimeouts(float dtime)
{
	std::list<session_t> timeouted_peers;
	std::list<session_t> peerIds = m_connection->getPeerIDs();

	for (session_t &peerId : peerIds) {
		PeerHelper peer = m_connection->getPeerNoEx(peerId);

		if (!peer)
			continue;

		UDPPeer *udpPeer = dynamic_cast<UDPPeer *>(&peer);
		if (!udpPeer)
			continue;

		PROFILE(std::stringstream peerIdentifier);
		PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
			<< ";" << peerId << ";RELIABLE]");
		PROFILE(ScopeProfiler
		peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));

		SharedBuffer<u8> data(2); // data for sending ping, required here because of goto

		/*
			Check peer timeout
		*/
		if (peer->isTimedOut(m_timeout)) {
			infostream << m_connection->getDesc()
				<< "RunTimeouts(): Peer " << peer->id
				<< " has timed out."
				<< " (source=peer->timeout_counter)"
				<< std::endl;
			// Add peer to the list
			timeouted_peers.push_back(peer->id);
			// Don't bother going through the buffers of this one
			continue;
		}

		float resend_timeout = udpPeer->getResendTimeout();
		bool retry_count_exceeded = false;
		for (Channel &channel : udpPeer->channels) {
			std::list<BufferedPacket> timed_outs;

			if (udpPeer->getLegacyPeer())
				channel.setWindowSize(WINDOW_SIZE);

			// Remove timed out incomplete unreliable split packets
			channel.incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);

			// Increment reliable packet times
			channel.outgoing_reliables_sent.incrementTimeouts(dtime);

			unsigned int numpeers = m_connection->m_peers.size();

			if (numpeers == 0)
				return;

			// Re-send timed out outgoing reliables
			timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout,
				(m_max_data_packets_per_iteration / numpeers));

			channel.UpdatePacketLossCounter(timed_outs.size());
			g_profiler->graphAdd("packets_lost", timed_outs.size());

			m_iteration_packets_avaialble -= timed_outs.size();

			for (std::list<BufferedPacket>::iterator k = timed_outs.begin();
				k != timed_outs.end(); ++k) {
				session_t peer_id = readPeerId(*(k->data));
				u8 channelnum = readChannel(*(k->data));
				u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE + 1]));

				channel.UpdateBytesLost(k->data.getSize());
				k->resend_count++;

				if (k->resend_count > MAX_RELIABLE_RETRY) {
					retry_count_exceeded = true;
					timeouted_peers.push_back(peer->id);
					/* no need to check additional packets if a single one did timeout*/
					break;
				}

				LOG(derr_con << m_connection->getDesc()
					<< "RE-SENDING timed-out RELIABLE to "
					<< k->address.serializeString()
					<< "(t/o=" << resend_timeout << "): "
					<< "from_peer_id=" << peer_id
					<< ", channel=" << ((int) channelnum & 0xff)
					<< ", seqnum=" << seqnum
					<< std::endl);

				rawSend(*k);

				// do not handle rtt here as we can't decide if this packet was
				// lost or really takes more time to transmit
			}

			if (retry_count_exceeded) {
				break; /* no need to check other channels if we already did timeout */
			}

			channel.UpdateTimers(dtime, udpPeer->getLegacyPeer());
		}

		/* skip to next peer if we did timeout */
		if (retry_count_exceeded)
			continue;

		/* send ping if necessary */
		if (udpPeer->Ping(dtime, data)) {
			LOG(dout_con << m_connection->getDesc()
				<< "Sending ping for peer_id: " << udpPeer->id << std::endl);
			/* this may fail if there ain't a sequence number left */
			if (!rawSendAsPacket(udpPeer->id, 0, data, true)) {
				//retrigger with reduced ping interval
				udpPeer->Ping(4.0, data);
			}
		}

		udpPeer->RunCommandQueues(m_max_packet_size,
			m_max_commands_per_iteration,
			m_max_packets_requeued);
	}

	// Remove timed out peers
	for (u16 timeouted_peer : timeouted_peers) {
		LOG(derr_con << m_connection->getDesc()
			<< "RunTimeouts(): Removing peer " << timeouted_peer << std::endl);
		m_connection->deletePeer(timeouted_peer, true);
	}
}

void ConnectionSendThread::rawSend(const BufferedPacket &packet)
{
	try {
		m_connection->m_udpSocket.Send(packet.address, *packet.data,
			packet.data.getSize());
		LOG(dout_con << m_connection->getDesc()
			<< " rawSend: " << packet.data.getSize()
			<< " bytes sent" << std::endl);
	} catch (SendFailedException &e) {
		LOG(derr_con << m_connection->getDesc()
			<< "Connection::rawSend(): SendFailedException: "
			<< packet.address.serializeString() << std::endl);
	}
}

void ConnectionSendThread::sendAsPacketReliable(BufferedPacket &p, Channel *channel)
{
	try {
		p.absolute_send_time = porting::getTimeMs();
		// Buffer the packet
		channel->outgoing_reliables_sent.insert(p,
			(channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
				% (MAX_RELIABLE_WINDOW_SIZE + 1));
	}
	catch (AlreadyExistsException &e) {
		LOG(derr_con << m_connection->getDesc()
			<< "WARNING: Going to send a reliable packet"
			<< " in outgoing buffer" << std::endl);
	}

	// Send the packet
	rawSend(p);
}

bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum,
	SharedBuffer<u8> data, bool reliable)
{
	PeerHelper peer = m_connection->getPeerNoEx(peer_id);
	if (!peer) {
		LOG(dout_con << m_connection->getDesc()
			<< " INFO: dropped packet for non existent peer_id: "
			<< peer_id << std::endl);
		FATAL_ERROR_IF(!reliable,
			"Trying to send raw packet reliable but no peer found!");
		return false;
	}
	Channel *channel = &(dynamic_cast<UDPPeer *>(&peer)->channels[channelnum]);

	if (reliable) {
		bool have_sequence_number_for_raw_packet = true;
		u16 seqnum =
			channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);

		if (!have_sequence_number_for_raw_packet)
			return false;

		SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
		Address peer_address;
		peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);

		// Add base headers and make a packet
		BufferedPacket p = con::makePacket(peer_address, reliable,
			m_connection->GetProtocolID(), m_connection->GetPeerID(),
			channelnum);

		// first check if our send window is already maxed out
		if (channel->outgoing_reliables_sent.size()
			< channel->getWindowSize()) {
			LOG(dout_con << m_connection->getDesc()
				<< " INFO: sending a reliable packet to peer_id " << peer_id
				<< " channel: " << (u32)channelnum
				<< " seqnum: " << seqnum << std::endl);
			sendAsPacketReliable(p, channel);
			return true;
		}

		LOG(dout_con << m_connection->getDesc()
			<< " INFO: queueing reliable packet for peer_id: " << peer_id
			<< " channel: " << (u32)channelnum
			<< " seqnum: " << seqnum << std::endl);
		channel->queued_reliables.push(p);
		return false;
	}

	Address peer_address;
	if (peer->getAddress(MTP_UDP, peer_address)) {
		// Add base headers and make a packet
		BufferedPacket p = con::makePacket(peer_address, data,
			m_connection->GetProtocolID(), m_connection->GetPeerID(),
			channelnum);

		// Send the packet
		rawSend(p);
		return true;
	}

	LOG(dout_con << m_connection->getDesc()
		<< " INFO: dropped unreliable packet for peer_id: " << peer_id
		<< " because of (yet) missing udp address" << std::endl);
	return false;
}

void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
{
	assert(c.reliable);  // Pre-condition

	switch (c.type) {
		case CONNCMD_NONE:
			LOG(dout_con << m_connection->getDesc()
				<< "UDP processing reliable CONNCMD_NONE" << std::endl);
			return;

		case CONNCMD_SEND:
			LOG(dout_con << m_connection->getDesc()
				<< "UDP processing reliable CONNCMD_SEND" << std::endl);
			sendReliable(c);
			return;

		case CONNCMD_SEND_TO_ALL:
			LOG(dout_con << m_connection->getDesc()
				<< "UDP processing CONNCMD_SEND_TO_ALL" << std::endl);
			sendToAllReliable(c);
			return;

		case CONCMD_CREATE_PEER:
			LOG(dout_con << m_connection->getDesc()
				<< "UDP processing reliable CONCMD_CREATE_PEER" << std::endl);
			if (!rawSendAsPacket(c.peer_id, c.channelnum, c.data, c.reliable)) {
				/* put to queue if we couldn't send it immediately */
				sendReliable(c);
			}
			return;

		case CONCMD_DISABLE_LEGACY:
			LOG(dout_con << m_connection->getDesc()
				<< "UDP processing reliable CONCMD_DISABLE_LEGACY" << std::endl);
			if (!rawSendAsPacket(c.peer_id, c.channelnum, c.data, c.reliable)) {
				/* put to queue if we couldn't send it immediately */
				sendReliable(c);
			}
			return;

		case CONNCMD_SERVE:
		case CONNCMD_CONNECT:
		case CONNCMD_DISCONNECT:
		case CONCMD_ACK:
			FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
		default:
			LOG(dout_con << m_connection->getDesc()
				<< " Invalid reliable command type: " << c.type << std::endl);
	}
}


void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
{
	assert(!c.reliable); // Pre-condition

	switch (c.type) {
		case CONNCMD_NONE:
			LOG(dout_con << m_connection->getDesc()
				<< " UDP processing CONNCMD_NONE" << std::endl);
			return;
		case CONNCMD_SERVE:
			LOG(dout_con << m_connection->getDesc()
				<< " UDP processing CONNCMD_SERVE port="
				<< c.address.serializeString() << std::endl);
			serve(c.address);
			return;
		case CONNCMD_CONNECT:
			LOG(dout_con << m_connection->getDesc()
				<< " UDP processing CONNCMD_CONNECT" << std::endl);
			connect(c.address);
			return;
		case CONNCMD_DISCONNECT:
			LOG(dout_con << m_connection->getDesc()
				<< " UDP processing CONNCMD_DISCONNECT" << std::endl);
			disconnect();
			return;
		case CONNCMD_DISCONNECT_PEER:
			LOG(dout_con << m_connection->getDesc()
				<< " UDP processing CONNCMD_DISCONNECT_PEER" << std::endl);
			disconnect_peer(c.peer_id);
			return;
		case CONNCMD_SEND:
			LOG(dout_con << m_connection->getDesc()
				<< " UDP processing CONNCMD_SEND" << std::endl);
			send(c.peer_id, c.channelnum, c.data);
			return;
		case CONNCMD_SEND_TO_ALL:
			LOG(dout_con << m_connection->getDesc()
				<< " UDP processing CONNCMD_SEND_TO_ALL" << std::endl);
			sendToAll(c.channelnum, c.data);
			return;
		case CONCMD_ACK:
			LOG(dout_con << m_connection->getDesc()
				<< " UDP processing CONCMD_ACK" << std::endl);
			sendAsPacket(c.peer_id, c.channelnum, c.data, true);
			return;
		case CONCMD_CREATE_PEER:
			FATAL_ERROR("Got command that should be reliable as unreliable command");
		default:
			LOG(dout_con << m_connection->getDesc()
				<< " Invalid command type: " << c.type << std::endl);
	}
}

void ConnectionSendThread::serve(Address bind_address)
{
	LOG(dout_con << m_connection->getDesc()
		<< "UDP serving at port " << bind_address.serializeString() << std::endl);
	try {
		m_connection->m_udpSocket.Bind(bind_address);
		m_connection->SetPeerID(PEER_ID_SERVER);
	}
	catch (SocketException &e) {
		// Create event
		ConnectionEvent ce;
		ce.bindFailed();
		m_connection->putEvent(ce);
	}
}

void ConnectionSendThread::connect(Address address)
{
	LOG(dout_con << m_connection->getDesc() << " connecting to "
		<< address.serializeString()
		<< ":" << address.getPort() << std::endl);

	UDPPeer *peer = m_connection->createServerPeer(address);

	// Create event
	ConnectionEvent e;
	e.peerAdded(peer->id, peer->address);
	m_connection->putEvent(e);

	Address bind_addr;

	if (address.isIPv6())
		bind_addr.setAddress((IPv6AddressBytes *) NULL);
	else
		bind_addr.setAddress(0, 0, 0, 0);

	m_connection->m_udpSocket.Bind(bind_addr);

	// Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
	m_connection->SetPeerID(PEER_ID_INEXISTENT);
	NetworkPacket pkt(0, 0);
	m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
}

void ConnectionSendThread::disconnect()
{
	LOG(dout_con << m_connection->getDesc() << " disconnecting" << std::endl);

	// Create and send DISCO packet
	SharedBuffer<u8> data(2);
	writeU8(&data[0], PACKET_TYPE_CONTROL);
	writeU8(&data[1], CONTROLTYPE_DISCO);


	// Send to all
	std::list<session_t> peerids = m_connection->getPeerIDs();

	for (session_t peerid : peerids) {
		sendAsPacket(peerid, 0, data, false);
	}
}

void ConnectionSendThread::disconnect_peer(session_t peer_id)
{
	LOG(dout_con << m_connection->getDesc() << " disconnecting peer" << std::endl);

	// Create and send DISCO packet
	SharedBuffer<u8> data(2);
	writeU8(&data[0], PACKET_TYPE_CONTROL);
	writeU8(&data[1], CONTROLTYPE_DISCO);
	sendAsPacket(peer_id, 0, data, false);

	PeerHelper peer = m_connection->getPeerNoEx(peer_id);

	if (!peer)
		return;

	if (dynamic_cast<UDPPeer *>(&peer) == 0) {
		return;
	}

	dynamic_cast<UDPPeer *>(&peer)->m_pending_disconnect = true;
}

void ConnectionSendThread::send(session_t peer_id, u8 channelnum,
	SharedBuffer<u8> data)
{
	assert(channelnum < CHANNEL_COUNT); // Pre-condition

	PeerHelper peer = m_connection->getPeerNoEx(peer_id);
	if (!peer) {
		LOG(dout_con << m_connection->getDesc() << " peer: peer_id=" << peer_id
			<< ">>>NOT<<< found on sending packet"
			<< ", channel " << (channelnum % 0xFF)
			<< ", size: " << data.getSize() << std::endl);
		return;
	}

	LOG(dout_con << m_connection->getDesc() << " sending to peer_id=" << peer_id
		<< ", channel " << (channelnum % 0xFF)
		<< ", size: " << data.getSize() << std::endl);

	u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);

	u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
	std::list<SharedBuffer<u8>> originals;

	makeAutoSplitPacket(data, chunksize_max, split_sequence_number, &originals);

	peer->setNextSplitSequenceNumber(channelnum, split_sequence_number);

	for (const SharedBuffer<u8> &original : originals) {
		sendAsPacket(peer_id, channelnum, original);
	}
}

void ConnectionSendThread::sendReliable(ConnectionCommand &c)
{
	PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
	if (!peer)
		return;

	peer->PutReliableSendCommand(c, m_max_packet_size);
}

void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
{
	std::list<session_t> peerids = m_connection->getPeerIDs();

	for (session_t peerid : peerids) {
		send(peerid, channelnum, data);
	}
}

void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
{
	std::list<session_t> peerids = m_connection->getPeerIDs();

	for (session_t peerid : peerids) {
		PeerHelper peer = m_connection->getPeerNoEx(peerid);

		if (!peer)
			continue;

		peer->PutReliableSendCommand(c, m_max_packet_size);
	}
}

void ConnectionSendThread::sendPackets(float dtime)
{
	std::list<session_t> peerIds = m_connection->getPeerIDs();
	std::list<session_t> pendingDisconnect;
	std::map<session_t, bool> pending_unreliable;

	for (session_t peerId : peerIds) {
		PeerHelper peer = m_connection->getPeerNoEx(peerId);
		//peer may have been removed
		if (!peer) {
			LOG(dout_con << m_connection->getDesc() << " Peer not found: peer_id="
				<< peerId
				<< std::endl);
			continue;
		}
		peer->m_increment_packets_remaining =
			m_iteration_packets_avaialble / m_connection->m_peers.size();

		UDPPeer *udpPeer = dynamic_cast<UDPPeer *>(&peer);

		if (!udpPeer) {
			continue;
		}

		if (udpPeer->m_pending_disconnect) {
			pendingDisconnect.push_back(peerId);
		}

		PROFILE(std::stringstream
		peerIdentifier);
		PROFILE(
			peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << peerId
				<< ";RELIABLE]");
		PROFILE(ScopeProfiler
		peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));

		LOG(dout_con << m_connection->getDesc()
			<< " Handle per peer queues: peer_id=" << peerId
			<< " packet quota: " << peer->m_increment_packets_remaining << std::endl);

		// first send queued reliable packets for all peers (if possible)
		for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
			Channel &channel = udpPeer->channels[i];
			u16 next_to_ack = 0;

			channel.outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
			u16 next_to_receive = 0;
			channel.incoming_reliables.getFirstSeqnum(next_to_receive);

			LOG(dout_con << m_connection->getDesc() << "\t channel: "
				<< i << ", peer quota:"
				<< peer->m_increment_packets_remaining
				<< std::endl
				<< "\t\t\treliables on wire: "
				<< channel.outgoing_reliables_sent.size()
				<< ", waiting for ack for " << next_to_ack
				<< std::endl
				<< "\t\t\tincoming_reliables: "
				<< channel.incoming_reliables.size()
				<< ", next reliable packet: "
				<< channel.readNextIncomingSeqNum()
				<< ", next queued: " << next_to_receive
				<< std::endl
				<< "\t\t\treliables queued : "
				<< channel.queued_reliables.size()
				<< std::endl
				<< "\t\t\tqueued commands  : "
				<< channel.queued_commands.size()
				<< std::endl);

			while (!channel.queued_reliables.empty() &&
					channel.outgoing_reliables_sent.size()
					< channel.getWindowSize() &&
					peer->m_increment_packets_remaining > 0) {
				BufferedPacket p = channel.queued_reliables.front();
				channel.queued_reliables.pop();
				LOG(dout_con << m_connection->getDesc()
					<< " INFO: sending a queued reliable packet "
					<< " channel: " << i
					<< ", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE + 1])
					<< std::endl);
				sendAsPacketReliable(p, &channel);
				peer->m_increment_packets_remaining--;
			}
		}
	}

	if (!m_outgoing_queue.empty()) {
		LOG(dout_con << m_connection->getDesc()
			<< " Handle non reliable queue ("
			<< m_outgoing_queue.size() << " pkts)" << std::endl);
	}

	unsigned int initial_queuesize = m_outgoing_queue.size();
	/* send non reliable packets*/
	for (unsigned int i = 0; i < initial_queuesize; i++) {
		OutgoingPacket packet = m_outgoing_queue.front();
		m_outgoing_queue.pop();

		if (packet.reliable)
			continue;

		PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
		if (!peer) {
			LOG(dout_con << m_connection->getDesc()
				<< " Outgoing queue: peer_id=" << packet.peer_id
				<< ">>>NOT<<< found on sending packet"
				<< ", channel " << (packet.channelnum % 0xFF)
				<< ", size: " << packet.data.getSize() << std::endl);
			continue;
		}

		/* send acks immediately */
		if (packet.ack) {
			rawSendAsPacket(packet.peer_id, packet.channelnum,
				packet.data, packet.reliable);
			peer->m_increment_packets_remaining =
				MYMIN(0, peer->m_increment_packets_remaining--);
		} else if (
			(peer->m_increment_packets_remaining > 0) ||
				(stopRequested())) {
			rawSendAsPacket(packet.peer_id, packet.channelnum,
				packet.data, packet.reliable);
			peer->m_increment_packets_remaining--;
		} else {
			m_outgoing_queue.push(packet);
			pending_unreliable[packet.peer_id] = true;
		}
	}

	for (session_t peerId : pendingDisconnect) {
		if (!pending_unreliable[peerId]) {
			m_connection->deletePeer(peerId, false);
		}
	}
}

void ConnectionSendThread::sendAsPacket(session_t peer_id, u8 channelnum,
	SharedBuffer<u8> data, bool ack)
{
	OutgoingPacket packet(peer_id, channelnum, data, false, ack);
	m_outgoing_queue.push(packet);
}

ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
	Thread("ConnectionReceive")
{
}

void *ConnectionReceiveThread::run()
{
	assert(m_connection);