i_tcp.c 34.3 KB
Newer Older
Alam Ed Arias committed
1 2 3
// SONIC ROBO BLAST 2
//-----------------------------------------------------------------------------
// Copyright (C) 1998-2000 by DooM Legacy Team.
James R. committed
4
// Copyright (C) 1999-2020 by Sonic Team Junior.
Alam Ed Arias committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
//
// This program is free software distributed under the
// terms of the GNU General Public License, version 2.
// See the 'LICENSE' file for more details.
//-----------------------------------------------------------------------------
/// \file  i_tcp.c
/// \brief TCP driver, socket code.
///        This is not really OS-dependent because all OSes have the same socket API.
///        Just use ifdef for OS-dependent parts.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifdef __GNUC__
#include <unistd.h>
#endif

#ifndef NO_IPV6
23
	#define HAVE_IPV6
Alam Ed Arias committed
24 25
#endif

Monster Iestyn committed
26
#ifdef _WIN32
27 28 29 30 31 32
	#define USE_WINSOCK
	#if defined (_WIN64) || defined (HAVE_IPV6)
		#define USE_WINSOCK2
	#else //_WIN64/HAVE_IPV6
		#define USE_WINSOCK1
	#endif
Alam Ed Arias committed
33 34 35
#endif //WIN32 OS

#ifdef USE_WINSOCK2
36
	#include <ws2tcpip.h>
Alam Ed Arias committed
37 38 39 40 41
#endif

#include "doomdef.h"

#if defined (NOMD5) && !defined (NONET)
42
	//#define NONET
Alam Ed Arias committed
43 44
#endif

45
#ifdef NONET
46
	#undef HAVE_MINIUPNPC
47
#else
48 49
	#ifdef USE_WINSOCK1
		#include <winsock.h>
50
	#else
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
		#ifndef USE_WINSOCK
			#include <arpa/inet.h>
			#ifdef __APPLE_CC__
				#ifndef _BSD_SOCKLEN_T_
					#define _BSD_SOCKLEN_T_
				#endif //_BSD_SOCKLEN_T_
			#endif //__APPLE_CC__
			#include <sys/socket.h>
			#include <netinet/in.h>
			#include <netdb.h>
			#include <sys/ioctl.h>
		#endif //normal BSD API

		#include <errno.h>
		#include <time.h>

		#if (defined (__unix__) && !defined (MSDOS)) || defined(__APPLE__) || defined (UNIXCOMMON)
			#include <sys/time.h>
		#endif // UNIXCOMMON
70
	#endif
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

	#ifdef USE_WINSOCK
		// some undefined under win32
		#undef errno
		//#define errno WSAGetLastError() //Alam_GBC: this is the correct way, right?
		#define errno h_errno // some very strange things happen when not using h_error?!?
		#ifdef EWOULDBLOCK
		#undef EWOULDBLOCK
		#endif
		#define EWOULDBLOCK WSAEWOULDBLOCK
		#ifdef EMSGSIZE
		#undef EMSGSIZE
		#endif
		#define EMSGSIZE WSAEMSGSIZE
		#ifdef ECONNREFUSED
		#undef ECONNREFUSED
		#endif
		#define ECONNREFUSED WSAECONNREFUSED
		#ifdef ETIMEDOUT
		#undef ETIMEDOUT
		#endif
		#define ETIMEDOUT WSAETIMEDOUT
		#ifndef IOC_VENDOR
		#define IOC_VENDOR 0x18000000
		#endif
		#ifndef _WSAIOW
		#define _WSAIOW(x,y) (IOC_IN|(x)|(y))
		#endif
		#ifndef SIO_UDP_CONNRESET
		#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
		#endif
		#ifndef AI_ADDRCONFIG
		#define AI_ADDRCONFIG 0x00000400
		#endif
		#ifndef STATUS_INVALID_PARAMETER
		#define STATUS_INVALID_PARAMETER 0xC000000D
		#endif
	#endif // USE_WINSOCK

	#ifdef __DJGPP__
		#ifdef WATTCP // Alam_GBC: Wattcp may need this
			#include <tcp.h>
			#define strerror strerror_s
		#else // wattcp
			#include <lsck/lsck.h>
		#endif // libsocket
	#endif // djgpp

	typedef union
	{
		struct sockaddr     any;
		struct sockaddr_in  ip4;
	#ifdef HAVE_IPV6
		struct sockaddr_in6 ip6;
Alam Ed Arias committed
125
	#endif
126 127 128 129 130 131 132 133 134 135 136 137
	} mysockaddr_t;

	#ifdef HAVE_MINIUPNPC
		#ifdef STATIC_MINIUPNPC
			#define STATICLIB
		#endif
		#include "miniupnpc/miniwget.h"
		#include "miniupnpc/miniupnpc.h"
		#include "miniupnpc/upnpcommands.h"
		#undef STATICLIB
		static UINT8 UPNP_support = TRUE;
	#endif // HAVE_MINIUPNC
Alam Ed Arias committed
138 139 140 141 142 143 144 145

#endif // !NONET

#define MAXBANS 100

#include "i_system.h"
#include "i_net.h"
#include "d_net.h"
146
#include "d_netfil.h"
Alam Ed Arias committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
#include "i_tcp.h"
#include "m_argv.h"

#include "doomstat.h"

// win32 or djgpp
#if defined (USE_WINSOCK) || defined (__DJGPP__)
	// winsock stuff (in winsock a socket is not a file)
	#define ioctl ioctlsocket
	#define close closesocket
#endif

#include "i_addrinfo.h"

#ifdef __DJGPP__

#ifdef WATTCP
#define SELECTTEST
#endif

167
#else
Alam Ed Arias committed
168 169 170 171 172 173
#define SELECTTEST
#endif

#define DEFAULTPORT "5029"

#if defined (USE_WINSOCK) && !defined (NONET)
174 175
	typedef SOCKET SOCKET_TYPE;
	#define ERRSOCKET (SOCKET_ERROR)
Alam Ed Arias committed
176
#else
177 178 179 180 181 182
	#if (defined (__unix__) && !defined (MSDOS)) || defined (__APPLE__) || defined (__HAIKU__)
		typedef int SOCKET_TYPE;
	#else
		typedef unsigned long SOCKET_TYPE;
	#endif
	#define ERRSOCKET (-1)
Alam Ed Arias committed
183 184 185
#endif

#ifndef NONET
186
	// define socklen_t in DOS/Windows if it is not already defined
187 188 189 190 191 192 193 194 195 196 197 198 199
	#if (defined (WATTCP) && !defined (__libsocket_socklen_t)) || defined (USE_WINSOCK1)
		typedef int socklen_t;
	#endif
	static SOCKET_TYPE mysockets[MAXNETNODES+1] = {ERRSOCKET};
	static size_t mysocketses = 0;
	static int myfamily[MAXNETNODES+1] = {0};
	static SOCKET_TYPE nodesocket[MAXNETNODES+1] = {ERRSOCKET};
	static mysockaddr_t clientaddress[MAXNETNODES+1];
	static mysockaddr_t broadcastaddress[MAXNETNODES+1];
	static size_t broadcastaddresses = 0;
	static boolean nodeconnected[MAXNETNODES+1];
	static mysockaddr_t banned[MAXBANS];
	static UINT8 bannedmask[MAXBANS];
Alam Ed Arias committed
200 201 202 203 204 205
#endif

static size_t numbans = 0;
static boolean SOCK_bannednode[MAXNETNODES+1]; /// \note do we really need the +1?
static boolean init_tcp_driver = false;

206 207
static const char *serverport_name = DEFAULTPORT;
static const char *clientport_name;/* any port */
Alam Ed Arias committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

#ifndef NONET

#ifdef WATTCP
static void wattcp_outch(char s)
{
	static char old = '\0';
	char pr[2] = {s,0};
	if (s == old && old == ' ') return;
	else old = s;
	if (s == '\r') CONS_Printf("\n");
	else if (s != '\n') CONS_Printf(pr);
}
#endif

223 224
#ifdef USE_WINSOCK
// stupid microsoft makes things complicated
225
static char *get_WSAErrorStr(int e)
226
{
227
	static char buf[256]; // allow up to 255 bytes
228 229

	buf[0] = '\0';
230 231 232 233 234 235 236

	FormatMessageA(
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		(DWORD)e,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
237 238 239 240 241 242
		(LPTSTR)buf,
		sizeof (buf),
		NULL);

	if (!buf[0]) // provide a fallback error message if no message is available for some reason
		sprintf(buf, "Unknown error");
243 244 245 246 247 248 249

	return buf;
}
#undef strerror
#define strerror get_WSAErrorStr
#endif

Alam Ed Arias committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
#ifdef USE_WINSOCK2
#define inet_ntop inet_ntopA
#define HAVE_NTOP
static const char* inet_ntopA(short af, const void *cp, char *buf, socklen_t len)
{
	DWORD Dlen = len, AFlen = 0;
	SOCKADDR_STORAGE any;
	LPSOCKADDR anyp = (LPSOCKADDR)&any;
	LPSOCKADDR_IN any4 = (LPSOCKADDR_IN)&any;
	LPSOCKADDR_IN6 any6 = (LPSOCKADDR_IN6)&any;

	if (!buf)
	{
		WSASetLastError(STATUS_INVALID_PARAMETER);
		return NULL;
	}

	if (af != AF_INET && af != AF_INET6)
	{
		WSASetLastError(WSAEAFNOSUPPORT);
		return NULL;
	}

	ZeroMemory(&any, sizeof(SOCKADDR_STORAGE));
	any.ss_family = af;

	switch (af)
	{
		case AF_INET:
		{
			CopyMemory(&any4->sin_addr, cp, sizeof(IN_ADDR));
			AFlen = sizeof(SOCKADDR_IN);
			break;
		}
		case AF_INET6:
		{
			CopyMemory(&any6->sin6_addr, cp, sizeof(IN6_ADDR));
			AFlen = sizeof(SOCKADDR_IN6);
			break;
		}
	}

	if (WSAAddressToStringA(anyp, AFlen, NULL, buf, &Dlen) == SOCKET_ERROR)
		return NULL;
	return buf;
}
#elif !defined (USE_WINSOCK1)
#define HAVE_NTOP
#endif

#ifdef HAVE_MINIUPNPC // based on old XChat patch
static struct UPNPUrls urls;
static struct IGDdatas data;
static char lanaddr[64];

static void I_ShutdownUPnP(void)
{
	FreeUPNPUrls(&urls);
}

static inline void I_InitUPnP(void)
{
	struct UPNPDev * devlist = NULL;
	int upnp_error = -2;
	CONS_Printf(M_GetText("Looking for UPnP Internet Gateway Device\n"));
	devlist = upnpDiscover(2000, NULL, NULL, 0, false, &upnp_error);
	if (devlist)
	{
		struct UPNPDev *dev = devlist;
		char * descXML;
		int descXMLsize = 0;
		while (dev)
		{
			if (strstr (dev->st, "InternetGatewayDevice"))
				break;
			dev = dev->pNext;
		}
		if (!dev)
			dev = devlist; /* defaulting to first device */

		CONS_Printf(M_GetText("Found UPnP device:\n desc: %s\n st: %s\n"),
		           dev->descURL, dev->st);

		UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
		CONS_Printf(M_GetText("Local LAN IP address: %s\n"), lanaddr);
		descXML = miniwget(dev->descURL, &descXMLsize);
		if (descXML)
		{
			parserootdesc(descXML, descXMLsize, &data);
			free(descXML);
			descXML = NULL;
			memset(&urls, 0, sizeof(struct UPNPUrls));
			memset(&data, 0, sizeof(struct IGDdatas));
			GetUPNPUrls(&urls, &data, dev->descURL);
			I_AddExitFunc(I_ShutdownUPnP);
		}
		freeUPNPDevlist(devlist);
	}
	else if (upnp_error == UPNPDISCOVER_SOCKET_ERROR)
	{
		CONS_Printf(M_GetText("No UPnP devices discovered\n"));
	}
}

static inline void I_UPnP_add(const char * addr, const char *port, const char * servicetype)
{
	if (addr == NULL)
		addr = lanaddr;
	if (!urls.controlURL || urls.controlURL[0] == '\0')
		return;
	UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
	                    port, port, addr, "SRB2", servicetype, NULL, NULL);
}

static inline void I_UPnP_rem(const char *port, const char * servicetype)
{
	if (!urls.controlURL || urls.controlURL[0] == '\0')
		return;
	UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype,
	                       port, servicetype, NULL);
}
#endif

static const char *SOCK_AddrToStr(mysockaddr_t *sk)
{
	static char s[64]; // 255.255.255.255:65535 or IPv6:65535
#ifdef HAVE_NTOP
	void *addr;

	if(sk->any.sa_family == AF_INET)
		addr = &sk->ip4.sin_addr;
#ifdef HAVE_IPV6
	else if(sk->any.sa_family == AF_INET6)
		addr = &sk->ip6.sin6_addr;
#endif
	else
		addr = NULL;

	if(addr == NULL)
		sprintf(s, "No address");
	else if(inet_ntop(sk->any.sa_family, addr, s, sizeof (s)) == NULL)
		sprintf(s, "Unknown family type, error #%u", errno);
#ifdef HAVE_IPV6
	else if(sk->any.sa_family == AF_INET6 && sk->ip6.sin6_port != 0)
		strcat(s, va(":%d", ntohs(sk->ip6.sin6_port)));
#endif
	else if(sk->any.sa_family == AF_INET  && sk->ip4.sin_port  != 0)
		strcat(s, va(":%d", ntohs(sk->ip4.sin_port)));
#else
	if (sk->any.sa_family == AF_INET)
	{
		strcpy(s, inet_ntoa(sk->ip4.sin_addr));
		if (sk->ip4.sin_port != 0) strcat(s, va(":%d", ntohs(sk->ip4.sin_port)));
	}
	else
		sprintf(s, "Unknown type");
#endif
	return s;
}
#endif

static const char *SOCK_GetNodeAddress(INT32 node)
{
	if (node == 0)
		return "self";
#ifdef NONET
	return NULL;
#else
	if (!nodeconnected[node])
		return NULL;
	return SOCK_AddrToStr(&clientaddress[node]);
#endif
}

static const char *SOCK_GetBanAddress(size_t ban)
{
	if (ban >= numbans)
		return NULL;
#ifdef NONET
	return NULL;
#else
	return SOCK_AddrToStr(&banned[ban]);
#endif
}

static const char *SOCK_GetBanMask(size_t ban)
{
#ifdef NONET
	(void)ban;
#else
	static char s[16]; //255.255.255.255 netmask? no, just CDIR for only
	if (ban >= numbans)
		return NULL;
	if (sprintf(s,"%d",bannedmask[ban]) > 0)
		return s;
#endif
	return NULL;
}

#ifndef NONET
static boolean SOCK_cmpaddr(mysockaddr_t *a, mysockaddr_t *b, UINT8 mask)
{
	UINT32 bitmask = INADDR_NONE;

	if (mask && mask < 32)
455
		bitmask = htonl((UINT32)(-1) << (32 - mask));
Alam Ed Arias committed
456 457 458 459 460 461 462 463 464 465 466 467 468

	if (b->any.sa_family == AF_INET)
		return (a->ip4.sin_addr.s_addr & bitmask) == (b->ip4.sin_addr.s_addr & bitmask)
			&& (b->ip4.sin_port == 0 || (a->ip4.sin_port == b->ip4.sin_port));
#ifdef HAVE_IPV6
	else if (b->any.sa_family == AF_INET6)
		return memcmp(&a->ip6.sin6_addr, &b->ip6.sin6_addr, sizeof(b->ip6.sin6_addr))
			&& (b->ip6.sin6_port == 0 || (a->ip6.sin6_port == b->ip6.sin6_port));
#endif
	else
		return false;
}

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
// This is a hack. For some reason, nodes aren't being freed properly.
// This goes through and cleans up what nodes were supposed to be freed.
/** \warning This function causes the file downloading to stop if someone joins.
  *          How? Because it removes nodes that are connected but not in game,
  *          which is exactly what clients downloading a file are.
  */
static void cleanupnodes(void)
{
	SINT8 j;

	if (!Playing())
		return;

	// Why can't I start at zero?
	for (j = 1; j < MAXNETNODES; j++)
484
		if (!(nodeingame[j] || SendingFile(j)))
485 486 487
			nodeconnected[j] = false;
}

Alam Ed Arias committed
488 489 490 491
static SINT8 getfreenode(void)
{
	SINT8 j;

492 493
	cleanupnodes();

Alam Ed Arias committed
494 495 496 497 498 499
	for (j = 0; j < MAXNETNODES; j++)
		if (!nodeconnected[j])
		{
			nodeconnected[j] = true;
			return j;
		}
500 501 502 503 504 505 506 507 508 509 510

	/** \warning No free node? Just in case a node might not have been freed properly,
	  *          look if there are connected nodes that aren't in game, and forget them.
	  *          It's dirty, and might result in a poor guy having to restart
	  *          downloading a needed wad, but it's better than not letting anyone join...
	  */
	/*I_Error("No more free nodes!!1!11!11!!1111\n");
	for (j = 1; j < MAXNETNODES; j++)
		if (!nodeingame[j])
			return j;*/

Alam Ed Arias committed
511 512 513
	return -1;
}

LJ Sonic committed
514
#ifdef _DEBUG
515
void Command_Numnodes(void)
Alam Ed Arias committed
516
{
517 518 519
	INT32 connected = 0;
	INT32 ingame = 0;
	INT32 i;
Alam Ed Arias committed
520

521 522 523 524
	for (i = 1; i < MAXNETNODES; i++)
	{
		if (!(nodeconnected[i] || nodeingame[i]))
			continue;
Alam Ed Arias committed
525

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
		if (nodeconnected[i])
			connected++;
		if (nodeingame[i])
			ingame++;

		CONS_Printf("%2d - ", i);
		if (nodetoplayer[i] != -1)
			CONS_Printf("player %.2d", nodetoplayer[i]);
		else
			CONS_Printf("         ");
		if (nodeconnected[i])
			CONS_Printf(" - connected");
		else
			CONS_Printf(" -          ");
		if (nodeingame[i])
			CONS_Printf(" - ingame");
		else
			CONS_Printf(" -       ");
		CONS_Printf(" - %s\n", I_GetNodeAddress(i));
	}

	CONS_Printf("\n"
				"Connected: %d\n"
				"Ingame:    %d\n",
				connected, ingame);
Alam Ed Arias committed
551 552
}
#endif
553
#endif
Alam Ed Arias committed
554 555

#ifndef NONET
556 557
// Returns true if a packet was received from a new node, false in all other cases
static boolean SOCK_Get(void)
Alam Ed Arias committed
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
{
	size_t i, n;
	int j;
	ssize_t c;
	mysockaddr_t fromaddress;
	socklen_t fromlen;

	for (n = 0; n < mysocketses; n++)
	{
		fromlen = (socklen_t)sizeof(fromaddress);
		c = recvfrom(mysockets[n], (char *)&doomcom->data, MAXPACKETLENGTH, 0,
			(void *)&fromaddress, &fromlen);
		if (c != ERRSOCKET)
		{
			// find remote node number
James R. committed
573
			for (j = 1; j <= MAXNETNODES; j++) //include LAN
Alam Ed Arias committed
574 575 576 577 578 579
			{
				if (SOCK_cmpaddr(&fromaddress, &clientaddress[j], 0))
				{
					doomcom->remotenode = (INT16)j; // good packet from a game player
					doomcom->datalength = (INT16)c;
					nodesocket[j] = mysockets[n];
580
					return false;
Alam Ed Arias committed
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
				}
			}
			// not found

			// find a free slot
			j = getfreenode();
			if (j > 0)
			{
				M_Memcpy(&clientaddress[j], &fromaddress, fromlen);
				nodesocket[j] = mysockets[n];
				DEBFILE(va("New node detected: node:%d address:%s\n", j,
						SOCK_GetNodeAddress(j)));
				doomcom->remotenode = (INT16)j; // good packet from a game player
				doomcom->datalength = (INT16)c;

				// check if it's a banned dude so we can send a refusal later
				for (i = 0; i < numbans; i++)
				{
					if (SOCK_cmpaddr(&fromaddress, &banned[i], bannedmask[i]))
					{
						SOCK_bannednode[j] = true;
						DEBFILE("This dude has been banned\n");
						break;
					}
				}
				if (i == numbans)
					SOCK_bannednode[j] = false;
608
				return true;
Alam Ed Arias committed
609 610 611 612 613
			}
			else
				DEBFILE("New node detected: No more free slots\n");
		}
	}
614

Alam Ed Arias committed
615
	doomcom->remotenode = -1; // no packet
616
	return false;
Alam Ed Arias committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
}
#endif

// check if we can send (do not go over the buffer)
#ifndef NONET

static fd_set masterset;

#ifdef SELECTTEST
static boolean FD_CPY(fd_set *src, fd_set *dst, SOCKET_TYPE *fd, size_t len)
{
	size_t i;
	boolean testset = false;
	FD_ZERO(dst);
	for (i = 0; i < len;i++)
	{
Alam Ed Arias committed
633
		if(fd[i] != (SOCKET_TYPE)ERRSOCKET &&
Alam Ed Arias committed
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
		   FD_ISSET(fd[i], src) && !FD_ISSET(fd[i], dst)) // no checking for dups
		{
			FD_SET(fd[i], dst);
			testset = true;
		}
	}
	return testset;
}

static boolean SOCK_CanSend(void)
{
	struct timeval timeval_for_select = {0, 0};
	fd_set tset;
	int wselect;

	if(!FD_CPY(&masterset, &tset, mysockets, mysocketses))
		return false;
	wselect = select(255, NULL, &tset, NULL, &timeval_for_select);
	if (wselect >= 1)
		return true;
	return false;
}

static boolean SOCK_CanGet(void)
{
	struct timeval timeval_for_select = {0, 0};
	fd_set tset;
	int rselect;

	if(!FD_CPY(&masterset, &tset, mysockets, mysocketses))
		return false;
	rselect = select(255, &tset, NULL, NULL, &timeval_for_select);
	if (rselect >= 1)
		return true;
	return false;
}
#endif
#endif

#ifndef NONET
674
static inline ssize_t SOCK_SendToAddr(SOCKET_TYPE socket, mysockaddr_t *sockaddr)
Alam Ed Arias committed
675 676 677 678 679 680
{
	socklen_t d4 = (socklen_t)sizeof(struct sockaddr_in);
#ifdef HAVE_IPV6
	socklen_t d6 = (socklen_t)sizeof(struct sockaddr_in6);
#endif
	socklen_t d, da = (socklen_t)sizeof(mysockaddr_t);
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696

	switch (sockaddr->any.sa_family)
	{
		case AF_INET:  d = d4; break;
#ifdef HAVE_IPV6
		case AF_INET6: d = d6; break;
#endif
		default:       d = da; break;
	}

	return sendto(socket, (char *)&doomcom->data, doomcom->datalength, 0, &sockaddr->any, d);
}

static void SOCK_Send(void)
{
	ssize_t c = ERRSOCKET;
Alam Ed Arias committed
697 698 699 700 701 702 703 704 705 706 707 708
	size_t i, j;

	if (!nodeconnected[doomcom->remotenode])
		return;

	if (doomcom->remotenode == BROADCASTADDR)
	{
		for (i = 0; i < mysocketses; i++)
		{
			for (j = 0; j < broadcastaddresses; j++)
			{
				if (myfamily[i] == broadcastaddress[j].any.sa_family)
709
					SOCK_SendToAddr(mysockets[i], &broadcastaddress[j]);
Alam Ed Arias committed
710 711 712 713
			}
		}
		return;
	}
Alam Ed Arias committed
714
	else if (nodesocket[doomcom->remotenode] == (SOCKET_TYPE)ERRSOCKET)
Alam Ed Arias committed
715 716 717 718
	{
		for (i = 0; i < mysocketses; i++)
		{
			if (myfamily[i] == clientaddress[doomcom->remotenode].any.sa_family)
719
				SOCK_SendToAddr(mysockets[i], &clientaddress[doomcom->remotenode]);
Alam Ed Arias committed
720 721 722 723 724
		}
		return;
	}
	else
	{
725
		c = SOCK_SendToAddr(nodesocket[doomcom->remotenode], &clientaddress[doomcom->remotenode]);
Alam Ed Arias committed
726 727
	}

728 729 730 731 732 733 734
	if (c == ERRSOCKET)
	{
		int e = errno; // save error code so it can't be modified later
		if (e != ECONNREFUSED && e != EWOULDBLOCK)
			I_Error("SOCK_Send, error sending to node %d (%s) #%u: %s", doomcom->remotenode,
				SOCK_GetNodeAddress(doomcom->remotenode), e, strerror(e));
	}
Alam Ed Arias committed
735 736 737 738 739 740 741 742 743 744 745 746 747
}
#endif

#ifndef NONET
static void SOCK_FreeNodenum(INT32 numnode)
{
	// can't disconnect from self :)
	if (!numnode || numnode > MAXNETNODES)
		return;

	DEBFILE(va("Free node %d (%s)\n", numnode, SOCK_GetNodeAddress(numnode)));

	nodeconnected[numnode] = false;
Alam Ed Arias committed
748
	nodesocket[numnode] = ERRSOCKET;
Alam Ed Arias committed
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773

	// put invalid address
	memset(&clientaddress[numnode], 0, sizeof (clientaddress[numnode]));
}
#endif

//
// UDPsocket
//
#ifndef NONET

// allocate a socket
static SOCKET_TYPE UDP_Bind(int family, struct sockaddr *addr, socklen_t addrlen)
{
	SOCKET_TYPE s = socket(family, SOCK_DGRAM, IPPROTO_UDP);
	int opt;
	socklen_t opts;
#ifdef FIONBIO
#ifdef WATTCP
	char trueval = true;
#else
	unsigned long trueval = true;
#endif
#endif
	mysockaddr_t straddr;
774 775
	struct sockaddr_in sin;
	socklen_t len = sizeof(sin);
Alam Ed Arias committed
776

Alam Ed Arias committed
777
	if (s == (SOCKET_TYPE)ERRSOCKET)
Alam Ed Arias committed
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
		return (SOCKET_TYPE)ERRSOCKET;
#ifdef USE_WINSOCK
	{ // Alam_GBC: disable the new UDP connection reset behavior for Win2k and up
#ifdef USE_WINSOCK2
		DWORD dwBytesReturned = 0;
		BOOL bfalse = FALSE;
		WSAIoctl(s, SIO_UDP_CONNRESET, &bfalse, sizeof(bfalse),
		         NULL, 0, &dwBytesReturned, NULL, NULL);
#else
		unsigned long falseval = false;
		ioctl(s, SIO_UDP_CONNRESET, &falseval);
#endif
	}
#endif

	straddr.any = *addr;
	I_OutputMsg("Binding to %s\n", SOCK_AddrToStr(&straddr));

	if (family == AF_INET)
	{
		mysockaddr_t tmpaddr;
		tmpaddr.any = *addr ;
		if (tmpaddr.ip4.sin_addr.s_addr == htonl(INADDR_ANY))
		{
			opt = true;
			opts = (socklen_t)sizeof(opt);
			setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, opts);
		}
		// make it broadcastable
		opt = true;
		opts = (socklen_t)sizeof(opt);
		if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&opt, opts))
		{
			CONS_Alert(CONS_WARNING, M_GetText("Could not get broadcast rights\n")); // I do not care anymore
		}
	}
#ifdef HAVE_IPV6
	else if (family == AF_INET6)
	{
		if (memcmp(addr, &in6addr_any, sizeof(in6addr_any)) == 0) //IN6_ARE_ADDR_EQUAL
		{
			opt = true;
			opts = (socklen_t)sizeof(opt);
			setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, opts);
		}
#ifdef IPV6_V6ONLY
		// make it IPv6 ony
		opt = true;
		opts = (socklen_t)sizeof(opt);
		if (setsockopt(s, SOL_SOCKET, IPV6_V6ONLY, (char *)&opt, opts))
		{
			CONS_Alert(CONS_WARNING, M_GetText("Could not limit IPv6 bind\n")); // I do not care anymore
		}
#endif
	}
#endif

	if (bind(s, addr, addrlen) == ERRSOCKET)
	{
		close(s);
		I_OutputMsg("Binding failed\n");
		return (SOCKET_TYPE)ERRSOCKET;
	}

#ifdef FIONBIO
	// make it non blocking
	opt = true;
	if (ioctl(s, FIONBIO, &trueval) != 0)
	{
		close(s);
		I_OutputMsg("Seting FIOBIO on failed\n");
		return (SOCKET_TYPE)ERRSOCKET;
	}
#endif

	opts = (socklen_t)sizeof(opt);
	getsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&opt, &opts);
	CONS_Printf(M_GetText("Network system buffer: %dKb\n"), opt>>10);

	if (opt < 64<<10) // 64k
	{
		opt = 64<<10;
		opts = (socklen_t)sizeof(opt);
		setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&opt, opts);
		getsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&opt, &opts);
		if (opt < 64<<10)
			CONS_Alert(CONS_WARNING, M_GetText("Can't set buffer length to 64k, file transfer will be bad\n"));
		else
			CONS_Printf(M_GetText("Network system buffer set to: %dKb\n"), opt>>10);
	}

869 870 871 872 873
	if (getsockname(s, (struct sockaddr *)&sin, &len) == -1)
		CONS_Alert(CONS_WARNING, M_GetText("Failed to get port number\n"));
	else
		current_port = (UINT16)ntohs(sin.sin_port);

Alam Ed Arias committed
874 875 876 877 878 879 880 881 882 883 884
	return s;
}

static boolean UDP_Socket(void)
{
	size_t s;
	struct my_addrinfo *ai, *runp, hints;
	int gaie;
#ifdef HAVE_IPV6
	const INT32 b_ipv6 = M_CheckParm("-ipv6");
#endif
885
	const char *serv;
Alam Ed Arias committed
886 887 888


	for (s = 0; s < mysocketses; s++)
Alam Ed Arias committed
889
		mysockets[s] = ERRSOCKET;
Alam Ed Arias committed
890
	for (s = 0; s < MAXNETNODES+1; s++)
Alam Ed Arias committed
891
		nodesocket[s] = ERRSOCKET;
Alam Ed Arias committed
892 893 894 895 896 897 898 899 900
	FD_ZERO(&masterset);
	s = 0;

	memset(&hints, 0x00, sizeof (hints));
	hints.ai_flags = AI_NUMERICHOST;
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_protocol = IPPROTO_UDP;

901
	if (serverrunning)
902
		serv = serverport_name;
903
	else
904
		serv = clientport_name;
905

Alam Ed Arias committed
906 907 908 909
	if (M_CheckParm("-bindaddr"))
	{
		while (M_IsNextParm())
		{
910
			gaie = I_getaddrinfo(M_GetNextParm(), serv, &hints, &ai);
Alam Ed Arias committed
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
			if (gaie == 0)
			{
				runp = ai;
				while (runp != NULL && s < MAXNETNODES+1)
				{
					mysockets[s] = UDP_Bind(runp->ai_family, runp->ai_addr, (socklen_t)runp->ai_addrlen);
					if (mysockets[s] != (SOCKET_TYPE)ERRSOCKET)
					{
						FD_SET(mysockets[s], &masterset);
						myfamily[s] = hints.ai_family;
						s++;
					}
					runp = runp->ai_next;
				}
				I_freeaddrinfo(ai);
			}
		}
	}
	else
	{
931
		gaie = I_getaddrinfo("0.0.0.0", serv, &hints, &ai);
Alam Ed Arias committed
932 933 934 935 936 937 938 939 940 941 942 943 944 945
		if (gaie == 0)
		{
			runp = ai;
			while (runp != NULL && s < MAXNETNODES+1)
			{
				mysockets[s] = UDP_Bind(runp->ai_family, runp->ai_addr, (socklen_t)runp->ai_addrlen);
				if (mysockets[s] != (SOCKET_TYPE)ERRSOCKET)
				{
					FD_SET(mysockets[s], &masterset);
					myfamily[s] = hints.ai_family;
					s++;
#ifdef HAVE_MINIUPNPC
					if (UPNP_support)
					{
946 947
						I_UPnP_rem(serverport_name, "UDP");
						I_UPnP_add(NULL, serverport_name, "UDP");
Alam Ed Arias committed
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
					}
#endif
				}
				runp = runp->ai_next;
			}
			I_freeaddrinfo(ai);
		}
	}
#ifdef HAVE_IPV6
	if (b_ipv6)
	{
		hints.ai_family = AF_INET6;
		if (M_CheckParm("-bindaddr6"))
		{
			while (M_IsNextParm())
			{
964
				gaie = I_getaddrinfo(M_GetNextParm(), serv, &hints, &ai);
Alam Ed Arias committed
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
				if (gaie == 0)
				{
					runp = ai;
					while (runp != NULL && s < MAXNETNODES+1)
					{
						mysockets[s] = UDP_Bind(runp->ai_family, runp->ai_addr, (socklen_t)runp->ai_addrlen);
						if (mysockets[s] != (SOCKET_TYPE)ERRSOCKET)
						{
							FD_SET(mysockets[s], &masterset);
							myfamily[s] = hints.ai_family;
							s++;
						}
						runp = runp->ai_next;
					}
					I_freeaddrinfo(ai);
				}
			}
		}
		else
		{
985
			gaie = I_getaddrinfo("::", serv, &hints, &ai);
Alam Ed Arias committed
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
			if (gaie == 0)
			{
				runp = ai;
				while (runp != NULL && s < MAXNETNODES+1)
				{
					mysockets[s] = UDP_Bind(runp->ai_family, runp->ai_addr, (socklen_t)runp->ai_addrlen);
					if (mysockets[s] != (SOCKET_TYPE)ERRSOCKET)
					{
						FD_SET(mysockets[s], &masterset);
						myfamily[s] = hints.ai_family;
						s++;
					}
					runp = runp->ai_next;
				}
				I_freeaddrinfo(ai);
			}
		}
	}
#endif

	mysocketses = s;
	if (s == 0) // no sockets?
		return false;

	s = 0;

	// ip + udp
	packetheaderlength = 20 + 8; // for stats

	hints.ai_family = AF_INET;
	gaie = I_getaddrinfo("127.0.0.1", "0", &hints, &ai);
	if (gaie == 0)
	{
		runp = ai;
1020
		while (runp != NULL && s < MAXNETNODES+1)
Alam Ed Arias committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		{
			memcpy(&clientaddress[s], runp->ai_addr, runp->ai_addrlen);
			s++;
			runp = runp->ai_next;
		}
		I_freeaddrinfo(ai);
	}
	else
	{
		clientaddress[s].any.sa_family = AF_INET;
		clientaddress[s].ip4.sin_port = htons(0);
		clientaddress[s].ip4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); //GetLocalAddress(); // my own ip
		s++;
	}
1035 1036 1037

	s = 0;

Alam Ed Arias committed
1038 1039 1040 1041 1042
	// setup broadcast adress to BROADCASTADDR entry
	gaie = I_getaddrinfo("255.255.255.255", "0", &hints, &ai);
	if (gaie == 0)
	{
		runp = ai;
1043
		while (runp != NULL && s < MAXNETNODES+1)
Alam Ed Arias committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
		{
			memcpy(&broadcastaddress[s], runp->ai_addr, runp->ai_addrlen);
			s++;
			runp = runp->ai_next;
		}
		I_freeaddrinfo(ai);
	}
	else
	{
		broadcastaddress[s].any.sa_family = AF_INET;
		broadcastaddress[s].ip4.sin_port = htons(0);
		broadcastaddress[s].ip4.sin_addr.s_addr = htonl(INADDR_BROADCAST);
		s++;
	}
#ifdef HAVE_IPV6
	if (b_ipv6)
	{
		hints.ai_family = AF_INET6;
		gaie = I_getaddrinfo("ff02::1", "0", &hints, &ai);
		if (gaie == 0)
		{
			runp = ai;
1066
			while (runp != NULL && s < MAXNETNODES+1)
Alam Ed Arias committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
			{
				memcpy(&broadcastaddress[s], runp->ai_addr, runp->ai_addrlen);
				s++;
				runp = runp->ai_next;
			}
			I_freeaddrinfo(ai);
		}
	}
#endif

	broadcastaddresses = s;

	doomcom->extratics = 1; // internet is very high ping

	return true;
}
#endif

boolean I_InitTcpDriver(void)
{
	boolean tcp_was_up = init_tcp_driver;
#ifndef NONET
	if (!init_tcp_driver)
	{
#ifdef USE_WINSOCK
#ifdef USE_WINSOCK2
		const WORD VerNeed = MAKEWORD(2,2);
#else
		const WORD VerNeed = MAKEWORD(1,1);
#endif
		WSADATA WSAData;
		const int WSAresult = WSAStartup(VerNeed, &WSAData);
		if (WSAresult != 0)
		{
			LPCSTR WSError = NULL;
			switch (WSAresult)
			{
				case WSASYSNOTREADY:
					WSError = "The underlying network subsystem is not ready for network communication";
					break;
				case WSAEINPROGRESS:
					WSError = "A blocking Windows Sockets 1.1 operation is in progress";
					break;
				case WSAEPROCLIM:
					WSError = "Limit on the number of tasks supported by the Windows Sockets implementation has been reached";
					break;
				case WSAEFAULT:
					WSError = "WSAData is not a valid pointer? What kind of setup do you have?";
					break;
				default:
					WSError = va("Error code %u",WSAresult);
					break;
			}
			if (WSAresult != WSAVERNOTSUPPORTED)
				CONS_Debug(DBG_NETPLAY, "WinSock(TCP/IP) error: %s\n",WSError);
		}
#ifdef USE_WINSOCK2
		if(LOBYTE(WSAData.wVersion) != 2 ||
			HIBYTE(WSAData.wVersion) != 2)
		{
			WSACleanup();
			CONS_Debug(DBG_NETPLAY, "No WinSock(TCP/IP) 2.2 driver detected\n");
		}
#else
		if (LOBYTE(WSAData.wVersion) != 1 ||
			HIBYTE(WSAData.wVersion) != 1)
		{
			WSACleanup();
			CONS_Debug(DBG_NETPLAY, "No WinSock(TCP/IP) 1.1 driver detected\n");
		}
#endif
		CONS_Debug(DBG_NETPLAY, "WinSock description: %s\n",WSAData.szDescription);
		CONS_Debug(DBG_NETPLAY, "WinSock System Status: %s\n",WSAData.szSystemStatus);
#endif
#ifdef __DJGPP__
#ifdef WATTCP // Alam_GBC: survive bootp, dhcp, rarp and wattcp/pktdrv from failing to load
		survive_eth   = 1; // would be needed to not exit if pkt_eth_init() fails
		survive_bootp = 1; // ditto for BOOTP
		survive_dhcp  = 1; // ditto for DHCP/RARP
		survive_rarp  = 1;
		//_watt_do_exit = false;
		//_watt_handle_cbreak = false;
		//_watt_no_config = true;
		_outch = wattcp_outch;
		init_misc();
//#ifdef DEBUGFILE
		dbug_init();
//#endif
		switch (sock_init())
		{
			case 0:
				init_tcp_driver = true;
				break;
			case 3:
				CONS_Debug(DBG_NETPLAY, "No packet driver detected\n");
				break;
			case 4:
				CONS_Debug(DBG_NETPLAY, "Error while talking to packet driver\n");
				break;
			case 5:
				CONS_Debug(DBG_NETPLAY, "BOOTP failed\n");
				break;
			case 6:
				CONS_Debug(DBG_NETPLAY, "DHCP failed\n");
				break;
			case 7:
				CONS_Debug(DBG_NETPLAY, "RARP failed\n");
				break;
			case 8:
				CONS_Debug(DBG_NETPLAY, "TCP/IP failed\n");
				break;
			case 9:
				CONS_Debug(DBG_NETPLAY, "PPPoE login/discovery failed\n");
				break;
			default:
				CONS_Debug(DBG_NETPLAY, "Unknown error with TCP/IP stack\n");
				break;
		}
		hires_timer(0);
#else // wattcp
		if (__lsck_init())
			init_tcp_driver = true;
		else
			CONS_Debug(DBG_NETPLAY, "No TCP/IP driver detected\n");
#endif // libsocket
#endif // __DJGPP__
#ifndef __DJGPP__
		init_tcp_driver = true;
#endif
	}
#endif
	if (!tcp_was_up && init_tcp_driver)
	{
		I_AddExitFunc(I_ShutdownTcpDriver);
#ifdef HAVE_MINIUPNPC
		if (M_CheckParm("-useUPnP"))
			I_InitUPnP();
		else
			UPNP_support = false;
#endif
	}
	return init_tcp_driver;
}

#ifndef NONET
static void SOCK_CloseSocket(void)
{
	size_t i;
	for (i=0; i < MAXNETNODES+1; i++)
	{
		if (mysockets[i] != (SOCKET_TYPE)ERRSOCKET
		 && FD_ISSET(mysockets[i], &masterset))
		{
#if !defined (__DJGPP__) || defined (WATTCP)
			FD_CLR(mysockets[i], &masterset);
			close(mysockets[i]);
#endif
		}
Alam Ed Arias committed
1225
		mysockets[i] = ERRSOCKET;
Alam Ed Arias committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
	}
}
#endif

void I_ShutdownTcpDriver(void)
{
#ifndef NONET
	SOCK_CloseSocket();

	CONS_Printf("I_ShutdownTcpDriver: ");
#ifdef USE_WINSOCK
	WS_addrinfocleanup();
	WSACleanup();
#endif
#ifdef __DJGPP__
#ifdef WATTCP // wattcp
	//_outch = NULL;
	sock_exit();
#else
	__lsck_uninit();
#endif // libsocket
#endif // __DJGPP__
	CONS_Printf("shut down\n");
	init_tcp_driver = false;
#endif
}

#ifndef NONET
static SINT8 SOCK_NetMakeNodewPort(const char *address, const char *port)
{
	SINT8 newnode = -1;
1257
	struct my_addrinfo *ai = NULL, *runp, hints;
Alam Ed Arias committed
1258 1259 1260
	int gaie;

	 if (!port || !port[0])
1261
		port = DEFAULTPORT;
Alam Ed Arias committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286

	DEBFILE(va("Creating new node: %s@%s\n", address, port));

	memset (&hints, 0x00, sizeof (hints));
	hints.ai_flags = 0;
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_protocol = IPPROTO_UDP;

	gaie = I_getaddrinfo(address, port, &hints, &ai);
	if (gaie == 0)
	{
		newnode = getfreenode();
	}
	if (newnode == -1)
	{
		I_freeaddrinfo(ai);
		return -1;
	}
	else
		runp = ai;

	while (runp != NULL)
	{
		// find ip of the server
1287 1288 1289 1290 1291 1292
		if (sendto(mysockets[0], NULL, 0, 0, runp->ai_addr, runp->ai_addrlen) == 0)
		{
			memcpy(&clientaddress[newnode], runp->ai_addr, runp->ai_addrlen);
			break;
		}
		runp = runp->ai_next;
Alam Ed Arias committed
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
	}
	I_freeaddrinfo(ai);
	return newnode;
}
#endif

static boolean SOCK_OpenSocket(void)
{
#ifndef NONET
	size_t i;

	memset(clientaddress, 0, sizeof (clientaddress));

	nodeconnected[0] = true; // always connected to self
	for (i = 1; i < MAXNETNODES; i++)
		nodeconnected[i] = false;
	nodeconnected[BROADCASTADDR] = true;
	I_NetSend = SOCK_Send;
	I_NetGet = SOCK_Get;
	I_NetCloseSocket = SOCK_CloseSocket;
	I_NetFreeNodenum = SOCK_FreeNodenum;
	I_NetMakeNodewPort = SOCK_NetMakeNodewPort;

#ifdef SELECTTEST
	// seem like not work with libsocket : (
	I_NetCanSend = SOCK_CanSend;
	I_NetCanGet = SOCK_CanGet;
#endif

	// build the socket but close it first
	SOCK_CloseSocket();
	return UDP_Socket();
#else
	return false;
#endif
}

static boolean SOCK_Ban(INT32 node)
{
	if (node > MAXNETNODES)
		return false;
#ifdef NONET
	return false;
#else
	if (numbans == MAXBANS)
		return false;

	M_Memcpy(&banned[numbans], &clientaddress[node], sizeof (mysockaddr_t));
	if (banned[numbans].any.sa_family == AF_INET)
	{
		banned[numbans].ip4.sin_port = 0;
		bannedmask[numbans] = 32;
	}
#ifdef HAVE_IPV6
	else if (banned[numbans].any.sa_family == AF_INET6)
	{
		banned[numbans].ip6.sin6_port = 0;
		bannedmask[numbans] = 128;
	}
#endif
	numbans++;
	return true;
#endif
}

static boolean SOCK_SetBanAddress(const char *address, const char *mask)
{
#ifdef NONET
	(void)address;
	(void)mask;
	return false;
#else
	struct my_addrinfo *ai, *runp, hints;
	int gaie;

	if (numbans == MAXBANS || !address)
		return false;

	memset(&hints, 0x00, sizeof(hints));
	hints.ai_flags = 0;
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_protocol = IPPROTO_UDP;

	gaie = I_getaddrinfo(address, "0", &hints, &ai);
	if (gaie != 0)
		return false;

	runp = ai;

	while(runp != NULL && numbans != MAXBANS)
	{
		memcpy(&banned[numbans], runp->ai_addr, runp->ai_addrlen);

		if (mask)
			bannedmask[numbans] = (UINT8)atoi(mask);
#ifdef HAVE_IPV6
		else if (runp->ai_family == AF_INET6)
			bannedmask[numbans] = 128;
#endif
		else
			bannedmask[numbans] = 32;

		if (bannedmask[numbans] > 32 && runp->ai_family == AF_INET)
			bannedmask[numbans] = 32;
#ifdef HAVE_IPV6
		else if (bannedmask[numbans] > 128 && runp->ai_family == AF_INET6)
			bannedmask[numbans] = 128;
#endif
		numbans++;
		runp = runp->ai_next;
	}

	I_freeaddrinfo(ai);

	return true;
#endif
}

static void SOCK_ClearBans(void)
{
	numbans = 0;
}

boolean I_InitTcpNetwork(void)
{
	char serverhostname[255];
1420
	const char *urlparam = NULL;
Alam Ed Arias committed
1421 1422 1423 1424 1425
	boolean ret = false;
	// initilize the OS's TCP/IP stack
	if (!I_InitTcpDriver())
		return false;

1426
	if (M_CheckParm("-port") || M_CheckParm("-serverport"))
1427 1428
	// Combined -udpport and -clientport into -port
	// As it was really redundant having two seperate parms that does the same thing
1429
	/* Sorry Steel, I'm adding these back. But -udpport is a stupid name. */
Alam Ed Arias committed
1430
	{
James R. committed
1431 1432 1433 1434
		/*
		If it's NULL, that's okay! Because then
		we'll get a random port from getaddrinfo.
		*/
1435
		serverport_name = M_GetNextParm();
Alam Ed Arias committed
1436
	}
1437 1438
	if (M_CheckParm("-clientport"))
		clientport_name = M_GetNextParm();
Alam Ed Arias committed
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473

	// parse network game options,
	if (M_CheckParm("-server") || dedicated)
	{
		server = true;

		// If a number of clients (i.e. nodes) is specified, the server will wait for the clients
		// to connect before starting.
		// If no number is specified here, the server starts with 1 client, and others can join
		// in-game.
		// Since Boris has implemented join in-game, there is no actual need for specifying a
		// particular number here.
		// FIXME: for dedicated server, numnodes needs to be set to 0 upon start
		if (dedicated)
			doomcom->numnodes = 0;
/*		else if (M_IsNextParm())
			doomcom->numnodes = (INT16)atoi(M_GetNextParm());*/
		else
			doomcom->numnodes = 1;

		if (doomcom->numnodes < 0)
			doomcom->numnodes = 0;
		if (doomcom->numnodes > MAXNETNODES)
			doomcom->numnodes = MAXNETNODES;

		// server
		servernode = 0;
		// FIXME:
		// ??? and now ?
		// server on a big modem ??? 4*isdn
		net_bandwidth = 16000;
		hardware_MAXPACKETLENGTH = INETPACKETLENGTH;

		ret = true;
	}
1474
	else if ((urlparam = M_GetUrlProtocolArg()) != NULL || M_CheckParm("-connect"))
Alam Ed Arias committed
1475
	{
1476 1477 1478 1479
		if (urlparam != NULL)
			strlcpy(serverhostname, urlparam, sizeof(serverhostname));
		else if (M_IsNextParm())
			strlcpy(serverhostname, M_GetNextParm(), sizeof(serverhostname));
Alam Ed Arias committed
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
		else
			serverhostname[0] = 0; // assuming server in the LAN, use broadcast to detect it

		// server address only in ip
		if (serverhostname[0])
		{
			COM_BufAddText("connect \"");
			COM_BufAddText(serverhostname);
			COM_BufAddText("\"\n");

			// probably modem
			hardware_MAXPACKETLENGTH = INETPACKETLENGTH;
		}
		else
		{
			// so we're on a LAN
			COM_BufAddText("connect any\n");

			net_bandwidth = 800000;
			hardware_MAXPACKETLENGTH = MAXPACKETLENGTH;
		}
	}

	I_NetOpenSocket = SOCK_OpenSocket;
	I_Ban = SOCK_Ban;
	I_ClearBans = SOCK_ClearBans;
	I_GetNodeAddress = SOCK_GetNodeAddress;
	I_GetBanAddress = SOCK_GetBanAddress;
	I_GetBanMask = SOCK_GetBanMask;
	I_SetBanAddress = SOCK_SetBanAddress;
	bannednode = SOCK_bannednode;

	return ret;
}

#include "i_addrinfo.c"