summaryrefslogtreecommitdiff
path: root/tracker/common/Socket.cpp
blob: 93109bab44f3e2034a0115ea5c43571e5fe634ca (plain) (blame)
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
// $NoKeywords: $
//=============================================================================
#if !defined( _X360 )
#define FD_SETSIZE 1024
#endif

#include <assert.h>
#include "winlite.h"
#if !defined( _X360 )
#include "winsock.h"
#else
#include "winsockx.h"
#endif
#include "msgbuffer.h"
#include "socket.h"
#include "inetapi.h"
#include "tier0/vcrmode.h"

#include <VGUI/IVGui.h>

#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif

//-----------------------------------------------------------------------------
// Purpose: All socket I/O occurs on a thread
//-----------------------------------------------------------------------------
class CSocketThread
{
public:
	typedef struct threadsocket_s
	{
		struct threadsocket_s	*next;
		CSocket					*socket;
	} threadsocket_t;

	// Construction
							CSocketThread( void );
	virtual 				~CSocketThread( void );

	// Sockets add/remove themselves via their constructor
	virtual void			AddSocketToThread( CSocket *socket );
	virtual void			RemoveSocketFromThread( CSocket *socket );

	// Lock changes to socket list, etc.
	virtual void			Lock( void );
	// Unlock socket list, etc.
	virtual void			Unlock( void );

	// Retrieve handle to shutdown event
	virtual HANDLE			GetShutdownHandle( void );
	// Get head of socket list
	virtual threadsocket_t	*GetSocketList( void );

	// Sample clock for socket thread
	virtual float			GetClock( void );

private:
	// Initialize the clock
	void					InitTimer( void );

private:
	// Critical section used for synchronizing access to socket list
	CRITICAL_SECTION		cs;
	// List of sockets we are listening on
	threadsocket_t			*m_pSocketList;
	// Thread handle
	HANDLE					m_hThread;
	// Thread id
	DWORD					m_nThreadId;
	// Event to set when we want to tell the thread to shut itself down
	HANDLE					m_hShutdown;

	// High performance clock frequency
	double					m_dClockFrequency;
	// Current accumulated time
	double					m_dCurrentTime;
	// How many bits to shift raw 64 bit sample count by
	int						m_nTimeSampleShift;
	// Previous 32 bit sample count
	unsigned int			m_uiPreviousTime;
};

// Singleton handler
static CSocketThread *GetSocketThread()
{
	static CSocketThread g_SocketThread;
	return &g_SocketThread;
}

//-----------------------------------------------------------------------------
// Purpose: Main winsock processing thread
// Input  : threadobject - 
// Output : static DWORD WINAPI
//-----------------------------------------------------------------------------
static DWORD WINAPI SocketThreadFunc( LPVOID threadobject )
{
	// Get pointer to CSocketThread object
	CSocketThread *socketthread = ( CSocketThread * )threadobject;
	assert( socketthread );
	if ( !socketthread )
	{
		return 0;
	}

	// Keep looking for data until shutdown event is triggered
	while ( 1 )
	{
		// List of sockets
		CSocketThread::threadsocket_t *sockets;
		// file descriptor set for sockets
		fd_set		fdset;
		// number of sockets with messages ready
		int			number;
		// number of sockets added to fd_set
		int			count;

		// Check for shutdown event
		if ( WAIT_OBJECT_0 == VCRHook_WaitForSingleObject( socketthread->GetShutdownHandle(), 0 ) )
		{
			break;
		}

		// Clear the set
		FD_ZERO(&fdset);

		// No changes to list right now
		socketthread->Lock();

		// Add all active sockets to the fdset
		count = 0;
		for ( sockets = socketthread->GetSocketList(); sockets; sockets = sockets->next )
		{
			FD_SET( static_cast<u_int>( sockets->socket->GetSocketNumber() ), &fdset );
			count = max( count, sockets->socket->GetSocketNumber() );
		}

		// Done
		socketthread->Unlock();

		if ( count )
		{
			struct timeval tv;
			tv.tv_sec	= 0;
			tv.tv_usec	= 100000; // 100 millisecond == 100000 usec

			// Block for 100000 usec, or until a message is in the queue
			number = select( count + 1, &fdset, NULL, NULL, &tv );
#if !defined( NO_VCR )
			VCRGenericValue( "", &number, sizeof( number ) );
#endif
			if ( number > 0 )
			{
				// Iterate through socket list and see who has data waiting				//
				// No changes to list right now
				socketthread->Lock();

				// Check FD_SET for incoming network messages
				for ( sockets = socketthread->GetSocketList(); sockets; sockets = sockets->next )
				{
					bool bSet = FD_ISSET( sockets->socket->GetSocketNumber(), &fdset );
#if !defined( NO_VCR )
					VCRGenericValue( "", &bSet, sizeof( bSet ) );
#endif
					if ( bSet )
					{
						// keep reading as long as there is data on the socket
						while (sockets->socket->ReceiveData())
						{
						}
					}
				}

				// Done
				socketthread->Unlock();
			}
		}

		// no need to sleep here, much better let it sleep in the select
	}

	ExitThread( 0 );

	return 0;
}

//-----------------------------------------------------------------------------
// Purpose: Construction
//-----------------------------------------------------------------------------
CSocketThread::CSocketThread( void )
{
	InitTimer();

	m_pSocketList = NULL;

	InitializeCriticalSection( &cs );

	m_hShutdown	= CreateEvent( NULL, TRUE, FALSE, NULL );
	assert( m_hShutdown );

	m_hThread = 0;
	m_nThreadId = 0;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
CSocketThread::~CSocketThread( void )
{
	Lock();
	if ( m_hThread )
	{
		SetEvent( m_hShutdown );
		Sleep( 2 );
		TerminateThread( m_hThread, 0 );
	}
	Unlock();

	// Kill the socket
//!! need to validate this line
//	assert( !m_pSocketList );

	if ( m_hThread )
	{
		CloseHandle( m_hThread );
	}

	CloseHandle( m_hShutdown );

	DeleteCriticalSection( &cs );
}
	
//-----------------------------------------------------------------------------
// Purpose: Initialize socket thread timer
//-----------------------------------------------------------------------------
void CSocketThread::InitTimer( void )
{
	BOOL success;
	LARGE_INTEGER	PerformanceFreq;
	unsigned int	lowpart, highpart;

	// Start clock at zero
	m_dCurrentTime			= 0.0;

	success = QueryPerformanceFrequency( &PerformanceFreq );
	assert( success );

	// get 32 out of the 64 time bits such that we have around
	// 1 microsecond resolution
	lowpart		= (unsigned int)PerformanceFreq.LowPart;
	highpart	= (unsigned int)PerformanceFreq.HighPart;
	
	m_nTimeSampleShift	= 0;

	while ( highpart || ( lowpart > 2000000.0 ) )
	{
		m_nTimeSampleShift++;
		lowpart >>= 1;
		lowpart |= (highpart & 1) << 31;
		highpart >>= 1;
	}
	
	m_dClockFrequency = 1.0 / (double)lowpart;

	// Get initial sample
	unsigned int		temp;
	LARGE_INTEGER		PerformanceCount;
	QueryPerformanceCounter( &PerformanceCount );
	if ( !m_nTimeSampleShift )
	{
		temp = (unsigned int)PerformanceCount.LowPart;
	}
	else
	{
		// Rotate counter to right by m_nTimeSampleShift places
		temp = ((unsigned int)PerformanceCount.LowPart >> m_nTimeSampleShift) |
			   ((unsigned int)PerformanceCount.HighPart << (32 - m_nTimeSampleShift));
	}

	// Set first time stamp
	m_uiPreviousTime = temp;
}

//-----------------------------------------------------------------------------
// Purpose: Thread local timer function
// Output : float
//-----------------------------------------------------------------------------
float CSocketThread::GetClock( void )
{
	LARGE_INTEGER		PerformanceCount;
	unsigned int		temp, t2;
	double				time;

	// Get sample counter
	QueryPerformanceCounter( &PerformanceCount );

	if ( !m_nTimeSampleShift )
	{
		temp = (unsigned int)PerformanceCount.LowPart;
	}
	else
	{
		// Rotate counter to right by m_nTimeSampleShift places
		temp = ((unsigned int)PerformanceCount.LowPart >> m_nTimeSampleShift) |
			   ((unsigned int)PerformanceCount.HighPart << (32 - m_nTimeSampleShift));
	}

	// check for turnover or backward time
	if ( ( temp <= m_uiPreviousTime ) && 
		( ( m_uiPreviousTime - temp ) < 0x10000000) )
	{
		m_uiPreviousTime = temp;	// so we can't get stuck
	}
	else
	{
		// gap in performance clocks
		t2 = temp - m_uiPreviousTime;

		// Convert to time using frequencey of clock
		time = (double)t2 * m_dClockFrequency;

		// Remember old time
		m_uiPreviousTime = temp;

		// Increment clock
		m_dCurrentTime += time;
	}
#if !defined( NO_VCR )
	VCRGenericValue( "", &m_dCurrentTime, sizeof( m_dCurrentTime ) );
#endif
	// Convert to float
    return (float)m_dCurrentTime;
}

//-----------------------------------------------------------------------------
// Purpose: Returns handle of shutdown event
// Output : HANDLE
//-----------------------------------------------------------------------------
HANDLE CSocketThread::GetShutdownHandle( void )
{
	return m_hShutdown;
}

//-----------------------------------------------------------------------------
// Purpose: Returns head of socket list
// Output : CSocketThread::threadsocket_t
//-----------------------------------------------------------------------------
CSocketThread::threadsocket_t *CSocketThread::GetSocketList( void )
{
	return m_pSocketList;
}

int socketCount = 0;

//-----------------------------------------------------------------------------
// Purpose: Locks object and adds socket to thread
//-----------------------------------------------------------------------------
void CSocketThread::AddSocketToThread( CSocket *socket )
{
	// create the thread if it isn't there
	if (!m_hThread)
	{
		m_hThread = VCRHook_CreateThread( NULL, 0, SocketThreadFunc, (void *)this, 0, &m_nThreadId );
		assert( m_hThread );
	}

	socketCount++;

	threadsocket_t *p = new threadsocket_t;
	p->socket = socket;

	Lock();
	p->next = m_pSocketList;
	m_pSocketList = p;
	Unlock();
}

//-----------------------------------------------------------------------------
// Purpose: Locks list and removes specified socket from thread
//-----------------------------------------------------------------------------
void CSocketThread::RemoveSocketFromThread( CSocket *socket )
{
	if (!m_hThread)
		return;

	socketCount--;

	Lock();
	if ( m_pSocketList )
	{
		threadsocket_t *p, *n;
		p = m_pSocketList;
		if ( p->socket == socket )
		{
			m_pSocketList = m_pSocketList->next;
			delete p;
		}
		else
		{
			while ( p->next )
			{
				n = p->next;
				if ( n->socket == socket )
				{
					p->next = n->next;
					delete n;
					break;
				}
				p = n;
			}
		}
	}
	Unlock();
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CSocketThread::Lock( void )
{
	VCRHook_EnterCriticalSection( &cs );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CSocketThread::Unlock( void )
{
	LeaveCriticalSection( &cs );
}

//-----------------------------------------------------------------------------
// Purpose: Constructs a message handler for incoming socket messages
//-----------------------------------------------------------------------------
CMsgHandler::CMsgHandler( HANDLERTYPE type, void *typeinfo /*=NULL*/ )
{
	m_Type	= type;
	m_pNext = NULL;
	
	// Assume no socket
	SetSocket( NULL );

	// Assume no special checking
	m_ByteCode		= 0;
	m_szString[ 0 ] = 0;

	switch ( m_Type )
	{
	default:
	case MSGHANDLER_ALL:
		break;
	case MSGHANDLER_BYTECODE:
		m_ByteCode = *(unsigned char *)typeinfo;
		break;
	case MSGHANDLER_STRING:
		strcpy( m_szString, (char *)typeinfo );
		break;
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
CMsgHandler::~CMsgHandler( void )
{
}

//-----------------------------------------------------------------------------
// Purpose: Default message handler for received messages
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CMsgHandler::Process( netadr_t *from, CMsgBuffer *msg )
{
	// Swallow message by default
	return true;
}

//-----------------------------------------------------------------------------
// Purpose: Check for special handling
// Input  : *from - 
//			*msg - 
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CMsgHandler::ProcessMessage( netadr_t *from, CMsgBuffer *msg )
{
	bool bret = false;
	unsigned char ch;
	const char *str;

	// Crack bytecode or string code
	switch( m_Type )
	{
	case MSGHANDLER_BYTECODE:
		msg->Push();
		ch = (unsigned char)msg->ReadByte();
		msg->Pop();
		if ( ch == m_ByteCode )
		{
			bret = Process( from, msg );
		}
		break;
	case MSGHANDLER_STRING:
		msg->Push();
		str = msg->ReadString();
		msg->Pop();
		if ( str && str[ 0 ] && !stricmp( m_szString, str ) )
		{
			bret = Process( from, msg );
		}
		break;
	default:
	case MSGHANDLER_ALL:
		bret = Process( from, msg );
		break;
	}

	return bret;
}

//-----------------------------------------------------------------------------
// Purpose: Get next in chain of handlers
//-----------------------------------------------------------------------------
CMsgHandler	*CMsgHandler::GetNext( void ) const
{
	return m_pNext;
}

//-----------------------------------------------------------------------------
// Purpose: Set next in handler chain
// Input  : *next - 
//-----------------------------------------------------------------------------
void CMsgHandler::SetNext( CMsgHandler *next )
{
	m_pNext = next;
}

//-----------------------------------------------------------------------------
// Purpose: Get underlying socket object
// Output : CSocket
//-----------------------------------------------------------------------------
CSocket *CMsgHandler::GetSocket( void ) const
{
	return m_pSocket;
}

//-----------------------------------------------------------------------------
// Purpose: Set underlying socket object
// Input  : *socket - 
//-----------------------------------------------------------------------------
void CMsgHandler::SetSocket( CSocket *socket )
{
	m_pSocket = socket;
}

//-----------------------------------------------------------------------------
// Purpose: Creates a non-blocking, broadcast capable, UDP socket.  If port is
//  specified, binds it to listen on that port, otherwise, chooses a random port.
//-----------------------------------------------------------------------------
CSocket::CSocket( const char *socketname, int port /*= -1*/ ) : m_SendBuffer(socketname)
{
	struct sockaddr_in	address;
	unsigned long _true = 1;
	int i = 1;

	m_pSocketName		= socketname;

	m_bValid			= false;
	m_bResolved			= false;
	m_pMessageHandlers	= NULL;
	m_nUserData			= 0;
	m_bBroadcastSend	= false;
	m_iTotalPackets		= 0;
	m_iCurrentPackets	= 0;
	m_iRetries			= 0;

	m_pBufferCS = new CRITICAL_SECTION;
	InitializeCriticalSection((CRITICAL_SECTION *)m_pBufferCS);

	// ensure the socketthread singleton has been created
	GetSocketThread();

	// Set up the socket
	m_Socket = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP );
	if ( m_Socket == -1 )
	{
		//int err = WSAGetLastError();
		// WSANOTINITIALISED
		return;
	}

	// Set it to non-blocking
	if ( ioctlsocket ( m_Socket, FIONBIO, &_true ) == -1 )
	{
		closesocket( m_Socket );
		m_Socket = 0;
		return;
	}

	// Allow broadcast packets
	if ( setsockopt( m_Socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i) ) == -1 )
	{
		closesocket( m_Socket );
		m_Socket = 0;
		return;
	}

	// LATER: Support specifying interface name
	//if (!net_interface || !net_interface[0] || !stricmp(net_interface, "localhost"))
	address.sin_addr.s_addr = INADDR_ANY;
	//else
	//	NET_StringToSockaddr (net_interface, (struct sockaddr *)&address);

	if ( port == -1 )
	{
		address.sin_port = 0;
	}
	else
	{
		address.sin_port = htons( (short)port );
	}

	address.sin_family = AF_INET;

	// only bind if we're required to be on a certain port
	if ( address.sin_port > 0)
	{
		// Bind the socket to specified port
		if ( bind( m_Socket, (struct sockaddr *)&address, sizeof(address) ) == -1 )
		{
			closesocket (m_Socket);
			m_Socket = 0;
			return;
		}
	}

	// Mark as valid
	m_bValid = true;

	// Only add valid sockets to thread
	GetSocketThread()->AddSocketToThread( this );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
CSocket::~CSocket( void )
{
	DeleteCriticalSection((CRITICAL_SECTION *)m_pBufferCS);
	delete (CRITICAL_SECTION *)m_pBufferCS;

	// Try to remove socket from thread
	GetSocketThread()->RemoveSocketFromThread( this );

	// Ask message handlers to remove selves?
	if ( m_bValid )
	{
		::shutdown(m_Socket, 0x01);
		::shutdown(m_Socket, 0x02);
		closesocket( m_Socket );
		m_Socket = 0;
	}

	// Remove handlers
	CMsgHandler *handler = m_pMessageHandlers;
	while ( handler )
	{
		RemoveMessageHandler( handler );
		delete handler;
		handler = m_pMessageHandlers;
	}
	m_pMessageHandlers = NULL;
}

//-----------------------------------------------------------------------------
// Purpose: Add hander to head of chain
// Input  : *handler - 
//-----------------------------------------------------------------------------
void CSocket::AddMessageHandler( CMsgHandler *handler )
{
	handler->SetNext( m_pMessageHandlers );
	m_pMessageHandlers = handler;

	// Set the socket pointer
	handler->SetSocket( this );
}

//-----------------------------------------------------------------------------
// Purpose: Removed indicated handler
// Input  : *handler - 
//-----------------------------------------------------------------------------
void CSocket::RemoveMessageHandler( CMsgHandler *handler )
{
	if ( !handler )
	{
		return;
	}

	CMsgHandler *list = m_pMessageHandlers;
	if ( list == handler )
	{
		m_pMessageHandlers = m_pMessageHandlers->GetNext();
		return;
	}

	while ( list )
	{
		if ( list->GetNext() == handler )
		{
			list->SetNext( handler->GetNext() );
			handler->SetNext( NULL );
			return;
		}
		list = list->GetNext();
	}
}

//-----------------------------------------------------------------------------
// Purpose: Send message to specified address
// Input  : *to - 
// Output : int - number of bytes sent
//-----------------------------------------------------------------------------
int CSocket::SendMessage( netadr_t *to, CMsgBuffer *msg /*= NULL*/ )
{
	m_bBroadcastSend = false;
	m_ToAddress = *to;

	if ( !m_bValid )
	{
		return 0;
	}

	if ( !msg )
	{
		msg = GetSendBuffer();
	}

	struct sockaddr	addr;
	net->NetAdrToSockAddr ( to, &addr );

	int bytessent = sendto( m_Socket, (const char *)msg->GetData(), msg->GetCurSize(), 0, &addr, sizeof( addr ) );
	if ( bytessent == msg->GetCurSize() )
	{
		return bytessent;
	}

	return 0;
}

//-----------------------------------------------------------------------------
// Purpose: Send broadcast message on specified port
// Input  : port - 
// Output : int - number of bytes sent
//-----------------------------------------------------------------------------
int CSocket::Broadcast( int port, CMsgBuffer *msg /*= NULL*/ )
{
	m_bBroadcastSend = true;
	memset( &m_ToAddress, 0, sizeof( m_ToAddress ) );

	if ( !m_bValid )
	{
		return 0;
	}

	if ( !msg )
	{
		msg = GetSendBuffer();
	}

	struct sockaddr	addr;
	netadr_t to;

	to.port = (unsigned short)htons( (unsigned short)port );
	to.type = NA_BROADCAST;

	net->NetAdrToSockAddr ( &to, &addr );

	int bytessent = sendto( m_Socket, (const char *)msg->GetData(), msg->GetCurSize(), 0, &addr, sizeof( addr ) );
	if ( bytessent == msg->GetCurSize() )
	{
		return bytessent;
	}

	return 0;
}

//-----------------------------------------------------------------------------
// Purpose: Retrieve internal message buffer
// Output : CMsgBuffer
//-----------------------------------------------------------------------------
CMsgBuffer *CSocket::GetSendBuffer( void )
{
	return &m_SendBuffer;
}

//-----------------------------------------------------------------------------
// Purpose: Called once per frame (outside of the socket thread) to allow socket to receive incoming messages
//  and route them as appropriate
//-----------------------------------------------------------------------------
void CSocket::Frame( void )
{
	// No data waiting
	if (!m_MsgBuffers.Size())
		return;

	VCRHook_EnterCriticalSection( (CRITICAL_SECTION *)m_pBufferCS );

	// pass up all the receive buffers
	for (int i = 0; i < m_MsgBuffers.Size(); i++)
	{
		// See if there's a handler for this message
		CMsgHandler *handler = m_pMessageHandlers;
		netadr_t addr = m_MsgBuffers[i].GetNetAddress();
		while ( handler )
		{
			// Swallow message?
			if ( handler->ProcessMessage( &addr, &m_MsgBuffers[i] ) )
				break;

			handler = handler->GetNext();
		}
	}

	// free the buffer list
	m_MsgBuffers.RemoveAll();

	LeaveCriticalSection((CRITICAL_SECTION *)m_pBufferCS);
}

//-----------------------------------------------------------------------------
// Purpose: Is socket set up correctly
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CSocket::IsValid( void ) const
{
	return m_bValid;
}

//-----------------------------------------------------------------------------
// Purpose: 
// Output : float
//-----------------------------------------------------------------------------
float CSocket::GetClock( void )
{
	return GetSocketThread()->GetClock();
}

//-----------------------------------------------------------------------------
// Purpose: Resolves the socket address
// Output : const netadr_t
//-----------------------------------------------------------------------------
const netadr_t *CSocket::GetAddress( void )
{
	assert( m_bValid );

	if ( !m_bResolved )
	{
		m_bResolved = true;
		// Determine resulting socket address
		net->GetSocketAddress( m_Socket, &m_Address );
	}

	return &m_Address;
}

//-----------------------------------------------------------------------------
// Purpose: Let the user store/retrieve a 32 bit value
// Input  : userData - 
//-----------------------------------------------------------------------------
void CSocket::SetUserData( unsigned int userData )
{
	m_nUserData = userData;
}

//-----------------------------------------------------------------------------
// Purpose: Let the user store/retrieve a 32 bit value
// Output : unsigned int
//-----------------------------------------------------------------------------
unsigned int CSocket::GetUserData(void ) const
{
	return m_nUserData;
}

//-----------------------------------------------------------------------------
// Purpose: Returns the underlying socket id number for setting up the fd_set
//-----------------------------------------------------------------------------
int CSocket::GetSocketNumber( void ) const
{
	return m_Socket;
}

//-----------------------------------------------------------------------------
// Purpose: Called once FD_ISSET is detected
//-----------------------------------------------------------------------------
bool CSocket::ReceiveData( void )
{
	// Check for data
	struct sockaddr	from;
	int			fromlen;
	int			bytes;
	unsigned char buffer[ CMsgBuffer::NET_MAXMESSAGE ];

	fromlen = sizeof( from );
	bytes = VCRHook_recvfrom( m_Socket, (char *)buffer, CMsgBuffer::NET_MAXMESSAGE, 0, (struct sockaddr *)&from, &fromlen );

	//int port = ntohs( ((struct sockaddr_in *)&from)->sin_port);

	// Socket error
	if ( bytes == -1 )
	{
		return false;
	}

	// Too much data, ignore it
	if ( bytes >= CMsgBuffer::NET_MAXMESSAGE )
	{
		return false;
	}

	// Packets must have -1 tag
	if ( bytes < 4 )
	{
		return false;
	}

	// Mark the time no matter what since FD_SET said there was data and we should have it now
	float recvTime = GetClock();
	
	if( *(int *)&buffer[0] == -2 ) // its a split packet :)
	{
		int curPacket=0,offset=0;
		SPLITPACKET *pak =reinterpret_cast<SPLITPACKET *>(&buffer[0]);

		if(m_iTotalPackets==0)  // this is the first in the series
		{	
			m_iTotalPackets = (pak->packetID & 0x0f);
			m_iSeqNo = pak->sequenceNumber;
			m_iRetries=0;

			m_iCurrentPackets=1;// packet numbers start at zero, total is the total number (i.e =2 for packet 0,1)
			curPacket= (pak->packetID & 0xf0)>>4;
		} 
		else if (m_iSeqNo == pak->sequenceNumber) 
		{
			m_iCurrentPackets++;
			curPacket= (pak->packetID & 0xf0)>>4;
		}
		else 
		{
			m_iRetries++;
			if(m_iRetries>MAX_RETRIES)  // make sure we give up eventually on fragments
			{
				m_iTotalPackets=0;
			}
			return false; // TODO: add support for multiple fragments at one time?
		}


		if(curPacket==0) 
		{
			offset=4; // strip the "-1" at the front of the first packet
		}

		if(curPacket<MAX_PACKETS)  // just in case...
		{
			m_CurPacket[curPacket].Clear(); // new packet, clear the buffer out
			m_CurPacket[curPacket].WriteBuf(bytes-offset-sizeof(SPLITPACKET),&buffer[offset+sizeof(SPLITPACKET)]);
		}

		if(m_iCurrentPackets==m_iTotalPackets) 
		{

			VCRHook_EnterCriticalSection((CRITICAL_SECTION *)m_pBufferCS);

			// Get from address
			netadr_t addr;
			net->SockAddrToNetAdr( &from, &addr );
			
			// append to the receive buffer
			int idx = m_MsgBuffers.AddToTail();
			CMsgBuffer &msgBuffer = m_MsgBuffers[idx];
			
			msgBuffer.Clear();

			// copy all our fragments together
			for(int i=0;i<m_iTotalPackets;i++)
			{
				// buffer must be big enough for us to use, that is where the data originally came from :)
				m_CurPacket[i].ReadBuf(m_CurPacket[i].GetCurSize(),buffer);
				msgBuffer.WriteBuf(m_CurPacket[i].GetCurSize(),buffer);
			}
			msgBuffer.SetTime(recvTime);
			msgBuffer.SetNetAddress(addr);

			LeaveCriticalSection((CRITICAL_SECTION *)m_pBufferCS);

			m_iTotalPackets = 0;  // we have collected all the fragments for
								  //this packet, we can start on a new one now

		}


	}
	else if ( *(int *)&buffer[0] == -1 )		// Must have 255,255,255,255 oob tag
	{	
		/*
		// Fake packet loss
		if ( rand() % 1000 < 200 )
			return;
		*/

		VCRHook_EnterCriticalSection((CRITICAL_SECTION *)m_pBufferCS);

		// Get from address
		netadr_t addr;
		net->SockAddrToNetAdr( &from, &addr );
		
		// append to the receive buffer
		int idx = m_MsgBuffers.AddToTail();
		CMsgBuffer &msgBuffer = m_MsgBuffers[idx];
		
		// Copy payload minus the -1 tag
		msgBuffer.Clear();
		msgBuffer.WriteBuf( bytes - 4, &buffer[ 4 ] );
		msgBuffer.SetTime(recvTime);
		msgBuffer.SetNetAddress(addr);

		LeaveCriticalSection((CRITICAL_SECTION *)m_pBufferCS);
	} 

	return true;
}