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 
21 #include <winsock2.h>
22 
23 #include "console.h"
24 #include "net.h"
25 #include "net_wins.h"
26 #include "quakedef.h"
27 #include "sys.h"
28 #include "winquake.h"
29 
30 /* socket for fielding new connections */
31 static int net_acceptsocket = -1;
32 static int net_controlsocket;
33 static int net_broadcastsocket = 0;
34 static netadr_t broadcastaddr;
35 
36 /*
37  * There are three addresses that we may use in different ways:
38  *   myAddr	- This is the "default" address returned by the OS
39  *   localAddr	- This is an address to advertise in CCREP_SERVER_INFO
40  *		 and CCREP_ACCEPT response packets, rather than the
41  *		 default address (sometimes the default address is not
42  *		 suitable for LAN clients; i.e. loopback address). Set
43  *		 on the command line using the "-localip" option.
44  *   bindAddr	- The address to which we bind our network socket. The
45  *		 default is INADDR_ANY, but in some cases we may want
46  *		 to only listen on a particular address. Set on the
47  *		 command line using the "-ip" option.
48  */
49 static netadr_t myAddr;
50 static netadr_t localAddr;
51 static netadr_t bindAddr;
52 
53 int winsock_initialized = 0;
54 WSADATA winsockdata;
55 
56 static double blocktime;
57 
58 
59 static void
NetadrToSockadr(const netadr_t * a,struct sockaddr_in * s)60 NetadrToSockadr(const netadr_t *a, struct sockaddr_in *s)
61 {
62     memset(s, 0, sizeof(*s));
63     s->sin_family = AF_INET;
64 
65     s->sin_addr.s_addr = a->ip.l;
66     s->sin_port = a->port;
67 }
68 
69 static void
SockadrToNetadr(const struct sockaddr_in * s,netadr_t * a)70 SockadrToNetadr(const struct sockaddr_in *s, netadr_t *a)
71 {
72     a->ip.l = s->sin_addr.s_addr;
73     a->port = s->sin_port;
74 }
75 
76 static BOOL PASCAL FAR
BlockingHook(void)77 BlockingHook(void)
78 {
79     MSG msg;
80     BOOL ret;
81 
82     if ((Sys_DoubleTime() - blocktime) > 2.0) {
83 	WSACancelBlockingCall();
84 	return FALSE;
85     }
86 
87     /* get the next message, if any */
88     ret = (BOOL)PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
89 
90     /* if we got one, process it */
91     if (ret) {
92 	TranslateMessage(&msg);
93 	DispatchMessage(&msg);
94     }
95 
96     /* TRUE if we got a message */
97     return ret;
98 }
99 
100 
101 int
WINS_Init(void)102 WINS_Init(void)
103 {
104     int i;
105     int err;
106     char buff[MAXHOSTNAMELEN];
107     char *colon;
108     struct hostent *local;
109     netadr_t addr;
110 
111     if (COM_CheckParm("-noudp"))
112 	return -1;
113 
114     if (!winsock_initialized) {
115 	err = WSAStartup(MAKEWORD(1,1), &winsockdata);
116 	if (err) {
117 	    Con_SafePrintf("Winsock initialization failed.\n");
118 	    return -1;
119 	}
120     }
121     winsock_initialized++;
122 
123     /* determine my name & address */
124     myAddr.ip.l = htonl(INADDR_LOOPBACK);
125     myAddr.port = htons(DEFAULTnet_hostport);
126     err = gethostname(buff, MAXHOSTNAMELEN);
127     if (err) {
128 	Con_Printf("%s: WARNING: gethostname failed.\n", __func__);
129     } else {
130 	buff[MAXHOSTNAMELEN - 1] = 0;
131 	blocktime = Sys_DoubleTime();
132 	WSASetBlockingHook(BlockingHook);
133 	local = gethostbyname(buff);
134 	WSAUnhookBlockingHook();
135 	if (!local) {
136 	    Con_Printf("%s: WARNING: gethostbyname timed out.\n", __func__);
137 	} else if (local->h_addrtype != AF_INET) {
138 	    Con_Printf("%s: address from gethostbyname not IPv4\n", __func__);
139 	} else {
140 	    struct in_addr *inaddr = (struct in_addr *)local->h_addr_list[0];
141 	    myAddr.ip.l = inaddr->S_un.S_addr;
142 	}
143     }
144     Con_Printf("UDP, Local address: %s\n", NET_AdrToString(&myAddr));
145 
146     i = COM_CheckParm("-ip");
147     if (i && i < com_argc - 1) {
148 	bindAddr.ip.l = inet_addr(com_argv[i + 1]);
149 	if (bindAddr.ip.l == INADDR_NONE)
150 	    Sys_Error("%s: %s is not a valid IP address", __func__,
151 		      com_argv[i + 1]);
152 	Con_Printf("Binding to IP Interface Address of %s\n", com_argv[i + 1]);
153     } else {
154 	bindAddr.ip.l = INADDR_NONE;
155     }
156 
157     i = COM_CheckParm("-localip");
158     if (i && i < com_argc - 1) {
159 	localAddr.ip.l = inet_addr(com_argv[i + 1]);
160 	if (localAddr.ip.l == INADDR_NONE)
161 	    Sys_Error("%s: %s is not a valid IP address", __func__,
162 		      com_argv[i + 1]);
163 	Con_Printf("Advertising %s as the local IP in response packets\n",
164 		   com_argv[i + 1]);
165     } else {
166 	localAddr.ip.l = INADDR_NONE;
167     }
168 
169     net_controlsocket = WINS_OpenSocket(0);
170     if (net_controlsocket == -1) {
171 	Con_Printf("%s: Unable to open control socket\n", __func__);
172 	if (--winsock_initialized == 0)
173 	    WSACleanup();
174 	return -1;
175     }
176 
177     broadcastaddr.ip.l = INADDR_BROADCAST;
178     broadcastaddr.port = htons(net_hostport);
179 
180     WINS_GetSocketAddr(net_controlsocket, &addr);
181     strcpy(my_tcpip_address, NET_AdrToString(&addr));
182     colon = strrchr(my_tcpip_address, ':');
183     if (colon)
184 	*colon = 0;
185 
186     Con_Printf("Winsock TCP/IP Initialized (%s)\n", my_tcpip_address);
187     tcpipAvailable = true;
188 
189     return net_controlsocket;
190 }
191 
192 
193 void
WINS_Shutdown(void)194 WINS_Shutdown(void)
195 {
196     WINS_Listen(false);
197     WINS_CloseSocket(net_controlsocket);
198     if (--winsock_initialized == 0)
199 	WSACleanup();
200 }
201 
202 
203 void
WINS_Listen(qboolean state)204 WINS_Listen(qboolean state)
205 {
206     /* enable listening */
207     if (state) {
208 	if (net_acceptsocket != -1)
209 	    return;
210 	if ((net_acceptsocket = WINS_OpenSocket(net_hostport)) == -1)
211 	    Sys_Error("%s: Unable to open accept socket", __func__);
212 	return;
213     }
214 
215     /* disable listening */
216     if (net_acceptsocket == -1)
217 	return;
218 
219     WINS_CloseSocket(net_acceptsocket);
220     net_acceptsocket = -1;
221 }
222 
223 
224 int
WINS_OpenSocket(int port)225 WINS_OpenSocket(int port)
226 {
227     int newsocket;
228     struct sockaddr_in address;
229     netadr_t addr;
230     u_long _true = 1;
231 
232     if ((newsocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
233 	return -1;
234     if (ioctlsocket(newsocket, FIONBIO, &_true) == -1)
235 	goto ErrorReturn;
236 
237     address.sin_family = AF_INET;
238     if (bindAddr.ip.l != INADDR_NONE)
239 	address.sin_addr.s_addr = bindAddr.ip.l;
240     else
241 	address.sin_addr.s_addr = INADDR_ANY;
242     address.sin_port = htons((unsigned short)port);
243     if (bind(newsocket, (struct sockaddr *)&address, sizeof(address)) == 0)
244 	return newsocket;
245 
246     SockadrToNetadr(&address, &addr);
247     if (tcpipAvailable)
248 	Sys_Error("Unable to bind to %s", NET_AdrToString(&addr));
249     else /* we are still in init phase, no need to error */
250 	Con_Printf("Unable to bind to %s\n", NET_AdrToString(&addr));
251 
252   ErrorReturn:
253     closesocket(newsocket);
254     return -1;
255 }
256 
257 
258 int
WINS_CloseSocket(int socket)259 WINS_CloseSocket(int socket)
260 {
261     if (socket == net_broadcastsocket)
262 	net_broadcastsocket = 0;
263     return closesocket(socket);
264 }
265 
266 
267 int
WINS_CheckNewConnections(void)268 WINS_CheckNewConnections(void)
269 {
270     char buf[4096];
271     int ret;
272 
273     if (net_acceptsocket == -1)
274 	return -1;
275 
276     ret = recvfrom(net_acceptsocket, buf, sizeof(buf), MSG_PEEK, NULL, NULL);
277     if (ret >= 0)
278 	return net_acceptsocket;
279 
280     return -1;
281 }
282 
283 
284 int
WINS_Read(int socket,void * buf,int len,netadr_t * addr)285 WINS_Read(int socket, void *buf, int len, netadr_t *addr)
286 {
287     struct sockaddr_in saddr;
288     int addrlen = sizeof(saddr);
289     int ret;
290 
291     ret = recvfrom(socket, (char *)buf, len, 0, (struct sockaddr *)&saddr,
292 		   &addrlen);
293     SockadrToNetadr(&saddr, addr);
294     if (ret == -1) {
295 	int err = WSAGetLastError();
296 
297 	if (err == WSAEWOULDBLOCK || err == WSAECONNREFUSED)
298 	    return 0;
299     }
300     return ret;
301 }
302 
303 
304 static int
WINS_MakeSocketBroadcastCapable(int socket)305 WINS_MakeSocketBroadcastCapable(int socket)
306 {
307     int i = 1;
308 
309     /* make this socket broadcast capable */
310     if (setsockopt
311 	(socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) < 0)
312 	return -1;
313     net_broadcastsocket = socket;
314 
315     return 0;
316 }
317 
318 
319 int
WINS_Broadcast(int socket,const void * buf,int len)320 WINS_Broadcast(int socket, const void *buf, int len)
321 {
322     int ret;
323 
324     if (socket != net_broadcastsocket) {
325 	if (net_broadcastsocket != 0)
326 	    Sys_Error("Attempted to use multiple broadcasts sockets");
327 	ret = WINS_MakeSocketBroadcastCapable(socket);
328 	if (ret == -1) {
329 	    Con_Printf("Unable to make socket broadcast capable\n");
330 	    return ret;
331 	}
332     }
333 
334     return WINS_Write(socket, buf, len, &broadcastaddr);
335 }
336 
337 
338 int
WINS_Write(int socket,const void * buf,int len,const netadr_t * addr)339 WINS_Write(int socket, const void *buf, int len, const netadr_t *addr)
340 {
341     struct sockaddr_in saddr;
342     int ret;
343 
344     NetadrToSockadr(addr, &saddr);
345     ret = sendto(socket, (char *)buf, len, 0, (struct sockaddr *)&saddr,
346 		 sizeof(saddr));
347     if (ret == -1)
348 	if (WSAGetLastError() == WSAEWOULDBLOCK)
349 	    return 0;
350 
351     return ret;
352 }
353 
354 
355 int
WINS_GetSocketAddr(int socket,netadr_t * addr)356 WINS_GetSocketAddr(int socket, netadr_t *addr)
357 {
358     struct sockaddr_in saddr;
359     int len = sizeof(saddr);
360 
361     memset(&saddr, 0, len);
362     getsockname(socket, (struct sockaddr *)&saddr, &len);
363 
364     /*
365      * The returned IP is embedded in our repsonse to a broadcast request for
366      * server info from clients. The server admin may wish to advertise a
367      * specific IP for various reasons, so allow the "default" address
368      * returned by the OS to be overridden.
369      */
370     if (localAddr.ip.l != INADDR_NONE)
371 	saddr.sin_addr.s_addr = localAddr.ip.l;
372     else {
373 	struct in_addr a = saddr.sin_addr;
374 	if (!a.s_addr || a.s_addr == htonl(INADDR_LOOPBACK))
375 	    saddr.sin_addr.s_addr = myAddr.ip.l;
376     }
377     SockadrToNetadr(&saddr, addr);
378 
379     return 0;
380 }
381 
382 
383 int
WINS_GetNameFromAddr(const netadr_t * addr,char * name)384 WINS_GetNameFromAddr(const netadr_t *addr, char *name)
385 {
386     struct hostent *hostentry;
387 
388     hostentry = gethostbyaddr((char *)&addr->ip.l, sizeof(addr->ip.l), AF_INET);
389     if (hostentry) {
390 	strncpy(name, (char *)hostentry->h_name, NET_NAMELEN - 1);
391 	return 0;
392     }
393     strcpy(name, NET_AdrToString(addr));
394 
395     return 0;
396 }
397 
398 
399 int
WINS_GetAddrFromName(const char * name,netadr_t * addr)400 WINS_GetAddrFromName(const char *name, netadr_t *addr)
401 {
402     struct hostent *hostentry;
403 
404     if (name[0] >= '0' && name[0] <= '9')
405 	return NET_PartialIPAddress(name, &myAddr, addr);
406 
407     hostentry = gethostbyname(name);
408     if (!hostentry)
409 	return -1;
410 
411     addr->ip.l = *(int *)hostentry->h_addr_list[0];
412     addr->port = htons(net_hostport);
413 
414     return 0;
415 }
416 
417 
418 int
WINS_GetDefaultMTU(void)419 WINS_GetDefaultMTU(void)
420 {
421     return 1400;
422 }
423