Debian Codegraph @

code/qcommon/net_chan.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22
23 #include "q_shared.h"
24 #include "qcommon.h"
25
26 /*
27
28 packet header
29 -------------
30 4 outgoing sequence. high bit will be set if this is a fragmented message
31 [2 qport (only for client to server)]
32 [2 fragment start byte]
33 [2 fragment length. if < FRAGMENT_SIZE, this is the last fragment]
34
35 if the sequence number is -1, the packet should be handled as an out-of-band
36 message instead of as part of a netcon.
37
38 All fragments will have the same sequence numbers.
39
40 The qport field is a workaround for bad address translating routers that
41 sometimes remap the client's source port on a packet during gameplay.
42
43 If the base part of the net address matches and the qport matches, then the
44 channel matches even if the IP port differs. The IP port should be updated
45 to the new value before sending out any replies.
46
47 */
48
49
50 #define MAX_PACKETLEN 1400 // max size of a network packet
51
52 #define FRAGMENT_SIZE (MAX_PACKETLEN - 100)
53 #define PACKET_HEADER 10 // two ints and a short
54
55 #define FRAGMENT_BIT (1U<<31)
56
57 cvar_t *showpackets;
58 cvar_t *showdrop;
59 cvar_t *net_qport;
60
61 static char *netsrcString[2] = {
62 "client",
63 "server"
64 };
65
66 /*
67 ===============
68 Netchan_Init
69
70 ===============
71 */
72 void Netchan_Init( int port ) {
73 port &= 0xffff;
74 showpackets = Cvar_Get ("showpackets", "0", CVAR_TEMP );
75 showdrop = Cvar_Get ("showdrop", "0", CVAR_TEMP );
76 net_qport = Cvar_Get ("net_qport", va("%i", port), CVAR_INIT );
77 }
78
79 /*
80 ==============
81 Netchan_Setup
82
83 called to open a channel to a remote system
84 ==============
85 */
86 void Netchan_Setup(netsrc_t sock, netchan_t *chan, netadr_t adr, int qport, int challenge, qboolean compat)
87 {
88 Com_Memset (chan, 0, sizeof(*chan));
89
90 chan->sock = sock;
91 chan->remoteAddress = adr;
92 chan->qport = qport;
93 chan->incomingSequence = 0;
94 chan->outgoingSequence = 1;
95 chan->challenge = challenge;
96
97 #ifdef LEGACY_PROTOCOL
98 chan->compat = compat;
99 #endif
100 }
101
102 /*
103 =================
104 Netchan_TransmitNextFragment
105
106 Send one fragment of the current message
107 =================
108 */
109 void Netchan_TransmitNextFragment( netchan_t *chan ) {
110 msg_t send;
111 byte send_buf[MAX_PACKETLEN];
112 int fragmentLength;
113 int outgoingSequence;
114
115 // write the packet header
116 MSG_InitOOB (&send, send_buf, sizeof(send_buf)); // <-- only do the oob here
117
118 outgoingSequence = chan->outgoingSequence | FRAGMENT_BIT;
119 MSG_WriteLong(&send, outgoingSequence);
120
121 // send the qport if we are a client
122 if ( chan->sock == NS_CLIENT ) {
123 MSG_WriteShort( &send, net_qport->integer );
124 }
125
126 #ifdef LEGACY_PROTOCOL
127 if(!chan->compat)
128 #endif
129 MSG_WriteLong(&send, NETCHAN_GENCHECKSUM(chan->challenge, chan->outgoingSequence));
130
131 // copy the reliable message to the packet first
132 fragmentLength = FRAGMENT_SIZE;
133 if ( chan->unsentFragmentStart + fragmentLength > chan->unsentLength ) {
134 fragmentLength = chan->unsentLength - chan->unsentFragmentStart;
135 }
136
137 MSG_WriteShort( &send, chan->unsentFragmentStart );
138 MSG_WriteShort( &send, fragmentLength );
139 MSG_WriteData( &send, chan->unsentBuffer + chan->unsentFragmentStart, fragmentLength );
140
141 // send the datagram
142 NET_SendPacket(chan->sock, send.cursize, send.data, chan->remoteAddress);
143
144 // Store send time and size of this packet for rate control
145 chan->lastSentTime = Sys_Milliseconds();
146 chan->lastSentSize = send.cursize;
147
148 if ( showpackets->integer ) {
149 Com_Printf ("%s send %4i : s=%i fragment=%i,%i\n"
150 , netsrcString[ chan->sock ]
151 , send.cursize
152 , chan->outgoingSequence
153 , chan->unsentFragmentStart, fragmentLength);
154 }
155
156 chan->unsentFragmentStart += fragmentLength;
157
158 // this exit condition is a little tricky, because a packet
159 // that is exactly the fragment length still needs to send
160 // a second packet of zero length so that the other side
161 // can tell there aren't more to follow
162 if ( chan->unsentFragmentStart == chan->unsentLength && fragmentLength != FRAGMENT_SIZE ) {
163 chan->outgoingSequence++;
164 chan->unsentFragments = qfalse;
165 }
166 }
167
168
169 /*
170 ===============
171 Netchan_Transmit
172
173 Sends a message to a connection, fragmenting if necessary
174 A 0 length will still generate a packet.
175 ================
176 */
177 void Netchan_Transmit( netchan_t *chan, int length, const byte *data ) {
178 msg_t send;
179 byte send_buf[MAX_PACKETLEN];
180
181 if ( length > MAX_MSGLEN ) {
182 Com_Error( ERR_DROP, "Netchan_Transmit: length = %i", length );
183 }
184 chan->unsentFragmentStart = 0;
185
186 // fragment large reliable messages
187 if ( length >= FRAGMENT_SIZE ) {
188 chan->unsentFragments = qtrue;
189 chan->unsentLength = length;
190 Com_Memcpy( chan->unsentBuffer, data, length );
191
192 // only send the first fragment now
193 Netchan_TransmitNextFragment( chan );
194
195 return;
196 }
197
198 // write the packet header
199 MSG_InitOOB (&send, send_buf, sizeof(send_buf));
200
201 MSG_WriteLong( &send, chan->outgoingSequence );
202
203 // send the qport if we are a client
204 if(chan->sock == NS_CLIENT)
205 MSG_WriteShort(&send, net_qport->integer);
206
207 #ifdef LEGACY_PROTOCOL
208 if(!chan->compat)
209 #endif
210 MSG_WriteLong(&send, NETCHAN_GENCHECKSUM(chan->challenge, chan->outgoingSequence));
211
212 chan->outgoingSequence++;
213
214 MSG_WriteData( &send, data, length );
215
216 // send the datagram
217 NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress );
218
219 // Store send time and size of this packet for rate control
220 chan->lastSentTime = Sys_Milliseconds();
221 chan->lastSentSize = send.cursize;
222
223 if ( showpackets->integer ) {
224 Com_Printf( "%s send %4i : s=%i ack=%i\n"
225 , netsrcString[ chan->sock ]
226 , send.cursize
227 , chan->outgoingSequence - 1
228 , chan->incomingSequence );
229 }
230 }
231
232 /*
233 =================
234 Netchan_Process
235
236 Returns qfalse if the message should not be processed due to being
237 out of order or a fragment.
238
239 Msg must be large enough to hold MAX_MSGLEN, because if this is the
240 final fragment of a multi-part message, the entire thing will be
241 copied out.
242 =================
243 */
244 qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) {
245 int sequence;
246 int fragmentStart, fragmentLength;
247 qboolean fragmented;
248
249 // XOR unscramble all data in the packet after the header
250 // Netchan_UnScramblePacket( msg );
251
252 // get sequence numbers
253 MSG_BeginReadingOOB( msg );
254 sequence = MSG_ReadLong( msg );
255
256 // check for fragment information
257 if ( sequence & FRAGMENT_BIT ) {
258 sequence &= ~FRAGMENT_BIT;
259 fragmented = qtrue;
260 } else {
261 fragmented = qfalse;
262 }
263
264 // read the qport if we are a server
265 if ( chan->sock == NS_SERVER ) {
266 MSG_ReadShort( msg );
267 }
268
269 #ifdef LEGACY_PROTOCOL
270 if(!chan->compat)
271 #endif
272 {
273 int checksum = MSG_ReadLong(msg);
274
275 // UDP spoofing protection
276 if(NETCHAN_GENCHECKSUM(chan->challenge, sequence) != checksum)
277 return qfalse;
278 }
279
280 // read the fragment information
281 if ( fragmented ) {
282 fragmentStart = MSG_ReadShort( msg );
283 fragmentLength = MSG_ReadShort( msg );
284 } else {
285 fragmentStart = 0; // stop warning message
286 fragmentLength = 0;
287 }
288
289 if ( showpackets->integer ) {
290 if ( fragmented ) {
291 Com_Printf( "%s recv %4i : s=%i fragment=%i,%i\n"
292 , netsrcString[ chan->sock ]
293 , msg->cursize
294 , sequence
295 , fragmentStart, fragmentLength );
296 } else {
297 Com_Printf( "%s recv %4i : s=%i\n"
298 , netsrcString[ chan->sock ]
299 , msg->cursize
300 , sequence );
301 }
302 }
303
304 //
305 // discard out of order or duplicated packets
306 //
307 if ( sequence <= chan->incomingSequence ) {
308 if ( showdrop->integer || showpackets->integer ) {
309 Com_Printf( "%s:Out of order packet %i at %i\n"
310 , NET_AdrToString( chan->remoteAddress )
311 , sequence
312 , chan->incomingSequence );
313 }
314 return qfalse;
315 }
316
317 //
318 // dropped packets don't keep the message from being used
319 //
320 chan->dropped = sequence - (chan->incomingSequence+1);
321 if ( chan->dropped > 0 ) {
322 if ( showdrop->integer || showpackets->integer ) {
323 Com_Printf( "%s:Dropped %i packets at %i\n"
324 , NET_AdrToString( chan->remoteAddress )
325 , chan->dropped
326 , sequence );
327 }
328 }
329
330
331 //
332 // if this is the final framgent of a reliable message,
333 // bump incoming_reliable_sequence
334 //
335 if ( fragmented ) {
336 // TTimo
337 // make sure we add the fragments in correct order
338 // either a packet was dropped, or we received this one too soon
339 // we don't reconstruct the fragments. we will wait till this fragment gets to us again
340 // (NOTE: we could probably try to rebuild by out of order chunks if needed)
341 if ( sequence != chan->fragmentSequence ) {
342 chan->fragmentSequence = sequence;
343 chan->fragmentLength = 0;
344 }
345
346 // if we missed a fragment, dump the message
347 if ( fragmentStart != chan->fragmentLength ) {
348 if ( showdrop->integer || showpackets->integer ) {
349 Com_Printf( "%s:Dropped a message fragment\n"
350 , NET_AdrToString( chan->remoteAddress ));
351 }
352 // we can still keep the part that we have so far,
353 // so we don't need to clear chan->fragmentLength
354 return qfalse;
355 }
356
357 // copy the fragment to the fragment buffer
358 if ( fragmentLength < 0 || msg->readcount + fragmentLength > msg->cursize ||
359 chan->fragmentLength + fragmentLength > sizeof( chan->fragmentBuffer ) ) {
360 if ( showdrop->integer || showpackets->integer ) {
361 Com_Printf ("%s:illegal fragment length\n"
362 , NET_AdrToString (chan->remoteAddress ) );
363 }
364 return qfalse;
365 }
366
367 Com_Memcpy( chan->fragmentBuffer + chan->fragmentLength,
368 msg->data + msg->readcount, fragmentLength );
369
370 chan->fragmentLength += fragmentLength;
371
372 // if this wasn't the last fragment, don't process anything
373 if ( fragmentLength == FRAGMENT_SIZE ) {
374 return qfalse;
375 }
376
377 if ( chan->fragmentLength > msg->maxsize ) {
378 Com_Printf( "%s:fragmentLength %i > msg->maxsize\n"
379 , NET_AdrToString (chan->remoteAddress ),
380 chan->fragmentLength );
381 return qfalse;
382 }
383
384 // copy the full message over the partial fragment
385
386 // make sure the sequence number is still there
387 *(int *)msg->data = LittleLong( sequence );
388
389 Com_Memcpy( msg->data + 4, chan->fragmentBuffer, chan->fragmentLength );
390 msg->cursize = chan->fragmentLength + 4;
391 chan->fragmentLength = 0;
392 msg->readcount = 4; // past the sequence number
393 msg->bit = 32; // past the sequence number
394
395 // TTimo
396 // clients were not acking fragmented messages
397 chan->incomingSequence = sequence;
398
399 return qtrue;
400 }
401
402 //
403 // the message can now be read from the current message pointer
404 //
405 chan->incomingSequence = sequence;
406
407 return qtrue;
408 }
409
410
411 //==============================================================================
412
413
414 /*
415 =============================================================================
416
417 LOOPBACK BUFFERS FOR LOCAL PLAYER
418
419 =============================================================================
420 */
421
422 // there needs to be enough loopback messages to hold a complete
423 // gamestate of maximum size
424 #define MAX_LOOPBACK 16
425
426 typedef struct {
427 byte data[MAX_PACKETLEN];
428 int datalen;
429 } loopmsg_t;
430
431 typedef struct {
432 loopmsg_t msgs[MAX_LOOPBACK];
433 int get, send;
434 } loopback_t;
435
436 loopback_t loopbacks[2];
437
438
439 qboolean NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, msg_t *net_message)
440 {
441 int i;
442 loopback_t *loop;
443
444 loop = &loopbacks[sock];
445
446 if (loop->send - loop->get > MAX_LOOPBACK)
447 loop->get = loop->send - MAX_LOOPBACK;
448
449 if (loop->get >= loop->send)
450 return qfalse;
451
452 i = loop->get & (MAX_LOOPBACK-1);
453 loop->get++;
454
455 Com_Memcpy (net_message->data, loop->msgs[i].data, loop->msgs[i].datalen);
456 net_message->cursize = loop->msgs[i].datalen;
457 Com_Memset (net_from, 0, sizeof(*net_from));
458 net_from->type = NA_LOOPBACK;
459 return qtrue;
460
461 }
462
463
464 void NET_SendLoopPacket (netsrc_t sock, int length, const void *data, netadr_t to)
465 {
466 int i;
467 loopback_t *loop;
468
469 loop = &loopbacks[sock^1];
470
471 i = loop->send & (MAX_LOOPBACK-1);
472 loop->send++;
473
474 Com_Memcpy (loop->msgs[i].data, data, length);
475 loop->msgs[i].datalen = length;
476 }
477
478 //=============================================================================
479
480 typedef struct packetQueue_s {
481 struct packetQueue_s *next;
482 int length;
483 byte *data;
484 netadr_t to;
485 int release;
486 } packetQueue_t;
487
488 packetQueue_t *packetQueue = NULL;
489
490 static void NET_QueuePacket( int length, const void *data, netadr_t to,
491 int offset )
492 {
493 packetQueue_t *new, *next = packetQueue;
494
495 if(offset > 999)
496 offset = 999;
497
498 new = S_Malloc(sizeof(packetQueue_t));
499 new->data = S_Malloc(length);
500 Com_Memcpy(new->data, data, length);
501 new->length = length;
502 new->to = to;
503 new->release = Sys_Milliseconds() + (int)((float)offset / com_timescale->value);
504 new->next = NULL;
505
506 if(!packetQueue) {
507 packetQueue = new;
508 return;
509 }
510 while(next) {
511 if(!next->next) {
512 next->next = new;
513 return;
514 }
515 next = next->next;
516 }
517 }
518
519 void NET_FlushPacketQueue(void)
520 {
521 packetQueue_t *last;
522 int now;
523
524 while(packetQueue) {
525 now = Sys_Milliseconds();
526 if(packetQueue->release >= now)
527 break;
528 Sys_SendPacket(packetQueue->length, packetQueue->data,
529 packetQueue->to);
530 last = packetQueue;
531 packetQueue = packetQueue->next;
532 Z_Free(last->data);
533 Z_Free(last);
534 }
535 }
536
537 void NET_SendPacket( netsrc_t sock, int length, const void *data, netadr_t to ) {
538
539 // sequenced packets are shown in netchan, so just show oob
540 if ( showpackets->integer && *(int *)data == -1 ) {
541 Com_Printf ("send packet %4i\n", length);
542 }
543
544 if ( to.type == NA_LOOPBACK ) {
545 NET_SendLoopPacket (sock, length, data, to);
546 return;
547 }
548 if ( to.type == NA_BOT ) {
549 return;
550 }
551 if ( to.type == NA_BAD ) {
552 return;
553 }
554
555 if ( sock == NS_CLIENT && cl_packetdelay->integer > 0 ) {
556 NET_QueuePacket( length, data, to, cl_packetdelay->integer );
557 }
558 else if ( sock == NS_SERVER && sv_packetdelay->integer > 0 ) {
559 NET_QueuePacket( length, data, to, sv_packetdelay->integer );
560 }
561 else {
562 Sys_SendPacket( length, data, to );
563 }
564 }
565
566 /*
567 ===============
568 NET_OutOfBandPrint
569
570 Sends a text message in an out-of-band datagram
571 ================
572 */
573 void QDECL NET_OutOfBandPrint( netsrc_t sock, netadr_t adr, const char *format, ... ) {
574 va_list argptr;
575 char string[MAX_MSGLEN];
576
577
578 // set the header
579 string[0] = -1;
580 string[1] = -1;
581 string[2] = -1;
582 string[3] = -1;
583
584 va_start( argptr, format );
585 Q_vsnprintf( string+4, sizeof(string)-4, format, argptr );
586 va_end( argptr );
587
588 // send the datagram
589 NET_SendPacket( sock, strlen( string ), string, adr );
590 }
591
592 /*
593 ===============
594 NET_OutOfBandPrint
595
596 Sends a data message in an out-of-band datagram (only used for "connect")
597 ================
598 */
599 void QDECL NET_OutOfBandData( netsrc_t sock, netadr_t adr, byte *format, int len ) {
600 byte string[MAX_MSGLEN*2];
601 int i;
602 msg_t mbuf;
603
604 // set the header
605 string[0] = 0xff;
606 string[1] = 0xff;
607 string[2] = 0xff;
608 string[3] = 0xff;
609
610 for(i=0;i<len;i++) {
611 string[i+4] = format[i];
612 }
613
614 mbuf.data = string;
615 mbuf.cursize = len+4;
616 Huff_Compress( &mbuf, 12);
617 // send the datagram
618 NET_SendPacket( sock, mbuf.cursize, mbuf.data, adr );
619 }
620
621 /*
622 =============
623 NET_StringToAdr
624
625 Traps "localhost" for loopback, passes everything else to system
626 return 0 on address not found, 1 on address found with port, 2 on address found without port.
627 =============
628 */
629 int NET_StringToAdr( const char *s, netadr_t *a, netadrtype_t family )
630 {
631 char base[MAX_STRING_CHARS], *search;
632 char *port = NULL;
633
634 if (!strcmp (s, "localhost")) {
635 Com_Memset (a, 0, sizeof(*a));
636 a->type = NA_LOOPBACK;
637 // as NA_LOOPBACK doesn't require ports report port was given.
638 return 1;
639 }
640
641 Q_strncpyz( base, s, sizeof( base ) );
642
643 if(*base == '[' || Q_CountChar(base, ':') > 1)
644 {
645 // This is an ipv6 address, handle it specially.
646 search = strchr(base, ']');
647 if(search)
648 {
649 *search = '\0';
650 search++;
651
652 if(*search == ':')
653 port = search + 1;
654 }
655
656 if(*base == '[')
657 search = base + 1;
658 else
659 search = base;
660 }
661 else
662 {
663 // look for a port number
664 port = strchr( base, ':' );
665
666 if ( port ) {
667 *port = '\0';
668 port++;
669 }
670
671 search = base;
672 }
673
674 if(!Sys_StringToAdr(search, a, family))
675 {
676 a->type = NA_BAD;
677 return 0;
678 }
679
680 if(port)
681 {
682 a->port = BigShort((short) atoi(port));
683 return 1;
684 }
685 else
686 {
687 a->port = BigShort(PORT_SERVER);
688 return 2;
689 }
690 }