aboutsummaryrefslogtreecommitdiff
path: root/src/inventory.cpp
blob: 77ecf5876bf36500206ba8b7eb5697c0e7a2c033 (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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
/*
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.
*/

#include "inventory.h"
#include "serialization.h"
#include "debug.h"
#include <algorithm>
#include <sstream>
#include "log.h"
#include "itemdef.h"
#include "util/strfnd.h"
#include "content_mapnode.h" // For loading legacy MaterialItems
#include "nameidmapping.h" // For loading legacy MaterialItems
#include "util/serialize.h"
#include "util/string.h"

/*
	ItemStack
*/

static content_t content_translate_from_19_to_internal(content_t c_from)
{
	for (const auto &tt : trans_table_19) {
		if(tt[1] == c_from) {
			return tt[0];
		}
	}
	return c_from;
}

ItemStack::ItemStack(const std::string &name_, u16 count_,
		u16 wear_, IItemDefManager *itemdef) :
	name(itemdef->getAlias(name_)),
	count(count_),
	wear(wear_)
{
	if (name.empty() || count == 0)
		clear();
	else if (itemdef->get(name).type == ITEM_TOOL)
		count = 1;
}

void ItemStack::serialize(std::ostream &os) const
{
	if (empty())
		return;

	// Check how many parts of the itemstring are needed
	int parts = 1;
	if(count != 1)
		parts = 2;
	if(wear != 0)
		parts = 3;
	if (!metadata.empty())
		parts = 4;

	os<<serializeJsonStringIfNeeded(name);
	if(parts >= 2)
		os<<" "<<count;
	if(parts >= 3)
		os<<" "<<wear;
	if (parts >= 4) {
		os << " ";
		metadata.serialize(os);
	}
}

void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
{
	clear();

	// Read name
	name = deSerializeJsonStringIfNeeded(is);

	// Skip space
	std::string tmp;
	std::getline(is, tmp, ' ');
	if(!tmp.empty())
		throw SerializationError("Unexpected text after item name");

	if(name == "MaterialItem")
	{
		// Obsoleted on 2011-07-30

		u16 material;
		is>>material;
		u16 materialcount;
		is>>materialcount;
		// Convert old materials
		if(material <= 0xff)
			material = content_translate_from_19_to_internal(material);
		if(material > 0xfff)
			throw SerializationError("Too large material number");
		// Convert old id to name
		NameIdMapping legacy_nimap;
		content_mapnode_get_name_id_mapping(&legacy_nimap);
		legacy_nimap.getName(material, name);
		if(name.empty())
			name = "unknown_block";
		if (itemdef)
			name = itemdef->getAlias(name);
		count = materialcount;
	}
	else if(name == "MaterialItem2")
	{
		// Obsoleted on 2011-11-16

		u16 material;
		is>>material;
		u16 materialcount;
		is>>materialcount;
		if(material > 0xfff)
			throw SerializationError("Too large material number");
		// Convert old id to name
		NameIdMapping legacy_nimap;
		content_mapnode_get_name_id_mapping(&legacy_nimap);
		legacy_nimap.getName(material, name);
		if(name.empty())
			name = "unknown_block";
		if (itemdef)
			name = itemdef->getAlias(name);
		count = materialcount;
	}
	else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
			|| name == "craft" || name == "CraftItem")
	{
		// Obsoleted on 2012-01-07

		std::string all;
		std::getline(is, all, '\n');
		// First attempt to read inside ""
		Strfnd fnd(all);
		fnd.next("\"");
		// If didn't skip to end, we have ""s
		if(!fnd.at_end()){
			name = fnd.next("\"");
		} else { // No luck, just read a word then
			fnd.start(all);
			name = fnd.next(" ");
		}
		fnd.skip_over(" ");
		if (itemdef)
			name = itemdef->getAlias(name);
		count = stoi(trim(fnd.next("")));
		if(count == 0)
			count = 1;
	}
	else if(name == "MBOItem")
	{
		// Obsoleted on 2011-10-14
		throw SerializationError("MBOItem not supported anymore");
	}
	else if(name == "tool" || name == "ToolItem")
	{
		// Obsoleted on 2012-01-07

		std::string all;
		std::getline(is, all, '\n');
		// First attempt to read inside ""
		Strfnd fnd(all);
		fnd.next("\"");
		// If didn't skip to end, we have ""s
		if(!fnd.at_end()){
			name = fnd.next("\"");
		} else { // No luck, just read a word then
			fnd.start(all);
			name = fnd.next(" ");
		}
		count = 1;
		// Then read wear
		fnd.skip_over(" ");
		if (itemdef)
			name = itemdef->getAlias(name);
		wear = stoi(trim(fnd.next("")));
	}
	else
	{
		do  // This loop is just to allow "break;"
		{
			// The real thing

			// Apply item aliases
			if (itemdef)
				name = itemdef->getAlias(name);

			// Read the count
			std::string count_str;
			std::getline(is, count_str, ' ');
			if (count_str.empty()) {
				count = 1;
				break;
			}

			count = stoi(count_str);

			// Read the wear
			std::string wear_str;
			std::getline(is, wear_str, ' ');
			if(wear_str.empty())
				break;

			wear = stoi(wear_str);

			// Read metadata
			metadata.deSerialize(is);

			// In case fields are added after metadata, skip space here:
			//std::getline(is, tmp, ' ');
			//if(!tmp.empty())
			//	throw SerializationError("Unexpected text after metadata");

		} while(false);
	}

	if (name.empty() || count == 0)
		clear();
	else if (itemdef && itemdef->get(name).type == ITEM_TOOL)
		count = 1;
}

void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
{
	std::istringstream is(str, std::ios::binary);
	deSerialize(is, itemdef);
}

std::string ItemStack::getItemString() const
{
	std::ostringstream os(std::ios::binary);
	serialize(os);
	return os.str();
}

std::string ItemStack::getDescription(IItemDefManager *itemdef) const
{
	std::string desc = metadata.getString("description");
	if (desc.empty())
		desc = getDefinition(itemdef).description;
	return desc.empty() ? name : desc;
}


ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef)
{
	// If the item is empty or the position invalid, bail out
	if(newitem.empty())
	{
		// nothing can be added trivially
	}
	// If this is an empty item, it's an easy job.
	else if(empty())
	{
		*this = newitem;
		newitem.clear();
	}
	// If item name or metadata differs, bail out
	else if (name != newitem.name
		|| metadata != newitem.metadata)
	{
		// cannot be added
	}
	// If the item fits fully, add counter and delete it
	else if(newitem.count <= freeSpace(itemdef))
	{
		add(newitem.count);
		newitem.clear();
	}
	// Else the item does not fit fully. Add all that fits and return
	// the rest.
	else
	{
		u16 freespace = freeSpace(itemdef);
		add(freespace);
		newitem.remove(freespace);
	}

	return newitem;
}

bool ItemStack::itemFits(ItemStack newitem,
		ItemStack *restitem,
		IItemDefManager *itemdef) const
{

	// If the item is empty or the position invalid, bail out
	if(newitem.empty())
	{
		// nothing can be added trivially
	}
	// If this is an empty item, it's an easy job.
	else if(empty())
	{
		newitem.clear();
	}
	// If item name or metadata differs, bail out
	else if (name != newitem.name
		|| metadata != newitem.metadata)
	{
		// cannot be added
	}
	// If the item fits fully, delete it
	else if(newitem.count <= freeSpace(itemdef))
	{
		newitem.clear();
	}
	// Else the item does not fit fully. Return the rest.
	else
	{
		u16 freespace = freeSpace(itemdef);
		newitem.remove(freespace);
	}

	if(restitem)
		*restitem = newitem;

	return newitem.empty();
}

ItemStack ItemStack::takeItem(u32 takecount)
{
	if(takecount == 0 || count == 0)
		return ItemStack();

	ItemStack result = *this;
	if(takecount >= count)
	{
		// Take all
		clear();
	}
	else
	{
		// Take part
		remove(takecount);
		result.count = takecount;
	}
	return result;
}

ItemStack ItemStack::peekItem(u32 peekcount) const
{
	if(peekcount == 0 || count == 0)
		return ItemStack();

	ItemStack result = *this;
	if(peekcount < count)
		result.count = peekcount;
	return result;
}

/*
	Inventory
*/

InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef):
	m_name(name),
	m_size(size),
	m_itemdef(itemdef)
{
	clearItems();
}

void InventoryList::clearItems()
{
	m_items.clear();

	for (u32 i=0; i < m_size; i++) {
		m_items.emplace_back();
	}

	setModified();
}

void InventoryList::setSize(u32 newsize)
{
	if (newsize == m_items.size())
		return;

	m_items.resize(newsize);
	m_size = newsize;
	setModified();
}

void InventoryList::setWidth(u32 newwidth)
{
	m_width = newwidth;
	setModified();
}

void InventoryList::setName(const std::string &name)
{
	m_name = name;
	setModified();
}

void InventoryList::serialize(std::ostream &os, bool incremental) const
{
	//os.imbue(std::locale("C"));

	os<<"Width "<<m_width<<"\n";

	for (const auto &item : m_items) {
		if (item.empty()) {
			os<<"Empty";
		} else {
			os<<"Item ";
			item.serialize(os);
		}
		// TODO: Implement this:
		// if (!incremental || item.checkModified())
		// os << "Keep";
		os<<"\n";
	}

	os<<"EndInventoryList\n";
}

void InventoryList::deSerialize(std::istream &is)
{
	//is.imbue(std::locale("C"));
	setModified();

	u32 item_i = 0;
	m_width = 0;

	while (is.good()) {
		std::string line;
		std::getline(is, line, '\n');

		std::istringstream iss(line);
		//iss.imbue(std::locale("C"));

		std::string name;
		std::getline(iss, name, ' ');

		if (name == "EndInventoryList" || name == "end") {
			// If partial incremental: Clear leftover items (should not happen!)
			for (size_t i = item_i; i < m_items.size(); ++i)
				m_items[i].clear();
			return;
		}

		if (name == "Width") {
			iss >> m_width;
			if (iss.fail())
				throw SerializationError("incorrect width property");
		}
		else if(name == "Item")
		{
			if(item_i > getSize() - 1)
				throw SerializationError("too many items");
			ItemStack item;
			item.deSerialize(iss, m_itemdef);
			m_items[item_i++] = item;
		}
		else if(name == "Empty")
		{
			if(item_i > getSize() - 1)
				throw SerializationError("too many items");
			m_items[item_i++].clear();
		} else if (name == "Keep") {
			++item_i; // Unmodified item
		}
	}

	// Contents given to deSerialize() were not terminated properly: throw error.

	std::ostringstream ss;
	ss << "Malformatted inventory list. list="
		<< m_name << ", read " << item_i << " of " << getSize()
		<< " ItemStacks." << std::endl;
	throw SerializationError(ss.str());
}

InventoryList::InventoryList(const InventoryList &other)
{
	*this = other;
}

InventoryList & InventoryList::operator = (const InventoryList &other)
{
	m_items = other.m_items;
	m_size = other.m_size;
	m_width = other.m_width;
	m_name = other.m_name;
	m_itemdef = other.m_itemdef;
	//setDirty(true);

	return *this;
}

bool InventoryList::operator == (const InventoryList &other) const
{
	if(m_size != other.m_size)
		return false;
	if(m_width != other.m_width)
		return false;
	if(m_name != other.m_name)
		return false;
	for (u32 i = 0; i < m_items.size(); i++)
		if (m_items[i] != other.m_items[i])
			return false;

	return true;
}

const std::string &InventoryList::getName() const
{
	return m_name;
}

u32 InventoryList::getSize() const
{
	return m_items.size();
}

u32 InventoryList::getWidth() const
{
	return m_width;
}

u32 InventoryList::getUsedSlots() const
{
	u32 num = 0;
	for (const auto &m_item : m_items) {
		if (!m_item.empty())
			num++;
	}
	return num;
}

u32 InventoryList::getFreeSlots() const
{
	return getSize() - getUsedSlots();
}

const ItemStack& InventoryList::getItem(u32 i) const
{
	assert(i < m_size); // Pre-condition
	return m_items[i];
}

ItemStack& InventoryList::getItem(u32 i)
{
	assert(i < m_size); // Pre-condition
	return m_items[i];
}

ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
{
	if(i >= m_items.size())
		return newitem;

	ItemStack olditem = m_items[i];
	m_items[i] = newitem;
	setModified();
	return olditem;
}

void InventoryList::deleteItem(u32 i)
{
	assert(i < m_items.size()); // Pre-condition
	m_items[i].clear();
	setModified();
}

ItemStack InventoryList::addItem(const ItemStack &newitem_)
{
	ItemStack newitem = newitem_;

	if(newitem.empty())
		return newitem;

	/*
		First try to find if it could be added to some existing items
	*/
	for(u32 i=0; i<m_items.size(); i++)
	{
		// Ignore empty slots
		if(m_items[i].empty())
			continue;
		// Try adding
		newitem = addItem(i, newitem);
		if(newitem.empty())
			return newitem; // All was eaten
	}

	/*
		Then try to add it to empty slots
	*/
	for(u32 i=0; i<m_items.size(); i++)
	{
		// Ignore unempty slots
		if(!m_items[i].empty())
			continue;
		// Try adding
		newitem = addItem(i, newitem);
		if(newitem.empty())
			return newitem; // All was eaten
	}

	// Return leftover
	return newitem;
}

ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
{
	if(i >= m_items.size())
		return newitem;

	ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
	if (leftover != newitem)
		setModified();
	return leftover;
}

bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
		ItemStack *restitem) const
{
	if(i >= m_items.size())
	{
		if(restitem)
			*restitem = newitem;
		return false;
	}

	return m_items[i].itemFits(newitem, restitem, m_itemdef);
}

bool InventoryList::roomForItem(const ItemStack &item_) const
{
	ItemStack item = item_;
	ItemStack leftover;
	for(u32 i=0; i<m_items.size(); i++)
	{
		if(itemFits(i, item, &leftover))
			return true;
		item = leftover;
	}
	return false;
}

bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const
{
	u32 count = item.count;
	if (count == 0)
		return true;

	for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
		if (count == 0)
			break;
		if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) {
			if (i->count >= count)
				return true;

			count -= i->count;
		}
	}
	return false;
}

ItemStack InventoryList::removeItem(const ItemStack &item)
{
	ItemStack removed;
	for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
		if (i->name == item.name) {
			u32 still_to_remove = item.count - removed.count;
			ItemStack leftover = removed.addItem(i->takeItem(still_to_remove),
					m_itemdef);
			// Allow oversized stacks
			removed.count += leftover.count;

			if (removed.count == item.count)
				break;
		}
	}
	if (!removed.empty())
		setModified();
	return removed;
}

ItemStack InventoryList::takeItem(u32 i, u32 takecount)
{
	if(i >= m_items.size())
		return ItemStack();

	ItemStack taken = m_items[i].takeItem(takecount);
	if (!taken.empty())
		setModified();
	return taken;
}

void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
{
	// Take item from source list
	ItemStack item1;
	if (count == 0)
		item1 = changeItem(i, ItemStack());
	else
		item1 = takeItem(i, count);

	if (item1.empty())
		return;

	ItemStack leftover;
	leftover = dest->addItem(item1);

	if (!leftover.empty()) {
		// Add the remaining part back to the source item
		addItem(i, leftover);
	}
}

u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
		u32 count, bool swap_if_needed, bool *did_swap)
{
	if(this == dest && i == dest_i)
		return count;

	// Take item from source list
	ItemStack item1;
	if(count == 0)
		item1 = changeItem(i, ItemStack());
	else
		item1 = takeItem(i, count);

	if(item1.empty())
		return 0;

	// Try to add the item to destination list
	u32 oldcount = item1.count;
	item1 = dest->addItem(dest_i, item1);

	// If something is returned, the item was not fully added
	if(!item1.empty())
	{
		// If olditem is returned, nothing was added.
		bool nothing_added = (item1.count == oldcount);

		// If something else is returned, part of the item was left unadded.
		// Add the other part back to the source item
		addItem(i, item1);

		// If olditem is returned, nothing was added.
		// Swap the items
		if (nothing_added && swap_if_needed) {
			// Tell that we swapped
			if (did_swap != NULL) {
				*did_swap = true;
			}
			// Take item from source list
			item1 = changeItem(i, ItemStack());
			// Adding was not possible, swap the items.
			ItemStack item2 = dest->changeItem(dest_i, item1);
			// Put item from destination list to the source list
			changeItem(i, item2);
		}
	}
	return (oldcount - item1.count);
}

/*
	Inventory
*/

Inventory::~Inventory()
{
	clear();
}

void Inventory::clear()
{
	for (auto &m_list : m_lists) {
		delete m_list;
	}
	m_lists.clear();
	setModified();
}

Inventory::Inventory(IItemDefManager *itemdef)
{
	m_itemdef = itemdef;
	setModified();
}

Inventory::Inventory(const Inventory &other)
{
	*this = other;
}

Inventory & Inventory::operator = (const Inventory &other)
{
	// Gracefully handle self assignment
	if(this != &other)
	{
		clear();
		m_itemdef = other.m_itemdef;
		for (InventoryList *list : other.m_lists) {
			m_lists.push_back(new InventoryList(*list));
		}
		setModified();
	}
	return *this;
}

bool Inventory::operator == (const Inventory &other) const
{
	if(m_lists.size() != other.m_lists.size())
		return false;

	for(u32 i=0; i<m_lists.size(); i++)
	{
		if(*m_lists[i] != *other.m_lists[i])
			return false;
	}
	return true;
}

void Inventory::serialize(std::ostream &os, bool incremental) const
{
	//std::cout << "Serialize " << (int)incremental << ", n=" << m_lists.size() << std::endl;
	for (const InventoryList *list : m_lists) {
		if (!incremental || list->checkModified()) {
			os << "List " << list->getName() << " " << list->getSize() << "\n";
			list->serialize(os, incremental);
		} else {
			os << "KeepList " << list->getName() << "\n";
		}
	}

	os<<"EndInventory\n";
}

void Inventory::deSerialize(std::istream &is)
{
	std::vector<InventoryList *> new_lists;
	new_lists.reserve(m_lists.size());

	while (is.good()) {
		std::string line;
		std::getline(is, line, '\n');

		std::istringstream iss(line);

		std::string name;
		std::getline(iss, name, ' ');

		if (name == "EndInventory" || name == "end") {
			// Remove all lists that were not sent
			for (auto &list : m_lists) {
				if (std::find(new_lists.begin(), new_lists.end(), list) != new_lists.end())
					continue;

				delete list;
				list = nullptr;
				setModified();
			}
			m_lists.erase(std::remove(m_lists.begin(), m_lists.end(),
					nullptr), m_lists.end());
			return;
		}

		if (name == "List") {
			std::string listname;
			u32 listsize;

			std::getline(iss, listname, ' ');
			iss>>listsize;

			InventoryList *list = getList(listname);
			bool create_new = !list;
			if (create_new)
				list = new InventoryList(listname, listsize, m_itemdef);
			else
				list->setSize(listsize);
			list->deSerialize(is);

			new_lists.push_back(list);
			if (create_new)
				m_lists.push_back(list);

		} else if (name == "KeepList") {
			// Incrementally sent list
			std::string listname;
			std::getline(iss, listname, ' ');

			InventoryList *list = getList(listname);
			if (list) {
				new_lists.push_back(list);
			} else {
				errorstream << "Inventory::deSerialize(): Tried to keep list '" <<
					listname << "' which is non-existent." << std::endl;
			}
		}
		// Any additional fields will throw errors when received by a client
		// older than PROTOCOL_VERSION 38
	}

	// Contents given to deSerialize() were not terminated properly: throw error.

	std::ostringstream ss;
	ss << "Malformatted inventory (damaged?). "
		<< m_lists.size() << " lists read." << std::endl;
	throw SerializationError(ss.str());
}

InventoryList * Inventory::addList(const std::string &name, u32 size)
{
	setModified();
	s32 i = getListIndex(name);
	if(i != -1)
	{
		if(m_lists[i]->getSize() != size)
		{
			delete m_lists[i];
			m_lists[i] = new InventoryList(name, size, m_itemdef);
			m_lists[i]->setModified();
		}
		return m_lists[i];
	}


	//don't create list with invalid name
	if (name.find(' ') != std::string::npos)
		return nullptr;

	InventoryList *list = new InventoryList(name, size, m_itemdef);
	list->setModified();
	m_lists.push_back(list);
	return list;
}

InventoryList * Inventory::getList(const std::string &name)
{
	s32 i = getListIndex(name);
	if(i == -1)
		return NULL;
	return m_lists[i];
}

std::vector<const InventoryList*> Inventory::getLists()
{
	std::vector<const InventoryList*> lists;
	for (auto list : m_lists) {
		lists.push_back(list);
	}
	return lists;
}

bool Inventory::deleteList(const std::string &name)
{
	s32 i = getListIndex(name);
	if(i == -1)
		return false;

	setModified();
	delete m_lists[i];
	m_lists.erase(m_lists.begin() + i);
	return true;
}

const InventoryList * Inventory::getList(const std::string &name) const
{
	s32 i = getListIndex(name);
	if(i == -1)
		return NULL;
	return m_lists[i];
}

const s32 Inventory::getListIndex(const std::string &name) const
{
	for(u32 i=0; i<m_lists.size(); i++)
	{
		if(m_lists[i]->getName() == name)
			return i;
	}
	return -1;
}

//END
n class="hl kwa">break; } return i; } RPBSearchResult ReliablePacketBuffer::notFound() { return m_list.end(); } bool ReliablePacketBuffer::getFirstSeqnum(u16& result) { MutexAutoLock listlock(m_list_mutex); if (m_list.empty()) return false; BufferedPacket p = *m_list.begin(); result = readU16(&p.data[BASE_HEADER_SIZE+1]); return true; } BufferedPacket ReliablePacketBuffer::popFirst() { MutexAutoLock listlock(m_list_mutex); if (m_list.empty()) throw NotFoundException("Buffer is empty"); BufferedPacket p = *m_list.begin(); m_list.erase(m_list.begin()); --m_list_size; if (m_list_size == 0) { m_oldest_non_answered_ack = 0; } else { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); } return p; } BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum) { MutexAutoLock listlock(m_list_mutex); RPBSearchResult r = findPacket(seqnum); if (r == notFound()) { LOG(dout_con<<"Sequence number: " << seqnum << " not found in reliable buffer"<<std::endl); throw NotFoundException("seqnum not found in buffer"); } BufferedPacket p = *r; RPBSearchResult next = r; ++next; if (next != notFound()) { u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1])); m_oldest_non_answered_ack = s; } m_list.erase(r); --m_list_size; if (m_list_size == 0) { m_oldest_non_answered_ack = 0; } else { m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); } return p; } void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected) { MutexAutoLock listlock(m_list_mutex); if (p.data.getSize() < BASE_HEADER_SIZE + 3) { errorstream << "ReliablePacketBuffer::insert(): Invalid data size for " "reliable packet" << std::endl; return; } u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]); if (type != TYPE_RELIABLE) { errorstream << "ReliablePacketBuffer::insert(): type is not reliable" << std::endl; return; } u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]); if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) { errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of " "expected window " << std::endl; return; } if (seqnum == next_expected) { errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected" << std::endl; return; } ++m_list_size; sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error? // Find the right place for the packet and insert it there // If list is empty, just add it if (m_list.empty()) { m_list.push_back(p); m_oldest_non_answered_ack = seqnum; // Done. return; } // Otherwise find the right place std::list<BufferedPacket>::iterator i = m_list.begin(); // Find the first packet in the list which has a higher seqnum u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1])); /* case seqnum is smaller then next_expected seqnum */ /* this is true e.g. on wrap around */ if (seqnum < next_expected) { while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) { ++i; if (i != m_list.end()) s = readU16(&(i->data[BASE_HEADER_SIZE+1])); } } /* non wrap around case (at least for incoming and next_expected */ else { while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) { ++i; if (i != m_list.end()) s = readU16(&(i->data[BASE_HEADER_SIZE+1])); } } if (s == seqnum) { if ( (readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) || (i->data.getSize() != p.data.getSize()) || (i->address != p.address) ) { /* if this happens your maximum transfer window may be to big */ fprintf(stderr, "Duplicated seqnum %d non matching packet detected:\n", seqnum); fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n", readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(), i->address.serializeString().c_str()); fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n", readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(), p.address.serializeString().c_str()); throw IncomingDataCorruption("duplicated packet isn't same as original one"); } /* nothing to do this seems to be a resent packet */ /* for paranoia reason data should be compared */ --m_list_size; } /* insert or push back */ else if (i != m_list.end()) { m_list.insert(i, p); } else { m_list.push_back(p); } /* update last packet number */ m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); } void ReliablePacketBuffer::incrementTimeouts(float dtime) { MutexAutoLock listlock(m_list_mutex); for(std::list<BufferedPacket>::iterator i = m_list.begin(); i != m_list.end(); ++i) { i->time += dtime; i->totaltime += dtime; } } std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout, unsigned int max_packets) { MutexAutoLock listlock(m_list_mutex); std::list<BufferedPacket> timed_outs; for(std::list<BufferedPacket>::iterator i = m_list.begin(); i != m_list.end(); ++i) { if (i->time >= timeout) { timed_outs.push_back(*i); //this packet will be sent right afterwards reset timeout here i->time = 0.0; if (timed_outs.size() >= max_packets) break; } } return timed_outs; } /* IncomingSplitBuffer */ IncomingSplitBuffer::~IncomingSplitBuffer() { MutexAutoLock listlock(m_map_mutex); for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin(); i != m_buf.end(); ++i) { delete i->second; } } /* This will throw a GotSplitPacketException when a full split packet is constructed. */ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable) { MutexAutoLock listlock(m_map_mutex); u32 headersize = BASE_HEADER_SIZE + 7; if (p.data.getSize() < headersize) { errorstream << "Invalid data size for split packet" << std::endl; return SharedBuffer<u8>(); } u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]); u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]); u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]); u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]); if (type != TYPE_SPLIT) { errorstream << "IncomingSplitBuffer::insert(): type is not split" << std::endl; return SharedBuffer<u8>(); } // Add if doesn't exist if (m_buf.find(seqnum) == m_buf.end()) { IncomingSplitPacket *sp = new IncomingSplitPacket(); sp->chunk_count = chunk_count; sp->reliable = reliable; m_buf[seqnum] = sp; } IncomingSplitPacket *sp = m_buf[seqnum]; // TODO: These errors should be thrown or something? Dunno. if (chunk_count != sp->chunk_count) LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count <<" != sp->chunk_count="<<sp->chunk_count <<std::endl); if (reliable != sp->reliable) LOG(derr_con<<"Connection: WARNING: reliable="<<reliable <<" != sp->reliable="<<sp->reliable <<std::endl); // If chunk already exists, ignore it. // Sometimes two identical packets may arrive when there is network // lag and the server re-sends stuff. if (sp->chunks.find(chunk_num) != sp->chunks.end()) return SharedBuffer<u8>(); // Cut chunk data out of packet u32 chunkdatasize = p.data.getSize() - headersize; SharedBuffer<u8> chunkdata(chunkdatasize); memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize); // Set chunk data in buffer sp->chunks[chunk_num] = chunkdata; // If not all chunks are received, return empty buffer if (sp->allReceived() == false) return SharedBuffer<u8>(); // Calculate total size u32 totalsize = 0; for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin(); i != sp->chunks.end(); ++i) { totalsize += i->second.getSize(); } SharedBuffer<u8> fulldata(totalsize); // Copy chunks to data buffer u32 start = 0; for(u32 chunk_i=0; chunk_i<sp->chunk_count; chunk_i++) { SharedBuffer<u8> buf = sp->chunks[chunk_i]; u16 chunkdatasize = buf.getSize(); memcpy(&fulldata[start], *buf, chunkdatasize); start += chunkdatasize;; } // Remove sp from buffer m_buf.erase(seqnum); delete sp; return fulldata; } void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout) { std::list<u16> remove_queue; { MutexAutoLock listlock(m_map_mutex); for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin(); i != m_buf.end(); ++i) { IncomingSplitPacket *p = i->second; // Reliable ones are not removed by timeout if (p->reliable == true) continue; p->time += dtime; if (p->time >= timeout) remove_queue.push_back(i->first); } } for(std::list<u16>::iterator j = remove_queue.begin(); j != remove_queue.end(); ++j) { MutexAutoLock listlock(m_map_mutex); LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl); delete m_buf[*j]; m_buf.erase(*j); } } /* Channel */ Channel::Channel() : window_size(MIN_RELIABLE_WINDOW_SIZE), next_incoming_seqnum(SEQNUM_INITIAL), next_outgoing_seqnum(SEQNUM_INITIAL), next_outgoing_split_seqnum(SEQNUM_INITIAL), current_packet_loss(0), current_packet_too_late(0), current_packet_successfull(0), packet_loss_counter(0), current_bytes_transfered(0), current_bytes_received(0), current_bytes_lost(0), max_kbps(0.0), cur_kbps(0.0), avg_kbps(0.0), max_incoming_kbps(0.0), cur_incoming_kbps(0.0), avg_incoming_kbps(0.0), max_kbps_lost(0.0), cur_kbps_lost(0.0), avg_kbps_lost(0.0), bpm_counter(0.0), rate_samples(0) { } Channel::~Channel() { } u16 Channel::readNextIncomingSeqNum() { MutexAutoLock internal(m_internal_mutex); return next_incoming_seqnum; } u16 Channel::incNextIncomingSeqNum() { MutexAutoLock internal(m_internal_mutex); u16 retval = next_incoming_seqnum; next_incoming_seqnum++; return retval; } u16 Channel::readNextSplitSeqNum() { MutexAutoLock internal(m_internal_mutex); return next_outgoing_split_seqnum; } void Channel::setNextSplitSeqNum(u16 seqnum) { MutexAutoLock internal(m_internal_mutex); next_outgoing_split_seqnum = seqnum; } u16 Channel::getOutgoingSequenceNumber(bool& successful) { MutexAutoLock internal(m_internal_mutex); u16 retval = next_outgoing_seqnum; u16 lowest_unacked_seqnumber; /* shortcut if there ain't any packet in outgoing list */ if (outgoing_reliables_sent.empty()) { next_outgoing_seqnum++; return retval; } if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber)) { if (lowest_unacked_seqnumber < next_outgoing_seqnum) { // ugly cast but this one is required in order to tell compiler we // know about difference of two unsigned may be negative in general // but we already made sure it won't happen in this case if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) { successful = false; return 0; } } else { // ugly cast but this one is required in order to tell compiler we // know about difference of two unsigned may be negative in general // but we already made sure it won't happen in this case if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) > window_size) { successful = false; return 0; } } } next_outgoing_seqnum++; return retval; } u16 Channel::readOutgoingSequenceNumber() { MutexAutoLock internal(m_internal_mutex); return next_outgoing_seqnum; } bool Channel::putBackSequenceNumber(u16 seqnum) { if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) { next_outgoing_seqnum = seqnum; return true; } return false; } void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets) { MutexAutoLock internal(m_internal_mutex); current_bytes_transfered += bytes; current_packet_successfull += packets; } void Channel::UpdateBytesReceived(unsigned int bytes) { MutexAutoLock internal(m_internal_mutex); current_bytes_received += bytes; } void Channel::UpdateBytesLost(unsigned int bytes) { MutexAutoLock internal(m_internal_mutex); current_bytes_lost += bytes; } void Channel::UpdatePacketLossCounter(unsigned int count) { MutexAutoLock internal(m_internal_mutex); current_packet_loss += count; } void Channel::UpdatePacketTooLateCounter() { MutexAutoLock internal(m_internal_mutex); current_packet_too_late++; } void Channel::UpdateTimers(float dtime,bool legacy_peer) { bpm_counter += dtime; packet_loss_counter += dtime; if (packet_loss_counter > 1.0) { packet_loss_counter -= 1.0; unsigned int packet_loss = 11; /* use a neutral value for initialization */ unsigned int packets_successfull = 0; //unsigned int packet_too_late = 0; bool reasonable_amount_of_data_transmitted = false; { MutexAutoLock internal(m_internal_mutex); packet_loss = current_packet_loss; //packet_too_late = current_packet_too_late; packets_successfull = current_packet_successfull; if (current_bytes_transfered > (unsigned int) (window_size*512/2)) { reasonable_amount_of_data_transmitted = true; } current_packet_loss = 0; current_packet_too_late = 0; current_packet_successfull = 0; } /* dynamic window size is only available for non legacy peers */ if (!legacy_peer) { float successfull_to_lost_ratio = 0.0; bool done = false; if (packets_successfull > 0) { successfull_to_lost_ratio = packet_loss/packets_successfull; } else if (packet_loss > 0) { window_size = MYMAX( (window_size - 10), MIN_RELIABLE_WINDOW_SIZE); done = true; } if (!done) { if ((successfull_to_lost_ratio < 0.01) && (window_size < MAX_RELIABLE_WINDOW_SIZE)) { /* don't even think about increasing if we didn't even * use major parts of our window */ if (reasonable_amount_of_data_transmitted) window_size = MYMIN( (window_size + 100), MAX_RELIABLE_WINDOW_SIZE); } else if ((successfull_to_lost_ratio < 0.05) && (window_size < MAX_RELIABLE_WINDOW_SIZE)) { /* don't even think about increasing if we didn't even * use major parts of our window */ if (reasonable_amount_of_data_transmitted) window_size = MYMIN( (window_size + 50), MAX_RELIABLE_WINDOW_SIZE); } else if (successfull_to_lost_ratio > 0.15) { window_size = MYMAX( (window_size - 100), MIN_RELIABLE_WINDOW_SIZE); } else if (successfull_to_lost_ratio > 0.1) { window_size = MYMAX( (window_size - 50), MIN_RELIABLE_WINDOW_SIZE); } } } } if (bpm_counter > 10.0) { { MutexAutoLock internal(m_internal_mutex); cur_kbps = (((float) current_bytes_transfered)/bpm_counter)/1024.0; current_bytes_transfered = 0; cur_kbps_lost = (((float) current_bytes_lost)/bpm_counter)/1024.0; current_bytes_lost = 0; cur_incoming_kbps = (((float) current_bytes_received)/bpm_counter)/1024.0; current_bytes_received = 0; bpm_counter = 0; } if (cur_kbps > max_kbps) { max_kbps = cur_kbps; } if (cur_kbps_lost > max_kbps_lost) { max_kbps_lost = cur_kbps_lost; } if (cur_incoming_kbps > max_incoming_kbps) { max_incoming_kbps = cur_incoming_kbps; } rate_samples = MYMIN(rate_samples+1,10); float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples); avg_kbps = avg_kbps * old_fraction + cur_kbps * (1.0 - old_fraction); avg_kbps_lost = avg_kbps_lost * old_fraction + cur_kbps_lost * (1.0 - old_fraction); avg_incoming_kbps = avg_incoming_kbps * old_fraction + cur_incoming_kbps * (1.0 - old_fraction); } } /* Peer */ PeerHelper::PeerHelper() : m_peer(0) {} PeerHelper::PeerHelper(Peer* peer) : m_peer(peer) { if (peer != NULL) { if (!peer->IncUseCount()) { m_peer = 0; } } } PeerHelper::~PeerHelper() { if (m_peer != 0) m_peer->DecUseCount(); m_peer = 0; } PeerHelper& PeerHelper::operator=(Peer* peer) { m_peer = peer; if (peer != NULL) { if (!peer->IncUseCount()) { m_peer = 0; } } return *this; } Peer* PeerHelper::operator->() const { return m_peer; } Peer* PeerHelper::operator&() const { return m_peer; } bool PeerHelper::operator!() { return ! m_peer; } bool PeerHelper::operator!=(void* ptr) { return ((void*) m_peer != ptr); } bool Peer::IncUseCount() { MutexAutoLock lock(m_exclusive_access_mutex); if (!m_pending_deletion) { this->m_usage++; return true; } return false; } void Peer::DecUseCount() { { MutexAutoLock lock(m_exclusive_access_mutex); sanity_check(m_usage > 0); m_usage--; if (!((m_pending_deletion) && (m_usage == 0))) return; } delete this; } void Peer::RTTStatistics(float rtt, std::string profiler_id, unsigned int num_samples) { if (m_last_rtt > 0) { /* set min max values */ if (rtt < m_rtt.min_rtt) m_rtt.min_rtt = rtt; if (rtt >= m_rtt.max_rtt) m_rtt.max_rtt = rtt; /* do average calculation */ if (m_rtt.avg_rtt < 0.0) m_rtt.avg_rtt = rtt; else m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) + rtt * (1/num_samples); /* do jitter calculation */ //just use some neutral value at beginning float jitter = m_rtt.jitter_min; if (rtt > m_last_rtt) jitter = rtt-m_last_rtt; if (rtt <= m_last_rtt) jitter = m_last_rtt - rtt; if (jitter < m_rtt.jitter_min) m_rtt.jitter_min = jitter; if (jitter >= m_rtt.jitter_max) m_rtt.jitter_max = jitter; if (m_rtt.jitter_avg < 0.0) m_rtt.jitter_avg = jitter; else m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) + jitter * (1/num_samples); if (profiler_id != "") { g_profiler->graphAdd(profiler_id + "_rtt", rtt); g_profiler->graphAdd(profiler_id + "_jitter", jitter); } } /* save values required for next loop */ m_last_rtt = rtt; } bool Peer::isTimedOut(float timeout) { MutexAutoLock lock(m_exclusive_access_mutex); u32 current_time = porting::getTimeMs(); float dtime = CALC_DTIME(m_last_timeout_check,current_time); m_last_timeout_check = current_time; m_timeout_counter += dtime; return m_timeout_counter > timeout; } void Peer::Drop() { { MutexAutoLock usage_lock(m_exclusive_access_mutex); m_pending_deletion = true; if (m_usage != 0) return; } PROFILE(std::stringstream peerIdentifier1); PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc() << ";" << id << ";RELIABLE]"); PROFILE(g_profiler->remove(peerIdentifier1.str())); PROFILE(std::stringstream peerIdentifier2); PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc() << ";" << id << ";RELIABLE]"); PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG)); delete this; } UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) : Peer(a_address,a_id,connection), m_pending_disconnect(false), resend_timeout(0.5), m_legacy_peer(true) { } bool UDPPeer::getAddress(MTProtocols type,Address& toset) { if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY)) { toset = address; return true; } return false; } void UDPPeer::setNonLegacyPeer() { m_legacy_peer = false; for(unsigned int i=0; i< CHANNEL_COUNT; i++) { channels->setWindowSize(g_settings->getU16("max_packets_per_iteration")); } } void UDPPeer::reportRTT(float rtt) { if (rtt < 0.0) { return; } RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10); float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR; if (timeout < RESEND_TIMEOUT_MIN) timeout = RESEND_TIMEOUT_MIN; if (timeout > RESEND_TIMEOUT_MAX) timeout = RESEND_TIMEOUT_MAX; MutexAutoLock usage_lock(m_exclusive_access_mutex); resend_timeout = timeout; } bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data) { m_ping_timer += dtime; if (m_ping_timer >= PING_TIMEOUT) { // Create and send PING packet writeU8(&data[0], TYPE_CONTROL); writeU8(&data[1], CONTROLTYPE_PING); m_ping_timer = 0.0; return true; } return false; } void UDPPeer::PutReliableSendCommand(ConnectionCommand &c, unsigned int max_packet_size) { if (m_pending_disconnect) return; if ( channels[c.channelnum].queued_commands.empty() && /* don't queue more packets then window size */ (channels[c.channelnum].queued_reliables.size() < (channels[c.channelnum].getWindowSize()/2))) { LOG(dout_con<<m_connection->getDesc() <<" processing reliable command for peer id: " << c.peer_id <<" data size: " << c.data.getSize() << std::endl); if (!processReliableSendCommand(c,max_packet_size)) { channels[c.channelnum].queued_commands.push_back(c); } } else { LOG(dout_con<<m_connection->getDesc() <<" Queueing reliable command for peer id: " << c.peer_id <<" data size: " << c.data.getSize() <<std::endl); channels[c.channelnum].queued_commands.push_back(c); } } bool UDPPeer::processReliableSendCommand( ConnectionCommand &c, unsigned int max_packet_size) { if (m_pending_disconnect) return true; u32 chunksize_max = max_packet_size - BASE_HEADER_SIZE - RELIABLE_HEADER_SIZE; sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512); std::list<SharedBuffer<u8> > originals; u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum(); if (c.raw) { originals.push_back(c.data); } else { originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number); channels[c.channelnum].setNextSplitSeqNum(split_sequence_number); } bool have_sequence_number = true; bool have_initial_sequence_number = false; std::queue<BufferedPacket> toadd; volatile u16 initial_sequence_number = 0; for(std::list<SharedBuffer<u8> >::iterator i = originals.begin(); i != originals.end(); ++i) { u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number); /* oops, we don't have enough sequence numbers to send this packet */ if (!have_sequence_number) break; if (!have_initial_sequence_number) { initial_sequence_number = seqnum; have_initial_sequence_number = true; } SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum); // Add base headers and make a packet BufferedPacket p = con::makePacket(address, reliable, m_connection->GetProtocolID(), m_connection->GetPeerID(), c.channelnum); toadd.push(p); } if (have_sequence_number) { volatile u16 pcount = 0; while(toadd.size() > 0) { BufferedPacket p = toadd.front(); toadd.pop(); // LOG(dout_con<<connection->getDesc() // << " queuing reliable packet for peer_id: " << c.peer_id // << " channel: " << (c.channelnum&0xFF) // << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1]) // << std::endl) channels[c.channelnum].queued_reliables.push(p); pcount++; } sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF); return true; } else { volatile u16 packets_available = toadd.size(); /* we didn't get a single sequence number no need to fill queue */ if (!have_initial_sequence_number) { return false; } while(toadd.size() > 0) { /* remove packet */ toadd.pop(); bool successfully_put_back_sequence_number = channels[c.channelnum].putBackSequenceNumber( (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1))); FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error"); } LOG(dout_con<<m_connection->getDesc() << " Windowsize exceeded on reliable sending " << c.data.getSize() << " bytes" << std::endl << "\t\tinitial_sequence_number: " << initial_sequence_number << std::endl << "\t\tgot at most : " << packets_available << " packets" << std::endl << "\t\tpackets queued : " << channels[c.channelnum].outgoing_reliables_sent.size() << std::endl); return false; } } void UDPPeer::RunCommandQueues( unsigned int max_packet_size, unsigned int maxcommands, unsigned int maxtransfer) { for (unsigned int i = 0; i < CHANNEL_COUNT; i++) { unsigned int commands_processed = 0; if ((channels[i].queued_commands.size() > 0) && (channels[i].queued_reliables.size() < maxtransfer) && (commands_processed < maxcommands)) { try { ConnectionCommand c = channels[i].queued_commands.front(); LOG(dout_con << m_connection->getDesc() << " processing queued reliable command " << std::endl); // Packet is processed, remove it from queue if (processReliableSendCommand(c,max_packet_size)) { channels[i].queued_commands.pop_front(); } else { LOG(dout_con << m_connection->getDesc() << " Failed to queue packets for peer_id: " << c.peer_id << ", delaying sending of " << c.data.getSize() << " bytes" << std::endl); } } catch (ItemNotFoundException &e) { // intentionally empty } } } } u16 UDPPeer::getNextSplitSequenceNumber(u8 channel) { assert(channel < CHANNEL_COUNT); // Pre-condition return channels[channel].readNextIncomingSeqNum(); } void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum) { assert(channel < CHANNEL_COUNT); // Pre-condition channels[channel].setNextSplitSeqNum(seqnum); } SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel, BufferedPacket toadd, bool reliable) { assert(channel < CHANNEL_COUNT); // Pre-condition return channels[channel].incoming_splits.insert(toadd,reliable); } /******************************************************************************/ /* Connection Threads */ /******************************************************************************/ ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size, float timeout) : Thread("ConnectionSend"), m_connection(NULL), m_max_packet_size(max_packet_size), m_timeout(timeout), m_max_commands_per_iteration(1), m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration")), m_max_packets_requeued(256) { } void * ConnectionSendThread::run() { assert(m_connection); LOG(dout_con<<m_connection->getDesc() <<"ConnectionSend thread started"<<std::endl); u32 curtime = porting::getTimeMs(); u32 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<u16> peerIds = m_connection->getPeerIDs(); if (!m_outgoing_queue.empty() && !peerIds.empty()) return true; for(std::list<u16>::iterator j = peerIds.begin(); j != peerIds.end(); ++j) { PeerHelper peer = m_connection->getPeerNoEx(*j); if (!peer) continue; if (dynamic_cast<UDPPeer*>(&peer) == 0) continue; for(u16 i=0; i < CHANNEL_COUNT; i++) { Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i]; if (channel->queued_commands.size() > 0) { return true; } } } return false; } void ConnectionSendThread::runTimeouts(float dtime) { std::list<u16> timeouted_peers; std::list<u16> peerIds = m_connection->getPeerIDs(); for(std::list<u16>::iterator j = peerIds.begin(); j != peerIds.end(); ++j) { PeerHelper peer = m_connection->getPeerNoEx(*j); if (!peer) continue; if (dynamic_cast<UDPPeer*>(&peer) == 0) continue; PROFILE(std::stringstream peerIdentifier); PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc() << ";" << *j << ";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 = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout(); for(u16 i=0; i<CHANNEL_COUNT; i++) { std::list<BufferedPacket> timed_outs; Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i]; if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer()) channel->setWindowSize(g_settings->getU16("workaround_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) { u16 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++; 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 } channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer()); } /* send ping if necessary */ if (dynamic_cast<UDPPeer*>(&peer)->Ping(dtime,data)) { LOG(dout_con<<m_connection->getDesc() <<"Sending ping for peer_id: " << dynamic_cast<UDPPeer*>(&peer)->id <<std::endl); /* this may fail if there ain't a sequence number left */ if (!rawSendAsPacket(dynamic_cast<UDPPeer*>(&peer)->id, 0, data, true)) { //retrigger with reduced ping interval dynamic_cast<UDPPeer*>(&peer)->Ping(4.0,data); } } dynamic_cast<UDPPeer*>(&peer)->RunCommandQueues(m_max_packet_size, m_max_commands_per_iteration, m_max_packets_requeued); } // Remove timed out peers for(std::list<u16>::iterator i = timeouted_peers.begin(); i != timeouted_peers.end(); ++i) { LOG(derr_con<<m_connection->getDesc() <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl); m_connection->deletePeer(*i, 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(u16 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: " << channelnum <<" seqnum: " << seqnum << std::endl); sendAsPacketReliable(p,channel); return true; } else { LOG(dout_con<<m_connection->getDesc() <<" INFO: queueing reliable packet for peer_id: " << peer_id <<" channel: " << channelnum <<" seqnum: " << seqnum << std::endl); channel->queued_reliables.push(p); return false; } } else { 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; } else { 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; } } //never reached 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], TYPE_CONTROL); writeU8(&data[1], CONTROLTYPE_DISCO); // Send to all std::list<u16> peerids = m_connection->getPeerIDs(); for (std::list<u16>::iterator i = peerids.begin(); i != peerids.end(); ++i) { sendAsPacket(*i, 0,data,false); } } void ConnectionSendThread::disconnect_peer(u16 peer_id) { LOG(dout_con<<m_connection->getDesc()<<" disconnecting peer"<<std::endl); // Create and send DISCO packet SharedBuffer<u8> data(2); writeU8(&data[0], 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(u16 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; originals = makeAutoSplitPacket(data, chunksize_max,split_sequence_number); peer->setNextSplitSequenceNumber(channelnum,split_sequence_number); for(std::list<SharedBuffer<u8> >::iterator i = originals.begin(); i != originals.end(); ++i) { SharedBuffer<u8> original = *i; 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<u16> peerids = m_connection->getPeerIDs(); for (std::list<u16>::iterator i = peerids.begin(); i != peerids.end(); ++i) { send(*i, channelnum, data); } } void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c) { std::list<u16> peerids = m_connection->getPeerIDs(); for (std::list<u16>::iterator i = peerids.begin(); i != peerids.end(); ++i) { PeerHelper peer = m_connection->getPeerNoEx(*i); if (!peer) continue; peer->PutReliableSendCommand(c,m_max_packet_size); } } void ConnectionSendThread::sendPackets(float dtime) { std::list<u16> peerIds = m_connection->getPeerIDs(); std::list<u16> pendingDisconnect; std::map<u16,bool> pending_unreliable; for(std::list<u16>::iterator j = peerIds.begin(); j != peerIds.end(); ++j) { PeerHelper peer = m_connection->getPeerNoEx(*j); //peer may have been removed if (!peer) { LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl); continue; } peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size(); if (dynamic_cast<UDPPeer*>(&peer) == 0) { continue; } if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect) { pendingDisconnect.push_back(*j); } PROFILE(std::stringstream peerIdentifier); PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]");