platformNet.cpp 57 KB

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