]> icculus.org git repositories - divverent/darkplaces.git/blob - net_wins.c
minor cleaning of obsolete protocol stuff (svc_fog is now considered unused, because...
[divverent/darkplaces.git] / net_wins.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_wins.c
21
22 #include "quakedef.h"
23 #include "winquake.h"
24
25 #define MAXHOSTNAMELEN          256
26
27 static int net_acceptsocket = -1;               // socket for fielding new connections
28 static int net_controlsocket;
29 static int net_broadcastsocket = 0;
30 static struct qsockaddr broadcastaddr;
31
32 static unsigned long myAddr;
33
34 qboolean        winsock_lib_initialized;
35
36 int (PASCAL FAR *pWSAStartup)(WORD wVersionRequired, LPWSADATA lpWSAData);
37 int (PASCAL FAR *pWSACleanup)(void);
38 int (PASCAL FAR *pWSAGetLastError)(void);
39 SOCKET (PASCAL FAR *psocket)(int af, int type, int protocol);
40 int (PASCAL FAR *pioctlsocket)(SOCKET s, long cmd, u_long FAR *argp);
41 int (PASCAL FAR *psetsockopt)(SOCKET s, int level, int optname,
42                                                           const char FAR * optval, int optlen);
43 int (PASCAL FAR *precvfrom)(SOCKET s, char FAR * buf, int len, int flags,
44                                                         struct sockaddr FAR *from, int FAR * fromlen);
45 int (PASCAL FAR *psendto)(SOCKET s, const char FAR * buf, int len, int flags,
46                                                   const struct sockaddr FAR *to, int tolen);
47 int (PASCAL FAR *pclosesocket)(SOCKET s);
48 int (PASCAL FAR *pgethostname)(char FAR * name, int namelen);
49 struct hostent FAR * (PASCAL FAR *pgethostbyname)(const char FAR * name);
50 struct hostent FAR * (PASCAL FAR *pgethostbyaddr)(const char FAR * addr,
51                                                                                                   int len, int type);
52 int (PASCAL FAR *pgetsockname)(SOCKET s, struct sockaddr FAR *name,
53                                                            int FAR * namelen);
54
55 #include "net_wins.h"
56
57 int winsock_initialized = 0;
58 WSADATA         winsockdata;
59
60 //=============================================================================
61
62 static double   blocktime;
63
64 BOOL PASCAL FAR BlockingHook(void)  
65
66     MSG         msg;
67     BOOL        ret;
68  
69         if ((Sys_DoubleTime() - blocktime) > 2.0)
70         {
71                 WSACancelBlockingCall();
72                 return false;
73         }
74
75     /* get the next message, if any */ 
76     ret = (BOOL) PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); 
77  
78     /* if we got one, process it */ 
79     if (ret) { 
80         TranslateMessage(&msg); 
81         DispatchMessage(&msg); 
82     } 
83  
84     /* true if we got a message */ 
85     return ret; 
86
87
88
89 void WINS_GetLocalAddress(void)
90 {
91         struct hostent  *local = NULL;
92         char                    buff[MAXHOSTNAMELEN];
93         unsigned long   addr;
94
95         if (myAddr != INADDR_ANY)
96                 return;
97
98         if (pgethostname(buff, MAXHOSTNAMELEN) == SOCKET_ERROR)
99                 return;
100
101         blocktime = Sys_DoubleTime();
102         WSASetBlockingHook(BlockingHook);
103         local = pgethostbyname(buff);
104         WSAUnhookBlockingHook();
105         if (local == NULL)
106                 return;
107
108         myAddr = *(int *)local->h_addr_list[0];
109
110         addr = ntohl(myAddr);
111         sprintf(my_tcpip_address, "%d.%d.%d.%d", (int) ((addr >> 24) & 0xff), (int) ((addr >> 16) & 0xff), (int) ((addr >> 8) & 0xff), (int) (addr & 0xff));
112 }
113
114
115 int WINS_Init (void)
116 {
117         int             i;
118         char    buff[MAXHOSTNAMELEN];
119         char    *p;
120         int             r;
121         WORD    wVersionRequested;
122         HINSTANCE hInst;
123
124 // initialize the Winsock function vectors (we do this instead of statically linking
125 // so we can run on Win 3.1, where there isn't necessarily Winsock)
126     hInst = LoadLibrary("wsock32.dll");
127         
128         if (hInst == NULL)
129         {
130                 Con_SafePrintf ("Failed to load wsock32.dll\n");
131                 winsock_lib_initialized = false;
132                 return -1;
133         }
134
135         winsock_lib_initialized = true;
136
137     pWSAStartup = (void *)GetProcAddress(hInst, "WSAStartup");
138     pWSACleanup = (void *)GetProcAddress(hInst, "WSACleanup");
139     pWSAGetLastError = (void *)GetProcAddress(hInst, "WSAGetLastError");
140     psocket = (void *)GetProcAddress(hInst, "socket");
141     pioctlsocket = (void *)GetProcAddress(hInst, "ioctlsocket");
142     psetsockopt = (void *)GetProcAddress(hInst, "setsockopt");
143     precvfrom = (void *)GetProcAddress(hInst, "recvfrom");
144     psendto = (void *)GetProcAddress(hInst, "sendto");
145     pclosesocket = (void *)GetProcAddress(hInst, "closesocket");
146     pgethostname = (void *)GetProcAddress(hInst, "gethostname");
147     pgethostbyname = (void *)GetProcAddress(hInst, "gethostbyname");
148     pgethostbyaddr = (void *)GetProcAddress(hInst, "gethostbyaddr");
149     pgetsockname = (void *)GetProcAddress(hInst, "getsockname");
150
151     if (!pWSAStartup || !pWSACleanup || !pWSAGetLastError ||
152                 !psocket || !pioctlsocket || !psetsockopt ||
153                 !precvfrom || !psendto || !pclosesocket ||
154                 !pgethostname || !pgethostbyname || !pgethostbyaddr ||
155                 !pgetsockname)
156         {
157                 Con_SafePrintf ("Couldn't GetProcAddress from wsock32.dll\n");
158                 return -1;
159         }
160
161         if (COM_CheckParm ("-noudp"))
162                 return -1;
163
164         if (winsock_initialized == 0)
165         {
166                 wVersionRequested = MAKEWORD(1, 1); 
167
168                 r = pWSAStartup (MAKEWORD(1, 1), &winsockdata);
169
170                 if (r)
171                 {
172                         Con_SafePrintf ("Winsock initialization failed.\n");
173                         return -1;
174                 }
175         }
176         winsock_initialized++;
177
178         // determine my name
179         if (pgethostname(buff, MAXHOSTNAMELEN) == SOCKET_ERROR)
180         {
181                 Con_DPrintf ("Winsock TCP/IP Initialization failed.\n");
182                 if (--winsock_initialized == 0)
183                         pWSACleanup ();
184                 return -1;
185         }
186
187         // if the quake hostname isn't set, set it to the machine name
188         if (strcmp(hostname.string, "UNNAMED") == 0)
189         {
190                 // see if it's a text IP address (well, close enough)
191                 for (p = buff; *p; p++)
192                         if ((*p < '0' || *p > '9') && *p != '.')
193                                 break;
194
195                 // if it is a real name, strip off the domain; we only want the host
196                 if (*p)
197                 {
198                         for (i = 0; i < 15; i++)
199                                 if (buff[i] == '.')
200                                         break;
201                         buff[i] = 0;
202                 }
203                 Cvar_Set ("hostname", buff);
204         }
205
206         i = COM_CheckParm ("-ip");
207         if (i)
208         {
209                 if (i < com_argc-1)
210                 {
211                         myAddr = inet_addr(com_argv[i+1]);
212                         if (myAddr == INADDR_NONE)
213                                 Sys_Error ("%s is not a valid IP address", com_argv[i+1]);
214                         strcpy(my_tcpip_address, com_argv[i+1]);
215                 }
216                 else
217                 {
218                         Sys_Error ("NET_Init: you must specify an IP address after -ip");
219                 }
220         }
221         else
222         {
223                 myAddr = INADDR_ANY;
224                 strcpy(my_tcpip_address, "INADDR_ANY");
225         }
226
227         if ((net_controlsocket = WINS_OpenSocket (0)) == -1)
228         {
229                 Con_Printf("WINS_Init: Unable to open control socket\n");
230                 if (--winsock_initialized == 0)
231                         pWSACleanup ();
232                 return -1;
233         }
234
235         ((struct sockaddr_in *)&broadcastaddr)->sin_family = AF_INET;
236         ((struct sockaddr_in *)&broadcastaddr)->sin_addr.s_addr = INADDR_BROADCAST;
237         ((struct sockaddr_in *)&broadcastaddr)->sin_port = htons((unsigned short)net_hostport);
238
239         Con_Printf("Winsock TCP/IP Initialized\n");
240         tcpipAvailable = true;
241
242         return net_controlsocket;
243 }
244
245 //=============================================================================
246
247 void WINS_Shutdown (void)
248 {
249         WINS_Listen (false);
250         WINS_CloseSocket (net_controlsocket);
251         if (--winsock_initialized == 0)
252                 pWSACleanup ();
253 }
254
255 //=============================================================================
256
257 void WINS_Listen (qboolean state)
258 {
259         // enable listening
260         if (state)
261         {
262                 if (net_acceptsocket != -1)
263                         return;
264                 WINS_GetLocalAddress();
265                 if ((net_acceptsocket = WINS_OpenSocket (net_hostport)) == -1)
266                         Sys_Error ("WINS_Listen: Unable to open accept socket\n");
267                 return;
268         }
269
270         // disable listening
271         if (net_acceptsocket == -1)
272                 return;
273         WINS_CloseSocket (net_acceptsocket);
274         net_acceptsocket = -1;
275 }
276
277 //=============================================================================
278
279 int WINS_OpenSocket (int port)
280 {
281         int newsocket;
282         struct sockaddr_in address;
283         u_long _true = 1;
284
285         if ((newsocket = psocket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
286                 return -1;
287
288         if (pioctlsocket (newsocket, FIONBIO, &_true) == -1)
289                 goto ErrorReturn;
290
291         address.sin_family = AF_INET;
292         address.sin_addr.s_addr = myAddr;
293         address.sin_port = htons((unsigned short)port);
294         if( bind (newsocket, (void *)&address, sizeof(address)) == 0)
295                 return newsocket;
296
297         Sys_Error ("Unable to bind to %s", WINS_AddrToString((struct qsockaddr *)&address));
298 ErrorReturn:
299         pclosesocket (newsocket);
300         return -1;
301 }
302
303 //=============================================================================
304
305 int WINS_CloseSocket (int socket)
306 {
307         if (socket == net_broadcastsocket)
308                 net_broadcastsocket = 0;
309         return pclosesocket (socket);
310 }
311
312
313 //=============================================================================
314 /*
315 ============
316 PartialIPAddress
317
318 this lets you type only as much of the net address as required, using
319 the local network components to fill in the rest
320 ============
321 */
322 static int PartialIPAddress (char *in, struct qsockaddr *hostaddr)
323 {
324         char buff[256];
325         char *b;
326         int addr;
327         int num;
328         int mask;
329         int run;
330         int port;
331         
332         buff[0] = '.';
333         b = buff;
334         strcpy(buff+1, in);
335         if (buff[1] == '.')
336                 b++;
337
338         addr = 0;
339         mask=-1;
340         while (*b == '.')
341         {
342                 b++;
343                 num = 0;
344                 run = 0;
345                 while (!( *b < '0' || *b > '9'))
346                 {
347                   num = num*10 + *b++ - '0';
348                   if (++run > 3)
349                         return -1;
350                 }
351                 if ((*b < '0' || *b > '9') && *b != '.' && *b != ':' && *b != 0)
352                         return -1;
353                 if (num < 0 || num > 255)
354                         return -1;
355                 mask<<=8;
356                 addr = (addr<<8) + num;
357         }
358         
359         if (*b++ == ':')
360                 port = atoi(b);
361         else
362                 port = net_hostport;
363
364         hostaddr->sa_family = AF_INET;
365         ((struct sockaddr_in *)hostaddr)->sin_port = htons((short)port);        
366         ((struct sockaddr_in *)hostaddr)->sin_addr.s_addr = (myAddr & htonl(mask)) | htonl(addr);
367         
368         return 0;
369 }
370 //=============================================================================
371
372 int WINS_Connect (int socket, struct qsockaddr *addr)
373 {
374         return 0;
375 }
376
377 //=============================================================================
378
379 int WINS_CheckNewConnections (void)
380 {
381         char buf[4096];
382
383         if (net_acceptsocket == -1)
384                 return -1;
385
386         if (precvfrom (net_acceptsocket, buf, sizeof(buf), MSG_PEEK, NULL, NULL) >= 0)
387         {
388                 return net_acceptsocket;
389         }
390         return -1;
391 }
392
393 //=============================================================================
394
395 int WINS_Read (int socket, qbyte *buf, int len, struct qsockaddr *addr)
396 {
397         int addrlen = sizeof (struct qsockaddr);
398         int ret;
399         int errno;
400
401         ret = precvfrom (socket, buf, len, 0, (struct sockaddr *)addr, &addrlen);
402         if (ret == -1)
403         {
404                  errno = pWSAGetLastError();
405
406                 if (errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED)
407                         return 0;
408
409         }
410         return ret;
411 }
412
413 //=============================================================================
414
415 int WINS_MakeSocketBroadcastCapable (int socket)
416 {
417         int     i = 1;
418
419         // make this socket broadcast capable
420         if (psetsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) < 0)
421                 return -1;
422         net_broadcastsocket = socket;
423
424         return 0;
425 }
426
427 //=============================================================================
428
429 int WINS_Broadcast (int socket, qbyte *buf, int len)
430 {
431         int ret;
432
433         if (socket != net_broadcastsocket)
434         {
435                 if (net_broadcastsocket != 0)
436                         Sys_Error("Attempted to use multiple broadcasts sockets\n");
437                 WINS_GetLocalAddress();
438                 ret = WINS_MakeSocketBroadcastCapable (socket);
439                 if (ret == -1)
440                 {
441                         Con_Printf("Unable to make socket broadcast capable\n");
442                         return ret;
443                 }
444         }
445
446         return WINS_Write (socket, buf, len, &broadcastaddr);
447 }
448
449 //=============================================================================
450
451 int WINS_Write (int socket, qbyte *buf, int len, struct qsockaddr *addr)
452 {
453         int ret;
454
455         ret = psendto (socket, buf, len, 0, (struct sockaddr *)addr, sizeof(struct qsockaddr));
456         if (ret == -1)
457                 if (pWSAGetLastError() == WSAEWOULDBLOCK)
458                         return 0;
459
460         return ret;
461 }
462
463 //=============================================================================
464
465 char *WINS_AddrToString (struct qsockaddr *addr)
466 {
467         static char buffer[22];
468         int haddr;
469
470         haddr = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr);
471         sprintf(buffer, "%d.%d.%d.%d:%d", (haddr >> 24) & 0xff, (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, ntohs(((struct sockaddr_in *)addr)->sin_port));
472         return buffer;
473 }
474
475 //=============================================================================
476
477 int WINS_StringToAddr (char *string, struct qsockaddr *addr)
478 {
479         int ha1, ha2, ha3, ha4, hp;
480         int ipaddr;
481
482         sscanf(string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp);
483         ipaddr = (ha1 << 24) | (ha2 << 16) | (ha3 << 8) | ha4;
484
485         addr->sa_family = AF_INET;
486         ((struct sockaddr_in *)addr)->sin_addr.s_addr = htonl(ipaddr);
487         ((struct sockaddr_in *)addr)->sin_port = htons((unsigned short)hp);
488         return 0;
489 }
490
491 //=============================================================================
492
493 int WINS_GetSocketAddr (int socket, struct qsockaddr *addr)
494 {
495         int addrlen = sizeof(struct qsockaddr);
496         unsigned int a;
497
498         memset(addr, 0, sizeof(struct qsockaddr));
499         pgetsockname(socket, (struct sockaddr *)addr, &addrlen);
500         a = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
501         if (a == 0 || a == inet_addr("127.0.0.1"))
502                 ((struct sockaddr_in *)addr)->sin_addr.s_addr = myAddr;
503
504         return 0;
505 }
506
507 //=============================================================================
508
509 int WINS_GetNameFromAddr (struct qsockaddr *addr, char *name)
510 {
511         struct hostent *hostentry;
512
513         hostentry = pgethostbyaddr ((char *)&((struct sockaddr_in *)addr)->sin_addr, sizeof(struct in_addr), AF_INET);
514         if (hostentry)
515         {
516                 strncpy (name, (char *)hostentry->h_name, NET_NAMELEN - 1);
517                 return 0;
518         }
519
520         strcpy (name, WINS_AddrToString (addr));
521         return 0;
522 }
523
524 //=============================================================================
525
526 int WINS_GetAddrFromName(char *name, struct qsockaddr *addr)
527 {
528         struct hostent *hostentry;
529
530         if (name[0] >= '0' && name[0] <= '9')
531                 return PartialIPAddress (name, addr);
532         
533         hostentry = pgethostbyname (name);
534         if (!hostentry)
535                 return -1;
536
537         addr->sa_family = AF_INET;
538         ((struct sockaddr_in *)addr)->sin_port = htons((unsigned short)net_hostport);   
539         ((struct sockaddr_in *)addr)->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0];
540
541         return 0;
542 }
543
544 //=============================================================================
545
546 int WINS_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2)
547 {
548         if (addr1->sa_family != addr2->sa_family)
549                 return -1;
550
551         if (((struct sockaddr_in *)addr1)->sin_addr.s_addr != ((struct sockaddr_in *)addr2)->sin_addr.s_addr)
552                 return -1;
553
554         if (((struct sockaddr_in *)addr1)->sin_port != ((struct sockaddr_in *)addr2)->sin_port)
555                 return 1;
556
557         return 0;
558 }
559
560 //=============================================================================
561
562 int WINS_GetSocketPort (struct qsockaddr *addr)
563 {
564         return ntohs(((struct sockaddr_in *)addr)->sin_port);
565 }
566
567
568 int WINS_SetSocketPort (struct qsockaddr *addr, int port)
569 {
570         ((struct sockaddr_in *)addr)->sin_port = htons((unsigned short)port);
571         return 0;
572 }
573
574 //=============================================================================