added in_pitch_min and in_pitch_max cvars to limit pitch (default: -90 to +90)
[divverent/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         byte                    data[MAX_DATAGRAM];
81 } packetBuffer;
82
83
84 //#ifdef DEBUG
85 char *StrAddr (struct qsockaddr *addr)
86 {
87         static char buf[34];
88         byte *p = (byte *)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) (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, (byte *)&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, (byte *)&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, (byte *)&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, (byte *)&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, (byte *)&packetBuffer, NET_DATAGRAMSIZE, &readaddr);
328
329 //      if ((rand() & 255) > 220)
330 //              continue;
331
332                 if (length == 0)
333                         break;
334
335                 if (length == -1)
336                 {
337                         Con_Printf("Read error\n");
338                         return -1;
339                 }
340
341                 if (sfunc.AddrCompare(&readaddr, &sock->addr) != 0)
342                 {
343 #ifdef DEBUG
344                         Con_DPrintf("Forged packet received\n");
345                         Con_DPrintf("Expected: %s\n", StrAddr (&sock->addr));
346                         Con_DPrintf("Received: %s\n", StrAddr (&readaddr));
347 #endif
348                         continue;
349                 }
350
351                 if (length < NET_HEADERSIZE)
352                 {
353                         shortPacketCount++;
354                         continue;
355                 }
356
357                 length = BigLong(packetBuffer.length);
358                 flags = length & (~NETFLAG_LENGTH_MASK);
359                 length &= NETFLAG_LENGTH_MASK;
360
361                 if (flags & NETFLAG_CTL)
362                         continue;
363
364                 sequence = BigLong(packetBuffer.sequence);
365                 packetsReceived++;
366
367                 if (flags & NETFLAG_UNRELIABLE)
368                 {
369                         if (sequence < sock->unreliableReceiveSequence)
370                         {
371                                 Con_DPrintf("Got a stale datagram\n");
372                                 ret = 0;
373                                 break;
374                         }
375                         if (sequence != sock->unreliableReceiveSequence)
376                         {
377                                 count = sequence - sock->unreliableReceiveSequence;
378                                 droppedDatagrams += count;
379                                 Con_DPrintf("Dropped %u datagram(s)\n", count);
380                         }
381                         sock->unreliableReceiveSequence = sequence + 1;
382
383                         length -= NET_HEADERSIZE;
384
385                         SZ_Clear (&net_message);
386                         SZ_Write (&net_message, packetBuffer.data, length);
387
388                         ret = 2;
389                         break;
390                 }
391
392                 if (flags & NETFLAG_ACK)
393                 {
394                         if (sequence != (sock->sendSequence - 1))
395                         {
396                                 Con_DPrintf("Stale ACK received\n");
397                                 continue;
398                         }
399                         if (sequence == sock->ackSequence)
400                         {
401                                 sock->ackSequence++;
402                                 if (sock->ackSequence != sock->sendSequence)
403                                         Con_DPrintf("ack sequencing error\n");
404                         }
405                         else
406                         {
407                                 Con_DPrintf("Duplicate ACK received\n");
408                                 continue;
409                         }
410                         sock->sendMessageLength -= MAX_DATAGRAM;
411                         if (sock->sendMessageLength > 0)
412                         {
413                                 memcpy(sock->sendMessage, sock->sendMessage+MAX_DATAGRAM, sock->sendMessageLength);
414                                 sock->sendNext = true;
415                         }
416                         else
417                         {
418                                 sock->sendMessageLength = 0;
419                                 sock->canSend = true;
420                         }
421                         continue;
422                 }
423
424                 if (flags & NETFLAG_DATA)
425                 {
426                         packetBuffer.length = BigLong(NET_HEADERSIZE | NETFLAG_ACK);
427                         packetBuffer.sequence = BigLong(sequence);
428                         sfunc.Write (sock->socket, (byte *)&packetBuffer, NET_HEADERSIZE, &readaddr);
429
430                         if (sequence != sock->receiveSequence)
431                         {
432                                 receivedDuplicateCount++;
433                                 continue;
434                         }
435                         sock->receiveSequence++;
436
437                         length -= NET_HEADERSIZE;
438
439                         if (flags & NETFLAG_EOM)
440                         {
441                                 SZ_Clear(&net_message);
442                                 SZ_Write(&net_message, sock->receiveMessage, sock->receiveMessageLength);
443                                 SZ_Write(&net_message, packetBuffer.data, length);
444                                 sock->receiveMessageLength = 0;
445
446                                 ret = 1;
447                                 break;
448                         }
449
450                         memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length);
451                         sock->receiveMessageLength += length;
452                         continue;
453                 }
454         }
455
456         if (sock->sendNext)
457                 SendMessageNext (sock);
458
459         return ret;
460 }
461
462
463 void PrintStats(qsocket_t *s)
464 {
465         Con_Printf("canSend = %4u   \n", s->canSend);
466         Con_Printf("sendSeq = %4u   ", s->sendSequence);
467         Con_Printf("recvSeq = %4u   \n", s->receiveSequence);
468         Con_Printf("\n");
469 }
470
471 void NET_Stats_f (void)
472 {
473         qsocket_t       *s;
474
475         if (Cmd_Argc () == 1)
476         {
477                 Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
478                 Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
479                 Con_Printf("reliable messages sent     = %i\n", messagesSent);
480                 Con_Printf("reliable messages received = %i\n", messagesReceived);
481                 Con_Printf("packetsSent                = %i\n", packetsSent);
482                 Con_Printf("packetsReSent              = %i\n", packetsReSent);
483                 Con_Printf("packetsReceived            = %i\n", packetsReceived);
484                 Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
485                 Con_Printf("shortPacketCount           = %i\n", shortPacketCount);
486                 Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
487         }
488         else if (strcmp(Cmd_Argv(1), "*") == 0)
489         {
490                 for (s = net_activeSockets; s; s = s->next)
491                         PrintStats(s);
492                 // LordHavoc: sockets are dynamically allocated now
493                 //for (s = net_freeSockets; s; s = s->next)
494                 //      PrintStats(s);
495         }
496         else
497         {
498                 for (s = net_activeSockets; s; s = s->next)
499                         if (Q_strcasecmp(Cmd_Argv(1), s->address) == 0)
500                                 break;
501                 // LordHavoc: sockets are dynamically allocated now
502                 //if (s == NULL)
503                 //      for (s = net_freeSockets; s; s = s->next)
504                 //              if (Q_strcasecmp(Cmd_Argv(1), s->address) == 0)
505                 //                      break;
506                 if (s == NULL)
507                         return;
508                 PrintStats(s);
509         }
510 }
511
512
513 static qboolean testInProgress = false;
514 static int              testPollCount;
515 static int              testDriver;
516 static int              testSocket;
517
518 static void Test_Poll(void);
519 PollProcedure   testPollProcedure = {NULL, 0.0, Test_Poll};
520
521 static void Test_Poll(void)
522 {
523         struct qsockaddr clientaddr;
524         int             control;
525         int             len;
526         char    name[32];
527         char    address[64];
528         int             colors;
529         int             frags;
530         int             connectTime;
531         byte    playerNumber;
532
533         net_landriverlevel = testDriver;
534
535         while (1)
536         {
537                 len = dfunc.Read (testSocket, net_message.data, net_message.maxsize, &clientaddr);
538                 if (len < sizeof(int))
539                         break;
540
541                 net_message.cursize = len;
542
543                 MSG_BeginReading ();
544                 control = BigLong(*((int *)net_message.data));
545                 MSG_ReadLong();
546                 if (control == -1)
547                         break;
548                 if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
549                         break;
550                 if ((control & NETFLAG_LENGTH_MASK) != len)
551                         break;
552
553                 if (MSG_ReadByte() != CCREP_PLAYER_INFO)
554                         Sys_Error("Unexpected repsonse to Player Info request\n");
555
556                 playerNumber = MSG_ReadByte();
557                 strcpy(name, MSG_ReadString());
558                 colors = MSG_ReadLong();
559                 frags = MSG_ReadLong();
560                 connectTime = MSG_ReadLong();
561                 strcpy(address, MSG_ReadString());
562
563                 Con_Printf("%s\n  frags:%3i  colors:%u %u  time:%u\n  %s\n", name, frags, colors >> 4, colors & 0x0f, connectTime / 60, address);
564         }
565
566         testPollCount--;
567         if (testPollCount)
568         {
569                 SchedulePollProcedure(&testPollProcedure, 0.1);
570         }
571         else
572         {
573                 dfunc.CloseSocket(testSocket);
574                 testInProgress = false;
575         }
576 }
577
578 static void Test_f (void)
579 {
580         char    *host;
581         int             n;
582         int             max = MAX_SCOREBOARD;
583         struct qsockaddr sendaddr;
584
585         if (testInProgress)
586                 return;
587
588         host = Cmd_Argv (1);
589
590         if (host && hostCacheCount)
591         {
592                 for (n = 0; n < hostCacheCount; n++)
593                         if (Q_strcasecmp (host, hostcache[n].name) == 0)
594                         {
595                                 if (hostcache[n].driver != myDriverLevel)
596                                         continue;
597                                 net_landriverlevel = hostcache[n].ldriver;
598                                 max = hostcache[n].maxusers;
599                                 memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr));
600                                 break;
601                         }
602                 if (n < hostCacheCount)
603                         goto JustDoIt;
604         }
605
606         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
607         {
608                 if (!net_landrivers[net_landriverlevel].initialized)
609                         continue;
610
611                 // see if we can resolve the host name
612                 if (dfunc.GetAddrFromName(host, &sendaddr) != -1)
613                         break;
614         }
615         if (net_landriverlevel == net_numlandrivers)
616                 return;
617
618 JustDoIt:
619         testSocket = dfunc.OpenSocket(0);
620         if (testSocket == -1)
621                 return;
622
623         testInProgress = true;
624         testPollCount = 20;
625         testDriver = net_landriverlevel;
626
627         for (n = 0; n < max; n++)
628         {
629                 SZ_Clear(&net_message);
630                 // save space for the header, filled in later
631                 MSG_WriteLong(&net_message, 0);
632                 MSG_WriteByte(&net_message, CCREQ_PLAYER_INFO);
633                 MSG_WriteByte(&net_message, n);
634                 *((int *)net_message.data) = BigLong(NETFLAG_CTL |      (net_message.cursize & NETFLAG_LENGTH_MASK));
635                 dfunc.Write (testSocket, net_message.data, net_message.cursize, &sendaddr);
636         }
637         SZ_Clear(&net_message);
638         SchedulePollProcedure(&testPollProcedure, 0.1);
639 }
640
641
642 static qboolean test2InProgress = false;
643 static int              test2Driver;
644 static int              test2Socket;
645
646 static void Test2_Poll(void);
647 PollProcedure   test2PollProcedure = {NULL, 0.0, Test2_Poll};
648
649 static void Test2_Poll(void)
650 {
651         struct qsockaddr clientaddr;
652         int             control;
653         int             len;
654         char    name[256];
655         char    value[256];
656
657         net_landriverlevel = test2Driver;
658         name[0] = 0;
659
660         len = dfunc.Read (test2Socket, net_message.data, net_message.maxsize, &clientaddr);
661         if (len < sizeof(int))
662                 goto Reschedule;
663
664         net_message.cursize = len;
665
666         MSG_BeginReading ();
667         control = BigLong(*((int *)net_message.data));
668         MSG_ReadLong();
669         if (control == -1)
670                 goto Error;
671         if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
672                 goto Error;
673         if ((control & NETFLAG_LENGTH_MASK) != len)
674                 goto Error;
675
676         if (MSG_ReadByte() != CCREP_RULE_INFO)
677                 goto Error;
678
679         strcpy(name, MSG_ReadString());
680         if (name[0] == 0)
681                 goto Done;
682         strcpy(value, MSG_ReadString());
683
684         Con_Printf("%-16.16s  %-16.16s\n", name, value);
685
686         SZ_Clear(&net_message);
687         // save space for the header, filled in later
688         MSG_WriteLong(&net_message, 0);
689         MSG_WriteByte(&net_message, CCREQ_RULE_INFO);
690         MSG_WriteString(&net_message, name);
691         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
692         dfunc.Write (test2Socket, net_message.data, net_message.cursize, &clientaddr);
693         SZ_Clear(&net_message);
694
695 Reschedule:
696         SchedulePollProcedure(&test2PollProcedure, 0.05);
697         return;
698
699 Error:
700         Con_Printf("Unexpected repsonse to Rule Info request\n");
701 Done:
702         dfunc.CloseSocket(test2Socket);
703         test2InProgress = false;
704         return;
705 }
706
707 static void Test2_f (void)
708 {
709         char    *host;
710         int             n;
711         struct qsockaddr sendaddr;
712
713         if (test2InProgress)
714                 return;
715
716         host = Cmd_Argv (1);
717
718         if (host && hostCacheCount)
719         {
720                 for (n = 0; n < hostCacheCount; n++)
721                         if (Q_strcasecmp (host, hostcache[n].name) == 0)
722                         {
723                                 if (hostcache[n].driver != myDriverLevel)
724                                         continue;
725                                 net_landriverlevel = hostcache[n].ldriver;
726                                 memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr));
727                                 break;
728                         }
729                 if (n < hostCacheCount)
730                         goto JustDoIt;
731         }
732
733         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
734         {
735                 if (!net_landrivers[net_landriverlevel].initialized)
736                         continue;
737
738                 // see if we can resolve the host name
739                 if (dfunc.GetAddrFromName(host, &sendaddr) != -1)
740                         break;
741         }
742         if (net_landriverlevel == net_numlandrivers)
743                 return;
744
745 JustDoIt:
746         test2Socket = dfunc.OpenSocket(0);
747         if (test2Socket == -1)
748                 return;
749
750         test2InProgress = true;
751         test2Driver = net_landriverlevel;
752
753         SZ_Clear(&net_message);
754         // save space for the header, filled in later
755         MSG_WriteLong(&net_message, 0);
756         MSG_WriteByte(&net_message, CCREQ_RULE_INFO);
757         MSG_WriteString(&net_message, "");
758         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
759         dfunc.Write (test2Socket, net_message.data, net_message.cursize, &sendaddr);
760         SZ_Clear(&net_message);
761         SchedulePollProcedure(&test2PollProcedure, 0.05);
762 }
763
764
765 int Datagram_Init (void)
766 {
767         int i;
768         int csock;
769
770         myDriverLevel = net_driverlevel;
771         Cmd_AddCommand ("net_stats", NET_Stats_f);
772         Cvar_RegisterVariable (&cl_port);
773
774         if (COM_CheckParm("-nolan"))
775                 return -1;
776
777         for (i = 0; i < net_numlandrivers; i++)
778                 {
779                 csock = net_landrivers[i].Init ();
780                 if (csock == -1)
781                         continue;
782                 net_landrivers[i].initialized = true;
783                 net_landrivers[i].controlSock = csock;
784                 }
785
786 #ifdef BAN_TEST
787         Cmd_AddCommand ("ban", NET_Ban_f);
788 #endif
789         Cmd_AddCommand ("test", Test_f);
790         Cmd_AddCommand ("test2", Test2_f);
791
792         return 0;
793 }
794
795
796 void Datagram_Shutdown (void)
797 {
798         int i;
799
800 //
801 // shutdown the lan drivers
802 //
803         for (i = 0; i < net_numlandrivers; i++)
804         {
805                 if (net_landrivers[i].initialized)
806                 {
807                         net_landrivers[i].Shutdown ();
808                         net_landrivers[i].initialized = false;
809                 }
810         }
811 }
812
813
814 void Datagram_Close (qsocket_t *sock)
815 {
816         sfunc.CloseSocket(sock->socket);
817 }
818
819
820 void Datagram_Listen (qboolean state)
821 {
822         int i;
823
824         for (i = 0; i < net_numlandrivers; i++)
825                 if (net_landrivers[i].initialized)
826                         net_landrivers[i].Listen (state);
827 }
828
829
830 static qsocket_t *_Datagram_CheckNewConnections (void)
831 {
832         struct qsockaddr clientaddr;
833         struct qsockaddr newaddr;
834         int                     newsock;
835         int                     acceptsock;
836         qsocket_t       *sock;
837         qsocket_t       *s;
838         int                     len;
839         int                     command;
840         int                     control;
841         int                     ret;
842
843         acceptsock = dfunc.CheckNewConnections();
844         if (acceptsock == -1)
845                 return NULL;
846
847         SZ_Clear(&net_message);
848
849         len = dfunc.Read (acceptsock, net_message.data, net_message.maxsize, &clientaddr);
850         if (len < sizeof(int))
851                 return NULL;
852         net_message.cursize = len;
853
854         MSG_BeginReading ();
855         control = BigLong(*((int *)net_message.data));
856         MSG_ReadLong();
857         if (control == -1)
858                 return NULL;
859         if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
860                 return NULL;
861         if ((control & NETFLAG_LENGTH_MASK) != len)
862                 return NULL;
863
864         command = MSG_ReadByte();
865         if (command == CCREQ_SERVER_INFO)
866         {
867                 if (strcmp(MSG_ReadString(), "QUAKE") != 0)
868                         return NULL;
869
870                 SZ_Clear(&net_message);
871                 // save space for the header, filled in later
872                 MSG_WriteLong(&net_message, 0);
873                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
874                 dfunc.GetSocketAddr(acceptsock, &newaddr);
875                 MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr));
876                 MSG_WriteString(&net_message, hostname.string);
877                 MSG_WriteString(&net_message, sv.name);
878                 MSG_WriteByte(&net_message, net_activeconnections);
879                 MSG_WriteByte(&net_message, svs.maxclients);
880                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
881                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
882                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
883                 SZ_Clear(&net_message);
884                 return NULL;
885         }
886
887         if (command == CCREQ_PLAYER_INFO)
888         {
889                 int                     playerNumber;
890                 int                     activeNumber;
891                 int                     clientNumber;
892                 client_t        *client;
893
894                 playerNumber = MSG_ReadByte();
895                 activeNumber = -1;
896                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
897                 {
898                         if (client->active)
899                         {
900                                 activeNumber++;
901                                 if (activeNumber == playerNumber)
902                                         break;
903                         }
904                 }
905                 if (clientNumber == svs.maxclients)
906                         return NULL;
907
908                 SZ_Clear(&net_message);
909                 // save space for the header, filled in later
910                 MSG_WriteLong(&net_message, 0);
911                 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
912                 MSG_WriteByte(&net_message, playerNumber);
913                 MSG_WriteString(&net_message, client->name);
914                 MSG_WriteLong(&net_message, client->colors);
915                 MSG_WriteLong(&net_message, (int)client->edict->v.frags);
916                 MSG_WriteLong(&net_message, (int)(net_time - client->netconnection->connecttime));
917                 MSG_WriteString(&net_message, client->netconnection->address);
918                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
919                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
920                 SZ_Clear(&net_message);
921
922                 return NULL;
923         }
924
925         if (command == CCREQ_RULE_INFO)
926         {
927                 char    *prevCvarName;
928                 cvar_t  *var;
929
930                 // find the search start location
931                 prevCvarName = MSG_ReadString();
932                 if (*prevCvarName)
933                 {
934                         var = Cvar_FindVar (prevCvarName);
935                         if (!var)
936                                 return NULL;
937                         var = var->next;
938                 }
939                 else
940                         var = cvar_vars;
941
942                 // search for the next server cvar
943                 while (var)
944                 {
945                         if (var->flags & CVAR_NOTIFY)
946                                 break;
947                         var = var->next;
948                 }
949
950                 // send the response
951
952                 SZ_Clear(&net_message);
953                 // save space for the header, filled in later
954                 MSG_WriteLong(&net_message, 0);
955                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
956                 if (var)
957                 {
958                         MSG_WriteString(&net_message, var->name);
959                         MSG_WriteString(&net_message, var->string);
960                 }
961                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
962                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
963                 SZ_Clear(&net_message);
964
965                 return NULL;
966         }
967
968         if (command != CCREQ_CONNECT)
969                 return NULL;
970
971         if (strcmp(MSG_ReadString(), "QUAKE") != 0)
972                 return NULL;
973
974         if (MSG_ReadByte() != NET_PROTOCOL_VERSION)
975         {
976                 SZ_Clear(&net_message);
977                 // save space for the header, filled in later
978                 MSG_WriteLong(&net_message, 0);
979                 MSG_WriteByte(&net_message, CCREP_REJECT);
980                 MSG_WriteString(&net_message, "Incompatible version.\n");
981                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
982                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
983                 SZ_Clear(&net_message);
984                 return NULL;
985         }
986
987 #ifdef BAN_TEST
988         // check for a ban
989         if (clientaddr.sa_family == AF_INET)
990         {
991                 unsigned long testAddr;
992                 testAddr = ((struct sockaddr_in *)&clientaddr)->sin_addr.s_addr;
993                 if ((testAddr & banMask) == banAddr)
994                 {
995                         SZ_Clear(&net_message);
996                         // save space for the header, filled in later
997                         MSG_WriteLong(&net_message, 0);
998                         MSG_WriteByte(&net_message, CCREP_REJECT);
999                         MSG_WriteString(&net_message, "You have been banned.\n");
1000                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1001                         dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
1002                         SZ_Clear(&net_message);
1003                         return NULL;
1004                 }
1005         }
1006 #endif
1007
1008         // see if this guy is already connected
1009         for (s = net_activeSockets; s; s = s->next)
1010         {
1011                 if (s->driver != net_driverlevel)
1012                         continue;
1013                 ret = dfunc.AddrCompare(&clientaddr, &s->addr);
1014                 if (ret >= 0)
1015                 {
1016                         // is this a duplicate connection reqeust?
1017                         if (ret == 0 && net_time - s->connecttime < 2.0)
1018                         {
1019                                 // yes, so send a duplicate reply
1020                                 SZ_Clear(&net_message);
1021                                 // save space for the header, filled in later
1022                                 MSG_WriteLong(&net_message, 0);
1023                                 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1024                                 dfunc.GetSocketAddr(s->socket, &newaddr);
1025                                 MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr));
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                         // it's somebody coming back in from a crash/disconnect
1032                         // so close the old qsocket and let their retry get them back in
1033                         NET_Close(s);
1034                         return NULL;
1035                 }
1036         }
1037
1038         // allocate a QSocket
1039         sock = NET_NewQSocket ();
1040         if (sock == NULL)
1041         {
1042                 // no room; try to let him know
1043                 SZ_Clear(&net_message);
1044                 // save space for the header, filled in later
1045                 MSG_WriteLong(&net_message, 0);
1046                 MSG_WriteByte(&net_message, CCREP_REJECT);
1047                 MSG_WriteString(&net_message, "Server is full.\n");
1048                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1049                 dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
1050                 SZ_Clear(&net_message);
1051                 return NULL;
1052         }
1053
1054         // allocate a network socket
1055         newsock = dfunc.OpenSocket(0);
1056         if (newsock == -1)
1057         {
1058                 NET_FreeQSocket(sock);
1059                 return NULL;
1060         }
1061
1062         // connect to the client
1063         if (dfunc.Connect (newsock, &clientaddr) == -1)
1064         {
1065                 dfunc.CloseSocket(newsock);
1066                 NET_FreeQSocket(sock);
1067                 return NULL;
1068         }
1069
1070         // everything is allocated, just fill in the details
1071         sock->socket = newsock;
1072         sock->landriver = net_landriverlevel;
1073         sock->addr = clientaddr;
1074         strcpy(sock->address, dfunc.AddrToString(&clientaddr));
1075
1076         // send him back the info about the server connection he has been allocated
1077         SZ_Clear(&net_message);
1078         // save space for the header, filled in later
1079         MSG_WriteLong(&net_message, 0);
1080         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1081         dfunc.GetSocketAddr(newsock, &newaddr);
1082         MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr));
1083 //      MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr));
1084         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1085         dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
1086         SZ_Clear(&net_message);
1087
1088         return sock;
1089 }
1090
1091 qsocket_t *Datagram_CheckNewConnections (void)
1092 {
1093         qsocket_t *ret = NULL;
1094
1095         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
1096                 if (net_landrivers[net_landriverlevel].initialized)
1097                         if ((ret = _Datagram_CheckNewConnections ()) != NULL)
1098                                 break;
1099         return ret;
1100 }
1101
1102
1103 static void _Datagram_SearchForHosts (qboolean xmit)
1104 {
1105         int             ret;
1106         int             n;
1107         int             i;
1108         struct qsockaddr readaddr;
1109         struct qsockaddr myaddr;
1110         int             control;
1111
1112         dfunc.GetSocketAddr (dfunc.controlSock, &myaddr);
1113         if (xmit)
1114         {
1115                 SZ_Clear(&net_message);
1116                 // save space for the header, filled in later
1117                 MSG_WriteLong(&net_message, 0);
1118                 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1119                 MSG_WriteString(&net_message, "QUAKE");
1120                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1121                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1122                 dfunc.Broadcast(dfunc.controlSock, net_message.data, net_message.cursize);
1123                 SZ_Clear(&net_message);
1124         }
1125
1126         while ((ret = dfunc.Read (dfunc.controlSock, net_message.data, net_message.maxsize, &readaddr)) > 0)
1127         {
1128                 if (ret < sizeof(int))
1129                         continue;
1130                 net_message.cursize = ret;
1131
1132                 // don't answer our own query
1133                 if (dfunc.AddrCompare(&readaddr, &myaddr) >= 0)
1134                         continue;
1135
1136                 // is the cache full?
1137                 if (hostCacheCount == HOSTCACHESIZE)
1138                         continue;
1139
1140                 MSG_BeginReading ();
1141                 control = BigLong(*((int *)net_message.data));
1142                 MSG_ReadLong();
1143                 if (control == -1)
1144                         continue;
1145                 if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
1146                         continue;
1147                 if ((control & NETFLAG_LENGTH_MASK) != ret)
1148                         continue;
1149
1150                 if (MSG_ReadByte() != CCREP_SERVER_INFO)
1151                         continue;
1152
1153                 dfunc.GetAddrFromName(MSG_ReadString(), &readaddr);
1154                 // search the cache for this server
1155                 for (n = 0; n < hostCacheCount; n++)
1156                         if (dfunc.AddrCompare(&readaddr, &hostcache[n].addr) == 0)
1157                                 break;
1158
1159                 // is it already there?
1160                 if (n < hostCacheCount)
1161                         continue;
1162
1163                 // add it
1164                 hostCacheCount++;
1165                 strcpy(hostcache[n].name, MSG_ReadString());
1166                 strcpy(hostcache[n].map, MSG_ReadString());
1167                 hostcache[n].users = MSG_ReadByte();
1168                 hostcache[n].maxusers = MSG_ReadByte();
1169                 if (MSG_ReadByte() != NET_PROTOCOL_VERSION)
1170                 {
1171                         strcpy(hostcache[n].cname, hostcache[n].name);
1172                         hostcache[n].cname[14] = 0;
1173                         strcpy(hostcache[n].name, "*");
1174                         strcat(hostcache[n].name, hostcache[n].cname);
1175                 }
1176                 memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr));
1177                 hostcache[n].driver = net_driverlevel;
1178                 hostcache[n].ldriver = net_landriverlevel;
1179                 strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr));
1180
1181                 // check for a name conflict
1182                 for (i = 0; i < hostCacheCount; i++)
1183                 {
1184                         if (i == n)
1185                                 continue;
1186                         if (Q_strcasecmp (hostcache[n].name, hostcache[i].name) == 0)
1187                         {
1188                                 i = strlen(hostcache[n].name);
1189                                 if (i < 15 && hostcache[n].name[i-1] > '8')
1190                                 {
1191                                         hostcache[n].name[i] = '0';
1192                                         hostcache[n].name[i+1] = 0;
1193                                 }
1194                                 else
1195                                         hostcache[n].name[i-1]++;
1196                                 i = -1;
1197                         }
1198                 }
1199         }
1200 }
1201
1202 void Datagram_SearchForHosts (qboolean xmit)
1203 {
1204         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
1205         {
1206                 if (hostCacheCount == HOSTCACHESIZE)
1207                         break;
1208                 if (net_landrivers[net_landriverlevel].initialized)
1209                         _Datagram_SearchForHosts (xmit);
1210         }
1211 }
1212
1213
1214 static qsocket_t *_Datagram_Connect (char *host)
1215 {
1216         struct qsockaddr sendaddr;
1217         struct qsockaddr readaddr;
1218         qsocket_t       *sock;
1219         int                     newsock;
1220         int                     ret;
1221         int                     reps;
1222         double          start_time;
1223         int                     control;
1224         char            *reason;
1225
1226         // see if we can resolve the host name
1227         if (dfunc.GetAddrFromName(host, &sendaddr) == -1)
1228                 return NULL;
1229
1230         newsock = dfunc.OpenSocket (cl_port.integer);
1231         if (newsock == -1)
1232                 return NULL;
1233
1234         sock = NET_NewQSocket ();
1235         if (sock == NULL)
1236                 goto ErrorReturn2;
1237         sock->socket = newsock;
1238         sock->landriver = net_landriverlevel;
1239
1240         // connect to the host
1241         if (dfunc.Connect (newsock, &sendaddr) == -1)
1242                 goto ErrorReturn;
1243
1244         // send the connection request
1245         Con_Printf("trying...\n"); CL_UpdateScreen ();
1246         start_time = net_time;
1247
1248         for (reps = 0; reps < 3; reps++)
1249         {
1250                 SZ_Clear(&net_message);
1251                 // save space for the header, filled in later
1252                 MSG_WriteLong(&net_message, 0);
1253                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1254                 MSG_WriteString(&net_message, "QUAKE");
1255                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1256                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1257                 dfunc.Write (newsock, net_message.data, net_message.cursize, &sendaddr);
1258                 SZ_Clear(&net_message);
1259                 do
1260                 {
1261                         ret = dfunc.Read (newsock, net_message.data, net_message.maxsize, &readaddr);
1262                         // if we got something, validate it
1263                         if (ret > 0)
1264                         {
1265                                 // is it from the right place?
1266                                 if (sfunc.AddrCompare(&readaddr, &sendaddr) != 0)
1267                                 {
1268 //#ifdef DEBUG
1269                                         Con_DPrintf("wrong reply address\n");
1270                                         Con_DPrintf("Expected: %s\n", StrAddr (&sendaddr));
1271                                         Con_DPrintf("Received: %s\n", StrAddr (&readaddr));
1272                                         CL_UpdateScreen ();
1273 //#endif
1274                                         ret = 0;
1275                                         continue;
1276                                 }
1277
1278                                 if (ret < sizeof(int))
1279                                 {
1280                                         ret = 0;
1281                                         continue;
1282                                 }
1283
1284                                 net_message.cursize = ret;
1285                                 MSG_BeginReading ();
1286
1287                                 control = BigLong(*((int *)net_message.data));
1288                                 MSG_ReadLong();
1289                                 if (control == -1)
1290                                 {
1291                                         ret = 0;
1292                                         continue;
1293                                 }
1294                                 if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
1295                                 {
1296                                         ret = 0;
1297                                         continue;
1298                                 }
1299                                 if ((control & NETFLAG_LENGTH_MASK) != ret)
1300                                 {
1301                                         ret = 0;
1302                                         continue;
1303                                 }
1304                         }
1305                 }
1306                 while (ret == 0 && (SetNetTime() - start_time) < 2.5);
1307                 if (ret)
1308                         break;
1309                 Con_Printf("still trying...\n"); CL_UpdateScreen ();
1310                 start_time = SetNetTime();
1311         }
1312
1313         if (ret == 0)
1314         {
1315                 reason = "No Response";
1316                 Con_Printf("%s\n", reason);
1317                 strcpy(m_return_reason, reason);
1318                 goto ErrorReturn;
1319         }
1320
1321         if (ret == -1)
1322         {
1323                 reason = "Network Error";
1324                 Con_Printf("%s\n", reason);
1325                 strcpy(m_return_reason, reason);
1326                 goto ErrorReturn;
1327         }
1328
1329         ret = MSG_ReadByte();
1330         if (ret == CCREP_REJECT)
1331         {
1332                 reason = MSG_ReadString();
1333                 Con_Printf("%s", reason);
1334                 strncpy(m_return_reason, reason, 31);
1335                 goto ErrorReturn;
1336         }
1337
1338         if (ret == CCREP_ACCEPT)
1339         {
1340                 memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr));
1341                 dfunc.SetSocketPort (&sock->addr, MSG_ReadLong());
1342         }
1343         else
1344         {
1345                 reason = "Bad Response";
1346                 Con_Printf("%s\n", reason);
1347                 strcpy(m_return_reason, reason);
1348                 goto ErrorReturn;
1349         }
1350
1351         dfunc.GetNameFromAddr (&sendaddr, sock->address);
1352
1353         Con_Printf ("Connection accepted to %s\n", sock->address);
1354         sock->lastMessageTime = SetNetTime();
1355
1356         // switch the connection to the specified address
1357         if (dfunc.Connect (newsock, &sock->addr) == -1)
1358         {
1359                 reason = "Connect to Game failed";
1360                 Con_Printf("%s\n", reason);
1361                 strcpy(m_return_reason, reason);
1362                 goto ErrorReturn;
1363         }
1364
1365         m_return_onerror = false;
1366         return sock;
1367
1368 ErrorReturn:
1369         NET_FreeQSocket(sock);
1370 ErrorReturn2:
1371         dfunc.CloseSocket(newsock);
1372         if (m_return_onerror)
1373         {
1374                 key_dest = key_menu;
1375                 m_state = m_return_state;
1376                 m_return_onerror = false;
1377         }
1378         return NULL;
1379 }
1380
1381 qsocket_t *Datagram_Connect (char *host)
1382 {
1383         qsocket_t *ret = NULL;
1384
1385         for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++)
1386                 if (net_landrivers[net_landriverlevel].initialized)
1387                         if ((ret = _Datagram_Connect (host)) != NULL)
1388                                 break;
1389         return ret;
1390 }