summaryrefslogtreecommitdiff
path: root/lib/server/Protocol.cpp
blob: 7e5812134a9e1932e433a9d5a2643279f3c81491 (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
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
// --------------------------------------------------------------------------
//
// File
//		Name:    Protocol.cpp
//		Purpose: Generic protocol support
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------

#include "Box.h"

#include <sys/types.h>

#include <cstdlib>
#include <cstring>
#include <cstdio>

#include <new>

#include "autogen_ConnectionException.h"
#include "autogen_ServerException.h"
#include "Protocol.h"
#include "ProtocolWire.h"
#include "SocketStream.h"
#include "PartialReadStream.h"
#include "ProtocolUncertainStream.h"
#include "Logging.h"

#include "MemLeakFindOn.h"

#ifdef BOX_RELEASE_BUILD
	#define PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK	1024
#else
//	#define PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK	1024
	#define PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK	4
#endif

#define UNCERTAIN_STREAM_SIZE_BLOCK	(64*1024)

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Protocol(IOStream &rStream)
//		Purpose: Constructor
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
Protocol::Protocol(std::auto_ptr<SocketStream> apConn)
: mapConn(apConn),
  mHandshakeDone(false),
  mMaxObjectSize(PROTOCOL_DEFAULT_MAXOBJSIZE),
  mTimeout(PROTOCOL_DEFAULT_TIMEOUT),
  mpBuffer(0),
  mBufferSize(0),
  mReadOffset(-1),
  mWriteOffset(-1),
  mValidDataSize(-1),
  mLogToSysLog(false),
  mLogToFile(NULL)  
{
	BOX_TRACE("Send block allocation size is " << 
		PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::~Protocol()
//		Purpose: Destructor
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
Protocol::~Protocol()
{
	// Free buffer?
	if(mpBuffer != 0)
	{
		free(mpBuffer);
		mpBuffer = 0;
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Handshake()
//		Purpose: Handshake with peer (exchange ident strings)
//		Created: 2003/08/20
//
// --------------------------------------------------------------------------
void Protocol::Handshake()
{
	// Already done?
	if(mHandshakeDone)
	{
		THROW_EXCEPTION(CommonException, Internal)
	}

	// Make handshake block
	PW_Handshake hsSend;
	::memset(&hsSend, 0, sizeof(hsSend));
	// Copy in ident string
	::strncpy(hsSend.mIdent, GetProtocolIdentString(), sizeof(hsSend.mIdent));
	
	// Send it
	mapConn->Write(&hsSend, sizeof(hsSend), GetTimeout());
	mapConn->WriteAllBuffered();

	// Receive a handshake from the peer
	PW_Handshake hsReceive;
	::memset(&hsReceive, 0, sizeof(hsReceive));
	char *readInto = (char*)&hsReceive;
	int bytesToRead = sizeof(hsReceive);
	while(bytesToRead > 0)
	{
		// Get some data from the stream
		int bytesRead = mapConn->Read(readInto, bytesToRead, GetTimeout());
		if(bytesRead == 0)
		{
			THROW_EXCEPTION(ConnectionException, Protocol_Timeout)
		}
		readInto += bytesRead;
		bytesToRead -= bytesRead;
	}
	ASSERT(bytesToRead == 0);
	
	// Are they the same?
	if(::memcmp(&hsSend, &hsReceive, sizeof(hsSend)) != 0)
	{
		THROW_EXCEPTION(ConnectionException, Protocol_HandshakeFailed)
	}

	// Mark as done
	mHandshakeDone = true;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::CheckAndReadHdr(void *)
//		Purpose: Check read for recieve call and get object header from stream.
//				 Don't use type here to avoid dependency in .h file.
//		Created: 2003/08/26
//
// --------------------------------------------------------------------------
void Protocol::CheckAndReadHdr(void *hdr)
{
	// Check usage
	if(mValidDataSize != -1 || mWriteOffset != -1 || mReadOffset != -1)
	{
		THROW_EXCEPTION(ServerException, Protocol_BadUsage)
	}
	
	// Handshake done?
	if(!mHandshakeDone)
	{
		Handshake();
	}

	// Get some data into this header
	if(!mapConn->ReadFullBuffer(hdr, sizeof(PW_ObjectHeader),
		0 /* not interested in bytes read if this fails */, mTimeout))
	{
		THROW_EXCEPTION(ConnectionException, Protocol_Timeout)
	}
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::ReceiveInternal()
//		Purpose: Receives an object from the stream, creating it
//			 from the factory object type
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
std::auto_ptr<Message> Protocol::ReceiveInternal()
{
	// Get object header
	PW_ObjectHeader objHeader;
	CheckAndReadHdr(&objHeader);
	
	// Hope it's not a stream
	if(ntohl(objHeader.mObjType) == SPECIAL_STREAM_OBJECT_TYPE)
	{
		THROW_EXCEPTION(ConnectionException, Protocol_StreamWhenObjExpected)
	}
	
	// Check the object size
	u_int32_t objSize = ntohl(objHeader.mObjSize);
	if(objSize < sizeof(objHeader) || objSize > mMaxObjectSize)
	{
		THROW_EXCEPTION(ConnectionException, Protocol_ObjTooBig)
	}

	// Create a blank object
	std::auto_ptr<Message> obj(MakeMessage(ntohl(objHeader.mObjType)));

	// Make sure memory is allocated to read it into
	EnsureBufferAllocated(objSize);
	
	// Read data
	if(!mapConn->ReadFullBuffer(mpBuffer, objSize - sizeof(objHeader),
		0 /* not interested in bytes read if this fails */, mTimeout))
	{
		THROW_EXCEPTION(ConnectionException, Protocol_Timeout)
	}

	// Setup ready to read out data from the buffer
	mValidDataSize = objSize - sizeof(objHeader);
	mReadOffset = 0;

	// Get the object to read its properties from the data recieved
	try
	{
		obj->SetPropertiesFromStreamData(*this);
	}
	catch(...)
	{
		// Make sure state is reset!
		mValidDataSize = -1;
		mReadOffset = -1;
		throw;
	}
	
	// Any data left over?
	bool dataLeftOver = (mValidDataSize != mReadOffset);
	
	// Unset read state, so future read calls don't fail
	mValidDataSize = -1;
	mReadOffset = -1;
	
	// Exception if not all the data was consumed
	if(dataLeftOver)
	{
		THROW_EXCEPTION(ConnectionException, Protocol_BadCommandRecieved)
	}

	return obj;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Send()
//		Purpose: Send an object to the other side of the connection.
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::SendInternal(const Message &rObject)
{
	// Check usage
	if(mValidDataSize != -1 || mWriteOffset != -1 || mReadOffset != -1)
	{
		THROW_EXCEPTION(ServerException, Protocol_BadUsage)
	}

	// Handshake done?
	if(!mHandshakeDone)
	{
		Handshake();
	}

	// Make sure there's a little bit of space allocated
	EnsureBufferAllocated(((sizeof(PW_ObjectHeader) + PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK - 1) / PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK) * PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK);
	ASSERT(mBufferSize >= (int)sizeof(PW_ObjectHeader));
	
	// Setup for write operation
	mValidDataSize = 0;		// Not used, but must not be -1
	mWriteOffset = sizeof(PW_ObjectHeader);
	
	try
	{
		rObject.WritePropertiesToStreamData(*this);
	}
	catch(...)
	{
		// Make sure state is reset!
		mValidDataSize = -1;
		mWriteOffset = -1;
		throw;
	}

	// How big?
	int writtenSize = mWriteOffset;

	// Reset write state
	mValidDataSize = -1;
	mWriteOffset = -1;	
	
	// Make header in the existing block
	PW_ObjectHeader *pobjHeader = (PW_ObjectHeader*)(mpBuffer);
	pobjHeader->mObjSize = htonl(writtenSize);
	pobjHeader->mObjType = htonl(rObject.GetType());

	// Write data
	mapConn->Write(mpBuffer, writtenSize, GetTimeout());
	mapConn->WriteAllBuffered();
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::EnsureBufferAllocated(int)
//		Purpose: Private. Ensures the buffer is at least the size requested.
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::EnsureBufferAllocated(int Size)
{
	if(mpBuffer != 0 && mBufferSize >= Size)
	{
		// Nothing to do!
		return;
	}
	
	// Need to allocate, or reallocate, the block
	if(mpBuffer != 0)
	{
		// Reallocate
		void *b = realloc(mpBuffer, Size);
		if(b == 0)
		{
			throw std::bad_alloc();
		}
		mpBuffer = (char*)b;
		mBufferSize = Size;
	}
	else
	{
		// Just allocate
		mpBuffer = (char*)malloc(Size);
		if(mpBuffer == 0)
		{
			throw std::bad_alloc();
		}
		mBufferSize = Size;
	}
}


#define READ_START_CHECK														\
	if(mValidDataSize == -1 || mWriteOffset != -1 || mReadOffset == -1)			\
	{																			\
		THROW_EXCEPTION(ServerException, Protocol_BadUsage)						\
	}

#define READ_CHECK_BYTES_AVAILABLE(bytesRequired)								\
	if((mReadOffset + (int)(bytesRequired)) > mValidDataSize)					\
	{																			\
		THROW_EXCEPTION(ConnectionException, Protocol_BadCommandRecieved)	\
	}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Read(void *, int)
//		Purpose: Read raw data from the stream (buffered)
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Read(void *Buffer, int Size)
{
	READ_START_CHECK
	READ_CHECK_BYTES_AVAILABLE(Size)
	
	// Copy data out
	::memmove(Buffer, mpBuffer + mReadOffset, Size);
	mReadOffset += Size;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Read(std::string &, int)
//		Purpose: Read raw data from the stream (buffered), into a std::string
//		Created: 2003/08/26
//
// --------------------------------------------------------------------------
void Protocol::Read(std::string &rOut, int Size)
{
	READ_START_CHECK
	READ_CHECK_BYTES_AVAILABLE(Size)
	
	rOut.assign(mpBuffer + mReadOffset, Size);
	mReadOffset += Size;
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Read(int64_t &)
//		Purpose: Read a value from the stream (buffered)
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Read(int64_t &rOut)
{
	READ_START_CHECK
	READ_CHECK_BYTES_AVAILABLE(sizeof(int64_t))
	
#ifdef HAVE_ALIGNED_ONLY_INT64
	int64_t nvalue;
	memcpy(&nvalue, mpBuffer + mReadOffset, sizeof(int64_t));
#else
	int64_t nvalue = *((int64_t*)(mpBuffer + mReadOffset));
#endif
	rOut = box_ntoh64(nvalue);

	mReadOffset += sizeof(int64_t);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Read(int32_t &)
//		Purpose: Read a value from the stream (buffered)
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Read(int32_t &rOut)
{
	READ_START_CHECK
	READ_CHECK_BYTES_AVAILABLE(sizeof(int32_t))
	
#ifdef HAVE_ALIGNED_ONLY_INT32
	int32_t nvalue;
	memcpy(&nvalue, mpBuffer + mReadOffset, sizeof(int32_t));
#else
	int32_t nvalue = *((int32_t*)(mpBuffer + mReadOffset));
#endif
	rOut = ntohl(nvalue);
	mReadOffset += sizeof(int32_t);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Read(int16_t &)
//		Purpose: Read a value from the stream (buffered)
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Read(int16_t &rOut)
{
	READ_START_CHECK
	READ_CHECK_BYTES_AVAILABLE(sizeof(int16_t))

	rOut = ntohs(*((int16_t*)(mpBuffer + mReadOffset)));
	mReadOffset += sizeof(int16_t);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Read(int8_t &)
//		Purpose: Read a value from the stream (buffered)
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Read(int8_t &rOut)
{
	READ_START_CHECK
	READ_CHECK_BYTES_AVAILABLE(sizeof(int8_t))

	rOut = *((int8_t*)(mpBuffer + mReadOffset));
	mReadOffset += sizeof(int8_t);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Read(std::string &)
//		Purpose: Read a value from the stream (buffered)
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Read(std::string &rOut)
{
	// READ_START_CHECK implied
	int32_t size;
	Read(size);
	
	READ_CHECK_BYTES_AVAILABLE(size)
	
	// initialise string
	rOut.assign(mpBuffer + mReadOffset, size);
	mReadOffset += size;
}




#define WRITE_START_CHECK														\
	if(mValidDataSize == -1 || mWriteOffset == -1 || mReadOffset != -1)			\
	{																			\
		THROW_EXCEPTION(ServerException, Protocol_BadUsage)						\
	}

#define WRITE_ENSURE_BYTES_AVAILABLE(bytesToWrite)								\
	if(mWriteOffset + (int)(bytesToWrite) > mBufferSize)						\
	{																			\
		EnsureBufferAllocated((((mWriteOffset + (int)(bytesToWrite)) + PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK - 1) / PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK) * PROTOCOL_ALLOCATE_SEND_BLOCK_CHUNK); \
		ASSERT(mWriteOffset + (int)(bytesToWrite) <= mBufferSize);			\
	}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Write(const void *, int)
//		Purpose: Writes the contents of a buffer to the stream
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Write(const void *Buffer, int Size)
{
	WRITE_START_CHECK
	WRITE_ENSURE_BYTES_AVAILABLE(Size)
	
	::memmove(mpBuffer + mWriteOffset, Buffer, Size);
	mWriteOffset += Size;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Write(int64_t)
//		Purpose: Writes a value to the stream
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Write(int64_t Value)
{
	WRITE_START_CHECK
	WRITE_ENSURE_BYTES_AVAILABLE(sizeof(int64_t))

	int64_t nvalue = box_hton64(Value);
#ifdef HAVE_ALIGNED_ONLY_INT64
	memcpy(mpBuffer + mWriteOffset, &nvalue, sizeof(int64_t));
#else
	*((int64_t*)(mpBuffer + mWriteOffset)) = nvalue;
#endif
	mWriteOffset += sizeof(int64_t);
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Write(int32_t)
//		Purpose: Writes a value to the stream
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Write(int32_t Value)
{
	WRITE_START_CHECK
	WRITE_ENSURE_BYTES_AVAILABLE(sizeof(int32_t))

	int32_t nvalue = htonl(Value);
#ifdef HAVE_ALIGNED_ONLY_INT32
	memcpy(mpBuffer + mWriteOffset, &nvalue, sizeof(int32_t));
#else
	*((int32_t*)(mpBuffer + mWriteOffset)) = nvalue;
#endif
	mWriteOffset += sizeof(int32_t);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Write(int16_t)
//		Purpose: Writes a value to the stream
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Write(int16_t Value)
{
	WRITE_START_CHECK
	WRITE_ENSURE_BYTES_AVAILABLE(sizeof(int16_t))

	*((int16_t*)(mpBuffer + mWriteOffset)) = htons(Value);
	mWriteOffset += sizeof(int16_t);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Write(int8_t)
//		Purpose: Writes a value to the stream
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Write(int8_t Value)
{
	WRITE_START_CHECK
	WRITE_ENSURE_BYTES_AVAILABLE(sizeof(int8_t))

	*((int8_t*)(mpBuffer + mWriteOffset)) = Value;
	mWriteOffset += sizeof(int8_t);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::Write(const std::string &)
//		Purpose: Writes a value to the stream
//		Created: 2003/08/19
//
// --------------------------------------------------------------------------
void Protocol::Write(const std::string &rValue)
{
	// WRITE_START_CHECK implied
	Write((int32_t)(rValue.size()));
	
	WRITE_ENSURE_BYTES_AVAILABLE(rValue.size())
	Write(rValue.c_str(), rValue.size());
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::ReceiveStream()
//		Purpose: Receive a stream from the remote side
//		Created: 2003/08/26
//
// --------------------------------------------------------------------------
std::auto_ptr<IOStream> Protocol::ReceiveStream()
{
	// Get object header
	PW_ObjectHeader objHeader;
	CheckAndReadHdr(&objHeader);
	
	// Hope it's not an object
	if(ntohl(objHeader.mObjType) != SPECIAL_STREAM_OBJECT_TYPE)
	{
		THROW_EXCEPTION(ConnectionException, Protocol_ObjWhenStreamExpected)
	}
	
	// Get the stream size
	u_int32_t streamSize = ntohl(objHeader.mObjSize);

	// Inform sub class
	InformStreamReceiving(streamSize);

	// Return a stream object
	if(streamSize == ProtocolStream_SizeUncertain)
	{
		BOX_TRACE("Receiving stream, size uncertain");
		return std::auto_ptr<IOStream>(
			new ProtocolUncertainStream(*mapConn));
	}
	else
	{
		BOX_TRACE("Receiving stream, size " << streamSize << " bytes");
		return std::auto_ptr<IOStream>(
			new PartialReadStream(*mapConn, streamSize));
	}
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::SendStream(IOStream &)
//		Purpose: Send a stream to the remote side
//		Created: 2003/08/26
//
// --------------------------------------------------------------------------
void Protocol::SendStream(IOStream &rStream)
{
	// Check usage
	if(mValidDataSize != -1 || mWriteOffset != -1 || mReadOffset != -1)
	{
		THROW_EXCEPTION(ServerException, Protocol_BadUsage)
	}

	// Handshake done?
	if(!mHandshakeDone)
	{
		Handshake();
	}

	// How should this be streamed?
	bool uncertainSize = false;
	IOStream::pos_type streamSize = rStream.BytesLeftToRead();
	if(streamSize == IOStream::SizeOfStreamUnknown
		|| streamSize > 0x7fffffff)
	{
		// Can't send this using the fixed size header
		uncertainSize = true;
	}

	if(streamSize == 0)
	{
		// Server protocol will throw an assertion failure if we
		// try to send a stream whose size is definitely zero:
		// ASSERT FAILED: [BytesToRead > 0] at PartialReadStream.cpp:31
		// so catch this on the client side to help debugging
		THROW_EXCEPTION_MESSAGE(ServerException, Protocol_BadUsage,
			"Sending a stream with a definite size of zero "
			"is not allowed in the protocol");
	}
	
	// Inform sub class
	InformStreamSending(streamSize);
	
	// Make header
	PW_ObjectHeader objHeader;
	objHeader.mObjSize = htonl(uncertainSize?(ProtocolStream_SizeUncertain):streamSize);
	objHeader.mObjType = htonl(SPECIAL_STREAM_OBJECT_TYPE);

	// Write header
	mapConn->Write(&objHeader, sizeof(objHeader), GetTimeout());
	// Could be sent in one of two ways
	if(uncertainSize)
	{
		// Don't know how big this is going to be -- so send it in chunks
		
		// Allocate memory
		uint8_t *blockA = (uint8_t *)malloc(UNCERTAIN_STREAM_SIZE_BLOCK + sizeof(int));
		if(blockA == 0)
		{
			throw std::bad_alloc();
		}
		uint8_t *block = blockA + sizeof(int);	// so that everything is word aligned for reading, but can put the one byte header before it
		
		try
		{
			int bytesInBlock = 0;
			while(rStream.StreamDataLeft())
			{
				// Read some of it
				bytesInBlock += rStream.Read(block + bytesInBlock, UNCERTAIN_STREAM_SIZE_BLOCK - bytesInBlock);
				
				// Send as much as we can out
				bytesInBlock -= SendStreamSendBlock(block, bytesInBlock);
			}

			// Everything recieved from stream, but need to send whatevers left in the block
			while(bytesInBlock > 0)
			{
				bytesInBlock -= SendStreamSendBlock(block, bytesInBlock);
			}
			
			// Send final byte to finish the stream
			BOX_TRACE("Sending end of stream byte");
			uint8_t endOfStream = ProtocolStreamHeader_EndOfStream;
			mapConn->Write(&endOfStream, 1, GetTimeout());
			BOX_TRACE("Sent end of stream byte");
		}
		catch(...)
		{
			free(blockA);
			throw;
		}
		
		// Clean up
		free(blockA);
	}
	else
	{
		// Fixed size stream, send it all in one go
		if(!rStream.CopyStreamTo(*mapConn, GetTimeout(),
			4096 /* slightly larger buffer */))
		{
			THROW_EXCEPTION(ConnectionException, Protocol_TimeOutWhenSendingStream)
		}
	}
	// Make sure everything is written
	mapConn->WriteAllBuffered();
	
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::SendStreamSendBlock(uint8_t *, int)
//		Purpose: Sends as much of the block as can be sent, moves the remainer down to the beginning,
//				 and returns the number of bytes sent. WARNING: Will write to Block[-1]
//		Created: 5/12/03
//
// --------------------------------------------------------------------------
int Protocol::SendStreamSendBlock(uint8_t *Block, int BytesInBlock)
{
	// Quick sanity check
	if(BytesInBlock == 0)
	{
		BOX_TRACE("Zero size block, not sending anything");
		return 0;
	}
	
	// Work out the header byte
	uint8_t header = 0;
	int writeSize = 0;
	if(BytesInBlock >= (64*1024))
	{
		header = ProtocolStreamHeader_SizeIs64k;
		writeSize = (64*1024);
	}
	else
	{
		// Scan the table to find the most that can be written
		for(int s = ProtocolStreamHeader_MaxEncodedSizeValue; s > 0; --s)
		{
			if(sProtocolStreamHeaderLengths[s] <= BytesInBlock)
			{
				header = s;
				writeSize = sProtocolStreamHeaderLengths[s];
				break;
			}
		}
	}
	ASSERT(header > 0);
	BOX_TRACE("Sending header byte " << (int)header << " plus " <<
		writeSize << " bytes to stream");
	
	// Store the header
	Block[-1] = header;
	
	// Write everything out
	mapConn->Write(Block - 1, writeSize + 1, GetTimeout());
	
	BOX_TRACE("Sent " << (writeSize+1) << " bytes to stream");
	// move the remainer to the beginning of the block for the next time round
	if(writeSize != BytesInBlock)
	{
		::memmove(Block, Block + writeSize, BytesInBlock - writeSize);
	}
	
	return writeSize;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::InformStreamReceiving(u_int32_t)
//		Purpose: Informs sub classes about streams being received
//		Created: 2003/10/27
//
// --------------------------------------------------------------------------
void Protocol::InformStreamReceiving(u_int32_t Size)
{
	if(GetLogToSysLog())
	{
		if(Size == Protocol::ProtocolStream_SizeUncertain)
		{
			BOX_TRACE("Receiving stream, size uncertain");
		}
		else
		{
			BOX_TRACE("Receiving stream, size " << Size);
		}
	}

	if(GetLogToFile())
	{
		::fprintf(GetLogToFile(),
			(Size == Protocol::ProtocolStream_SizeUncertain)
			? "Receiving stream, size uncertain\n"
			: "Receiving stream, size %d\n", Size);
		::fflush(GetLogToFile());
	}
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    Protocol::InformStreamSending(u_int32_t)
//		Purpose: Informs sub classes about streams being sent
//		Created: 2003/10/27
//
// --------------------------------------------------------------------------
void Protocol::InformStreamSending(u_int32_t Size)
{
	if(GetLogToSysLog())
	{
		if(Size == Protocol::ProtocolStream_SizeUncertain)
		{
			BOX_TRACE("Sending stream, size uncertain");
		}
		else
		{
			BOX_TRACE("Sending stream, size " << Size);
		}
	}
	
	if(GetLogToFile())
	{
		::fprintf(GetLogToFile(),
			(Size == Protocol::ProtocolStream_SizeUncertain)
			? "Sending stream, size uncertain\n"
			: "Sending stream, size %d\n", Size);
		::fflush(GetLogToFile());
	}
}


/* 
perl code to generate the table below

#!/usr/bin/perl
use strict;
open OUT,">protolengths.txt";
my $len = 0;
for(0 .. 255)
{
	print OUT "\t$len,\t// $_\n";
	my $inc = 1;
	$inc = 8 if $_ >= 64;
	$inc = 16 if $_ >= 96;
	$inc = 32 if $_ >= 112;
	$inc = 64 if $_ >= 128;
	$inc = 128 if $_ >= 135;
	$inc = 256 if $_ >= 147;
	$inc = 512 if $_ >= 159;
	$inc = 1024 if $_ >= 231;
	$len += $inc;
}
close OUT;

*/
const uint16_t Protocol::sProtocolStreamHeaderLengths[256] =
{
	0,	// 0
	1,	// 1
	2,	// 2
	3,	// 3
	4,	// 4
	5,	// 5
	6,	// 6
	7,	// 7
	8,	// 8
	9,	// 9
	10,	// 10
	11,	// 11
	12,	// 12
	13,	// 13
	14,	// 14
	15,	// 15
	16,	// 16
	17,	// 17
	18,	// 18
	19,	// 19
	20,	// 20
	21,	// 21
	22,	// 22
	23,	// 23
	24,	// 24
	25,	// 25
	26,	// 26
	27,	// 27
	28,	// 28
	29,	// 29
	30,	// 30
	31,	// 31
	32,	// 32
	33,	// 33
	34,	// 34
	35,	// 35
	36,	// 36
	37,	// 37
	38,	// 38
	39,	// 39
	40,	// 40
	41,	// 41
	42,	// 42
	43,	// 43
	44,	// 44
	45,	// 45
	46,	// 46
	47,	// 47
	48,	// 48
	49,	// 49
	50,	// 50
	51,	// 51
	52,	// 52
	53,	// 53
	54,	// 54
	55,	// 55
	56,	// 56
	57,	// 57
	58,	// 58
	59,	// 59
	60,	// 60
	61,	// 61
	62,	// 62
	63,	// 63
	64,	// 64
	72,	// 65
	80,	// 66
	88,	// 67
	96,	// 68
	104,	// 69
	112,	// 70
	120,	// 71
	128,	// 72
	136,	// 73
	144,	// 74
	152,	// 75
	160,	// 76
	168,	// 77
	176,	// 78
	184,	// 79
	192,	// 80
	200,	// 81
	208,	// 82
	216,	// 83
	224,	// 84
	232,	// 85
	240,	// 86
	248,	// 87
	256,	// 88
	264,	// 89
	272,	// 90
	280,	// 91
	288,	// 92
	296,	// 93
	304,	// 94
	312,	// 95
	320,	// 96
	336,	// 97
	352,	// 98
	368,	// 99
	384,	// 100
	400,	// 101
	416,	// 102
	432,	// 103
	448,	// 104
	464,	// 105
	480,	// 106
	496,	// 107
	512,	// 108
	528,	// 109
	544,	// 110
	560,	// 111
	576,	// 112
	608,	// 113
	640,	// 114
	672,	// 115
	704,	// 116
	736,	// 117
	768,	// 118
	800,	// 119
	832,	// 120
	864,	// 121
	896,	// 122
	928,	// 123
	960,	// 124
	992,	// 125
	1024,	// 126
	1056,	// 127
	1088,	// 128
	1152,	// 129
	1216,	// 130
	1280,	// 131
	1344,	// 132
	1408,	// 133
	1472,	// 134
	1536,	// 135
	1664,	// 136
	1792,	// 137
	1920,	// 138
	2048,	// 139
	2176,	// 140
	2304,	// 141
	2432,	// 142
	2560,	// 143
	2688,	// 144
	2816,	// 145
	2944,	// 146
	3072,	// 147
	3328,	// 148
	3584,	// 149
	3840,	// 150
	4096,	// 151
	4352,	// 152
	4608,	// 153
	4864,	// 154
	5120,	// 155
	5376,	// 156
	5632,	// 157
	5888,	// 158
	6144,	// 159
	6656,	// 160
	7168,	// 161
	7680,	// 162
	8192,	// 163
	8704,	// 164
	9216,	// 165
	9728,	// 166
	10240,	// 167
	10752,	// 168
	11264,	// 169
	11776,	// 170
	12288,	// 171
	12800,	// 172
	13312,	// 173
	13824,	// 174
	14336,	// 175
	14848,	// 176
	15360,	// 177
	15872,	// 178
	16384,	// 179
	16896,	// 180
	17408,	// 181
	17920,	// 182
	18432,	// 183
	18944,	// 184
	19456,	// 185
	19968,	// 186
	20480,	// 187
	20992,	// 188
	21504,	// 189
	22016,	// 190
	22528,	// 191
	23040,	// 192
	23552,	// 193
	24064,	// 194
	24576,	// 195
	25088,	// 196
	25600,	// 197
	26112,	// 198
	26624,	// 199
	27136,	// 200
	27648,	// 201
	28160,	// 202
	28672,	// 203
	29184,	// 204
	29696,	// 205
	30208,	// 206
	30720,	// 207
	31232,	// 208
	31744,	// 209
	32256,	// 210
	32768,	// 211
	33280,	// 212
	33792,	// 213
	34304,	// 214
	34816,	// 215
	35328,	// 216
	35840,	// 217
	36352,	// 218
	36864,	// 219
	37376,	// 220
	37888,	// 221
	38400,	// 222
	38912,	// 223
	39424,	// 224
	39936,	// 225
	40448,	// 226
	40960,	// 227
	41472,	// 228
	41984,	// 229
	42496,	// 230
	43008,	// 231
	44032,	// 232
	45056,	// 233
	46080,	// 234
	47104,	// 235
	48128,	// 236
	49152,	// 237
	50176,	// 238
	51200,	// 239
	52224,	// 240
	53248,	// 241
	54272,	// 242
	55296,	// 243
	56320,	// 244
	57344,	// 245
	58368,	// 246
	59392,	// 247
	60416,	// 248
	61440,	// 249
	62464,	// 250
	63488,	// 251
	64512,	// 252
	0,		// 253 = 65536 / 64k
	0,		// 254 = special (reserved)
	0		// 255 = special (reserved)
};

int64_t Protocol::GetBytesRead() const
{
	return mapConn->GetBytesRead();
}

int64_t Protocol::GetBytesWritten() const
{
	return mapConn->GetBytesWritten();
}