platformNet.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platformNet.h"
  23. #include "platform/threads/mutex.h"
  24. #include "core/strings/stringFunctions.h"
  25. #include "core/util/hashFunction.h"
  26. #include "console/consoleTypes.h"
  27. // jamesu - debug DNS
  28. //#define TORQUE_DEBUG_LOOKUPS
  29. #if defined (TORQUE_OS_WIN)
  30. #define TORQUE_USE_WINSOCK
  31. #include <errno.h>
  32. #include <ws2tcpip.h>
  33. #ifndef EINPROGRESS
  34. #define EINPROGRESS WSAEINPROGRESS
  35. #endif // EINPROGRESS
  36. #define ioctl ioctlsocket
  37. typedef S32 socklen_t;
  38. #elif defined ( TORQUE_OS_MAC )
  39. #include <unistd.h>
  40. #include <sys/types.h>
  41. #include <sys/socket.h>
  42. #include <sys/poll.h>
  43. #include <arpa/inet.h>
  44. #include <netdb.h>
  45. #include <netinet/in.h>
  46. #include <errno.h>
  47. #include <sys/ioctl.h>
  48. #include <net/if.h>
  49. typedef sockaddr_in SOCKADDR_IN;
  50. typedef sockaddr * PSOCKADDR;
  51. typedef sockaddr SOCKADDR;
  52. typedef in_addr IN_ADDR;
  53. typedef int SOCKET;
  54. #define INVALID_SOCKET -1
  55. #define SOCKET_ERROR -1
  56. #define closesocket close
  57. #elif defined( TORQUE_OS_LINUX )
  58. #include <unistd.h>
  59. #include <sys/types.h>
  60. #include <sys/socket.h>
  61. #include <sys/poll.h>
  62. #include <arpa/inet.h>
  63. #include <netdb.h>
  64. #include <netinet/in.h>
  65. #include <errno.h>
  66. #include <sys/ioctl.h>
  67. #include <net/if.h>
  68. typedef sockaddr_in SOCKADDR_IN;
  69. typedef sockaddr_in6 SOCKADDR_IN6;
  70. typedef sockaddr * PSOCKADDR;
  71. typedef sockaddr SOCKADDR;
  72. typedef in_addr IN_ADDR;
  73. typedef in6_addr IN6_ADDR;
  74. typedef int SOCKET;
  75. #define INVALID_SOCKET -1
  76. #define SOCKET_ERROR -1
  77. #define closesocket close
  78. #elif defined( TORQUE_OS_XENON )
  79. #include <Xtl.h>
  80. #include <string>
  81. #define TORQUE_USE_WINSOCK
  82. #define EINPROGRESS WSAEINPROGRESS
  83. #define ioctl ioctlsocket
  84. typedef S32 socklen_t;
  85. DWORD _getLastErrorAndClear()
  86. {
  87. DWORD err = WSAGetLastError();
  88. WSASetLastError( 0 );
  89. return err;
  90. }
  91. #else
  92. #endif
  93. #if defined(TORQUE_USE_WINSOCK)
  94. static const char* strerror_wsa( S32 code )
  95. {
  96. switch( code )
  97. {
  98. #define E( name ) case name: return #name;
  99. E( WSANOTINITIALISED );
  100. E( WSAENETDOWN );
  101. E( WSAEADDRINUSE );
  102. E( WSAEINPROGRESS );
  103. E( WSAEALREADY );
  104. E( WSAEADDRNOTAVAIL );
  105. E( WSAEAFNOSUPPORT );
  106. E( WSAEFAULT );
  107. E( WSAEINVAL );
  108. E( WSAEISCONN );
  109. E( WSAENETUNREACH );
  110. E( WSAEHOSTUNREACH );
  111. E( WSAENOBUFS );
  112. E( WSAENOTSOCK );
  113. E( WSAETIMEDOUT );
  114. E( WSAEWOULDBLOCK );
  115. E( WSAEACCES );
  116. #undef E
  117. default:
  118. return "Unknown";
  119. }
  120. }
  121. #endif
  122. #include "core/util/tVector.h"
  123. #include "platform/platformNetAsync.h"
  124. #include "console/console.h"
  125. #include "core/util/journal/process.h"
  126. #include "core/util/journal/journal.h"
  127. NetSocket NetSocket::INVALID = NetSocket::fromHandle(-1);
  128. template<class T> class ReservedSocketList
  129. {
  130. public:
  131. struct EntryType
  132. {
  133. T value;
  134. bool used;
  135. EntryType() : value(-1), used(false) { ; }
  136. bool operator==(const EntryType &e1)
  137. {
  138. return value == e1.value && used == e1.used;
  139. }
  140. bool operator!=(const EntryType &e1)
  141. {
  142. return !(value == e1.value && used == e1.used);
  143. }
  144. };
  145. Vector<EntryType> mSocketList;
  146. Mutex *mMutex;
  147. ReservedSocketList()
  148. {
  149. mMutex = new Mutex;
  150. }
  151. ~ReservedSocketList()
  152. {
  153. delete mMutex;
  154. }
  155. inline void modify() { Mutex::lockMutex(mMutex); }
  156. inline void endModify() { Mutex::unlockMutex(mMutex); }
  157. NetSocket reserve(SOCKET reserveId = -1, bool doLock = true);
  158. void remove(NetSocket socketToRemove, bool doLock = true);
  159. T activate(NetSocket socketToActivate, int family, bool useUDP, bool clearOnFail = false);
  160. T resolve(NetSocket socketToResolve);
  161. };
  162. const SOCKET InvalidSocketHandle = -1;
  163. static void IPSocketToNetAddress(const struct sockaddr_in *sockAddr, NetAddress *address);
  164. namespace PlatformNetState
  165. {
  166. static S32 initCount = 0;
  167. static const S32 defaultPort = 28000;
  168. static S32 netPort = 0;
  169. static NetSocket udpSocket = NetSocket::INVALID;
  170. static NetSocket udp6Socket = NetSocket::INVALID;
  171. static NetSocket multicast6Socket = NetSocket::INVALID;
  172. static ipv6_mreq multicast6Group;
  173. static ReservedSocketList<SOCKET> smReservedSocketList;
  174. static Net::Error getLastError()
  175. {
  176. #if defined(TORQUE_USE_WINSOCK)
  177. S32 err = WSAGetLastError();
  178. switch (err)
  179. {
  180. case 0:
  181. return Net::NoError;
  182. case WSAEWOULDBLOCK:
  183. return Net::WouldBlock;
  184. default:
  185. return Net::UnknownError;
  186. }
  187. #else
  188. if (errno == EAGAIN)
  189. return Net::WouldBlock;
  190. if (errno == 0)
  191. return Net::NoError;
  192. return Net::UnknownError;
  193. #endif
  194. }
  195. static S32 getDefaultGameProtocol()
  196. {
  197. // we turn off VDP in non-release builds because VDP does not support broadcast packets
  198. // which are required for LAN queries (PC->Xbox connectivity). The wire protocol still
  199. // uses the VDP packet structure, though.
  200. S32 protocol = IPPROTO_UDP;
  201. bool useVDP = false;
  202. #ifdef TORQUE_DISABLE_PC_CONNECTIVITY
  203. // Xbox uses a VDP (voice/data protocol) socket for networking
  204. protocol = IPPROTO_VDP;
  205. useVDP = true;
  206. #endif
  207. return protocol;
  208. }
  209. static struct addrinfo* pickAddressByProtocol(struct addrinfo* addr, int protocol)
  210. {
  211. for (addr; addr != NULL; addr = addr->ai_next)
  212. {
  213. if (addr->ai_family == protocol)
  214. return addr;
  215. }
  216. return NULL;
  217. }
  218. /// Extracts core address parts from an address string. Returns false if it's malformed.
  219. static bool extractAddressParts(const char *addressString, char outAddress[256], int &outPort, int &outFamily)
  220. {
  221. outPort = 0;
  222. outFamily = AF_UNSPEC;
  223. if (!dStrnicmp(addressString, "ipx:", 4))
  224. // ipx support deprecated
  225. return false;
  226. if (!dStrnicmp(addressString, "ip:", 3))
  227. {
  228. addressString += 3; // eat off the ip:
  229. outFamily = AF_INET;
  230. }
  231. else if (!dStrnicmp(addressString, "ip6:", 4))
  232. {
  233. addressString += 4; // eat off the ip6:
  234. outFamily = AF_INET6;
  235. }
  236. if (strlen(addressString) > 255)
  237. return false;
  238. char *portString = NULL;
  239. if (addressString[0] == '[')
  240. {
  241. // Must be ipv6 notation
  242. dStrcpy(outAddress, addressString+1);
  243. addressString = outAddress;
  244. portString = dStrchr(outAddress, ']');
  245. if (portString)
  246. {
  247. // Sort out the :port after the ]
  248. *portString++ = '\0';
  249. if (*portString != ':')
  250. {
  251. portString = NULL;
  252. }
  253. else
  254. {
  255. *portString++ = '\0';
  256. }
  257. }
  258. if (outFamily == AF_UNSPEC)
  259. {
  260. outFamily = AF_INET6;
  261. }
  262. }
  263. else
  264. {
  265. dStrcpy(outAddress, addressString);
  266. addressString = outAddress;
  267. // Check to see if we have multiple ":" which would indicate this is an ipv6 address
  268. char* scan = outAddress;
  269. int colonCount = 0;
  270. while (*scan != '\0' && colonCount < 2)
  271. {
  272. if (*scan++ == ':')
  273. colonCount++;
  274. }
  275. if (colonCount <= 1)
  276. {
  277. // either ipv4 or host
  278. portString = dStrchr(outAddress, ':');
  279. if (portString)
  280. {
  281. *portString++ = '\0';
  282. }
  283. }
  284. else if (outFamily == AF_UNSPEC)
  285. {
  286. // Must be ipv6
  287. outFamily = AF_INET6;
  288. }
  289. }
  290. if (portString)
  291. {
  292. outPort = dAtoi(portString);
  293. }
  294. return true;
  295. }
  296. };
  297. template<class T> NetSocket ReservedSocketList<T>::reserve(SOCKET reserveId, bool doLock)
  298. {
  299. MutexHandle handle;
  300. if (doLock)
  301. {
  302. handle.lock(mMutex, true);
  303. }
  304. S32 idx = mSocketList.find_next(EntryType());
  305. if (idx == -1)
  306. {
  307. EntryType entry;
  308. entry.value = reserveId;
  309. entry.used = true;
  310. mSocketList.push_back(entry);
  311. return NetSocket::fromHandle(mSocketList.size() - 1);
  312. }
  313. else
  314. {
  315. EntryType &entry = mSocketList[idx];
  316. entry.used = true;
  317. entry.value = reserveId;
  318. }
  319. return NetSocket::fromHandle(idx);
  320. }
  321. template<class T> void ReservedSocketList<T>::remove(NetSocket socketToRemove, bool doLock)
  322. {
  323. MutexHandle handle;
  324. if (doLock)
  325. {
  326. handle.lock(mMutex, true);
  327. }
  328. if ((U32)socketToRemove.getHandle() >= (U32)mSocketList.size())
  329. return;
  330. mSocketList[socketToRemove.getHandle()] = EntryType();
  331. }
  332. template<class T> T ReservedSocketList<T>::activate(NetSocket socketToActivate, int family, bool useUDP, bool clearOnFail)
  333. {
  334. MutexHandle h;
  335. h.lock(mMutex, true);
  336. int typeID = useUDP ? SOCK_DGRAM : SOCK_STREAM;
  337. int protocol = useUDP ? PlatformNetState::getDefaultGameProtocol() : 0;
  338. if ((U32)socketToActivate.getHandle() >= (U32)mSocketList.size())
  339. return -1;
  340. EntryType &entry = mSocketList[socketToActivate.getHandle()];
  341. if (!entry.used)
  342. return -1;
  343. T socketFd = entry.value;
  344. if (socketFd == -1)
  345. {
  346. socketFd = ::socket(family, typeID, protocol);
  347. if (socketFd == InvalidSocketHandle)
  348. {
  349. if (clearOnFail)
  350. {
  351. remove(socketToActivate, false);
  352. }
  353. return InvalidSocketHandle;
  354. }
  355. else
  356. {
  357. entry.used = true;
  358. entry.value = socketFd;
  359. return socketFd;
  360. }
  361. }
  362. return socketFd;
  363. }
  364. template<class T> T ReservedSocketList<T>::resolve(NetSocket socketToResolve)
  365. {
  366. MutexHandle h;
  367. h.lock(mMutex, true);
  368. if ((U32)socketToResolve.getHandle() >= (U32)mSocketList.size())
  369. return -1;
  370. EntryType &entry = mSocketList[socketToResolve.getHandle()];
  371. return entry.used ? entry.value : -1;
  372. }
  373. static ConnectionNotifyEvent* smConnectionNotify = NULL;
  374. static ConnectionAcceptedEvent* smConnectionAccept = NULL;
  375. static ConnectionReceiveEvent* smConnectionReceive = NULL;
  376. static PacketReceiveEvent* smPacketReceive = NULL;
  377. ConnectionNotifyEvent& Net::getConnectionNotifyEvent()
  378. {
  379. return *smConnectionNotify;
  380. }
  381. ConnectionAcceptedEvent& Net::getConnectionAcceptedEvent()
  382. {
  383. return *smConnectionAccept;
  384. }
  385. ConnectionReceiveEvent& Net::getConnectionReceiveEvent()
  386. {
  387. return *smConnectionReceive;
  388. }
  389. PacketReceiveEvent& Net::getPacketReceiveEvent()
  390. {
  391. return *smPacketReceive;
  392. }
  393. // Multicast stuff
  394. bool Net::smMulticastEnabled = true;
  395. //
  396. // Protocol Stuff
  397. bool Net::smIpv4Enabled = true;
  398. bool Net::smIpv6Enabled = false;
  399. //
  400. // the Socket structure helps us keep track of the
  401. // above states
  402. struct PolledSocket
  403. {
  404. // local enum for socket states for polled sockets
  405. enum SocketState
  406. {
  407. InvalidState,
  408. Connected,
  409. ConnectionPending,
  410. Listening,
  411. NameLookupRequired
  412. };
  413. PolledSocket()
  414. {
  415. fd = -1;
  416. handleFd = NetSocket::INVALID;
  417. state = InvalidState;
  418. remoteAddr[0] = 0;
  419. remotePort = -1;
  420. }
  421. SOCKET fd;
  422. NetSocket handleFd;
  423. S32 state;
  424. char remoteAddr[256];
  425. S32 remotePort;
  426. };
  427. // list of polled sockets
  428. static Vector<PolledSocket*> gPolledSockets( __FILE__, __LINE__ );
  429. static PolledSocket* addPolledSocket(NetSocket handleFd, SOCKET fd, S32 state,
  430. char* remoteAddr = NULL, S32 port = -1)
  431. {
  432. PolledSocket* sock = new PolledSocket();
  433. sock->fd = fd;
  434. sock->handleFd = handleFd;
  435. sock->state = state;
  436. if (remoteAddr)
  437. dStrcpy(sock->remoteAddr, remoteAddr);
  438. if (port != -1)
  439. sock->remotePort = port;
  440. gPolledSockets.push_back(sock);
  441. return sock;
  442. }
  443. bool netSocketWaitForWritable(NetSocket handleFd, S32 timeoutMs)
  444. {
  445. fd_set writefds;
  446. timeval timeout;
  447. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  448. FD_ZERO( &writefds );
  449. FD_SET( socketFd, &writefds );
  450. timeout.tv_sec = timeoutMs / 1000;
  451. timeout.tv_usec = ( timeoutMs % 1000 ) * 1000;
  452. if( select(socketFd + 1, NULL, &writefds, NULL, &timeout) > 0 )
  453. return true;
  454. return false;
  455. }
  456. bool Net::init()
  457. {
  458. #if defined(TORQUE_USE_WINSOCK)
  459. if(!PlatformNetState::initCount)
  460. {
  461. #ifdef TORQUE_OS_XENON
  462. // Configure startup parameters
  463. XNetStartupParams xnsp;
  464. memset( &xnsp, 0, sizeof( xnsp ) );
  465. xnsp.cfgSizeOfStruct = sizeof( XNetStartupParams );
  466. #ifndef TORQUE_DISABLE_PC_CONNECTIVITY
  467. xnsp.cfgFlags = XNET_STARTUP_BYPASS_SECURITY;
  468. Con::warnf("XNET_STARTUP_BYPASS_SECURITY enabled! This build can talk to PCs!");
  469. #endif
  470. AssertISV( !XNetStartup( &xnsp ), "Net::init - failed to init XNet" );
  471. #endif
  472. WSADATA stWSAData;
  473. AssertISV( !WSAStartup( 0x0101, &stWSAData ), "Net::init - failed to init WinSock!" );
  474. //logprintf("Winsock initialization %s", success ? "succeeded." : "failed!");
  475. }
  476. #endif
  477. PlatformNetState::initCount++;
  478. smConnectionNotify = new ConnectionNotifyEvent();
  479. smConnectionAccept = new ConnectionAcceptedEvent();
  480. smConnectionReceive = new ConnectionReceiveEvent();
  481. smPacketReceive = new PacketReceiveEvent();
  482. Process::notify(&Net::process, PROCESS_NET_ORDER);
  483. return(true);
  484. }
  485. void Net::shutdown()
  486. {
  487. Process::remove(&Net::process);
  488. while (gPolledSockets.size() > 0)
  489. closeConnectTo(gPolledSockets[0]->handleFd);
  490. closePort();
  491. PlatformNetState::initCount--;
  492. // Destroy event handlers
  493. delete smConnectionNotify;
  494. delete smConnectionAccept;
  495. delete smConnectionReceive;
  496. delete smPacketReceive;
  497. #if defined(TORQUE_USE_WINSOCK)
  498. if(!PlatformNetState::initCount)
  499. {
  500. WSACleanup();
  501. #ifdef TORQUE_OS_XENON
  502. XNetCleanup();
  503. #endif
  504. }
  505. #endif
  506. }
  507. // ipv4 version of name routines
  508. static void NetAddressToIPSocket(const NetAddress *address, struct sockaddr_in *sockAddr)
  509. {
  510. dMemset(sockAddr, 0, sizeof(struct sockaddr_in));
  511. sockAddr->sin_family = AF_INET;
  512. sockAddr->sin_port = htons(address->port);
  513. #if defined(TORQUE_OS_BSD)
  514. sockAddr->sin_len = sizeof(struct sockaddr_in);
  515. #endif
  516. if (address->type == NetAddress::IPBroadcastAddress)
  517. {
  518. sockAddr->sin_addr.s_addr = htonl(INADDR_BROADCAST);
  519. }
  520. else
  521. {
  522. dMemcpy(&sockAddr->sin_addr, &address->address.ipv4.netNum[0], 4);
  523. }
  524. }
  525. static void IPSocketToNetAddress(const struct sockaddr_in *sockAddr, NetAddress *address)
  526. {
  527. address->type = NetAddress::IPAddress;
  528. address->port = ntohs(sockAddr->sin_port);
  529. dMemcpy(&address->address.ipv4.netNum[0], &sockAddr->sin_addr, 4);
  530. }
  531. // ipv6 version of name routines
  532. static void NetAddressToIPSocket6(const NetAddress *address, struct sockaddr_in6 *sockAddr)
  533. {
  534. dMemset(sockAddr, 0, sizeof(struct sockaddr_in6));
  535. #ifdef SIN6_LEN
  536. sockAddr->sin6_len = sizeof(struct sockaddr_in6);
  537. #endif
  538. sockAddr->sin6_family = AF_INET6;
  539. sockAddr->sin6_port = ntohs(address->port);
  540. if (address->type == NetAddress::IPV6MulticastAddress)
  541. {
  542. sockAddr->sin6_addr = PlatformNetState::multicast6Group.ipv6mr_multiaddr;
  543. sockAddr->sin6_scope_id = PlatformNetState::multicast6Group.ipv6mr_interface;
  544. }
  545. else
  546. {
  547. sockAddr->sin6_flowinfo = address->address.ipv6.netFlow;
  548. sockAddr->sin6_scope_id = address->address.ipv6.netScope;
  549. dMemcpy(&sockAddr->sin6_addr, address->address.ipv6.netNum, sizeof(address->address.ipv6.netNum));
  550. }
  551. }
  552. static void IPSocket6ToNetAddress(const struct sockaddr_in6 *sockAddr, NetAddress *address)
  553. {
  554. address->type = NetAddress::IPV6Address;
  555. address->port = ntohs(sockAddr->sin6_port);
  556. dMemcpy(address->address.ipv6.netNum, &sockAddr->sin6_addr, sizeof(address->address.ipv6.netNum));
  557. address->address.ipv6.netFlow = sockAddr->sin6_flowinfo;
  558. address->address.ipv6.netScope = sockAddr->sin6_scope_id;
  559. }
  560. //
  561. NetSocket Net::openListenPort(U16 port, NetAddress::Type addressType)
  562. {
  563. if(Journal::IsPlaying())
  564. {
  565. U32 ret;
  566. Journal::Read(&ret);
  567. return NetSocket::fromHandle(ret);
  568. }
  569. Net::Error error = NoError;
  570. NetAddress address;
  571. if (Net::getListenAddress(addressType, &address) != Net::NoError)
  572. error = Net::WrongProtocolType;
  573. NetSocket handleFd = NetSocket::INVALID;
  574. SOCKET sockId = InvalidSocketHandle;
  575. if (error == NoError)
  576. {
  577. handleFd = openSocket();
  578. sockId = PlatformNetState::smReservedSocketList.activate(handleFd, address.type == NetAddress::IPAddress ? AF_INET : AF_INET6, false, true);
  579. }
  580. if (error == NoError && (handleFd == NetSocket::INVALID || sockId == InvalidSocketHandle))
  581. {
  582. Con::errorf("Unable to open listen socket: %s", strerror(errno));
  583. error = NotASocket;
  584. handleFd = NetSocket::INVALID;
  585. }
  586. if (error == NoError)
  587. {
  588. address.port = port;
  589. error = bindAddress(address, handleFd, false);
  590. if (error != NoError)
  591. {
  592. Con::errorf("Unable to bind port %d: %s", port, strerror(errno));
  593. closeSocket(handleFd);
  594. handleFd = NetSocket::INVALID;
  595. }
  596. }
  597. if (error == NoError)
  598. {
  599. error = listen(handleFd, 4);
  600. if (error != NoError)
  601. {
  602. Con::errorf("Unable to listen on port %d: %s", port, strerror(errno));
  603. closeSocket(handleFd);
  604. handleFd = NetSocket::INVALID;
  605. }
  606. }
  607. if (error == NoError)
  608. {
  609. setBlocking(handleFd, false);
  610. addPolledSocket(handleFd, sockId, PolledSocket::Listening);
  611. }
  612. if(Journal::IsRecording())
  613. Journal::Write(U32(handleFd.getHandle()));
  614. return handleFd;
  615. }
  616. NetSocket Net::openConnectTo(const char *addressString)
  617. {
  618. if (Journal::IsPlaying())
  619. {
  620. U32 ret;
  621. Journal::Read(&ret);
  622. return NetSocket::fromHandle(ret);
  623. }
  624. NetAddress address;
  625. NetSocket handleFd = NetSocket::INVALID;
  626. Net::Error error = NoError;
  627. error = Net::stringToAddress(addressString, &address, false);
  628. if (error == NoError && address.type != NetAddress::IPAddress && address.type != NetAddress::IPV6Address)
  629. {
  630. error = Net::WrongProtocolType;
  631. }
  632. if (error != NoError || error == NeedHostLookup)
  633. {
  634. handleFd = openSocket();
  635. }
  636. // Attempt to connect or queue a lookup
  637. if (error == NoError && address.type == NetAddress::IPAddress)
  638. {
  639. sockaddr_in ipAddr;
  640. NetAddressToIPSocket(&address, &ipAddr);
  641. SOCKET socketFd = PlatformNetState::smReservedSocketList.activate(handleFd, AF_INET, false, true);
  642. if (socketFd != InvalidSocketHandle)
  643. {
  644. setBlocking(handleFd, false);
  645. if (::connect(socketFd, (struct sockaddr *)&ipAddr, sizeof(ipAddr)) == -1 &&
  646. errno != EINPROGRESS)
  647. {
  648. Con::errorf("Error connecting %s: %s",
  649. addressString, strerror(errno));
  650. closeSocket(handleFd);
  651. handleFd = NetSocket::INVALID;
  652. }
  653. }
  654. else
  655. {
  656. PlatformNetState::smReservedSocketList.remove(handleFd);
  657. handleFd = NetSocket::INVALID;
  658. }
  659. if (handleFd != NetSocket::INVALID)
  660. {
  661. // add this socket to our list of polled sockets
  662. addPolledSocket(handleFd, socketFd, PolledSocket::ConnectionPending);
  663. }
  664. }
  665. else if (error == NoError && address.type == NetAddress::IPV6Address)
  666. {
  667. sockaddr_in6 ipAddr6;
  668. NetAddressToIPSocket6(&address, &ipAddr6);
  669. SOCKET socketFd = PlatformNetState::smReservedSocketList.activate(handleFd, AF_INET6, false, true);
  670. if (::connect(socketFd, (struct sockaddr *)&ipAddr6, sizeof(ipAddr6)) == -1 &&
  671. errno != EINPROGRESS)
  672. {
  673. setBlocking(handleFd, false);
  674. Con::errorf("Error connecting %s: %s",
  675. addressString, strerror(errno));
  676. closeSocket(handleFd);
  677. handleFd = NetSocket::INVALID;
  678. }
  679. else
  680. {
  681. PlatformNetState::smReservedSocketList.remove(handleFd);
  682. handleFd = NetSocket::INVALID;
  683. }
  684. if (handleFd != NetSocket::INVALID)
  685. {
  686. // add this socket to our list of polled sockets
  687. addPolledSocket(handleFd, socketFd, PolledSocket::ConnectionPending);
  688. }
  689. }
  690. else if (error == Net::NeedHostLookup)
  691. {
  692. // need to do an asynchronous name lookup. first, add the socket
  693. // to the polled list
  694. char addr[256];
  695. int port = 0;
  696. int actualFamily = AF_UNSPEC;
  697. if (PlatformNetState::extractAddressParts(addressString, addr, port, actualFamily))
  698. {
  699. addPolledSocket(handleFd, InvalidSocketHandle, PolledSocket::NameLookupRequired, addr, port);
  700. // queue the lookup
  701. gNetAsync.queueLookup(addressString, handleFd);
  702. }
  703. else
  704. {
  705. closeSocket(handleFd);
  706. handleFd = NetSocket::INVALID;
  707. }
  708. }
  709. else
  710. {
  711. closeSocket(handleFd);
  712. handleFd = NetSocket::INVALID;
  713. }
  714. if (Journal::IsRecording())
  715. Journal::Write(U32(handleFd.getHandle()));
  716. return handleFd;
  717. }
  718. void Net::closeConnectTo(NetSocket handleFd)
  719. {
  720. if(Journal::IsPlaying())
  721. return;
  722. // if this socket is in the list of polled sockets, remove it
  723. for (S32 i = 0; i < gPolledSockets.size(); ++i)
  724. {
  725. if (gPolledSockets[i]->handleFd == handleFd)
  726. {
  727. delete gPolledSockets[i];
  728. gPolledSockets.erase(i);
  729. break;
  730. }
  731. }
  732. closeSocket(handleFd);
  733. }
  734. Net::Error Net::sendtoSocket(NetSocket handleFd, const U8 *buffer, S32 bufferSize, S32 *outBufferWritten)
  735. {
  736. if(Journal::IsPlaying())
  737. {
  738. U32 e;
  739. S32 outBytes;
  740. Journal::Read(&e);
  741. Journal::Read(&outBytes);
  742. if (outBufferWritten)
  743. *outBufferWritten = outBytes;
  744. return (Net::Error) e;
  745. }
  746. S32 outBytes = 0;
  747. Net::Error e = send(handleFd, buffer, bufferSize, &outBytes);
  748. if (Journal::IsRecording())
  749. {
  750. Journal::Write(U32(e));
  751. Journal::Write(outBytes);
  752. }
  753. if (outBufferWritten)
  754. *outBufferWritten = outBytes;
  755. return e;
  756. }
  757. bool Net::openPort(S32 port, bool doBind)
  758. {
  759. if (PlatformNetState::udpSocket != NetSocket::INVALID)
  760. {
  761. closeSocket(PlatformNetState::udpSocket);
  762. PlatformNetState::udpSocket = NetSocket::INVALID;
  763. }
  764. if (PlatformNetState::udp6Socket != NetSocket::INVALID)
  765. {
  766. closeSocket(PlatformNetState::udp6Socket);
  767. PlatformNetState::udp6Socket = NetSocket::INVALID;
  768. }
  769. // Frequently port "0" is used even though it makes no sense, so instead use the default port.
  770. if (port == 0)
  771. {
  772. port = PlatformNetState::defaultPort;
  773. }
  774. // Update prefs
  775. Net::smMulticastEnabled = Con::getBoolVariable("pref::Net::Multicast6Enabled", true);
  776. Net::smIpv4Enabled = Con::getBoolVariable("pref::Net::IPV4Enabled", true);
  777. Net::smIpv6Enabled = Con::getBoolVariable("pref::Net::IPV6Enabled", false);
  778. // we turn off VDP in non-release builds because VDP does not support broadcast packets
  779. // which are required for LAN queries (PC->Xbox connectivity). The wire protocol still
  780. // uses the VDP packet structure, though.
  781. S32 protocol = PlatformNetState::getDefaultGameProtocol();
  782. SOCKET socketFd = InvalidSocketHandle;
  783. NetAddress address;
  784. if (Net::smIpv4Enabled)
  785. {
  786. if (Net::getListenAddress(NetAddress::IPAddress, &address) == Net::NoError)
  787. {
  788. address.port = port;
  789. socketFd = ::socket(AF_INET, SOCK_DGRAM, protocol);
  790. if (socketFd != InvalidSocketHandle)
  791. {
  792. PlatformNetState::udpSocket = PlatformNetState::smReservedSocketList.reserve(socketFd);
  793. Net::Error error = NoError;
  794. if (doBind)
  795. {
  796. error = bindAddress(address, PlatformNetState::udpSocket, true);
  797. }
  798. if (error == NoError)
  799. error = setBufferSize(PlatformNetState::udpSocket, 32768 * 8);
  800. #ifndef TORQUE_DISABLE_PC_CONNECTIVITY
  801. if (error == NoError)
  802. error = setBroadcast(PlatformNetState::udpSocket, true);
  803. #endif
  804. if (error == NoError)
  805. error = setBlocking(PlatformNetState::udpSocket, false);
  806. if (error == NoError)
  807. {
  808. Con::printf("UDP initialized on ipv4 port %d", port);
  809. }
  810. else
  811. {
  812. closeSocket(PlatformNetState::udpSocket);
  813. PlatformNetState::udpSocket = NetSocket::INVALID;
  814. Con::printf("Unable to initialize UDP on ipv4 - error %d", error);
  815. }
  816. }
  817. }
  818. else
  819. {
  820. Con::errorf("Unable to initialize UDP on ipv4 - invalid address.");
  821. PlatformNetState::udpSocket = NetSocket::INVALID;
  822. }
  823. }
  824. if (Net::smIpv6Enabled)
  825. {
  826. if (Net::getListenAddress(NetAddress::IPV6Address, &address) == Net::NoError)
  827. {
  828. address.port = port;
  829. socketFd = ::socket(AF_INET6, SOCK_DGRAM, protocol);
  830. if (socketFd != InvalidSocketHandle)
  831. {
  832. PlatformNetState::udp6Socket = PlatformNetState::smReservedSocketList.reserve(socketFd);
  833. Net::Error error = NoError;
  834. int v = 1;
  835. setsockopt(socketFd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&v, sizeof(v));
  836. PlatformNetState::getLastError();
  837. if (doBind)
  838. {
  839. error = bindAddress(address, PlatformNetState::udp6Socket, true);
  840. }
  841. if (error == NoError)
  842. error = setBufferSize(PlatformNetState::udp6Socket, 32768 * 8);
  843. if (error == NoError)
  844. error = setBlocking(PlatformNetState::udp6Socket, false);
  845. if (error == NoError)
  846. {
  847. Con::printf("UDP initialized on ipv6 port %d", port);
  848. }
  849. else
  850. {
  851. closeSocket(PlatformNetState::udp6Socket);
  852. PlatformNetState::udp6Socket = NetSocket::INVALID;
  853. Con::printf("Unable to initialize UDP on ipv6 - error %d", error);
  854. }
  855. if (Net::smMulticastEnabled && doBind)
  856. {
  857. Net::enableMulticast();
  858. }
  859. else
  860. {
  861. Net::disableMulticast();
  862. }
  863. }
  864. }
  865. }
  866. PlatformNetState::netPort = port;
  867. return PlatformNetState::udpSocket != NetSocket::INVALID || PlatformNetState::udp6Socket != NetSocket::INVALID;
  868. }
  869. NetSocket Net::getPort()
  870. {
  871. return PlatformNetState::udpSocket;
  872. }
  873. void Net::closePort()
  874. {
  875. if (PlatformNetState::udpSocket != NetSocket::INVALID)
  876. closeSocket(PlatformNetState::udpSocket);
  877. if (PlatformNetState::udp6Socket != NetSocket::INVALID)
  878. closeSocket(PlatformNetState::udp6Socket);
  879. }
  880. Net::Error Net::sendto(const NetAddress *address, const U8 *buffer, S32 bufferSize)
  881. {
  882. if(Journal::IsPlaying())
  883. return NoError;
  884. SOCKET socketFd;
  885. if(address->type == NetAddress::IPAddress || address->type == NetAddress::IPBroadcastAddress)
  886. {
  887. socketFd = PlatformNetState::smReservedSocketList.resolve(PlatformNetState::udpSocket);
  888. if (socketFd != InvalidSocketHandle)
  889. {
  890. sockaddr_in ipAddr;
  891. NetAddressToIPSocket(address, &ipAddr);
  892. if (::sendto(socketFd, (const char*)buffer, bufferSize, 0,
  893. (sockaddr *)&ipAddr, sizeof(sockaddr_in)) == SOCKET_ERROR)
  894. return PlatformNetState::getLastError();
  895. else
  896. return NoError;
  897. }
  898. else
  899. {
  900. return NotASocket;
  901. }
  902. }
  903. else if (address->type == NetAddress::IPV6Address || address->type == NetAddress::IPV6MulticastAddress)
  904. {
  905. socketFd = PlatformNetState::smReservedSocketList.resolve(address->type == NetAddress::IPV6MulticastAddress ? PlatformNetState::multicast6Socket : PlatformNetState::udp6Socket);
  906. if (socketFd != InvalidSocketHandle)
  907. {
  908. sockaddr_in6 ipAddr;
  909. NetAddressToIPSocket6(address, &ipAddr);
  910. if (::sendto(socketFd, (const char*)buffer, bufferSize, 0,
  911. (struct sockaddr *) &ipAddr, sizeof(sockaddr_in6)) == SOCKET_ERROR)
  912. return PlatformNetState::getLastError();
  913. else
  914. return NoError;
  915. }
  916. else
  917. {
  918. return NotASocket;
  919. }
  920. }
  921. return WrongProtocolType;
  922. }
  923. void Net::process()
  924. {
  925. // Process listening sockets
  926. processListenSocket(PlatformNetState::udpSocket);
  927. processListenSocket(PlatformNetState::udp6Socket);
  928. // process the polled sockets. This blob of code performs functions
  929. // similar to WinsockProc in winNet.cc
  930. if (gPolledSockets.size() == 0)
  931. return;
  932. S32 optval;
  933. socklen_t optlen = sizeof(S32);
  934. S32 bytesRead;
  935. Net::Error err;
  936. bool removeSock = false;
  937. PolledSocket *currentSock = NULL;
  938. NetSocket incomingHandleFd = NetSocket::INVALID;
  939. NetAddress out_h_addr;
  940. S32 out_h_length = 0;
  941. RawData readBuff;
  942. for (S32 i = 0; i < gPolledSockets.size();
  943. /* no increment, this is done at end of loop body */)
  944. {
  945. removeSock = false;
  946. currentSock = gPolledSockets[i];
  947. switch (currentSock->state)
  948. {
  949. case PolledSocket::InvalidState:
  950. Con::errorf("Error, InvalidState socket in polled sockets list");
  951. break;
  952. case PolledSocket::ConnectionPending:
  953. // see if it is now connected
  954. #ifdef TORQUE_OS_XENON
  955. // WSASetLastError has no return value, however part of the SO_ERROR behavior
  956. // is to clear the last error, so this needs to be done here.
  957. if( ( optval = _getLastErrorAndClear() ) == -1 )
  958. #else
  959. if (getsockopt(currentSock->fd, SOL_SOCKET, SO_ERROR,
  960. (char*)&optval, &optlen) == -1)
  961. #endif
  962. {
  963. Con::errorf("Error getting socket options: %s", strerror(errno));
  964. smConnectionNotify->trigger(currentSock->handleFd, Net::ConnectFailed);
  965. removeSock = true;
  966. }
  967. else
  968. {
  969. if (optval == EINPROGRESS)
  970. // still connecting...
  971. break;
  972. if (optval == 0)
  973. {
  974. // poll for writable status to be sure we're connected.
  975. bool ready = netSocketWaitForWritable(currentSock->handleFd,0);
  976. if(!ready)
  977. break;
  978. currentSock->state = PolledSocket::Connected;
  979. smConnectionNotify->trigger(currentSock->handleFd, Net::Connected);
  980. }
  981. else
  982. {
  983. // some kind of error
  984. Con::errorf("Error connecting: %s", strerror(errno));
  985. smConnectionNotify->trigger(currentSock->handleFd, Net::ConnectFailed);
  986. removeSock = true;
  987. }
  988. }
  989. break;
  990. case PolledSocket::Connected:
  991. // try to get some data
  992. bytesRead = 0;
  993. readBuff.alloc(MaxPacketDataSize);
  994. err = Net::recv(currentSock->handleFd, (U8*)readBuff.data, MaxPacketDataSize, &bytesRead);
  995. if(err == Net::NoError)
  996. {
  997. if (bytesRead > 0)
  998. {
  999. // got some data, post it
  1000. readBuff.size = bytesRead;
  1001. smConnectionReceive->trigger(currentSock->handleFd, readBuff);
  1002. }
  1003. else
  1004. {
  1005. // ack! this shouldn't happen
  1006. if (bytesRead < 0)
  1007. Con::errorf("Unexpected error on socket: %s", strerror(errno));
  1008. // zero bytes read means EOF
  1009. smConnectionNotify->trigger(currentSock->handleFd, Net::Disconnected);
  1010. removeSock = true;
  1011. }
  1012. }
  1013. else if (err != Net::NoError && err != Net::WouldBlock)
  1014. {
  1015. Con::errorf("Error reading from socket: %s", strerror(errno));
  1016. smConnectionNotify->trigger(currentSock->handleFd, Net::Disconnected);
  1017. removeSock = true;
  1018. }
  1019. break;
  1020. case PolledSocket::NameLookupRequired:
  1021. U32 newState;
  1022. // is the lookup complete?
  1023. if (!gNetAsync.checkLookup(
  1024. currentSock->handleFd, &out_h_addr, &out_h_length,
  1025. sizeof(out_h_addr)))
  1026. break;
  1027. if (out_h_length == -1)
  1028. {
  1029. Con::errorf("DNS lookup failed: %s", currentSock->remoteAddr);
  1030. newState = Net::DNSFailed;
  1031. removeSock = true;
  1032. }
  1033. else
  1034. {
  1035. // try to connect
  1036. out_h_addr.port = currentSock->remotePort;
  1037. const sockaddr *ai_addr = NULL;
  1038. int ai_addrlen = 0;
  1039. sockaddr_in socketAddress;
  1040. sockaddr_in6 socketAddress6;
  1041. if (out_h_addr.type == NetAddress::IPAddress)
  1042. {
  1043. ai_addr = (const sockaddr*)&socketAddress;
  1044. ai_addrlen = sizeof(socketAddress);
  1045. NetAddressToIPSocket(&out_h_addr, &socketAddress);
  1046. currentSock->fd = PlatformNetState::smReservedSocketList.activate(currentSock->handleFd, AF_INET, false);
  1047. setBlocking(currentSock->handleFd, false);
  1048. #ifdef TORQUE_DEBUG_LOOKUPS
  1049. char addrString[256];
  1050. NetAddress addr;
  1051. IPSocketToNetAddress(&socketAddress, &addr);
  1052. Net::addressToString(&addr, addrString);
  1053. Con::printf("DNS: lookup resolved to %s", addrString);
  1054. #endif
  1055. }
  1056. else if (out_h_addr.type == NetAddress::IPV6Address)
  1057. {
  1058. ai_addr = (const sockaddr*)&socketAddress6;
  1059. ai_addrlen = sizeof(socketAddress6);
  1060. NetAddressToIPSocket6(&out_h_addr, &socketAddress6);
  1061. currentSock->fd = PlatformNetState::smReservedSocketList.activate(currentSock->handleFd, AF_INET6, false);
  1062. setBlocking(currentSock->handleFd, false);
  1063. #ifdef TORQUE_DEBUG_LOOKUPS
  1064. char addrString[256];
  1065. NetAddress addr;
  1066. IPSocket6ToNetAddress(&socketAddress6, &addr);
  1067. Net::addressToString(&addr, addrString);
  1068. Con::printf("DNS: lookup resolved to %s", addrString);
  1069. #endif
  1070. }
  1071. else
  1072. {
  1073. Con::errorf("Error connecting to %s: Invalid Protocol",
  1074. currentSock->remoteAddr);
  1075. newState = Net::ConnectFailed;
  1076. removeSock = true;
  1077. }
  1078. if (ai_addr)
  1079. {
  1080. if (::connect(currentSock->fd, ai_addr,
  1081. ai_addrlen) == -1)
  1082. {
  1083. err = PlatformNetState::getLastError();
  1084. if (err != Net::WouldBlock)
  1085. {
  1086. Con::errorf("Error connecting to %s: %u",
  1087. currentSock->remoteAddr, err);
  1088. newState = Net::ConnectFailed;
  1089. removeSock = true;
  1090. }
  1091. else
  1092. {
  1093. newState = Net::DNSResolved;
  1094. currentSock->state = PolledSocket::ConnectionPending;
  1095. }
  1096. }
  1097. else
  1098. {
  1099. newState = Net::Connected;
  1100. currentSock->state = Connected;
  1101. }
  1102. }
  1103. }
  1104. smConnectionNotify->trigger(currentSock->handleFd, newState);
  1105. break;
  1106. case PolledSocket::Listening:
  1107. NetAddress incomingAddy;
  1108. incomingHandleFd = Net::accept(currentSock->handleFd, &incomingAddy);
  1109. if(incomingHandleFd != NetSocket::INVALID)
  1110. {
  1111. setBlocking(incomingHandleFd, false);
  1112. addPolledSocket(incomingHandleFd, PlatformNetState::smReservedSocketList.resolve(incomingHandleFd), Connected);
  1113. smConnectionAccept->trigger(currentSock->handleFd, incomingHandleFd, incomingAddy);
  1114. }
  1115. break;
  1116. }
  1117. // only increment index if we're not removing the connection, since
  1118. // the removal will shift the indices down by one
  1119. if (removeSock)
  1120. closeConnectTo(currentSock->handleFd);
  1121. else
  1122. i++;
  1123. }
  1124. }
  1125. void Net::processListenSocket(NetSocket socketHandle)
  1126. {
  1127. if (socketHandle == NetSocket::INVALID)
  1128. return;
  1129. sockaddr_storage sa;
  1130. sa.ss_family = AF_UNSPEC;
  1131. NetAddress srcAddress;
  1132. RawData tmpBuffer;
  1133. tmpBuffer.alloc(Net::MaxPacketDataSize);
  1134. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(socketHandle);
  1135. for (;;)
  1136. {
  1137. socklen_t addrLen = sizeof(sa);
  1138. S32 bytesRead = -1;
  1139. if (socketHandle != NetSocket::INVALID)
  1140. bytesRead = ::recvfrom(socketFd, (char *)tmpBuffer.data, Net::MaxPacketDataSize, 0, (struct sockaddr*)&sa, &addrLen);
  1141. if (bytesRead == -1)
  1142. break;
  1143. if (sa.ss_family == AF_INET)
  1144. IPSocketToNetAddress((sockaddr_in *)&sa, &srcAddress);
  1145. else if (sa.ss_family == AF_INET6)
  1146. IPSocket6ToNetAddress((sockaddr_in6 *)&sa, &srcAddress);
  1147. else
  1148. continue;
  1149. if (bytesRead <= 0)
  1150. continue;
  1151. if (srcAddress.type == NetAddress::IPAddress &&
  1152. srcAddress.address.ipv4.netNum[0] == 127 &&
  1153. srcAddress.address.ipv4.netNum[1] == 0 &&
  1154. srcAddress.address.ipv4.netNum[2] == 0 &&
  1155. srcAddress.address.ipv4.netNum[3] == 1 &&
  1156. srcAddress.port == PlatformNetState::netPort)
  1157. continue;
  1158. tmpBuffer.size = bytesRead;
  1159. smPacketReceive->trigger(srcAddress, tmpBuffer);
  1160. }
  1161. }
  1162. NetSocket Net::openSocket()
  1163. {
  1164. return PlatformNetState::smReservedSocketList.reserve();
  1165. }
  1166. Net::Error Net::closeSocket(NetSocket handleFd)
  1167. {
  1168. if(handleFd != NetSocket::INVALID)
  1169. {
  1170. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1171. PlatformNetState::smReservedSocketList.remove(handleFd);
  1172. if(!::closesocket(socketFd))
  1173. return NoError;
  1174. else
  1175. return PlatformNetState::getLastError();
  1176. }
  1177. else
  1178. return NotASocket;
  1179. }
  1180. Net::Error Net::connect(NetSocket handleFd, const NetAddress *address)
  1181. {
  1182. if(!(address->type == NetAddress::IPAddress || address->type == NetAddress::IPV6Address))
  1183. return WrongProtocolType;
  1184. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1185. if (address->type == NetAddress::IPAddress)
  1186. {
  1187. sockaddr_in socketAddress;
  1188. NetAddressToIPSocket(address, &socketAddress);
  1189. if (socketFd == InvalidSocketHandle)
  1190. {
  1191. socketFd = PlatformNetState::smReservedSocketList.activate(handleFd, AF_INET, false);
  1192. }
  1193. if (!::connect(socketFd, (struct sockaddr *) &socketAddress, sizeof(socketAddress)))
  1194. return NoError;
  1195. }
  1196. else if (address->type == NetAddress::IPV6Address)
  1197. {
  1198. sockaddr_in6 socketAddress;
  1199. NetAddressToIPSocket6(address, &socketAddress);
  1200. if (socketFd == InvalidSocketHandle)
  1201. {
  1202. socketFd = PlatformNetState::smReservedSocketList.activate(handleFd, AF_INET6, false);
  1203. }
  1204. if (!::connect(socketFd, (struct sockaddr *) &socketAddress, sizeof(socketAddress)))
  1205. return NoError;
  1206. }
  1207. return PlatformNetState::getLastError();
  1208. }
  1209. Net::Error Net::listen(NetSocket handleFd, S32 backlog)
  1210. {
  1211. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1212. if (socketFd == InvalidSocketHandle)
  1213. return NotASocket;
  1214. if(!::listen(socketFd, backlog))
  1215. return NoError;
  1216. return PlatformNetState::getLastError();
  1217. }
  1218. NetSocket Net::accept(NetSocket handleFd, NetAddress *remoteAddress)
  1219. {
  1220. sockaddr_storage addr;
  1221. socklen_t addrLen = sizeof(addr);
  1222. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1223. if (socketFd == InvalidSocketHandle)
  1224. return NetSocket::INVALID;
  1225. SOCKET acceptedSocketFd = ::accept(socketFd, (sockaddr *)&addr, &addrLen);
  1226. if (acceptedSocketFd != InvalidSocketHandle)
  1227. {
  1228. if (addr.ss_family == AF_INET)
  1229. {
  1230. // ipv4
  1231. IPSocketToNetAddress(((struct sockaddr_in*)&addr), remoteAddress);
  1232. }
  1233. else if (addr.ss_family == AF_INET6)
  1234. {
  1235. // ipv6
  1236. IPSocket6ToNetAddress(((struct sockaddr_in6*)&addr), remoteAddress);
  1237. }
  1238. NetSocket newHandleFd = PlatformNetState::smReservedSocketList.reserve(acceptedSocketFd);
  1239. return newHandleFd;
  1240. }
  1241. return NetSocket::INVALID;
  1242. }
  1243. Net::Error Net::bindAddress(const NetAddress &address, NetSocket handleFd, bool useUDP)
  1244. {
  1245. int error = 0;
  1246. sockaddr_storage socketAddress;
  1247. dMemset(&socketAddress, '\0', sizeof(socketAddress));
  1248. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1249. if (socketFd == InvalidSocketHandle)
  1250. {
  1251. if (handleFd.getHandle() == -1)
  1252. return NotASocket;
  1253. }
  1254. if (address.type == NetAddress::IPAddress)
  1255. {
  1256. socketFd = PlatformNetState::smReservedSocketList.activate(handleFd, AF_INET, useUDP);
  1257. NetAddressToIPSocket(&address, (struct sockaddr_in*)&socketAddress);
  1258. error = ::bind(socketFd, (struct sockaddr*)&socketAddress, sizeof(sockaddr_in));
  1259. }
  1260. else if (address.type == NetAddress::IPV6Address)
  1261. {
  1262. socketFd = PlatformNetState::smReservedSocketList.activate(handleFd, AF_INET6, useUDP);
  1263. NetAddressToIPSocket6(&address, (struct sockaddr_in6*)&socketAddress);
  1264. error = ::bind(socketFd, (struct sockaddr*)&socketAddress, sizeof(sockaddr_in6));
  1265. }
  1266. if (!error)
  1267. return NoError;
  1268. return PlatformNetState::getLastError();
  1269. }
  1270. Net::Error Net::setBufferSize(NetSocket handleFd, S32 bufferSize)
  1271. {
  1272. S32 error;
  1273. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1274. if (socketFd == InvalidSocketHandle)
  1275. return NotASocket;
  1276. error = ::setsockopt(socketFd, SOL_SOCKET, SO_RCVBUF, (char *) &bufferSize, sizeof(bufferSize));
  1277. if(!error)
  1278. error = ::setsockopt(socketFd, SOL_SOCKET, SO_SNDBUF, (char *) &bufferSize, sizeof(bufferSize));
  1279. if(!error)
  1280. return NoError;
  1281. return PlatformNetState::getLastError();
  1282. }
  1283. Net::Error Net::setBroadcast(NetSocket handleFd, bool broadcast)
  1284. {
  1285. S32 bc = broadcast;
  1286. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1287. if (socketFd == InvalidSocketHandle)
  1288. return NotASocket;
  1289. S32 error = ::setsockopt(socketFd, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc));
  1290. if(!error)
  1291. return NoError;
  1292. return PlatformNetState::getLastError();
  1293. }
  1294. Net::Error Net::setBlocking(NetSocket handleFd, bool blockingIO)
  1295. {
  1296. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1297. if (socketFd == InvalidSocketHandle)
  1298. return NotASocket;
  1299. unsigned long notblock = !blockingIO;
  1300. S32 error = ioctl(socketFd, FIONBIO, &notblock);
  1301. if(!error)
  1302. return NoError;
  1303. return PlatformNetState::getLastError();
  1304. }
  1305. Net::Error Net::getListenAddress(const NetAddress::Type type, NetAddress *address, bool forceDefaults)
  1306. {
  1307. if (type == NetAddress::IPAddress)
  1308. {
  1309. const char* serverIP = forceDefaults ? NULL : Con::getVariable("pref::Net::BindAddress");
  1310. if (!serverIP || serverIP[0] == '\0')
  1311. {
  1312. address->type = type;
  1313. address->port = PlatformNetState::defaultPort;
  1314. *((U32*)address->address.ipv4.netNum) = INADDR_ANY;
  1315. return Net::NoError;
  1316. }
  1317. else
  1318. {
  1319. return Net::stringToAddress(serverIP, address, false);
  1320. }
  1321. }
  1322. else if (type == NetAddress::IPBroadcastAddress)
  1323. {
  1324. address->type = type;
  1325. address->port = PlatformNetState::defaultPort;
  1326. *((U32*)address->address.ipv4.netNum) = INADDR_BROADCAST;
  1327. return Net::NoError;
  1328. }
  1329. else if (type == NetAddress::IPV6Address)
  1330. {
  1331. const char* serverIP6 = forceDefaults ? NULL : Con::getVariable("pref::Net::BindAddress6");
  1332. if (!serverIP6 || serverIP6[0] == '\0')
  1333. {
  1334. sockaddr_in6 addr;
  1335. dMemset(&addr, '\0', sizeof(addr));
  1336. addr.sin6_port = htons(PlatformNetState::defaultPort);
  1337. addr.sin6_addr = in6addr_any;
  1338. IPSocket6ToNetAddress(&addr, address);
  1339. return Net::NoError;
  1340. }
  1341. else
  1342. {
  1343. return Net::stringToAddress(serverIP6, address, false);
  1344. }
  1345. }
  1346. else if (type == NetAddress::IPV6MulticastAddress)
  1347. {
  1348. const char* multicastAddressValue = forceDefaults ? NULL : Con::getVariable("pref::Net::Multicast6Address");
  1349. if (!multicastAddressValue || multicastAddressValue[0] == '\0')
  1350. {
  1351. multicastAddressValue = TORQUE_NET_DEFAULT_MULTICAST_ADDRESS;
  1352. }
  1353. return Net::stringToAddress(multicastAddressValue, address, false);
  1354. }
  1355. else
  1356. {
  1357. return Net::WrongProtocolType;
  1358. }
  1359. }
  1360. void Net::getIdealListenAddress(NetAddress *address)
  1361. {
  1362. dMemset(address, '\0', sizeof(NetAddress));
  1363. if (Net::smIpv6Enabled)
  1364. {
  1365. if (Net::getListenAddress(NetAddress::IPV6Address, address) == NeedHostLookup)
  1366. {
  1367. Net::getListenAddress(NetAddress::IPV6Address, address, true);
  1368. }
  1369. }
  1370. else
  1371. {
  1372. if (Net::getListenAddress(NetAddress::IPAddress, address) == NeedHostLookup)
  1373. {
  1374. Net::getListenAddress(NetAddress::IPAddress, address, true);
  1375. }
  1376. }
  1377. }
  1378. Net::Error Net::send(NetSocket handleFd, const U8 *buffer, S32 bufferSize, S32 *outBytesWritten)
  1379. {
  1380. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1381. if (socketFd == InvalidSocketHandle)
  1382. return NotASocket;
  1383. errno = 0;
  1384. S32 bytesWritten = ::send(socketFd, (const char*)buffer, bufferSize, 0);
  1385. if(bytesWritten == -1)
  1386. #if defined(TORQUE_USE_WINSOCK)
  1387. Con::errorf("Could not write to socket. Error: %s",strerror_wsa( WSAGetLastError() ));
  1388. #else
  1389. Con::errorf("Could not write to socket. Error: %s",strerror(errno));
  1390. #endif
  1391. if (outBytesWritten)
  1392. *outBytesWritten = bytesWritten;
  1393. return PlatformNetState::getLastError();
  1394. }
  1395. Net::Error Net::recv(NetSocket handleFd, U8 *buffer, S32 bufferSize, S32 *bytesRead)
  1396. {
  1397. SOCKET socketFd = PlatformNetState::smReservedSocketList.resolve(handleFd);
  1398. if (socketFd == InvalidSocketHandle)
  1399. return NotASocket;
  1400. *bytesRead = ::recv(socketFd, (char*)buffer, bufferSize, 0);
  1401. if(*bytesRead == -1)
  1402. return PlatformNetState::getLastError();
  1403. return NoError;
  1404. }
  1405. bool Net::compareAddresses(const NetAddress *a1, const NetAddress *a2)
  1406. {
  1407. return a1->isSameAddressAndPort(*a2);
  1408. }
  1409. Net::Error Net::stringToAddress(const char *addressString, NetAddress *address, bool hostLookup, int requiredFamily)
  1410. {
  1411. char addr[256];
  1412. int port = 0;
  1413. int actualFamily = AF_UNSPEC;
  1414. if (!PlatformNetState::extractAddressParts(addressString, addr, port, actualFamily))
  1415. {
  1416. return WrongProtocolType;
  1417. }
  1418. // Make sure family matches (in cast we have IP: stuff in address)
  1419. if (requiredFamily != AF_UNSPEC && actualFamily != AF_UNSPEC && (actualFamily != requiredFamily))
  1420. {
  1421. return WrongProtocolType;
  1422. }
  1423. if (actualFamily == AF_UNSPEC)
  1424. {
  1425. actualFamily = requiredFamily;
  1426. }
  1427. addressString = addr;
  1428. dMemset(address, '\0', sizeof(NetAddress));
  1429. if (!dStricmp(addressString, "broadcast"))
  1430. {
  1431. address->type = NetAddress::IPBroadcastAddress;
  1432. if (!(actualFamily == AF_UNSPEC || actualFamily == AF_INET))
  1433. return WrongProtocolType;
  1434. if (port != 0)
  1435. address->port = port;
  1436. else
  1437. address->port = PlatformNetState::defaultPort;
  1438. }
  1439. else if (!dStricmp(addressString, "multicast"))
  1440. {
  1441. address->type = NetAddress::IPV6MulticastAddress;
  1442. if (!(actualFamily == AF_UNSPEC || actualFamily == AF_INET6))
  1443. return WrongProtocolType;
  1444. if (port != 0)
  1445. address->port = port;
  1446. else
  1447. address->port = PlatformNetState::defaultPort;
  1448. }
  1449. else
  1450. {
  1451. sockaddr_in ipAddr;
  1452. sockaddr_in6 ipAddr6;
  1453. dMemset(&ipAddr, 0, sizeof(ipAddr));
  1454. dMemset(&ipAddr6, 0, sizeof(ipAddr6));
  1455. bool hasInterface = dStrchr(addressString, '%') != NULL; // if we have an interface, best use getaddrinfo to parse
  1456. // Check if we've got a simple ipv4 / ipv6
  1457. if (inet_pton(AF_INET, addressString, &ipAddr.sin_addr) == 1)
  1458. {
  1459. if (!(actualFamily == AF_UNSPEC || actualFamily == AF_INET))
  1460. return WrongProtocolType;
  1461. IPSocketToNetAddress(((struct sockaddr_in*)&ipAddr), address);
  1462. if (port != 0)
  1463. address->port = port;
  1464. else
  1465. address->port = PlatformNetState::defaultPort;
  1466. return NoError;
  1467. }
  1468. else if (!hasInterface && inet_pton(AF_INET6, addressString, &ipAddr6.sin6_addr) == 1)
  1469. {
  1470. if (!(actualFamily == AF_UNSPEC || actualFamily == AF_INET6))
  1471. return WrongProtocolType;
  1472. IPSocket6ToNetAddress(((struct sockaddr_in6*)&ipAddr6), address);
  1473. if (port != 0)
  1474. address->port = port;
  1475. else
  1476. address->port = PlatformNetState::defaultPort;
  1477. return NoError;
  1478. }
  1479. else
  1480. {
  1481. if (!hostLookup && !hasInterface)
  1482. return NeedHostLookup;
  1483. int ret = 0;
  1484. struct addrinfo hint, *res = NULL;
  1485. dMemset(&hint, 0, sizeof(hint));
  1486. hint.ai_family = actualFamily;
  1487. hint.ai_flags = hostLookup ? 0 : AI_NUMERICHOST;
  1488. if (ret = getaddrinfo(addressString, NULL, &hint, &res) == 0)
  1489. {
  1490. if (actualFamily != AF_UNSPEC)
  1491. {
  1492. // Prefer desired protocol
  1493. res = PlatformNetState::pickAddressByProtocol(res, actualFamily);
  1494. }
  1495. if (res && res->ai_family == AF_INET)
  1496. {
  1497. // ipv4
  1498. IPSocketToNetAddress(((struct sockaddr_in*)res->ai_addr), address);
  1499. }
  1500. else if (res && res->ai_family == AF_INET6)
  1501. {
  1502. // ipv6
  1503. IPSocket6ToNetAddress(((struct sockaddr_in6*)res->ai_addr), address);
  1504. }
  1505. else
  1506. {
  1507. // unknown
  1508. return UnknownError;
  1509. }
  1510. if (port != 0)
  1511. address->port = port;
  1512. else
  1513. address->port = PlatformNetState::defaultPort;
  1514. }
  1515. }
  1516. }
  1517. return NoError;
  1518. }
  1519. void Net::addressToString(const NetAddress *address, char addressString[256])
  1520. {
  1521. if(address->type == NetAddress::IPAddress || address->type == NetAddress::IPBroadcastAddress)
  1522. {
  1523. sockaddr_in ipAddr;
  1524. NetAddressToIPSocket(address, &ipAddr);
  1525. if (ipAddr.sin_addr.s_addr == htonl(INADDR_BROADCAST) || address->type == NetAddress::IPBroadcastAddress)
  1526. {
  1527. if (ipAddr.sin_port == 0)
  1528. dSprintf(addressString, 256, "IP:Broadcast");
  1529. else
  1530. dSprintf(addressString, 256, "IP:Broadcast:%d", ntohs(ipAddr.sin_port));
  1531. }
  1532. else
  1533. {
  1534. char buffer[256];
  1535. buffer[0] = '\0';
  1536. sockaddr_in ipAddr;
  1537. NetAddressToIPSocket(address, &ipAddr);
  1538. inet_ntop(AF_INET, &(ipAddr.sin_addr), buffer, sizeof(buffer));
  1539. if (ipAddr.sin_port == 0)
  1540. dSprintf(addressString, 256, "IP:%s", buffer);
  1541. else
  1542. dSprintf(addressString, 256, "IP:%s:%i", buffer, ntohs(ipAddr.sin_port));
  1543. }
  1544. }
  1545. else if (address->type == NetAddress::IPV6Address)
  1546. {
  1547. char buffer[256];
  1548. buffer[0] = '\0';
  1549. sockaddr_in6 ipAddr;
  1550. NetAddressToIPSocket6(address, &ipAddr);
  1551. inet_ntop(AF_INET6, &(ipAddr.sin6_addr), buffer, sizeof(buffer));
  1552. if (ipAddr.sin6_port == 0)
  1553. dSprintf(addressString, 256, "IP6:%s", buffer);
  1554. else
  1555. dSprintf(addressString, 256, "IP6:[%s]:%i", buffer, ntohs(ipAddr.sin6_port));
  1556. }
  1557. else if (address->type == NetAddress::IPV6MulticastAddress)
  1558. {
  1559. if (address->port == 0)
  1560. dSprintf(addressString, 256, "IP6:Multicast");
  1561. else
  1562. dSprintf(addressString, 256, "IP6:Multicast:%d", address->port);
  1563. }
  1564. else
  1565. {
  1566. *addressString = 0;
  1567. return;
  1568. }
  1569. }
  1570. void Net::enableMulticast()
  1571. {
  1572. SOCKET socketFd;
  1573. if (Net::smIpv6Enabled)
  1574. {
  1575. socketFd = PlatformNetState::smReservedSocketList.resolve(PlatformNetState::udp6Socket);
  1576. if (socketFd != InvalidSocketHandle)
  1577. {
  1578. PlatformNetState::multicast6Socket = PlatformNetState::udp6Socket;
  1579. Net::Error error = NoError;
  1580. if (error == NoError)
  1581. {
  1582. unsigned long multicastTTL = 1;
  1583. if (setsockopt(socketFd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
  1584. (char*)&multicastTTL, sizeof(multicastTTL)) < 0)
  1585. {
  1586. error = PlatformNetState::getLastError();
  1587. }
  1588. }
  1589. // Find multicast to bind to...
  1590. NetAddress multicastAddress;
  1591. sockaddr_in6 multicastSocketAddress;
  1592. const char *multicastAddressValue = Con::getVariable("pref::Net::Multicast6Address");
  1593. if (!multicastAddressValue || multicastAddressValue[0] == '\0')
  1594. {
  1595. multicastAddressValue = TORQUE_NET_DEFAULT_MULTICAST_ADDRESS;
  1596. }
  1597. error = Net::stringToAddress(multicastAddressValue, &multicastAddress, false);
  1598. if (error == NoError)
  1599. {
  1600. dMemset(&PlatformNetState::multicast6Group, '\0', sizeof(&PlatformNetState::multicast6Group));
  1601. NetAddressToIPSocket6(&multicastAddress, &multicastSocketAddress);
  1602. dMemcpy(&PlatformNetState::multicast6Group.ipv6mr_multiaddr, &multicastSocketAddress.sin6_addr, sizeof(PlatformNetState::multicast6Group.ipv6mr_multiaddr));
  1603. }
  1604. // Setup group
  1605. if (error == NoError)
  1606. {
  1607. const char *multicastInterface = Con::getVariable("pref::Net::Multicast6Interface");
  1608. if (multicastInterface && multicastInterface[0] != '\0')
  1609. {
  1610. #ifdef TORQUE_USE_WINSOCK
  1611. PlatformNetState::multicast6Group.ipv6mr_interface = dAtoi(multicastInterface);
  1612. #else
  1613. PlatformNetState::multicast6Group.ipv6mr_interface = if_nametoindex(multicastInterface);
  1614. #endif
  1615. }
  1616. else
  1617. {
  1618. PlatformNetState::multicast6Group.ipv6mr_interface = 0; // 0 == accept from any interface
  1619. }
  1620. if (PlatformNetState::multicast6Group.ipv6mr_interface && error == NoError)
  1621. {
  1622. if (setsockopt(socketFd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&PlatformNetState::multicast6Group.ipv6mr_interface, sizeof(PlatformNetState::multicast6Group.ipv6mr_interface)) < 0)
  1623. {
  1624. error = PlatformNetState::getLastError();
  1625. }
  1626. }
  1627. if (error == NoError && setsockopt(socketFd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char*)&PlatformNetState::multicast6Group, sizeof(PlatformNetState::multicast6Group)) < 0)
  1628. {
  1629. error = PlatformNetState::getLastError();
  1630. }
  1631. }
  1632. if (error == NoError)
  1633. {
  1634. Con::printf("Multicast initialized on port %d", PlatformNetState::defaultPort);
  1635. }
  1636. else
  1637. {
  1638. PlatformNetState::multicast6Socket = NetSocket::INVALID;
  1639. Con::printf("Unable to multicast UDP - error %d", error);
  1640. }
  1641. }
  1642. }
  1643. }
  1644. void Net::disableMulticast()
  1645. {
  1646. if (PlatformNetState::multicast6Socket != NetSocket::INVALID)
  1647. {
  1648. PlatformNetState::multicast6Socket = NetSocket::INVALID;
  1649. }
  1650. }
  1651. bool Net::isMulticastEnabled()
  1652. {
  1653. return PlatformNetState::multicast6Socket != NetSocket::INVALID;
  1654. }
  1655. U32 NetAddress::getHash() const
  1656. {
  1657. U32 value = 0;
  1658. switch (type)
  1659. {
  1660. case NetAddress::IPAddress:
  1661. value = Torque::hash((const U8*)&address.ipv4.netNum, sizeof(address.ipv4.netNum), 0);
  1662. break;
  1663. case NetAddress::IPV6Address:
  1664. value = Torque::hash((const U8*)address.ipv6.netNum, sizeof(address.ipv6.netNum), 0);
  1665. break;
  1666. default:
  1667. value = 0;
  1668. break;
  1669. }
  1670. return value;
  1671. }
  1672. bool Net::isAddressTypeAvailable(NetAddress::Type addressType)
  1673. {
  1674. switch (addressType)
  1675. {
  1676. case NetAddress::IPAddress:
  1677. return PlatformNetState::udpSocket != NetSocket::INVALID;
  1678. case NetAddress::IPV6Address:
  1679. return PlatformNetState::udp6Socket != NetSocket::INVALID;
  1680. case NetAddress::IPBroadcastAddress:
  1681. return PlatformNetState::udpSocket != NetSocket::INVALID;
  1682. case NetAddress::IPV6MulticastAddress:
  1683. return PlatformNetState::multicast6Socket != NetSocket::INVALID;
  1684. default:
  1685. return false;
  1686. }
  1687. }