platformNet.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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 "core/strings/stringFunctions.h"
  24. #if defined (TORQUE_OS_WIN)
  25. #define TORQUE_USE_WINSOCK
  26. #include <errno.h>
  27. #include <winsock.h>
  28. #ifndef EINPROGRESS
  29. #define EINPROGRESS WSAEINPROGRESS
  30. #endif // EINPROGRESS
  31. #define ioctl ioctlsocket
  32. typedef S32 socklen_t;
  33. #elif defined ( TORQUE_OS_MAC )
  34. #include <unistd.h>
  35. #include <sys/types.h>
  36. #include <sys/socket.h>
  37. #include <sys/poll.h>
  38. #include <arpa/inet.h>
  39. #include <netdb.h>
  40. #include <netinet/in.h>
  41. #include <errno.h>
  42. #include <sys/ioctl.h>
  43. typedef sockaddr_in SOCKADDR_IN;
  44. typedef sockaddr * PSOCKADDR;
  45. typedef sockaddr SOCKADDR;
  46. typedef in_addr IN_ADDR;
  47. #define INVALID_SOCKET -1
  48. #define SOCKET_ERROR -1
  49. #define closesocket close
  50. #elif defined TORQUE_OS_LINUX
  51. #include <unistd.h>
  52. #include <sys/types.h>
  53. #include <sys/socket.h>
  54. #include <sys/poll.h>
  55. #include <arpa/inet.h>
  56. #include <netdb.h>
  57. #include <netinet/in.h>
  58. #include <errno.h>
  59. #include <sys/ioctl.h>
  60. typedef sockaddr_in SOCKADDR_IN;
  61. typedef sockaddr * PSOCKADDR;
  62. typedef sockaddr SOCKADDR;
  63. typedef in_addr IN_ADDR;
  64. #define INVALID_SOCKET -1
  65. #define SOCKET_ERROR -1
  66. #define closesocket close
  67. #elif defined( TORQUE_OS_XENON )
  68. #include <Xtl.h>
  69. #include <string>
  70. #define TORQUE_USE_WINSOCK
  71. #define EINPROGRESS WSAEINPROGRESS
  72. #define ioctl ioctlsocket
  73. typedef S32 socklen_t;
  74. DWORD _getLastErrorAndClear()
  75. {
  76. DWORD err = WSAGetLastError();
  77. WSASetLastError( 0 );
  78. return err;
  79. }
  80. #else
  81. #endif
  82. #if defined(TORQUE_USE_WINSOCK)
  83. static const char* strerror_wsa( S32 code )
  84. {
  85. switch( code )
  86. {
  87. #define E( name ) case name: return #name;
  88. E( WSANOTINITIALISED );
  89. E( WSAENETDOWN );
  90. E( WSAEADDRINUSE );
  91. E( WSAEINPROGRESS );
  92. E( WSAEALREADY );
  93. E( WSAEADDRNOTAVAIL );
  94. E( WSAEAFNOSUPPORT );
  95. E( WSAEFAULT );
  96. E( WSAEINVAL );
  97. E( WSAEISCONN );
  98. E( WSAENETUNREACH );
  99. E( WSAEHOSTUNREACH );
  100. E( WSAENOBUFS );
  101. E( WSAENOTSOCK );
  102. E( WSAETIMEDOUT );
  103. E( WSAEWOULDBLOCK );
  104. E( WSAEACCES );
  105. #undef E
  106. default:
  107. return "Unknown";
  108. }
  109. }
  110. #endif
  111. #include "core/util/tVector.h"
  112. #include "platform/platformNetAsync.h"
  113. #include "console/console.h"
  114. #include "core/util/journal/process.h"
  115. #include "core/util/journal/journal.h"
  116. static Net::Error getLastError();
  117. static S32 defaultPort = 28000;
  118. static S32 netPort = 0;
  119. static NetSocket udpSocket = InvalidSocket;
  120. ConnectionNotifyEvent Net::smConnectionNotify;
  121. ConnectionAcceptedEvent Net::smConnectionAccept;
  122. ConnectionReceiveEvent Net::smConnectionReceive;
  123. PacketReceiveEvent Net::smPacketReceive;
  124. // local enum for socket states for polled sockets
  125. enum SocketState
  126. {
  127. InvalidState,
  128. Connected,
  129. ConnectionPending,
  130. Listening,
  131. NameLookupRequired
  132. };
  133. // the Socket structure helps us keep track of the
  134. // above states
  135. struct Socket
  136. {
  137. Socket()
  138. {
  139. fd = InvalidSocket;
  140. state = InvalidState;
  141. remoteAddr[0] = 0;
  142. remotePort = -1;
  143. }
  144. NetSocket fd;
  145. S32 state;
  146. char remoteAddr[256];
  147. S32 remotePort;
  148. };
  149. // list of polled sockets
  150. static Vector<Socket*> gPolledSockets( __FILE__, __LINE__ );
  151. static Socket* addPolledSocket(NetSocket& fd, S32 state,
  152. char* remoteAddr = NULL, S32 port = -1)
  153. {
  154. Socket* sock = new Socket();
  155. sock->fd = fd;
  156. sock->state = state;
  157. if (remoteAddr)
  158. dStrcpy(sock->remoteAddr, remoteAddr);
  159. if (port != -1)
  160. sock->remotePort = port;
  161. gPolledSockets.push_back(sock);
  162. return sock;
  163. }
  164. enum {
  165. MaxConnections = 1024,
  166. };
  167. bool netSocketWaitForWritable(NetSocket fd, S32 timeoutMs)
  168. {
  169. fd_set writefds;
  170. timeval timeout;
  171. FD_ZERO(&writefds);
  172. FD_SET( fd, &writefds );
  173. timeout.tv_sec = timeoutMs / 1000;
  174. timeout.tv_usec = ( timeoutMs % 1000 ) * 1000;
  175. if( select(fd + 1, NULL, &writefds, NULL, &timeout) > 0 )
  176. return true;
  177. return false;
  178. }
  179. static S32 initCount = 0;
  180. bool Net::init()
  181. {
  182. #if defined(TORQUE_USE_WINSOCK)
  183. if(!initCount)
  184. {
  185. #ifdef TORQUE_OS_XENON
  186. // Configure startup parameters
  187. XNetStartupParams xnsp;
  188. memset( &xnsp, 0, sizeof( xnsp ) );
  189. xnsp.cfgSizeOfStruct = sizeof( XNetStartupParams );
  190. #ifndef TORQUE_DISABLE_PC_CONNECTIVITY
  191. xnsp.cfgFlags = XNET_STARTUP_BYPASS_SECURITY;
  192. Con::warnf("XNET_STARTUP_BYPASS_SECURITY enabled! This build can talk to PCs!");
  193. #endif
  194. AssertISV( !XNetStartup( &xnsp ), "Net::init - failed to init XNet" );
  195. #endif
  196. WSADATA stWSAData;
  197. AssertISV( !WSAStartup( 0x0101, &stWSAData ), "Net::init - failed to init WinSock!" );
  198. //logprintf("Winsock initialization %s", success ? "succeeded." : "failed!");
  199. }
  200. #endif
  201. initCount++;
  202. Process::notify(&Net::process, PROCESS_NET_ORDER);
  203. return(true);
  204. }
  205. void Net::shutdown()
  206. {
  207. Process::remove(&Net::process);
  208. while (gPolledSockets.size() > 0)
  209. closeConnectTo(gPolledSockets[0]->fd);
  210. closePort();
  211. initCount--;
  212. #if defined(TORQUE_USE_WINSOCK)
  213. if(!initCount)
  214. {
  215. WSACleanup();
  216. #ifdef TORQUE_OS_XENON
  217. XNetCleanup();
  218. #endif
  219. }
  220. #endif
  221. }
  222. Net::Error getLastError()
  223. {
  224. #if defined(TORQUE_USE_WINSOCK)
  225. S32 err = WSAGetLastError();
  226. switch(err)
  227. {
  228. case 0:
  229. return Net::NoError;
  230. case WSAEWOULDBLOCK:
  231. return Net::WouldBlock;
  232. default:
  233. return Net::UnknownError;
  234. }
  235. #else
  236. if (errno == EAGAIN)
  237. return Net::WouldBlock;
  238. if (errno == 0)
  239. return Net::NoError;
  240. return Net::UnknownError;
  241. #endif
  242. }
  243. static void netToIPSocketAddress(const NetAddress *address, struct sockaddr_in *sockAddr)
  244. {
  245. dMemset(sockAddr, 0, sizeof(struct sockaddr_in));
  246. sockAddr->sin_family = AF_INET;
  247. sockAddr->sin_port = htons(address->port);
  248. char tAddr[20];
  249. dSprintf(tAddr, 20, "%d.%d.%d.%d", address->netNum[0], address->netNum[1], address->netNum[2], address->netNum[3]);
  250. //fprintf(stdout,"netToIPSocketAddress(): %s\n",tAddr);fflush(NULL);
  251. sockAddr->sin_addr.s_addr = inet_addr(tAddr);
  252. }
  253. static void IPSocketToNetAddress(const struct sockaddr_in *sockAddr, NetAddress *address)
  254. {
  255. address->type = NetAddress::IPAddress;
  256. address->port = htons(sockAddr->sin_port);
  257. #ifndef TORQUE_OS_XENON
  258. char *tAddr;
  259. tAddr = inet_ntoa(sockAddr->sin_addr);
  260. //fprintf(stdout,"IPSocketToNetAddress(): %s\n",tAddr);fflush(NULL);
  261. U8 nets[4];
  262. nets[0] = atoi(strtok(tAddr, "."));
  263. nets[1] = atoi(strtok(NULL, "."));
  264. nets[2] = atoi(strtok(NULL, "."));
  265. nets[3] = atoi(strtok(NULL, "."));
  266. //fprintf(stdout,"0 = %d, 1 = %d, 2 = %d, 3 = %d\n", nets[0], nets[1], nets[2], nets[3]);
  267. address->netNum[0] = nets[0];
  268. address->netNum[1] = nets[1];
  269. address->netNum[2] = nets[2];
  270. address->netNum[3] = nets[3];
  271. #else
  272. address->netNum[0] = sockAddr->sin_addr.s_net;
  273. address->netNum[1] = sockAddr->sin_addr.s_host;
  274. address->netNum[2] = sockAddr->sin_addr.s_lh;
  275. address->netNum[3] = sockAddr->sin_addr.s_impno;
  276. #endif
  277. }
  278. NetSocket Net::openListenPort(U16 port)
  279. {
  280. if(Journal::IsPlaying())
  281. {
  282. U32 ret;
  283. Journal::Read(&ret);
  284. return NetSocket(ret);
  285. }
  286. NetSocket sock = openSocket();
  287. if (sock == InvalidSocket)
  288. {
  289. Con::errorf("Unable to open listen socket: %s", strerror(errno));
  290. return InvalidSocket;
  291. }
  292. if (bind(sock, port) != NoError)
  293. {
  294. Con::errorf("Unable to bind port %d: %s", port, strerror(errno));
  295. ::closesocket(sock);
  296. return InvalidSocket;
  297. }
  298. if (listen(sock, 4) != NoError)
  299. {
  300. Con::errorf("Unable to listen on port %d: %s", port, strerror(errno));
  301. ::closesocket(sock);
  302. return InvalidSocket;
  303. }
  304. setBlocking(sock, false);
  305. addPolledSocket(sock, Listening);
  306. if(Journal::IsRecording())
  307. Journal::Write(U32(sock));
  308. return sock;
  309. }
  310. NetSocket Net::openConnectTo(const char *addressString)
  311. {
  312. if(!dStrnicmp(addressString, "ipx:", 4))
  313. // ipx support deprecated
  314. return InvalidSocket;
  315. if(!dStrnicmp(addressString, "ip:", 3))
  316. addressString += 3; // eat off the ip:
  317. char remoteAddr[256];
  318. dStrcpy(remoteAddr, addressString);
  319. char *portString = dStrchr(remoteAddr, ':');
  320. U16 port;
  321. if(portString)
  322. {
  323. *portString++ = 0;
  324. port = htons(dAtoi(portString));
  325. }
  326. else
  327. port = htons(defaultPort);
  328. if(!dStricmp(remoteAddr, "broadcast"))
  329. return InvalidSocket;
  330. if(Journal::IsPlaying())
  331. {
  332. U32 ret;
  333. Journal::Read(&ret);
  334. return NetSocket(ret);
  335. }
  336. NetSocket sock = openSocket();
  337. setBlocking(sock, false);
  338. sockaddr_in ipAddr;
  339. dMemset(&ipAddr, 0, sizeof(ipAddr));
  340. ipAddr.sin_addr.s_addr = inet_addr(remoteAddr);
  341. if(ipAddr.sin_addr.s_addr != INADDR_NONE)
  342. {
  343. ipAddr.sin_port = port;
  344. ipAddr.sin_family = AF_INET;
  345. if(::connect(sock, (struct sockaddr *)&ipAddr, sizeof(ipAddr)) == -1)
  346. {
  347. S32 err = getLastError();
  348. if(err != Net::WouldBlock)
  349. {
  350. Con::errorf("Error connecting %s: %s",
  351. addressString, strerror(err));
  352. ::closesocket(sock);
  353. sock = InvalidSocket;
  354. }
  355. }
  356. if(sock != InvalidSocket)
  357. {
  358. // add this socket to our list of polled sockets
  359. addPolledSocket(sock, ConnectionPending);
  360. }
  361. }
  362. else
  363. {
  364. // need to do an asynchronous name lookup. first, add the socket
  365. // to the polled list
  366. addPolledSocket(sock, NameLookupRequired, remoteAddr, port);
  367. // queue the lookup
  368. gNetAsync.queueLookup(remoteAddr, sock);
  369. }
  370. if(Journal::IsRecording())
  371. Journal::Write(U32(sock));
  372. return sock;
  373. }
  374. void Net::closeConnectTo(NetSocket sock)
  375. {
  376. if(Journal::IsPlaying())
  377. return;
  378. // if this socket is in the list of polled sockets, remove it
  379. for (S32 i = 0; i < gPolledSockets.size(); ++i)
  380. {
  381. if (gPolledSockets[i]->fd == sock)
  382. {
  383. delete gPolledSockets[i];
  384. gPolledSockets.erase(i);
  385. break;
  386. }
  387. }
  388. closeSocket(sock);
  389. }
  390. Net::Error Net::sendtoSocket(NetSocket socket, const U8 *buffer, S32 bufferSize)
  391. {
  392. if(Journal::IsPlaying())
  393. {
  394. U32 e;
  395. Journal::Read(&e);
  396. return (Net::Error) e;
  397. }
  398. Net::Error e = send(socket, buffer, bufferSize);
  399. if(Journal::IsRecording())
  400. Journal::Write(U32(e));
  401. return e;
  402. }
  403. bool Net::openPort(S32 port, bool doBind)
  404. {
  405. if(udpSocket != InvalidSocket)
  406. ::closesocket(udpSocket);
  407. // we turn off VDP in non-release builds because VDP does not support broadcast packets
  408. // which are required for LAN queries (PC->Xbox connectivity). The wire protocol still
  409. // uses the VDP packet structure, though.
  410. S32 protocol = 0;
  411. bool useVDP = false;
  412. #ifdef TORQUE_DISABLE_PC_CONNECTIVITY
  413. // Xbox uses a VDP (voice/data protocol) socket for networking
  414. protocol = IPPROTO_VDP;
  415. useVDP = true;
  416. #endif
  417. udpSocket = socket(AF_INET, SOCK_DGRAM, protocol);
  418. if(udpSocket != InvalidSocket)
  419. {
  420. Net::Error error = NoError;
  421. if (doBind)
  422. {
  423. error = bind(udpSocket, port);
  424. }
  425. if(error == NoError)
  426. error = setBufferSize(udpSocket, 32768);
  427. if(error == NoError && !useVDP)
  428. error = setBroadcast(udpSocket, true);
  429. if(error == NoError)
  430. error = setBlocking(udpSocket, false);
  431. if(error == NoError)
  432. Con::printf("UDP initialized on port %d", port);
  433. else
  434. {
  435. ::closesocket(udpSocket);
  436. udpSocket = InvalidSocket;
  437. Con::printf("Unable to initialize UDP - error %d", error);
  438. }
  439. }
  440. netPort = port;
  441. return udpSocket != InvalidSocket;
  442. }
  443. NetSocket Net::getPort()
  444. {
  445. return udpSocket;
  446. }
  447. void Net::closePort()
  448. {
  449. if(udpSocket != InvalidSocket)
  450. ::closesocket(udpSocket);
  451. }
  452. Net::Error Net::sendto(const NetAddress *address, const U8 *buffer, S32 bufferSize)
  453. {
  454. if(Journal::IsPlaying())
  455. return NoError;
  456. if(address->type == NetAddress::IPAddress)
  457. {
  458. sockaddr_in ipAddr;
  459. netToIPSocketAddress(address, &ipAddr);
  460. if(::sendto(udpSocket, (const char*)buffer, bufferSize, 0,
  461. (sockaddr *) &ipAddr, sizeof(sockaddr_in)) == SOCKET_ERROR)
  462. return getLastError();
  463. else
  464. return NoError;
  465. }
  466. else
  467. {
  468. SOCKADDR_IN ipAddr;
  469. netToIPSocketAddress(address, &ipAddr);
  470. if(::sendto(udpSocket, (const char*)buffer, bufferSize, 0,
  471. (PSOCKADDR) &ipAddr, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
  472. return getLastError();
  473. else
  474. return NoError;
  475. }
  476. }
  477. void Net::process()
  478. {
  479. sockaddr sa;
  480. sa.sa_family = AF_UNSPEC;
  481. NetAddress srcAddress;
  482. RawData tmpBuffer;
  483. tmpBuffer.alloc(MaxPacketDataSize);
  484. for(;;)
  485. {
  486. socklen_t addrLen = sizeof(sa);
  487. S32 bytesRead = -1;
  488. if(udpSocket != InvalidSocket)
  489. bytesRead = recvfrom(udpSocket, (char *) tmpBuffer.data, MaxPacketDataSize, 0, &sa, &addrLen);
  490. if(bytesRead == -1)
  491. break;
  492. if(sa.sa_family == AF_INET)
  493. IPSocketToNetAddress((sockaddr_in *) &sa, &srcAddress);
  494. else
  495. continue;
  496. if(bytesRead <= 0)
  497. continue;
  498. if(srcAddress.type == NetAddress::IPAddress &&
  499. srcAddress.netNum[0] == 127 &&
  500. srcAddress.netNum[1] == 0 &&
  501. srcAddress.netNum[2] == 0 &&
  502. srcAddress.netNum[3] == 1 &&
  503. srcAddress.port == netPort)
  504. continue;
  505. tmpBuffer.size = bytesRead;
  506. Net::smPacketReceive.trigger(srcAddress, tmpBuffer);
  507. }
  508. // process the polled sockets. This blob of code performs functions
  509. // similar to WinsockProc in winNet.cc
  510. if (gPolledSockets.size() == 0)
  511. return;
  512. S32 optval;
  513. socklen_t optlen = sizeof(S32);
  514. S32 bytesRead;
  515. Net::Error err;
  516. bool removeSock = false;
  517. Socket *currentSock = NULL;
  518. sockaddr_in ipAddr;
  519. NetSocket incoming = InvalidSocket;
  520. char out_h_addr[1024];
  521. S32 out_h_length = 0;
  522. RawData readBuff;
  523. for (S32 i = 0; i < gPolledSockets.size();
  524. /* no increment, this is done at end of loop body */)
  525. {
  526. removeSock = false;
  527. currentSock = gPolledSockets[i];
  528. switch (currentSock->state)
  529. {
  530. case ::InvalidState:
  531. Con::errorf("Error, InvalidState socket in polled sockets list");
  532. break;
  533. case ::ConnectionPending:
  534. // see if it is now connected
  535. #ifdef TORQUE_OS_XENON
  536. // WSASetLastError has no return value, however part of the SO_ERROR behavior
  537. // is to clear the last error, so this needs to be done here.
  538. if( ( optval = _getLastErrorAndClear() ) == -1 )
  539. #else
  540. if (getsockopt(currentSock->fd, SOL_SOCKET, SO_ERROR,
  541. (char*)&optval, &optlen) == -1)
  542. #endif
  543. {
  544. Con::errorf("Error getting socket options: %s", strerror(errno));
  545. Net::smConnectionNotify.trigger(currentSock->fd, Net::ConnectFailed);
  546. removeSock = true;
  547. }
  548. else
  549. {
  550. if (optval == EINPROGRESS)
  551. // still connecting...
  552. break;
  553. if (optval == 0)
  554. {
  555. // poll for writable status to be sure we're connected.
  556. bool ready = netSocketWaitForWritable(currentSock->fd,0);
  557. if(!ready)
  558. break;
  559. currentSock->state = ::Connected;
  560. Net::smConnectionNotify.trigger(currentSock->fd, Net::Connected);
  561. }
  562. else
  563. {
  564. // some kind of error
  565. Con::errorf("Error connecting: %s", strerror(errno));
  566. Net::smConnectionNotify.trigger(currentSock->fd, Net::ConnectFailed);
  567. removeSock = true;
  568. }
  569. }
  570. break;
  571. case ::Connected:
  572. // try to get some data
  573. bytesRead = 0;
  574. readBuff.alloc(MaxPacketDataSize);
  575. err = Net::recv(currentSock->fd, (U8*)readBuff.data, MaxPacketDataSize, &bytesRead);
  576. if(err == Net::NoError)
  577. {
  578. if (bytesRead > 0)
  579. {
  580. // got some data, post it
  581. readBuff.size = bytesRead;
  582. Net::smConnectionReceive.trigger(currentSock->fd, readBuff);
  583. }
  584. else
  585. {
  586. // ack! this shouldn't happen
  587. if (bytesRead < 0)
  588. Con::errorf("Unexpected error on socket: %s", strerror(errno));
  589. // zero bytes read means EOF
  590. Net::smConnectionNotify.trigger(currentSock->fd, Net::Disconnected);
  591. removeSock = true;
  592. }
  593. }
  594. else if (err != Net::NoError && err != Net::WouldBlock)
  595. {
  596. Con::errorf("Error reading from socket: %s", strerror(errno));
  597. Net::smConnectionNotify.trigger(currentSock->fd, Net::Disconnected);
  598. removeSock = true;
  599. }
  600. break;
  601. case ::NameLookupRequired:
  602. // is the lookup complete?
  603. if (!gNetAsync.checkLookup(
  604. currentSock->fd, out_h_addr, &out_h_length,
  605. sizeof(out_h_addr)))
  606. break;
  607. U32 newState;
  608. if (out_h_length == -1)
  609. {
  610. Con::errorf("DNS lookup failed: %s", currentSock->remoteAddr);
  611. newState = Net::DNSFailed;
  612. removeSock = true;
  613. }
  614. else
  615. {
  616. // try to connect
  617. dMemcpy(&(ipAddr.sin_addr.s_addr), out_h_addr, out_h_length);
  618. ipAddr.sin_port = currentSock->remotePort;
  619. ipAddr.sin_family = AF_INET;
  620. if(::connect(currentSock->fd, (struct sockaddr *)&ipAddr,
  621. sizeof(ipAddr)) == -1)
  622. {
  623. S32 errorCode;
  624. #if defined(TORQUE_USE_WINSOCK)
  625. errorCode = WSAGetLastError();
  626. if( errorCode == WSAEINPROGRESS || errorCode == WSAEWOULDBLOCK )
  627. #else
  628. errorCode = errno;
  629. if (errno == EINPROGRESS)
  630. #endif
  631. {
  632. newState = Net::DNSResolved;
  633. currentSock->state = ::ConnectionPending;
  634. }
  635. else
  636. {
  637. const char* errorString;
  638. #if defined(TORQUE_USE_WINSOCK)
  639. errorString = strerror_wsa( errorCode );
  640. #else
  641. errorString = strerror( errorCode );
  642. #endif
  643. Con::errorf("Error connecting to %s: %s (%i)",
  644. currentSock->remoteAddr, errorString, errorCode);
  645. newState = Net::ConnectFailed;
  646. removeSock = true;
  647. }
  648. }
  649. else
  650. {
  651. newState = Net::Connected;
  652. currentSock->state = Net::Connected;
  653. }
  654. }
  655. Net::smConnectionNotify.trigger(currentSock->fd, newState);
  656. break;
  657. case ::Listening:
  658. NetAddress incomingAddy;
  659. incoming = Net::accept(currentSock->fd, &incomingAddy);
  660. if(incoming != InvalidSocket)
  661. {
  662. setBlocking(incoming, false);
  663. addPolledSocket(incoming, Connected);
  664. Net::smConnectionAccept.trigger(currentSock->fd, incoming, incomingAddy);
  665. }
  666. break;
  667. }
  668. // only increment index if we're not removing the connection, since
  669. // the removal will shift the indices down by one
  670. if (removeSock)
  671. closeConnectTo(currentSock->fd);
  672. else
  673. i++;
  674. }
  675. }
  676. NetSocket Net::openSocket()
  677. {
  678. NetSocket retSocket;
  679. retSocket = socket(AF_INET, SOCK_STREAM, 0);
  680. if(retSocket == InvalidSocket)
  681. return InvalidSocket;
  682. else
  683. return retSocket;
  684. }
  685. Net::Error Net::closeSocket(NetSocket socket)
  686. {
  687. if(socket != InvalidSocket)
  688. {
  689. if(!closesocket(socket))
  690. return NoError;
  691. else
  692. return getLastError();
  693. }
  694. else
  695. return NotASocket;
  696. }
  697. Net::Error Net::connect(NetSocket socket, const NetAddress *address)
  698. {
  699. if(address->type != NetAddress::IPAddress)
  700. return WrongProtocolType;
  701. sockaddr_in socketAddress;
  702. netToIPSocketAddress(address, &socketAddress);
  703. if(!::connect(socket, (sockaddr *) &socketAddress, sizeof(socketAddress)))
  704. return NoError;
  705. return getLastError();
  706. }
  707. Net::Error Net::listen(NetSocket socket, S32 backlog)
  708. {
  709. if(!::listen(socket, backlog))
  710. return NoError;
  711. return getLastError();
  712. }
  713. NetSocket Net::accept(NetSocket acceptSocket, NetAddress *remoteAddress)
  714. {
  715. sockaddr_in socketAddress;
  716. socklen_t addrLen = sizeof(socketAddress);
  717. NetSocket retVal = ::accept(acceptSocket, (sockaddr *) &socketAddress, &addrLen);
  718. if(retVal != InvalidSocket)
  719. {
  720. IPSocketToNetAddress(&socketAddress, remoteAddress);
  721. return retVal;
  722. }
  723. return InvalidSocket;
  724. }
  725. Net::Error Net::bind(NetSocket socket, U16 port)
  726. {
  727. S32 error;
  728. sockaddr_in socketAddress;
  729. dMemset((char *)&socketAddress, 0, sizeof(socketAddress));
  730. socketAddress.sin_family = AF_INET;
  731. // It's entirely possible that there are two NIC cards.
  732. // We let the user specify which one the server runs on.
  733. // thanks to [TPG]P1aGu3 for the name
  734. const char* serverIP = Con::getVariable( "pref::Net::BindAddress" );
  735. // serverIP is guaranteed to be non-0.
  736. AssertFatal( serverIP, "serverIP is NULL!" );
  737. if( serverIP[0] != '\0' ) {
  738. // we're not empty
  739. socketAddress.sin_addr.s_addr = inet_addr( serverIP );
  740. if( socketAddress.sin_addr.s_addr != INADDR_NONE ) {
  741. Con::printf( "Binding server port to %s", serverIP );
  742. } else {
  743. Con::warnf( ConsoleLogEntry::General,
  744. "inet_addr() failed for %s while binding!",
  745. serverIP );
  746. socketAddress.sin_addr.s_addr = INADDR_ANY;
  747. }
  748. } else {
  749. Con::printf( "Binding server port to default IP" );
  750. socketAddress.sin_addr.s_addr = INADDR_ANY;
  751. }
  752. socketAddress.sin_port = htons(port);
  753. error = ::bind(socket, (sockaddr *) &socketAddress, sizeof(socketAddress));
  754. if(!error)
  755. return NoError;
  756. return getLastError();
  757. }
  758. Net::Error Net::setBufferSize(NetSocket socket, S32 bufferSize)
  759. {
  760. S32 error;
  761. error = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *) &bufferSize, sizeof(bufferSize));
  762. if(!error)
  763. error = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *) &bufferSize, sizeof(bufferSize));
  764. if(!error)
  765. return NoError;
  766. return getLastError();
  767. }
  768. Net::Error Net::setBroadcast(NetSocket socket, bool broadcast)
  769. {
  770. S32 bc = broadcast;
  771. S32 error = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc));
  772. if(!error)
  773. return NoError;
  774. return getLastError();
  775. }
  776. Net::Error Net::setBlocking(NetSocket socket, bool blockingIO)
  777. {
  778. unsigned long notblock = !blockingIO;
  779. S32 error = ioctl(socket, FIONBIO, &notblock);
  780. if(!error)
  781. return NoError;
  782. return getLastError();
  783. }
  784. Net::Error Net::send(NetSocket socket, const U8 *buffer, S32 bufferSize)
  785. {
  786. errno = 0;
  787. S32 bytesWritten = ::send(socket, (const char*)buffer, bufferSize, 0);
  788. if(bytesWritten == -1)
  789. #if defined(TORQUE_USE_WINSOCK)
  790. Con::errorf("Could not write to socket. Error: %s",strerror_wsa( WSAGetLastError() ));
  791. #else
  792. Con::errorf("Could not write to socket. Error: %s",strerror(errno));
  793. #endif
  794. return getLastError();
  795. }
  796. Net::Error Net::recv(NetSocket socket, U8 *buffer, S32 bufferSize, S32 *bytesRead)
  797. {
  798. *bytesRead = ::recv(socket, (char*)buffer, bufferSize, 0);
  799. if(*bytesRead == -1)
  800. return getLastError();
  801. return NoError;
  802. }
  803. bool Net::compareAddresses(const NetAddress *a1, const NetAddress *a2)
  804. {
  805. if((a1->type != a2->type) ||
  806. (*((U32 *)a1->netNum) != *((U32 *)a2->netNum)) ||
  807. (a1->port != a2->port))
  808. return false;
  809. if(a1->type == NetAddress::IPAddress)
  810. return true;
  811. for(S32 i = 0; i < 6; i++)
  812. if(a1->nodeNum[i] != a2->nodeNum[i])
  813. return false;
  814. return true;
  815. }
  816. bool Net::stringToAddress(const char *addressString, NetAddress *address)
  817. {
  818. if(!dStrnicmp(addressString, "ipx:", 4))
  819. // ipx support deprecated
  820. return false;
  821. if(!dStrnicmp(addressString, "ip:", 3))
  822. addressString += 3; // eat off the ip:
  823. sockaddr_in ipAddr;
  824. char remoteAddr[256];
  825. if(strlen(addressString) > 255)
  826. return false;
  827. dStrcpy(remoteAddr, addressString);
  828. char *portString = dStrchr(remoteAddr, ':');
  829. if(portString)
  830. *portString++ = '\0';
  831. if(!dStricmp(remoteAddr, "broadcast"))
  832. ipAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  833. else
  834. {
  835. ipAddr.sin_addr.s_addr = inet_addr(remoteAddr);
  836. if (ipAddr.sin_addr.s_addr == INADDR_NONE) // error
  837. {
  838. // On the Xbox, 'gethostbyname' does not exist so...
  839. #ifndef TORQUE_OS_XENON
  840. struct hostent *hp;
  841. if((hp = gethostbyname(remoteAddr)) == 0)
  842. return false;
  843. else
  844. memcpy(&ipAddr.sin_addr.s_addr, hp->h_addr, sizeof(in_addr));
  845. #else
  846. // On the Xbox do XNetDnsLookup
  847. XNDNS *pxndns = NULL;
  848. HANDLE hEvent = CreateEvent(NULL, false, false, NULL);
  849. XNetDnsLookup(remoteAddr, hEvent, &pxndns);
  850. // Wait for event (passing NULL as a handle to XNetDnsLookup will NOT
  851. // cause it to behave synchronously, so do not remove the handle/wait
  852. while(pxndns->iStatus == WSAEINPROGRESS)
  853. WaitForSingleObject(hEvent, INFINITE);
  854. bool foundAddr = pxndns->iStatus == 0 && pxndns->cina > 0;
  855. if(foundAddr)
  856. {
  857. // Lets just grab the first address returned, for now
  858. memcpy(&ipAddr.sin_addr, pxndns->aina, sizeof(IN_ADDR));
  859. }
  860. XNetDnsRelease(pxndns);
  861. CloseHandle(hEvent);
  862. // If we didn't successfully resolve the DNS lookup, bail after the
  863. // handles are released
  864. if(!foundAddr)
  865. return false;
  866. #endif
  867. }
  868. }
  869. if(portString)
  870. ipAddr.sin_port = htons(dAtoi(portString));
  871. else
  872. ipAddr.sin_port = htons(defaultPort);
  873. ipAddr.sin_family = AF_INET;
  874. IPSocketToNetAddress(&ipAddr, address);
  875. return true;
  876. }
  877. void Net::addressToString(const NetAddress *address, char addressString[256])
  878. {
  879. if(address->type == NetAddress::IPAddress)
  880. {
  881. sockaddr_in ipAddr;
  882. netToIPSocketAddress(address, &ipAddr);
  883. if(ipAddr.sin_addr.s_addr == htonl(INADDR_BROADCAST))
  884. dSprintf(addressString, 256, "IP:Broadcast:%d", ntohs(ipAddr.sin_port));
  885. else
  886. {
  887. #ifndef TORQUE_OS_XENON
  888. dSprintf(addressString, 256, "IP:%s:%d", inet_ntoa(ipAddr.sin_addr),
  889. ntohs(ipAddr.sin_port));
  890. #else
  891. dSprintf(addressString, 256, "IP:%d.%d.%d.%d:%d", ipAddr.sin_addr.s_net,
  892. ipAddr.sin_addr.s_host, ipAddr.sin_addr.s_lh,
  893. ipAddr.sin_addr.s_impno, ntohs( ipAddr.sin_port ) );
  894. #endif
  895. }
  896. }
  897. else
  898. {
  899. *addressString = 0;
  900. return;
  901. }
  902. }