summaryrefslogtreecommitdiff
path: root/source/net_chan.c
blob: c1be960087403604ad9947dc0f9ccbcbf1b7ab65 (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
/*
Copyright (C) 1997-2001 Id Software, Inc.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#include "com_local.h"
#include "net_chan.h"

/*

packet header
-------------
31	sequence
1	does this message contain a reliable payload
31	acknowledge sequence
1	acknowledge receipt of even/odd message
16	qport

The remote connection never knows if it missed a reliable message, the
local side detects that it has been dropped by seeing a sequence acknowledge
higher thatn the last reliable sequence, but without the correct evon/odd
bit for the reliable set.

If the sender notices that a reliable message has been dropped, it will be
retransmitted.  It will not be retransmitted again until a message after
the retransmit has been acknowledged and the reliable still failed to get theref.

if the sequence number is -1, the packet should be handled without a netcon

The reliable message can be added to at any time by doing
MSG_Write* (&netchan->message, <data>).

If the message buffer is overflowed, either by a single message, or by
multiple frames worth piling up while the last reliable transmit goes
unacknowledged, the netchan signals a fatal error.

Reliable messages are always placed first in a packet, then the unreliable
message is included if there is sufficient room.

To the receiver, there is no distinction between the reliable and unreliable
parts of the message, they are just processed out as a single larger message.

Illogical packet sequence numbers cause the packet to be dropped, but do
not kill the connection.  This, combined with the tight window of valid
reliable acknowledgement numbers provides protection against malicious
address spoofing.


The qport field is a workaround for bad address translating routers that
sometimes remap the client's source port on a packet during gameplay.

If the base part of the net address matches and the qport matches, then the
channel matches even if the IP port differs.  The IP port should be updated
to the new value before sending out any replies.


If there is no information that needs to be transfered on a given frame,
such as during the connection stage while waiting for the client to load,
then a packet only needs to be delivered if there is something in the
unacknowledged reliable
*/

static cvar_t		*showpackets;
static cvar_t		*showdrop;

cvar_t		*net_qport;
cvar_t      *net_maxmsglen;
cvar_t      *net_chantype;

netadr_t	net_from;

/*
===============
Netchan_Init

===============
*/
void Netchan_Init( void ) {
	int		port;

	// pick a port value that should be nice and random
	port = Sys_Milliseconds() & 0xffff;

	showpackets = Cvar_Get( "showpackets", "0", 0 );
	showdrop = Cvar_Get( "showdrop", "0", 0 );
	net_qport = Cvar_Get( "qport", va( "%d", port ), 0 );
    net_maxmsglen = Cvar_Get( "net_maxmsglen", "1390", 0 );
    net_chantype = Cvar_Get( "net_chantype", "1", 0 );
}

/*
===============
Netchan_OutOfBandPrint

Sends a text message in an out-of-band datagram
================
*/
neterr_t Netchan_OutOfBandPrint( netsrc_t sock, const netadr_t *address,
                                 const char *format, ... )
{
	va_list		argptr;
	char        buffer[MAX_PACKETLEN_DEFAULT];
	size_t		len;

    // write the packet header
	*( uint32_t * )buffer = 0xffffffff;
	
	va_start( argptr, format );
	len = Q_vsnprintf( buffer + 4, sizeof( buffer ) - 4, format, argptr );
	va_end( argptr );

    // send the datagram
	return NET_SendPacket( sock, address, len + 4, buffer );
}

// ============================================================================

static size_t NetchanOld_TransmitNextFragment( netchan_t *netchan ) {
	Com_Error( ERR_FATAL, "NetchanOld_TransmitNextFragment: not implemented" );
	return 0;
}

/*
===============
NetchanOld_Transmit

tries to send an unreliable message to a connection, and handles the
transmition / retransmition of the reliable messages.

A 0 length will still generate a packet and deal with the reliable messages.
================
*/
static size_t NetchanOld_Transmit( netchan_t *netchan, size_t length, const void *data ) {
	netchan_old_t *chan = ( netchan_old_t * )netchan;
	sizebuf_t	send;
	byte		send_buf[MAX_PACKETLEN];
	qboolean	send_reliable;
	uint32_t	w1, w2;
	neterr_t	ret;

// check for message overflow
	if( netchan->message.overflowed ) {
		netchan->fatal_error = qtrue;
		Com_WPrintf( "%s: outgoing message overflow\n",
            NET_AdrToString( &netchan->remote_address ) );
		return 0;
	}

	send_reliable = qfalse;

	// if the remote side dropped the last reliable message, resend it
	if( netchan->incoming_acknowledged > chan->last_reliable_sequence &&
		chan->incoming_reliable_acknowledged != chan->reliable_sequence )
	{
		send_reliable = qtrue;
	}

// if the reliable transmit buffer is empty, copy the current message out
	if( !netchan->reliable_length && netchan->message.cursize ) {
		send_reliable = qtrue;
		memcpy( chan->reliable_buf, chan->message_buf,
            netchan->message.cursize );
		netchan->reliable_length = netchan->message.cursize;
		netchan->message.cursize = 0;
		chan->reliable_sequence ^= 1;
	}

// write the packet header
	w1 = ( netchan->outgoing_sequence & ~( 1 << 31 ) ) |
        ( send_reliable << 31 );
	w2 = ( netchan->incoming_sequence & ~( 1 << 31 ) ) |
        ( chan->incoming_reliable_sequence << 31 );

	netchan->outgoing_sequence++;
	netchan->reliable_ack_pending = qfalse;
	netchan->last_sent = com_localTime;

	SZ_TagInit( &send, send_buf, sizeof( send_buf ), SZ_NC_SEND_OLD );

	SZ_WriteLong( &send, w1 );
	SZ_WriteLong( &send, w2 );

	// send the qport if we are a client
	if( netchan->sock == NS_CLIENT ) {
		if( netchan->protocol < PROTOCOL_VERSION_R1Q2 ) {
			SZ_WriteShort( &send, netchan->qport );
		} else if( netchan->qport ) {
			SZ_WriteByte( &send, netchan->qport );
		}
	}

// copy the reliable message to the packet first
	if( send_reliable ) {
		SZ_Write( &send, chan->reliable_buf, netchan->reliable_length );
		chan->last_reliable_sequence = netchan->outgoing_sequence;
	}
	
// add the unreliable part if space is available
	if( send.maxsize - send.cursize >= length )
		SZ_Write( &send, data, length );
	else
		Com_WPrintf( "%s: dumped unreliable\n",
            NET_AdrToString( &netchan->remote_address ) );

	if( showpackets->integer ) {
        Com_Printf( "send %4"PRIz" : s=%d ack=%d rack=%d",
            send.cursize,
            netchan->outgoing_sequence - 1,
            netchan->incoming_sequence,
            chan->incoming_reliable_sequence );
		if( send_reliable ) {
			Com_Printf( " reliable=%i", chan->reliable_sequence );
		}
        Com_Printf( "\n" );
	}

	// send the datagram
	ret = NET_SendPacket( netchan->sock, &netchan->remote_address,
        send.cursize, send.data );
	if( ret == NET_ERROR ) {
		return 0;
	}

	return send.cursize;
}

/*
=================
NetchanOld_Process

called when the current net_message is from remote_address
modifies net_message so that it points to the packet payload
=================
*/
static qboolean NetchanOld_Process( netchan_t *netchan ) {
	netchan_old_t *chan = ( netchan_old_t * )netchan;
	uint32_t  	sequence, sequence_ack;
	uint32_t  	reliable_ack, reliable_message;

// get sequence numbers		
	MSG_BeginReading();
	sequence = MSG_ReadLong();
	sequence_ack = MSG_ReadLong();

	// read the qport if we are a server
	if( netchan->sock == NS_SERVER ) {
		if( netchan->protocol < PROTOCOL_VERSION_R1Q2 ) {
			MSG_ReadShort();
		} else if( netchan->qport ) {
			MSG_ReadByte();
		}
	}

	reliable_message = sequence >> 31;
	reliable_ack = sequence_ack >> 31;

	sequence &= ~( 1 << 31 );
	sequence_ack &= ~( 1 << 31 );	

	if( showpackets->integer ) {
        Com_Printf( "recv %4"PRIz" : s=%d ack=%d rack=%d",
            msg_read.cursize,
            sequence,
            sequence_ack,
            reliable_ack );
		if( reliable_message ) {
			Com_Printf( " reliable=%d", chan->incoming_reliable_sequence ^ 1 );
        }
        Com_Printf( "\n" );
	}

//
// discard stale or duplicated packets
//
	if( sequence <= netchan->incoming_sequence ) {
		if( showdrop->integer )
			Com_Printf( "%s: out of order packet %i at %i\n",
				NET_AdrToString( &netchan->remote_address ),
				sequence,
				netchan->incoming_sequence );
		return qfalse;
	}

//
// dropped packets don't keep the message from being used
//
	netchan->dropped = sequence - ( netchan->incoming_sequence + 1 );
	if( netchan->dropped > 0 ) {
		if( showdrop->integer )
			Com_Printf( "%s: dropped %i packets at %i\n",
			NET_AdrToString( &netchan->remote_address ),
			netchan->dropped,
			sequence );
	}

//
// if the current outgoing reliable message has been acknowledged
// clear the buffer to make way for the next
//
	chan->incoming_reliable_acknowledged = reliable_ack;
	if( reliable_ack == chan->reliable_sequence )
		netchan->reliable_length = 0;	// it has been received
	
//
// if this message contains a reliable message, bump incoming_reliable_sequence 
//
	netchan->incoming_sequence = sequence;
	netchan->incoming_acknowledged = sequence_ack;
	if( reliable_message ) {
		netchan->reliable_ack_pending = qtrue;
		chan->incoming_reliable_sequence ^= 1;
	}

//
// the message can now be read from the current message pointer
//
	netchan->last_received = com_localTime;

	return qtrue;
}

/*
===============
NetchanOld_ShouldUpdate
================
*/
static qboolean NetchanOld_ShouldUpdate( netchan_t *netchan ) {
	if( netchan->message.cursize || netchan->reliable_ack_pending ||
        com_localTime - netchan->last_sent > 1000 )
    {
		return qtrue;
	}

	return qfalse;
}

/*
==============
NetchanOld_Setup

called to open a channel to a remote system
==============
*/
static netchan_t *NetchanOld_Setup( netsrc_t sock, const netadr_t *adr,
        int qport, size_t maxpacketlen )
{
	netchan_old_t *chan;
	netchan_t *netchan;

	Z_Reserve( sizeof( *chan ) + maxpacketlen * 2 );

    chan = Z_ReservedAlloc( sizeof( *chan ) );
    memset( chan, 0, sizeof( *chan ) );
	netchan = ( netchan_t * )chan;
	netchan->sock = sock;
	netchan->remote_address = *adr;
	netchan->qport = qport;
    netchan->maxpacketlen = maxpacketlen;
	netchan->last_received = com_localTime;
	netchan->incoming_sequence = 0;
	netchan->outgoing_sequence = 1;

	netchan->Process = NetchanOld_Process;
	netchan->Transmit = NetchanOld_Transmit;
	netchan->TransmitNextFragment = NetchanOld_TransmitNextFragment;
	netchan->ShouldUpdate = NetchanOld_ShouldUpdate;

    chan->message_buf = Z_ReservedAlloc( maxpacketlen );
	SZ_Init( &netchan->message, chan->message_buf, maxpacketlen );

    chan->reliable_buf = Z_ReservedAlloc( maxpacketlen );

	return netchan;
}

// ============================================================================


/*
===============
NetchanNew_TransmitNextFragment
================
*/
static size_t NetchanNew_TransmitNextFragment( netchan_t *netchan ) {
	netchan_new_t *chan = ( netchan_new_t * )netchan;
	sizebuf_t	send;
	byte		send_buf[MAX_PACKETLEN];
	qboolean	send_reliable;
	uint32_t	w1, w2;
	uint16_t	offset;
	size_t		fragment_length;
	qboolean	more_fragments;
	neterr_t	ret;

	send_reliable = netchan->reliable_length ? qtrue : qfalse;

	// write the packet header
	w1 = ( netchan->outgoing_sequence & 0x3FFFFFFF ) | ( 1 << 30 ) |
        ( send_reliable << 31 );
	w2 = ( netchan->incoming_sequence & 0x3FFFFFFF ) | ( 0 << 30 ) |
        ( chan->incoming_reliable_sequence << 31 );

	SZ_TagInit( &send, send_buf, sizeof( send_buf ), SZ_NC_SEND_FRG );

	SZ_WriteLong( &send, w1 );
	SZ_WriteLong( &send, w2 );

	// send the qport if we are a client
	if( netchan->sock == NS_CLIENT && netchan->qport ) {
		SZ_WriteByte( &send, netchan->qport );
	}

	fragment_length = chan->fragment_out.cursize - chan->fragment_out.readcount;
	if( fragment_length > netchan->maxpacketlen ) {
		fragment_length = netchan->maxpacketlen;
	}
	
	more_fragments = qtrue;
	if( chan->fragment_out.readcount + fragment_length ==
        chan->fragment_out.cursize )
    {
		more_fragments = qfalse;
	}

	// write fragment offset
	offset = ( chan->fragment_out.readcount & 0x7FFF ) |
        ( more_fragments << 15 );
	SZ_WriteShort( &send, offset );

	// write fragment contents
	SZ_Write( &send, chan->fragment_out.data + chan->fragment_out.readcount,
        fragment_length );
	
	if( showpackets->integer ) {
		Com_Printf( "send %4"PRIz" : s=%d ack=%d rack=%d "
                    "fragment_offset=%"PRIz" more_fragments=%d",
			send.cursize,
			netchan->outgoing_sequence,
			netchan->incoming_sequence,
			chan->incoming_reliable_sequence,
			chan->fragment_out.readcount,
			more_fragments );
		if( send_reliable ) {
			Com_Printf( " reliable=%i ", chan->reliable_sequence );
		}
		Com_Printf( "\n" );
	}

	chan->fragment_out.readcount += fragment_length;
	netchan->fragment_pending = more_fragments;

	// if the message has been sent completely, clear the fragment buffer
	if( !netchan->fragment_pending ) {
		netchan->outgoing_sequence++;
		netchan->last_sent = com_localTime;
		SZ_Clear( &chan->fragment_out );
	}

	// send the datagram
	ret = NET_SendPacket( netchan->sock, &netchan->remote_address,
        send.cursize, send.data );
	if( ret == NET_ERROR ) {
		return 0;
	}

	return send.cursize;
}

/*
===============
NetchanNew_Transmit
================
*/
static size_t NetchanNew_Transmit( netchan_t *netchan, size_t length, const void *data ) {
	netchan_new_t *chan = ( netchan_new_t * )netchan;
	sizebuf_t	send;
	byte		send_buf[MAX_PACKETLEN];
	qboolean	send_reliable;
	uint32_t	w1, w2;
	neterr_t	ret;

// check for message overflow
	if( netchan->message.overflowed ) {
		netchan->fatal_error = qtrue;
		Com_WPrintf( "%s: outgoing message overflow\n",
            NET_AdrToString( &netchan->remote_address ) );
		return 0;
	}

	if( netchan->fragment_pending ) {
		return NetchanNew_TransmitNextFragment( netchan );
	}

	send_reliable = qfalse;

// if the remote side dropped the last reliable message, resend it
	if( netchan->incoming_acknowledged > chan->last_reliable_sequence &&
		chan->incoming_reliable_acknowledged != chan->reliable_sequence )
	{
		send_reliable = qtrue;
	}

// if the reliable transmit buffer is empty, copy the current message out
	if( !netchan->reliable_length && netchan->message.cursize ) {
		send_reliable = qtrue;
		memcpy( chan->reliable_buf, chan->message_buf,
            netchan->message.cursize );
		netchan->reliable_length = netchan->message.cursize;
		netchan->message.cursize = 0;
		chan->reliable_sequence ^= 1;
	}

	if( length > netchan->maxpacketlen || ( send_reliable &&
        ( netchan->reliable_length + length > netchan->maxpacketlen ) ) )
    {
		if( send_reliable ) {
			chan->last_reliable_sequence = netchan->outgoing_sequence;
			SZ_Write( &chan->fragment_out, chan->reliable_buf,
                netchan->reliable_length );
		}
        // add the unreliable part if space is available
        if( chan->fragment_out.maxsize - chan->fragment_out.cursize >= length )
		    SZ_Write( &chan->fragment_out, data, length );
        else
            Com_WPrintf( "%s: dumped unreliable\n",
                NET_AdrToString( &netchan->remote_address ) );
		return NetchanNew_TransmitNextFragment( netchan );
	}

// write the packet header
	w1 = ( netchan->outgoing_sequence & 0x3FFFFFFF ) | ( send_reliable << 31 );
	w2 = ( netchan->incoming_sequence & 0x3FFFFFFF ) |
        ( chan->incoming_reliable_sequence << 31 );

	netchan->outgoing_sequence++;
	netchan->reliable_ack_pending = qfalse;
	netchan->last_sent = com_localTime;

	SZ_TagInit( &send, send_buf, sizeof( send_buf ), SZ_NC_SEND_NEW );

	SZ_WriteLong( &send, w1 );
	SZ_WriteLong( &send, w2 );

	// send the qport if we are a client
	if( netchan->sock == NS_CLIENT && netchan->qport ) {
		SZ_WriteByte( &send, netchan->qport );
	}
	
	// copy the reliable message to the packet first
	if( send_reliable ) {
		chan->last_reliable_sequence = netchan->outgoing_sequence;
		SZ_Write( &send, chan->reliable_buf, netchan->reliable_length );
	}
	
	// add the unreliable part
	SZ_Write( &send, data, length );

	if( showpackets->integer ) {
        Com_Printf( "send %4"PRIz" : s=%d ack=%d rack=%d",
            send.cursize,
            netchan->outgoing_sequence - 1,
            netchan->incoming_sequence,
            chan->incoming_reliable_sequence );
		if( send_reliable ) {
			Com_Printf( " reliable=%d", chan->reliable_sequence );
        }
        Com_Printf( "\n" );
	}

	// send the datagram
	ret = NET_SendPacket( netchan->sock, &netchan->remote_address,
        send.cursize, send.data );
	if( ret == NET_ERROR ) {
		return 0;
	}

	return send.cursize;
}

/*
=================
NetchanNew_Process
=================
*/
static qboolean NetchanNew_Process( netchan_t *netchan ) {
	netchan_new_t *chan = ( netchan_new_t * )netchan;
	uint32_t    sequence, sequence_ack, reliable_ack;
    qboolean    reliable_message, fragmented_message, more_fragments;
	uint16_t	fragment_offset;
	size_t		length;

// get sequence numbers		
	MSG_BeginReading();
	sequence = MSG_ReadLong();
	sequence_ack = MSG_ReadLong();

	// read the qport if we are a server
	if( netchan->sock == NS_SERVER && netchan->qport ) {
		MSG_ReadByte();
	}

	reliable_message = sequence >> 31;
	reliable_ack = sequence_ack >> 31;
	fragmented_message = ( sequence >> 30 ) & 1;

	sequence &= 0x3FFFFFFF;
	sequence_ack &= 0x3FFFFFFF;

    fragment_offset = 0;
    more_fragments = qfalse;
	if( fragmented_message ) {
		fragment_offset = MSG_ReadShort();
        more_fragments = fragment_offset >> 15;
		fragment_offset &= 0x7FFF;
	}

	if( showpackets->integer ) {
		Com_Printf( "recv %4"PRIz" : s=%d ack=%d rack=%d",
            msg_read.cursize, sequence, sequence_ack, reliable_ack );
		if( fragmented_message ) {
			Com_Printf( " fragment_offset=%d more_fragments=%d",
                fragment_offset, more_fragments );
		}
		if( reliable_message ) {
			Com_Printf( " reliable=%d", chan->incoming_reliable_sequence ^ 1 );
		}
		Com_Printf( "\n" );
	}

//
// discard stale or duplicated packets
//
	if( sequence <= netchan->incoming_sequence ) {
		if( showdrop->integer || showpackets->integer ) {
			Com_Printf( "%s: out of order packet %i at %i\n",
                NET_AdrToString( &netchan->remote_address ),
                    sequence, netchan->incoming_sequence );
		}
		return qfalse;
	}

//
// dropped packets don't keep the message from being used
//
	netchan->dropped = sequence - ( netchan->incoming_sequence + 1 );
	if( netchan->dropped > 0 ) {
		if( showdrop->integer || showpackets->integer ) {
			Com_Printf( "%s: dropped %i packets at %i\n",
                NET_AdrToString( &netchan->remote_address ),
                    netchan->dropped, sequence );
		}
	}

//
// if the current outgoing reliable message has been acknowledged
// clear the buffer to make way for the next
//
	chan->incoming_reliable_acknowledged = reliable_ack;
	if( reliable_ack == chan->reliable_sequence ) {
		netchan->reliable_length = 0;	// it has been received
	}


//
// parse fragment header, if any
//
	if( fragmented_message ) {
		if( chan->fragment_sequence != sequence ) {
			// start new receive sequence
			chan->fragment_sequence = sequence;
			SZ_Clear( &chan->fragment_in );
		}

		if( fragment_offset < chan->fragment_in.cursize ) {
			if( showdrop->integer || showpackets->integer ) {
				Com_Printf( "%s: out of order fragment at %i\n",
                    NET_AdrToString( &netchan->remote_address ),
                        sequence );
			}
			return qfalse;
		}

		if( fragment_offset > chan->fragment_in.cursize ) {
			if( showdrop->integer || showpackets->integer ) {
				Com_Printf( "%s: dropped fragment(s) at %i\n",
                    NET_AdrToString( &netchan->remote_address ),
                        sequence );
			}
			return qfalse;
		}

		length = msg_read.cursize - msg_read.readcount;
		if( chan->fragment_in.cursize + length > chan->fragment_in.maxsize ) {
			if( showdrop->integer || showpackets->integer ) {
				Com_Printf( "%s: oversize fragment at %i\n",
                    NET_AdrToString( &netchan->remote_address ),
                        sequence );
			}
			return qfalse;
		}

		SZ_Write( &chan->fragment_in, msg_read.data +
            msg_read.readcount, length );
		if( more_fragments ) {
			return qfalse;
		}

		// message has been sucessfully assembled
		SZ_Clear( &msg_read );
		SZ_Write( &msg_read, chan->fragment_in.data,
            chan->fragment_in.cursize );
		SZ_Clear( &chan->fragment_in );
	}
	
	netchan->incoming_sequence = sequence;
	netchan->incoming_acknowledged = sequence_ack;
	
//
// if this message contains a reliable message, bump incoming_reliable_sequence 
//
	if( reliable_message ) {
		netchan->reliable_ack_pending = qtrue;
		chan->incoming_reliable_sequence ^= 1;
	}

//
// the message can now be read from the current message pointer
//
	netchan->last_received = com_localTime;

	return qtrue;
}

/*
==============
NetchanNew_ShouldUpdate
==============
*/
static qboolean NetchanNew_ShouldUpdate( netchan_t *netchan ) {
	netchan_new_t *chan = ( netchan_new_t * )netchan;

	if( netchan->message.cursize ||
        netchan->reliable_ack_pending ||
		chan->fragment_out.cursize ||
        com_localTime - netchan->last_sent > 1000 )
	{
		return qtrue;
	}

	return qfalse;
}

/*
==============
NetchanNew_Setup
==============
*/
static netchan_t *NetchanNew_Setup( netsrc_t sock, const netadr_t *adr,
        int qport, size_t maxpacketlen )
{
	netchan_new_t *chan;
	netchan_t *netchan;

	chan = Z_Mallocz( sizeof( *chan ) );
	netchan = ( netchan_t * )chan;
	netchan->sock = sock;
	netchan->remote_address = *adr;
	netchan->qport = qport;
    netchan->maxpacketlen = maxpacketlen;
	netchan->last_received = com_localTime;
	netchan->incoming_sequence = 0;
	netchan->outgoing_sequence = 1;

	netchan->Process = NetchanNew_Process;
	netchan->Transmit = NetchanNew_Transmit;
	netchan->TransmitNextFragment = NetchanNew_TransmitNextFragment;
	netchan->ShouldUpdate = NetchanNew_ShouldUpdate;

	SZ_Init( &netchan->message, chan->message_buf,
        sizeof( chan->message_buf ) );
	SZ_TagInit( &chan->fragment_in, chan->fragment_in_buf,
        sizeof( chan->fragment_in_buf ), SZ_NC_FRG_IN );
	SZ_TagInit( &chan->fragment_out, chan->fragment_out_buf,
        sizeof( chan->fragment_out_buf ), SZ_NC_FRG_OUT );

	return netchan;
}

/*
==============
Netchan_Setup
==============
*/
netchan_t *Netchan_Setup( netsrc_t sock, netchan_type_t type,
        const netadr_t *adr, int qport, size_t maxpacketlen, int protocol )
{
    netchan_t *netchan;

    clamp( maxpacketlen, 256, MAX_PACKETLEN_WRITABLE );

	switch( type ) {
	case NETCHAN_OLD:
		netchan = NetchanOld_Setup( sock, adr, qport, maxpacketlen );
        break;
	case NETCHAN_NEW:
		netchan = NetchanNew_Setup( sock, adr, qport, maxpacketlen );
        break;
	default:
		Com_Error( ERR_FATAL, "Netchan_Setup: bad type" );
        netchan = NULL;
	}

    netchan->protocol = protocol;
    netchan->type = type;

	return netchan;

}

/*
==============
Netchan_Close
==============
*/
void Netchan_Close( netchan_t *netchan ) {
	Z_Free( netchan );
}