20f06c58d9f8fd468a83d3c32bff586f5e570954
[xonotic/darkplaces.git] / net_dgrm.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // net_dgrm.c
21
22 // This is enables a simple IP banning mechanism
23 #define BAN_TEST
24
25 #ifdef BAN_TEST
26 #if defined(_WIN32)
27 #include <windows.h>
28 #elif defined (NeXT)
29 #include <sys/socket.h>
30 #include <arpa/inet.h>
31 #else
32 #define AF_INET                 2       /* internet */
33 struct in_addr
34 {
35         union
36         {
37                 struct { unsigned char s_b1,s_b2,s_b3,s_b4; } S_un_b;
38                 struct { unsigned short s_w1,s_w2; } S_un_w;
39                 unsigned long S_addr;
40         } S_un;
41 };
42 #define s_addr  S_un.S_addr     /* can be used for most tcp & ip code */
43 struct sockaddr_in
44 {
45     short                       sin_family;
46     unsigned short      sin_port;
47         struct in_addr  sin_addr;
48     char                        sin_zero[8];
49 };
50 char *inet_ntoa(struct in_addr in);
51 unsigned long inet_addr(const char *cp);
52 #endif
53 #endif  // BAN_TEST
54
55 #include "quakedef.h"
56 #include "net_dgrm.h"
57
58 cvar_t cl_port = {CVAR_SAVE, "cl_port", "0"};
59
60 // these two macros are to make the code more readable
61 #define sfunc   net_landrivers[sock->landriver]
62 #define dfunc   net_landrivers[net_landriverlevel]
63
64 static int net_landriverlevel;
65
66 /* statistic counters */
67 int     packetsSent = 0;
68 int     packetsReSent = 0;
69 int packetsReceived = 0;
70 int receivedDuplicateCount = 0;
71 int shortPacketCount = 0;
72 int droppedDatagrams;
73
74 static int myDriverLevel;
75
76 struct
77 {
78         unsigned int    length;
79         unsigned int    sequence;
80         qbyte                   data[MAX_DATAGRAM];
81 } packetBuffer;
82
83
84 //#ifdef DEBUG
85 char *StrAddr (struct qsockaddr *addr)
86 {
87         static char buf[34];
88         qbyte *p = (qbyte *)addr;
89         int n;
90
91         for (n = 0; n < 16; n++)
92                 sprintf (buf + n * 2, "%02x", *p++);
93         return buf;
94 }
95 //#endif
96
97
98 #ifdef BAN_TEST
99 unsigned long banAddr = 0x00000000;
100 unsigned long banMask = 0xffffffff;
101
102 void NET_Ban_f (void)
103 {
104         char    addrStr [32];
105         char    maskStr [32];
106         void    (*print) (const char *fmt, ...);
107
108         if (cmd_source == src_command)
109         {
110                 if (!sv.active)
111                 {
112                         Cmd_ForwardToServer ();
113                         return;
114                 }
115                 print = Con_Printf;
116         }
117         else
118         {
119                 if (pr_global_struct->deathmatch)
120                         return;
121                 print = SV_ClientPrintf;
122         }
123
124         switch (Cmd_Argc ())
125         {
126                 case 1:
127                         if (((struct in_addr *)&banAddr)->s_addr)
128                         {
129                                 strcpy(addrStr, inet_ntoa(*(struct in_addr *)&banAddr));
130                                 strcpy(maskStr, inet_ntoa(*(struct in_addr *)&banMask));
131                                 print("Banning %s [%s]\n", addrStr, maskStr);
132                         }
133                         else
134                                 print("Banning not active\n");
135                         break;
136
137                 case 2:
138                         if (Q_strcasecmp(Cmd_Argv(1), "off") == 0)
139                                 banAddr = 0x00000000;
140                         else
141                                 banAddr = inet_addr(Cmd_Argv(1));
142                         banMask = 0xffffffff;
143                         break;
144
145                 case 3:
146                         banAddr = inet_addr(Cmd_Argv(1));
147                         banMask = inet_addr(Cmd_Argv(2));
148                         break;
149
150                 default:
151                         print("BAN ip_address [mask]\n");
152                         break;
153         }
154 }
155 #endif
156
157
158 int Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data)
159 {
160         unsigned int    packetLen;
161         unsigned int    dataLen;
162         unsigned int    eom;
163
164 #ifdef DEBUG
165         if (data->cursize == 0)
166                 Sys_Error("Datagram_SendMessage: zero length message\n");
167
168         if (data->cursize > NET_MAXMESSAGE)
169                 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
170
171         if (sock->canSend == false)
172                 Sys_Error("SendMessage: called with canSend == false\n");
173 #endif
174
175         memcpy(sock->sendMessage, data->data, data->cursize);
176         sock->sendMessageLength = data->cursize;
177
178         if (data->cursize <= MAX_DATAGRAM)
179         {
180                 dataLen = data->cursize;
181                 eom = NETFLAG_EOM;
182         }
183         else
184         {
185                 dataLen = MAX_DATAGRAM;
186                 eom = 0;
187         }
188         packetLen = NET_HEADERSIZE + dataLen;
189
190         packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom));
191         packetBuffer.sequence = BigLong(sock->sendSequence++);
192         memcpy (packetBuffer.data, sock->sendMessage, dataLen);
193
194         sock->canSend = false;
195
196         if (sfunc.Write (sock->socket, (qbyte *)&packetBuffer, packetLen, &sock->addr) == -1)
197                 return -1;
198
199         sock->lastSendTime = net_time;
200         packetsSent++;
201         return 1;
202 }
203
204
205 int SendMessageNext (qsocket_t *sock)
206 {
207         unsigned int    packetLen;
208         unsigned int    dataLen;
209         unsigned int    eom;
210
211         if (sock->sendMessageLength <= MAX_DATAGRAM)
212         {
213                 dataLen = sock->sendMessageLength;
214                 eom = NETFLAG_EOM;
215         }
216         else
217         {
218                 dataLen = MAX_DATAGRAM;
219                 eom = 0;
220         }
221         packetLen = NET_HEADERSIZE + dataLen;
222
223         packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom));
224         packetBuffer.sequence = BigLong(sock->sendSequence++);
225         memcpy (packetBuffer.data, sock->sendMessage, dataLen);
226
227         sock->sendNext = false;
228
229         if (sfunc.Write (sock->socket, (qbyte *)&packetBuffer, packetLen, &sock->addr) == -1)
230                 return -1;
231
232         sock->lastSendTime = net_time;
233         packetsSent++;
234         return 1;
235 }
236
237
238 int ReSendMessage (qsocket_t *sock)
239 {
240         unsigned int    packetLen;
241         unsigned int    dataLen;
242         unsigned int    eom;
243
244         if (sock->sendMessageLength <= MAX_DATAGRAM)
245         {
246                 dataLen = sock->sendMessageLength;
247                 eom = NETFLAG_EOM;
248         }
249         else
250         {
251                 dataLen = MAX_DATAGRAM;
252                 eom = 0;
253         }
254         packetLen = NET_HEADERSIZE + dataLen;
255
256         packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom));
257         packetBuffer.sequence = BigLong(sock->sendSequence - 1);
258         memcpy (packetBuffer.data, sock->sendMessage, dataLen);
259
260         sock->sendNext = false;
261
262         if (sfunc.Write (sock->socket, (qbyte *)&packetBuffer, packetLen, &sock->addr) == -1)
263                 return -1;
264
265         sock->lastSendTime = net_time;
266         packetsReSent++;
267         return 1;
268 }
269
270
271 qboolean Datagram_CanSendMessage (qsocket_t *sock)
272 {
273         if (sock->sendNext)
274                 SendMessageNext (sock);
275
276         return sock->canSend;
277 }
278
279
280 qboolean Datagram_CanSendUnreliableMessage (qsocket_t *sock)
281 {
282         return true;
283 }
284
285
286 int Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data)
287 {
288         int     packetLen;
289
290 #ifdef DEBUG
291         if (data->cursize == 0)
292                 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
293
294         if (data->cursize > MAX_DATAGRAM)
295                 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
296 #endif
297
298         packetLen = NET_HEADERSIZE + data->cursize;
299
300         packetBuffer.length = BigLong(packetLen | NETFLAG_UNRELIABLE);
301         packetBuffer.sequence = BigLong(sock->unreliableSendSequence++);
302         memcpy (packetBuffer.data, data->data, data->cursize);
303
304         if (sfunc.Write (sock->socket, (qbyte *)&packetBuffer, packetLen, &sock->addr) == -1)
305                 return -1;
306
307         packetsSent++;
308         return 1;
309 }
310
311
312 int     Datagram_GetMessage (qsocket_t *sock)
313 {
314         unsigned int    length;
315         unsigned int    flags;
316         int                             ret = 0;
317         struct qsockaddr readaddr;
318         unsigned int    sequence;
319         unsigned int    count;
320
321         if (!sock->canSend)
322                 if ((net_time - sock->lastSendTime) > 1.0)
323                         ReSendMessage (sock);
324
325         while(1)
326         {
327                 length = sfunc.Read (sock->socket, (qbyte *)&packetBuffer, NET_DATAGRAMSIZE, &readaddr);
328
329                 if (length == 0)
330                         break;
331
332                 if (length == -1)
333                 {
334                         Con_Printf("Read error\n");
335                         return -1;
336                 }
337
338                 if (sfunc.AddrCompare(&readaddr, &sock->addr) != 0)
339                 {
340 #ifdef DEBUG
341                         Con_DPrintf("Forged packet received\n");
342                         Con_DPrintf("Expected: %s\n", StrAddr (&sock->addr));
343                         Con_DPrintf("Received: %s\n", StrAddr (&readaddr));
344 #endif
345                         continue;
346                 }
347
348                 if (length < NET_HEADERSIZE)
349                 {
350                         shortPacketCount++;
351                         continue;
352                 }
353
354                 length = BigLong(packetBuffer.length);
355                 flags = length & (~NETFLAG_LENGTH_MASK);
356                 length &= NETFLAG_LENGTH_MASK;
357
358                 if (flags & NETFLAG_CTL)
359                         continue;
360
361                 sequence = BigLong(packetBuffer.sequence);
362                 packetsReceived++;
363
364                 if (flags & NETFLAG_UNRELIABLE)
365                 {
366                         if (sequence < sock->unreliableReceiveSequence)
367                         {
368                                 Con_DPrintf("Got a stale datagram\n");
369                                 ret = 0;
370                                 break;
371                         }
372                         if (sequence != sock->unreliableReceiveSequence)
373                         {
374                                 count = sequence - sock->unreliableReceiveSequence;
375                                 droppedDatagrams += count;
376                                 Con_DPrintf("Dropped %u datagram(s)\n", count);
377                         }
378                         sock->unreliableReceiveSequence = sequence + 1;
379
380                         length -= NET_HEADERSIZE;
381
382                         SZ_Clear (&net_message);
383                         SZ_Write (&net_message, packetBuffer.data, length);
384
385                         ret = 2;
386                         break;
387                 }
388
389                 if (flags & NETFLAG_ACK)
390                 {
391                         if (sequence != (sock->sendSequence - 1))
392                         {
393                                 Con_DPrintf("Stale ACK received\n");
394                                 continue;
395                         }
396                         if (sequence == sock->ackSequence)
397                         {
398                                 sock->ackSequence++;
399                                 if (sock->ackSequence != sock->sendSequence)
400                                         Con_DPrintf("ack sequencing error\n");
401                         }
402                         else
403                         {
404                                 Con_DPrintf("Duplicate ACK received\n");
405                                 continue;
406                         }
407                         sock->sendMessageLength -= MAX_DATAGRAM;
408                         if (sock->sendMessageLength > 0)
409                         {
410                                 memcpy(sock->sendMessage, sock->sendMessage+MAX_DATAGRAM, sock->sendMessageLength);
411                                 sock->sendNext = true;
412                         }
413                         else
414                         {
415                                 sock->sendMessageLength = 0;
416                                 sock->canSend = true;
417                         }
418                         continue;
419                 }
420
421                 if (flags & NETFLAG_DATA)
422                 {
423                         packetBuffer.length = BigLong(NET_HEADERSIZE | NETFLAG_ACK);
424                         packetBuffer.sequence = BigLong(sequence);
425                         sfunc.Write (sock->socket, (qbyte *)&packetBuffer, NET_HEADERSIZE, &readaddr);
426
427                         if (sequence != sock->receiveSequence)
428                         {
429                                 receivedDuplicateCount++;
430                                 continue;
431                         }
432                         sock->receiveSequence++;
433
434                         length -= NET_HEADERSIZE;
435
436                         if (flags & NETFLAG_EOM)
437                         {
438                                 SZ_Clear(&net_message);
439                                 SZ_Write(&net_message, sock->receiveMessage, sock->receiveMessageLength);
440                                 SZ_Write(&net_message, packetBuffer.data, length);
441                                 sock->receiveMessageLength = 0;
442
443                                 ret = 1;
444                                 break;
445                         }
446
447                         memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length);
448                         sock->receiveMessageLength += length;
449                         continue;
450                 }
451         }
452
453         if (sock->sendNext)
454                 SendMessageNext (sock);
455
456         return ret;
457 }
458
459
460 void PrintStats(qsocket_t *s)
461 {
462         Con_Printf("canSend = %4u   \n", s->canSend);
463         Con_Printf("sendSeq = %4u   ", s->sendSequence);
464         Con_Printf("recvSeq = %4u   \n", s->receiveSequence);
465         Con_Printf("\n");
466 }
467
468 void NET_Stats_f (void)
469 {
470         qsocket_t       *s;
471
472         if (Cmd_Argc () == 1)
473         {
474                 Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
475                 Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
476                 Con_Printf("reliable messages sent     = %i\n", messagesSent);
477                 Con_Printf("reliable messages received = %i\n", messagesReceived);
478                 Con_Printf("packetsSent                = %i\n", packetsSent);
479                 Con_Printf("packetsReSent              = %i\n", packetsReSent);
480                 Con_Printf("packetsReceived            = %i\n", packetsReceived);
481                 Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
482                 Con_Printf("shortPacketCount           = %i\n", shortPacketCount);
483                 Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
484         }
485         else if (strcmp(Cmd_Argv(1), "*") == 0)
486         {
487                 for (s = net_activeSockets; s; s = s->next)
488                         PrintStats(s);
489         }
490         else
491         {
492                 for (s = net_activeSockets; s; s = s->next)
493                         if (Q_strcasecmp(Cmd_Argv(1), s->address) == 0)
494                                 break;
495                 if (s == NULL)
496                         return;
497                 PrintStats(s);
498         }
499 }
500
501
502 static qboolean testInProgress = false;
503 static int              testPollCount;
504 static int              testDriver;
505 static int              testSocket;
506
507 static void Test_Poll(void);
508 PollProcedure   testPollProcedure = {NULL, 0.0, Test_Poll};
509
510 static void Test_Poll(void)
511 {
512         struct qsockaddr clientaddr;
513         int             control;
514         int             len;
515         char    name[32];
516         char    address[64];
517         int             colors;
518         int             frags;
519         int             connectTime;
520         qbyte   playerNumber;
521         int             c;
522
523         net_landriverlevel = testDriver;
524
525         while (1)
526         {
527                 len = dfunc.Read (testSocket, net_message.data, net_message.maxsize, &clientaddr);
528                 if (len < sizeof(int))
529                         break;
530
531                 net_message.cursize = len;
532
533                 MSG_BeginReading ();
534                 control = BigLong(*((int *)net_message.data));
535                 MSG_ReadLong();
536                 if (control == -1)
537                         break;
538                 if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
539                         break;
540                 if ((control & NETFLAG_LENGTH_MASK) != len)
541                         break;
542
543                 c = MSG_ReadByte();
544                 if (c != CCREP_PLAYER_INFO)
545                         Sys_Error("Unexpected repsonse to Player Info request\n");
546
547                 playerNumber = MSG_ReadByte();
548                 strcpy(name, MSG_ReadString());
549                 colors = MSG_ReadLong();
550                 frags = MSG_ReadLong();
551                 connectTime = MSG_ReadLong();
552                 strcpy(address, MSG_ReadString());
553
554                 Con_Printf("%s\n  frags:%3i  colors:%u %u  time:%u\n  %s\n", name, frags, colors >> 4, colors & 0x0f, connectTime / 60, address);
555         }
556
557         testPollCount--;
558         if (testPollCount)
559         {
560                 SchedulePollProcedure(&testPollProcedure, 0.1);
561         }
562         else
563         {
564                 dfunc.CloseSocket(testSocket);
565                 testInProgress = false;
566         }
567 }
568
569 static void Test_f (void)
570 {
571         const char *host;
572         int n, max = MAX_SCOREBOARD;
573         struct qsockaddr sendaddr;
574
575         if (testInProgress)
576                 return;
577
578         host = Cmd_Argv (1);
579
580         if (host && hostCacheCount)
581         {
582                 for (n = 0; n < hostCacheCount; n++)
583                         if (Q_strcasecmp (host, hostcache[n].name) == 0)
584                         {
585                                 if (hostcache[n].driver != myDriverLevel)
586                                         continue;
587                                 net_landriverlevel = hostcache[n].ldriver;
588                                 max = hostcache[n].maxusers;
589                                 memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr));
590                                 break;
591                         }
592                 if (n < hostCacheCount)
593                         goto JustDoIt;
594         }
595
596         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
597         {
598                 if (!net_landrivers[net_landriverlevel].initialized)
599                         continue;
600
601                 // see if we can resolve the host name
602                 if (dfunc.GetAddrFromName(host, &sendaddr) != -1)
603                         break;
604         }
605         if (net_landriverlevel == net_numlandrivers)
606                 return;
607
608 JustDoIt:
609         testSocket = dfunc.OpenSocket(0);
610         if (testSocket == -1)
611                 return;
612
613         testInProgress = true;
614         testPollCount = 20;
615         testDriver = net_landriverlevel;
616
617         for (n = 0; n < max; n++)
618         {
619                 SZ_Clear(&net_message);
620                 // save space for the header, filled in later
621                 MSG_WriteLong(&net_message, 0);
622                 MSG_WriteByte(&net_message, CCREQ_PLAYER_INFO);
623                 MSG_WriteByte(&net_message, n);
624                 *((int *)net_message.data) = BigLong(NETFLAG_CTL |      (net_message.cursize & NETFLAG_LENGTH_MASK));
625                 dfunc.Write (testSocket, net_message.data, net_message.cursize, &sendaddr);
626         }
627         SZ_Clear(&net_message);
628         SchedulePollProcedure(&testPollProcedure, 0.1);
629 }
630
631
632 static qboolean test2InProgress = false;
633 static int              test2Driver;
634 static int              test2Socket;
635
636 static void Test2_Poll(void);
637 PollProcedure   test2PollProcedure = {NULL, 0.0, Test2_Poll};
638
639 static void Test2_Poll(void)
640 {
641         struct qsockaddr clientaddr;
642         int             control;
643         int             len;
644         int             c;
645         char    name[256];
646         char    value[256];
647
648         net_landriverlevel = test2Driver;
649         name[0] = 0;
650
651         len = dfunc.Read (test2Socket, net_message.data, net_message.maxsize, &clientaddr);
652         if (len < sizeof(int))
653                 goto Reschedule;
654
655         net_message.cursize = len;
656
657         MSG_BeginReading ();
658         control = BigLong(*((int *)net_message.data));
659         MSG_ReadLong();
660         if (control == -1)
661                 goto Error;
662         if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
663                 goto Error;
664         if ((control & NETFLAG_LENGTH_MASK) != len)
665                 goto Error;
666
667         c = MSG_ReadByte();
668         if (c != CCREP_RULE_INFO)
669                 goto Error;
670
671         strcpy(name, MSG_ReadString());
672         if (name[0] == 0)
673                 goto Done;
674         strcpy(value, MSG_ReadString());
675
676         Con_Printf("%-16.16s  %-16.16s\n", name, value);
677
678         SZ_Clear(&net_message);
679         // save space for the header, filled in later
680         MSG_WriteLong(&net_message, 0);
681         MSG_WriteByte(&net_message, CCREQ_RULE_INFO);
682         MSG_WriteString(&net_message, name);
683         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
684         dfunc.Write (test2Socket, net_message.data, net_message.cursize, &clientaddr);
685         SZ_Clear(&net_message);
686
687 Reschedule:
688         SchedulePollProcedure(&test2PollProcedure, 0.05);
689         return;
690
691 Error:
692         Con_Printf("Unexpected repsonse to Rule Info request\n");
693 Done:
694         dfunc.CloseSocket(test2Socket);
695         test2InProgress = false;
696         return;
697 }
698
699 static void Test2_f (void)
700 {
701         const char *host;
702         int n;
703         struct qsockaddr sendaddr;
704
705         if (test2InProgress)
706                 return;
707
708         host = Cmd_Argv (1);
709
710         if (host && hostCacheCount)
711         {
712                 for (n = 0; n < hostCacheCount; n++)
713                         if (Q_strcasecmp (host, hostcache[n].name) == 0)
714                         {
715                                 if (hostcache[n].driver != myDriverLevel)
716                                         continue;
717                                 net_landriverlevel = hostcache[n].ldriver;
718                                 memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr));
719                                 break;
720                         }
721                 if (n < hostCacheCount)
722                         goto JustDoIt;
723         }
724
725         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
726         {
727                 if (!net_landrivers[net_landriverlevel].initialized)
728                         continue;
729
730                 // see if we can resolve the host name
731                 if (dfunc.GetAddrFromName(host, &sendaddr) != -1)
732                         break;
733         }
734         if (net_landriverlevel == net_numlandrivers)
735                 return;
736
737 JustDoIt:
738         test2Socket = dfunc.OpenSocket(0);
739         if (test2Socket == -1)
740                 return;
741
742         test2InProgress = true;
743         test2Driver = net_landriverlevel;
744
745         SZ_Clear(&net_message);
746         // save space for the header, filled in later
747         MSG_WriteLong(&net_message, 0);
748         MSG_WriteByte(&net_message, CCREQ_RULE_INFO);
749         MSG_WriteString(&net_message, "");
750         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
751         dfunc.Write (test2Socket, net_message.data, net_message.cursize, &sendaddr);
752         SZ_Clear(&net_message);
753         SchedulePollProcedure(&test2PollProcedure, 0.05);
754 }
755
756
757 int Datagram_Init (void)
758 {
759         int i;
760         int csock;
761
762         myDriverLevel = net_driverlevel;
763         Cmd_AddCommand ("net_stats", NET_Stats_f);
764         Cvar_RegisterVariable (&cl_port);
765
766         if (COM_CheckParm("-nolan"))
767                 return -1;
768
769         for (i = 0; i < net_numlandrivers; i++)
770                 {
771                 csock = net_landrivers[i].Init ();
772                 if (csock == -1)
773                         continue;
774                 net_landrivers[i].initialized = true;
775                 net_landrivers[i].controlSock = csock;
776                 }
777
778 #ifdef BAN_TEST
779         Cmd_AddCommand ("ban", NET_Ban_f);
780 #endif
781         Cmd_AddCommand ("test", Test_f);
782         Cmd_AddCommand ("test2", Test2_f);
783
784         return 0;
785 }
786
787
788 void Datagram_Shutdown (void)
789 {
790         int i;
791
792 //
793 // shutdown the lan drivers
794 //
795         for (i = 0; i < net_numlandrivers; i++)
796         {
797                 if (net_landrivers[i].initialized)
798                 {
799                         net_landrivers[i].Shutdown ();
800                         net_landrivers[i].initialized = false;
801                 }
802         }
803 }
804
805
806 void Datagram_Close (qsocket_t *sock)
807 {
808         sfunc.CloseSocket(sock->socket);
809 }
810
811
812 void Datagram_Listen (qboolean state)
813 {
814         int i;
815
816         for (i = 0; i < net_numlandrivers; i++)
817                 if (net_landrivers[i].initialized)
818                         net_landrivers[i].Listen (state);
819 }
820
821
822 static qsocket_t *_Datagram_CheckNewConnections (void)
823 {
824         struct qsockaddr clientaddr;
825         struct qsockaddr newaddr;
826         int                     newsock;
827         int                     acceptsock;
828         qsocket_t       *sock;
829         qsocket_t       *s;
830         int                     len;
831         int                     command;
832         int                     control;
833         int                     ret;
834         int                     c;
835
836         acceptsock = dfunc.CheckNewConnections();
837         if (acceptsock == -1)
838                 return NULL;
839
840         SZ_Clear(&net_message);
841
842         len = dfunc.Read (acceptsock, net_message.data, net_message.maxsize, &clientaddr);
843         if (len < sizeof(int))
844                 return NULL;
845         net_message.cursize = len;
846
847         MSG_BeginReading ();
848         control = BigLong(*((int *)net_message.data));
849         MSG_ReadLong();
850         if (control == -1)
851                 return NULL;
852         if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
853                 return NULL;
854         if ((control & NETFLAG_LENGTH_MASK) != len)
855                 return NULL;
856
857         command = MSG_ReadByte();
858         if (command == CCREQ_SERVER_INFO)
859         {
860                 if (strcmp(MSG_ReadString(), "QUAKE") != 0)
861                         return NULL;
862
863                 SZ_Clear(&net_message);
864                 // save space for the header, filled in later
865                 MSG_WriteLong(&net_message, 0);
866                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
867                 dfunc.GetSocketAddr(acceptsock, &newaddr);
868                 MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr));
869                 MSG_WriteString(&net_message, hostname.string);
870                 MSG_WriteString(&net_message, sv.name);
871                 MSG_WriteByte(&net_message, net_activeconnections);
872                 MSG_WriteByte(&net_message, svs.maxclients);
873                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
874                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
875                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
876                 SZ_Clear(&net_message);
877                 return NULL;
878         }
879
880         if (command == CCREQ_PLAYER_INFO)
881         {
882                 int                     playerNumber;
883                 int                     activeNumber;
884                 int                     clientNumber;
885                 client_t        *client;
886
887                 playerNumber = MSG_ReadByte();
888                 activeNumber = -1;
889                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
890                 {
891                         if (client->active)
892                         {
893                                 activeNumber++;
894                                 if (activeNumber == playerNumber)
895                                         break;
896                         }
897                 }
898                 if (clientNumber == svs.maxclients)
899                         return NULL;
900
901                 SZ_Clear(&net_message);
902                 // save space for the header, filled in later
903                 MSG_WriteLong(&net_message, 0);
904                 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
905                 MSG_WriteByte(&net_message, playerNumber);
906                 MSG_WriteString(&net_message, client->name);
907                 MSG_WriteLong(&net_message, client->colors);
908                 MSG_WriteLong(&net_message, (int)client->edict->v.frags);
909                 MSG_WriteLong(&net_message, (int)(net_time - client->netconnection->connecttime));
910                 MSG_WriteString(&net_message, client->netconnection->address);
911                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
912                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
913                 SZ_Clear(&net_message);
914
915                 return NULL;
916         }
917
918         if (command == CCREQ_RULE_INFO)
919         {
920                 char    *prevCvarName;
921                 cvar_t  *var;
922
923                 // find the search start location
924                 prevCvarName = MSG_ReadString();
925                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
926
927                 // send the response
928
929                 SZ_Clear(&net_message);
930                 // save space for the header, filled in later
931                 MSG_WriteLong(&net_message, 0);
932                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
933                 if (var)
934                 {
935                         MSG_WriteString(&net_message, var->name);
936                         MSG_WriteString(&net_message, var->string);
937                 }
938                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
939                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
940                 SZ_Clear(&net_message);
941
942                 return NULL;
943         }
944
945         if (command != CCREQ_CONNECT)
946                 return NULL;
947
948         if (strcmp(MSG_ReadString(), "QUAKE") != 0)
949                 return NULL;
950
951         c = MSG_ReadByte();
952         if (c != NET_PROTOCOL_VERSION)
953         {
954                 SZ_Clear(&net_message);
955                 // save space for the header, filled in later
956                 MSG_WriteLong(&net_message, 0);
957                 MSG_WriteByte(&net_message, CCREP_REJECT);
958                 MSG_WriteString(&net_message, "Incompatible version.\n");
959                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
960                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
961                 SZ_Clear(&net_message);
962                 return NULL;
963         }
964
965 #ifdef BAN_TEST
966         // check for a ban
967         if (clientaddr.sa_family == AF_INET)
968         {
969                 unsigned long testAddr;
970                 testAddr = ((struct sockaddr_in *)&clientaddr)->sin_addr.s_addr;
971                 if ((testAddr & banMask) == banAddr)
972                 {
973                         SZ_Clear(&net_message);
974                         // save space for the header, filled in later
975                         MSG_WriteLong(&net_message, 0);
976                         MSG_WriteByte(&net_message, CCREP_REJECT);
977                         MSG_WriteString(&net_message, "You have been banned.\n");
978                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
979                         dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
980                         SZ_Clear(&net_message);
981                         return NULL;
982                 }
983         }
984 #endif
985
986         // see if this guy is already connected
987         for (s = net_activeSockets; s; s = s->next)
988         {
989                 if (s->driver != net_driverlevel)
990                         continue;
991                 ret = dfunc.AddrCompare(&clientaddr, &s->addr);
992                 if (ret >= 0)
993                 {
994                         // is this a duplicate connection reqeust?
995                         if (ret == 0 && net_time - s->connecttime < 2.0)
996                         {
997                                 // yes, so send a duplicate reply
998                                 SZ_Clear(&net_message);
999                                 // save space for the header, filled in later
1000                                 MSG_WriteLong(&net_message, 0);
1001                                 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1002                                 dfunc.GetSocketAddr(s->socket, &newaddr);
1003                                 MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr));
1004                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1005                                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
1006                                 SZ_Clear(&net_message);
1007                                 return NULL;
1008                         }
1009                         // it's somebody coming back in from a crash/disconnect
1010                         // so close the old qsocket and let their retry get them back in
1011                         NET_Close(s);
1012                         return NULL;
1013                 }
1014         }
1015
1016         // allocate a QSocket
1017         sock = NET_NewQSocket ();
1018         if (sock == NULL)
1019         {
1020                 // no room; try to let him know
1021                 SZ_Clear(&net_message);
1022                 // save space for the header, filled in later
1023                 MSG_WriteLong(&net_message, 0);
1024                 MSG_WriteByte(&net_message, CCREP_REJECT);
1025                 MSG_WriteString(&net_message, "Server is full.\n");
1026                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1027                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
1028                 SZ_Clear(&net_message);
1029                 return NULL;
1030         }
1031
1032         // allocate a network socket
1033         newsock = dfunc.OpenSocket(0);
1034         if (newsock == -1)
1035         {
1036                 NET_FreeQSocket(sock);
1037                 return NULL;
1038         }
1039
1040         // connect to the client
1041         if (dfunc.Connect (newsock, &clientaddr) == -1)
1042         {
1043                 dfunc.CloseSocket(newsock);
1044                 NET_FreeQSocket(sock);
1045                 return NULL;
1046         }
1047
1048         // everything is allocated, just fill in the details
1049         sock->socket = newsock;
1050         sock->landriver = net_landriverlevel;
1051         sock->addr = clientaddr;
1052         strcpy(sock->address, dfunc.AddrToString(&clientaddr));
1053
1054         // send him back the info about the server connection he has been allocated
1055         SZ_Clear(&net_message);
1056         // save space for the header, filled in later
1057         MSG_WriteLong(&net_message, 0);
1058         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1059         dfunc.GetSocketAddr(newsock, &newaddr);
1060         MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr));
1061         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1062         dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
1063         SZ_Clear(&net_message);
1064
1065         return sock;
1066 }
1067
1068 qsocket_t *Datagram_CheckNewConnections (void)
1069 {
1070         qsocket_t *ret = NULL;
1071
1072         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
1073                 if (net_landrivers[net_landriverlevel].initialized)
1074                         if ((ret = _Datagram_CheckNewConnections ()) != NULL)
1075                                 break;
1076         return ret;
1077 }
1078
1079
1080 static void _Datagram_SearchForHosts (qboolean xmit)
1081 {
1082         int             ret;
1083         int             n;
1084         int             i;
1085         struct qsockaddr readaddr;
1086         struct qsockaddr myaddr;
1087         int             control;
1088         int             c;
1089
1090         dfunc.GetSocketAddr (dfunc.controlSock, &myaddr);
1091         if (xmit)
1092         {
1093                 SZ_Clear(&net_message);
1094                 // save space for the header, filled in later
1095                 MSG_WriteLong(&net_message, 0);
1096                 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1097                 MSG_WriteString(&net_message, "QUAKE");
1098                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1099                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1100                 dfunc.Broadcast(dfunc.controlSock, net_message.data, net_message.cursize);
1101                 SZ_Clear(&net_message);
1102         }
1103
1104         while ((ret = dfunc.Read (dfunc.controlSock, net_message.data, net_message.maxsize, &readaddr)) > 0)
1105         {
1106                 if (ret < sizeof(int))
1107                         continue;
1108                 net_message.cursize = ret;
1109
1110                 // don't answer our own query
1111                 if (dfunc.AddrCompare(&readaddr, &myaddr) >= 0)
1112                         continue;
1113
1114                 // is the cache full?
1115                 if (hostCacheCount == HOSTCACHESIZE)
1116                         continue;
1117
1118                 MSG_BeginReading ();
1119                 control = BigLong(*((int *)net_message.data));
1120                 MSG_ReadLong();
1121                 if (control == -1)
1122                         continue;
1123                 if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
1124                         continue;
1125                 if ((control & NETFLAG_LENGTH_MASK) != ret)
1126                         continue;
1127
1128                 c = MSG_ReadByte();
1129                 if (c != CCREP_SERVER_INFO)
1130                         continue;
1131
1132                 dfunc.GetAddrFromName(MSG_ReadString(), &readaddr);
1133                 // search the cache for this server
1134                 for (n = 0; n < hostCacheCount; n++)
1135                         if (dfunc.AddrCompare(&readaddr, &hostcache[n].addr) == 0)
1136                                 break;
1137
1138                 // is it already there?
1139                 if (n < hostCacheCount)
1140                         continue;
1141
1142                 // add it
1143                 hostCacheCount++;
1144                 strcpy(hostcache[n].name, MSG_ReadString());
1145                 strcpy(hostcache[n].map, MSG_ReadString());
1146                 hostcache[n].users = MSG_ReadByte();
1147                 hostcache[n].maxusers = MSG_ReadByte();
1148                 c = MSG_ReadByte();
1149                 if (c != NET_PROTOCOL_VERSION)
1150                 {
1151                         strcpy(hostcache[n].cname, hostcache[n].name);
1152                         hostcache[n].cname[14] = 0;
1153                         strcpy(hostcache[n].name, "*");
1154                         strcat(hostcache[n].name, hostcache[n].cname);
1155                 }
1156                 memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr));
1157                 hostcache[n].driver = net_driverlevel;
1158                 hostcache[n].ldriver = net_landriverlevel;
1159                 strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr));
1160
1161                 // check for a name conflict
1162                 for (i = 0; i < hostCacheCount; i++)
1163                 {
1164                         if (i == n)
1165                                 continue;
1166                         if (Q_strcasecmp (hostcache[n].name, hostcache[i].name) == 0)
1167                         {
1168                                 i = strlen(hostcache[n].name);
1169                                 if (i < 15 && hostcache[n].name[i-1] > '8')
1170                                 {
1171                                         hostcache[n].name[i] = '0';
1172                                         hostcache[n].name[i+1] = 0;
1173                                 }
1174                                 else
1175                                         hostcache[n].name[i-1]++;
1176                                 i = -1;
1177                         }
1178                 }
1179         }
1180 }
1181
1182 void Datagram_SearchForHosts (qboolean xmit)
1183 {
1184         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
1185         {
1186                 if (hostCacheCount == HOSTCACHESIZE)
1187                         break;
1188                 if (net_landrivers[net_landriverlevel].initialized)
1189                         _Datagram_SearchForHosts (xmit);
1190         }
1191 }
1192
1193
1194 static qsocket_t *_Datagram_Connect (char *host)
1195 {
1196         struct qsockaddr sendaddr;
1197         struct qsockaddr readaddr;
1198         qsocket_t       *sock;
1199         int                     newsock;
1200         int                     ret;
1201         int                     reps;
1202         double          start_time;
1203         int                     control;
1204         char            *reason;
1205
1206         // see if we can resolve the host name
1207         if (dfunc.GetAddrFromName(host, &sendaddr) == -1)
1208                 return NULL;
1209
1210         newsock = dfunc.OpenSocket (cl_port.integer);
1211         if (newsock == -1)
1212                 return NULL;
1213
1214         sock = NET_NewQSocket ();
1215         if (sock == NULL)
1216                 goto ErrorReturn2;
1217         sock->socket = newsock;
1218         sock->landriver = net_landriverlevel;
1219
1220         // connect to the host
1221         if (dfunc.Connect (newsock, &sendaddr) == -1)
1222                 goto ErrorReturn;
1223
1224         // send the connection request
1225         Con_Printf("trying...\n");CL_UpdateScreen();CL_UpdateScreen();
1226         start_time = net_time;
1227
1228         for (reps = 0; reps < 3; reps++)
1229         {
1230                 SZ_Clear(&net_message);
1231                 // save space for the header, filled in later
1232                 MSG_WriteLong(&net_message, 0);
1233                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1234                 MSG_WriteString(&net_message, "QUAKE");
1235                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1236                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1237                 dfunc.Write (newsock, net_message.data, net_message.cursize, &sendaddr);
1238                 SZ_Clear(&net_message);
1239                 do
1240                 {
1241                         ret = dfunc.Read (newsock, net_message.data, net_message.maxsize, &readaddr);
1242                         // if we got something, validate it
1243                         if (ret > 0)
1244                         {
1245                                 // is it from the right place?
1246                                 if (sfunc.AddrCompare(&readaddr, &sendaddr) != 0)
1247                                 {
1248                                         Con_DPrintf("wrong reply address\n");
1249                                         Con_DPrintf("Expected: %s\n", StrAddr (&sendaddr));
1250                                         Con_DPrintf("Received: %s\n", StrAddr (&readaddr));
1251                                         CL_UpdateScreen ();
1252                                         ret = 0;
1253                                         continue;
1254                                 }
1255
1256                                 if (ret < sizeof(int))
1257                                 {
1258                                         ret = 0;
1259                                         continue;
1260                                 }
1261
1262                                 net_message.cursize = ret;
1263                                 MSG_BeginReading ();
1264
1265                                 control = BigLong(*((int *)net_message.data));
1266                                 MSG_ReadLong();
1267                                 if (control == -1)
1268                                 {
1269                                         ret = 0;
1270                                         continue;
1271                                 }
1272                                 if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
1273                                 {
1274                                         ret = 0;
1275                                         continue;
1276                                 }
1277                                 if ((control & NETFLAG_LENGTH_MASK) != ret)
1278                                 {
1279                                         ret = 0;
1280                                         continue;
1281                                 }
1282                         }
1283                 }
1284                 while (ret == 0 && (SetNetTime() - start_time) < 2.5);
1285                 if (ret)
1286                         break;
1287                 Con_Printf("still trying...\n");CL_UpdateScreen();CL_UpdateScreen();
1288                 start_time = SetNetTime();
1289         }
1290
1291         if (ret == 0)
1292         {
1293                 reason = "No Response";
1294                 Con_Printf("%s\n", reason);
1295                 strcpy(m_return_reason, reason);
1296                 goto ErrorReturn;
1297         }
1298
1299         if (ret == -1)
1300         {
1301                 reason = "Network Error";
1302                 Con_Printf("%s\n", reason);
1303                 strcpy(m_return_reason, reason);
1304                 goto ErrorReturn;
1305         }
1306
1307         ret = MSG_ReadByte();
1308         if (ret == CCREP_REJECT)
1309         {
1310                 reason = MSG_ReadString();
1311                 Con_Printf("%s", reason);
1312                 strncpy(m_return_reason, reason, 31);
1313                 goto ErrorReturn;
1314         }
1315
1316         if (ret == CCREP_ACCEPT)
1317         {
1318                 memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr));
1319                 dfunc.SetSocketPort (&sock->addr, MSG_ReadLong());
1320         }
1321         else
1322         {
1323                 reason = "Bad Response";
1324                 Con_Printf("%s\n", reason);
1325                 strcpy(m_return_reason, reason);
1326                 goto ErrorReturn;
1327         }
1328
1329         dfunc.GetNameFromAddr (&sendaddr, sock->address);
1330
1331         Con_Printf ("Connection accepted to %s\n", sock->address);
1332         sock->lastMessageTime = SetNetTime();
1333
1334         // switch the connection to the specified address
1335         if (dfunc.Connect (newsock, &sock->addr) == -1)
1336         {
1337                 reason = "Connect to Game failed";
1338                 Con_Printf("%s\n", reason);
1339                 strcpy(m_return_reason, reason);
1340                 goto ErrorReturn;
1341         }
1342
1343         m_return_onerror = false;
1344         return sock;
1345
1346 ErrorReturn:
1347         NET_FreeQSocket(sock);
1348 ErrorReturn2:
1349         dfunc.CloseSocket(newsock);
1350         if (m_return_onerror)
1351         {
1352                 key_dest = key_menu;
1353                 m_state = m_return_state;
1354                 m_return_onerror = false;
1355         }
1356         return NULL;
1357 }
1358
1359 qsocket_t *Datagram_Connect (char *host)
1360 {
1361         qsocket_t *ret = NULL;
1362
1363         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
1364                 if (net_landrivers[net_landriverlevel].initialized)
1365                         if ((ret = _Datagram_Connect (host)) != NULL)
1366                                 break;
1367         return ret;
1368 }
1369