iOSNet.mm 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 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 "platformiOS/platformiOS.h"
  23. #include "platform/platform.h"
  24. #include "platform/event.h"
  25. #include "platform/platformNetAsync.unix.h"
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #include <sys/socket.h>
  29. #include <arpa/inet.h>
  30. #include <netdb.h>
  31. #include <netinet/in.h>
  32. #include <errno.h>
  33. #include <sys/time.h>
  34. // Header clean-up by William Taysom
  35. #include <sys/ioctl.h>
  36. // IPX fixes from William Taysom.
  37. #define IPX_NODE_LEN 6
  38. // for 10.2 compatability...
  39. #ifndef socklen_t
  40. #define socklen_t unsigned int
  41. #endif
  42. struct sockaddr_ipx
  43. {
  44. sa_family_t sipx_family;
  45. U16 sipx_port;
  46. U32 sipx_network;
  47. unsigned char sipx_node[IPX_NODE_LEN];
  48. U8 sipx_type;
  49. unsigned char sipx_zero; /* 16 byte fill */
  50. };
  51. // end wtaysom changes (May 26, 2004)
  52. #include <stdlib.h>
  53. #include "console/console.h"
  54. #include "game/gameInterface.h"
  55. #include "io/fileStream.h"
  56. #include "collection/vector.h"
  57. static Net::Error getLastError();
  58. static S32 defaultPort = 28000;
  59. static S32 netPort = 0;
  60. static int ipxSocket = InvalidSocket;
  61. static int udpSocket = InvalidSocket;
  62. // local enum for socket states for polled sockets
  63. enum SocketState
  64. {
  65. InvalidState,
  66. Connected,
  67. ConnectionPending,
  68. Listening,
  69. NameLookupRequired
  70. };
  71. // the Socket structure helps us keep track of the
  72. // above states
  73. struct Socket
  74. {
  75. Socket()
  76. {
  77. fd = InvalidSocket;
  78. state = InvalidState;
  79. remoteAddr[0] = 0;
  80. remotePort = -1;
  81. }
  82. NetSocket fd;
  83. S32 state;
  84. char remoteAddr[256];
  85. S32 remotePort;
  86. };
  87. // list of polled sockets
  88. static Vector<Socket*> gPolledSockets;
  89. static Socket* addPolledSocket(NetSocket& fd, S32 state,
  90. char* remoteAddr = NULL, S32 port = -1)
  91. {
  92. Socket* sock = new Socket();
  93. sock->fd = fd;
  94. sock->state = state;
  95. if (remoteAddr)
  96. dStrcpy(sock->remoteAddr, remoteAddr);
  97. if (port != -1)
  98. sock->remotePort = port;
  99. gPolledSockets.push_back(sock);
  100. return sock;
  101. }
  102. enum {
  103. MaxConnections = 1024,
  104. };
  105. bool netSocketWaitForWritable(NetSocket fd, S32 timeoutMs)
  106. {
  107. fd_set writefds;
  108. timeval timeout;
  109. FD_ZERO(&writefds);
  110. FD_SET( fd, &writefds );
  111. timeout.tv_sec = timeoutMs / 1000;
  112. timeout.tv_usec = ( timeoutMs % 1000 ) * 1000;
  113. if( select(fd + 1, NULL, &writefds, NULL, &timeout) > 0 )
  114. return true;
  115. return false;
  116. }
  117. bool Net::init()
  118. {
  119. NetAsync::startAsync();
  120. return(true);
  121. }
  122. void Net::shutdown()
  123. {
  124. while (gPolledSockets.size() > 0)
  125. closeConnectTo(gPolledSockets[0]->fd);
  126. closePort();
  127. NetAsync::stopAsync();
  128. }
  129. static void netToIPSocketAddress(const NetAddress *address, struct sockaddr_in *sockAddr)
  130. {
  131. dMemset(sockAddr, 0, sizeof(struct sockaddr_in));
  132. sockAddr->sin_family = AF_INET;
  133. sockAddr->sin_port = htons(address->port);
  134. char tAddr[20];
  135. dSprintf(tAddr, 20, "%d.%d.%d.%d\n", address->netNum[0], address->netNum[1], address->netNum[2], address->netNum[3]);
  136. //fprintf(stdout,"netToIPSocketAddress(): %s\n",tAddr);fflush(NULL);
  137. sockAddr->sin_addr.s_addr = inet_addr(tAddr);
  138. }
  139. static void IPSocketToNetAddress(const struct sockaddr_in *sockAddr, NetAddress *address)
  140. {
  141. address->type = NetAddress::IPAddress;
  142. address->port = htons(sockAddr->sin_port);
  143. char *tAddr;
  144. tAddr = inet_ntoa(sockAddr->sin_addr);
  145. //fprintf(stdout,"IPSocketToNetAddress(): %s\n",tAddr);fflush(NULL);
  146. U8 nets[4];
  147. nets[0] = atoi(strtok(tAddr, "."));
  148. nets[1] = atoi(strtok(NULL, "."));
  149. nets[2] = atoi(strtok(NULL, "."));
  150. nets[3] = atoi(strtok(NULL, "."));
  151. //fprintf(stdout,"0 = %d, 1 = %d, 2 = %d, 3 = %d\n", nets[0], nets[1], nets[2], nets[3]);
  152. address->netNum[0] = nets[0];
  153. address->netNum[1] = nets[1];
  154. address->netNum[2] = nets[2];
  155. address->netNum[3] = nets[3];
  156. }
  157. static void netToIPXSocketAddress(const NetAddress *address, sockaddr_ipx *sockAddr)
  158. {
  159. dMemset(sockAddr, 0, sizeof(sockaddr_ipx));
  160. sockAddr->sipx_family = AF_INET;
  161. sockAddr->sipx_port = htons(address->port);
  162. sockAddr->sipx_network = address->netNum[0];
  163. sockAddr->sipx_node[0] = address->nodeNum[0];
  164. sockAddr->sipx_node[1] = address->nodeNum[1];
  165. sockAddr->sipx_node[2] = address->nodeNum[2];
  166. sockAddr->sipx_node[3] = address->nodeNum[3];
  167. sockAddr->sipx_node[4] = address->nodeNum[4];
  168. sockAddr->sipx_node[5] = address->nodeNum[5];
  169. }
  170. NetSocket Net::openListenPort(U16 port)
  171. {
  172. #ifdef TORQUE_ALLOW_JOURNALING
  173. if(Game->isJournalReading())
  174. {
  175. U32 ret;
  176. Game->journalRead(&ret);
  177. return NetSocket(ret);
  178. }
  179. #endif //TORQUE_ALLOW_JOURNALING
  180. NetSocket sock = openSocket();
  181. if (sock == InvalidSocket)
  182. {
  183. Con::errorf("Unable to open listen socket: %s", strerror(errno));
  184. return InvalidSocket;
  185. }
  186. if (bind(sock, port) != NoError)
  187. {
  188. Con::errorf("Unable to bind port %d: %s", port, strerror(errno));
  189. ::close(sock);
  190. return InvalidSocket;
  191. }
  192. if (listen(sock, 4) != NoError)
  193. {
  194. Con::errorf("Unable to listen on port %d: %s", port, strerror(errno));
  195. ::close(sock);
  196. return InvalidSocket;
  197. }
  198. setBlocking(sock, false);
  199. addPolledSocket(sock, Listening);
  200. #ifdef TORQUE_ALLOW_JOURNALING
  201. if (Game->isJournalWriting())
  202. Game->journalWrite(U32(sock));
  203. #endif //TORQUE_ALLOW_JOURNALING
  204. return sock;
  205. }
  206. NetSocket Net::openConnectTo(const char *addressString)
  207. {
  208. if(!dStrnicmp(addressString, "ipx:", 4))
  209. return InvalidSocket;
  210. if(!dStrnicmp(addressString, "ip:", 3))
  211. addressString += 3; // eat off the ip:
  212. char remoteAddr[256];
  213. dStrcpy(remoteAddr, addressString);
  214. char *portString = dStrchr(remoteAddr, ':');
  215. U16 port;
  216. if(portString)
  217. {
  218. *portString++ = 0;
  219. port = htons(dAtoi(portString));
  220. }
  221. else
  222. port = htons(defaultPort);
  223. if(!dStricmp(remoteAddr, "broadcast"))
  224. return InvalidSocket;
  225. #ifdef TORQUE_ALLOW_JOURNALING
  226. if(Game->isJournalReading())
  227. {
  228. U32 ret;
  229. Game->journalRead(&ret);
  230. return NetSocket(ret);
  231. }
  232. #endif //TORQUE_ALLOW_JOURNALING
  233. NetSocket sock = openSocket();
  234. setBlocking(sock, false);
  235. sockaddr_in ipAddr;
  236. dMemset(&ipAddr, 0, sizeof(ipAddr));
  237. if (inet_aton(remoteAddr, &ipAddr.sin_addr) != 0)
  238. {
  239. ipAddr.sin_port = port;
  240. ipAddr.sin_family = AF_INET;
  241. if(::connect(sock, (struct sockaddr *)&ipAddr, sizeof(ipAddr)) == -1 &&
  242. errno != EINPROGRESS)
  243. {
  244. Con::errorf("Error connecting %s: %s",
  245. addressString, strerror(errno));
  246. ::close(sock);
  247. sock = InvalidSocket;
  248. }
  249. if(sock != InvalidSocket) {
  250. // add this socket to our list of polled sockets
  251. addPolledSocket(sock, ConnectionPending);
  252. }
  253. }
  254. else
  255. {
  256. // need to do an asynchronous name lookup. first, add the socket
  257. // to the polled list
  258. addPolledSocket(sock, NameLookupRequired, remoteAddr, port);
  259. // queue the lookup
  260. gNetAsync.queueLookup(remoteAddr, sock);
  261. }
  262. #ifdef TORQUE_ALLOW_JOURNALING
  263. if(Game->isJournalWriting())
  264. Game->journalWrite(U32(sock));
  265. #endif //TORQUE_ALLOW_JOURNALING
  266. return sock;
  267. }
  268. void Net::closeConnectTo(NetSocket sock)
  269. {
  270. #ifdef TORQUE_ALLOW_JOURNALING
  271. if(Game->isJournalReading())
  272. return;
  273. #endif //TORQUE_ALLOW_JOURNALING
  274. // if this socket is in the list of polled sockets, remove it
  275. for (int i = 0; i < gPolledSockets.size(); ++i)
  276. if (gPolledSockets[i]->fd == sock)
  277. {
  278. delete gPolledSockets[i];
  279. gPolledSockets.erase(i);
  280. break;
  281. }
  282. closeSocket(sock);
  283. }
  284. Net::Error Net::sendtoSocket(NetSocket socket, const U8 *buffer, int bufferSize)
  285. {
  286. #ifdef TORQUE_ALLOW_JOURNALING
  287. if(Game->isJournalReading())
  288. {
  289. U32 e;
  290. Game->journalRead(&e);
  291. return (Net::Error) e;
  292. }
  293. #endif //TORQUE_ALLOW_JOURNALING
  294. Net::Error e = send(socket, buffer, bufferSize);
  295. #ifdef TORQUE_ALLOW_JOURNALING
  296. if(Game->isJournalWriting())
  297. Game->journalWrite(U32(e));
  298. #endif //TORQUE_ALLOW_JOURNALING
  299. return e;
  300. }
  301. bool Net::openPort(S32 port)
  302. {
  303. if(udpSocket != InvalidSocket)
  304. close(udpSocket);
  305. if(ipxSocket != InvalidSocket)
  306. close(ipxSocket);
  307. udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
  308. ipxSocket = socket(AF_IPX, SOCK_DGRAM, 0);
  309. if(udpSocket != InvalidSocket)
  310. {
  311. Net::Error error;
  312. error = bind(udpSocket, port);
  313. if(error == NoError)
  314. error = setBufferSize(udpSocket, 32768);
  315. if(error == NoError)
  316. error = setBroadcast(udpSocket, true);
  317. if(error == NoError)
  318. error = setBlocking(udpSocket, false);
  319. if(error == NoError)
  320. Con::printf("UDP initialized on port %d", port);
  321. else
  322. {
  323. close(udpSocket);
  324. udpSocket = InvalidSocket;
  325. Con::printf("Unable to initialize UDP - error %d", error);
  326. }
  327. }
  328. if(ipxSocket != InvalidSocket)
  329. {
  330. Net::Error error = NoError;
  331. sockaddr_ipx ipxAddress;
  332. memset((char *)&ipxAddress, 0, sizeof(ipxAddress));
  333. ipxAddress.sipx_family = AF_IPX;
  334. ipxAddress.sipx_port = htons(port);
  335. S32 err = ::bind(ipxSocket, (struct sockaddr *)&ipxAddress, sizeof(ipxAddress));
  336. if(err)
  337. error = getLastError();
  338. if(error == NoError)
  339. error = setBufferSize(ipxSocket, 32768);
  340. if(error == NoError)
  341. error = setBroadcast(ipxSocket, true);
  342. if(error == NoError)
  343. error = setBlocking(ipxSocket, false);
  344. if(error == NoError)
  345. Con::printf("IPX initialized on port %d", port);
  346. else
  347. {
  348. close(ipxSocket);
  349. ipxSocket = InvalidSocket;
  350. Con::printf("Unable to initialize IPX - error %d", error);
  351. }
  352. }
  353. netPort = port;
  354. return ipxSocket != InvalidSocket || udpSocket != InvalidSocket;
  355. }
  356. void Net::closePort()
  357. {
  358. if(ipxSocket != InvalidSocket)
  359. close(ipxSocket);
  360. if(udpSocket != InvalidSocket)
  361. close(udpSocket);
  362. }
  363. Net::Error Net::sendto(const NetAddress *address, const U8 *buffer, S32 bufferSize)
  364. {
  365. #ifdef TORQUE_ALLOW_JOURNALING
  366. if(Game->isJournalReading())
  367. return NoError;
  368. #endif //TORQUE_ALLOW_JOURNALING
  369. if(address->type == NetAddress::IPAddress)
  370. {
  371. sockaddr_in ipAddr;
  372. netToIPSocketAddress(address, &ipAddr);
  373. if(::sendto(udpSocket, (const char*)buffer, bufferSize, 0,
  374. (sockaddr *) &ipAddr, sizeof(sockaddr_in)) == -1)
  375. return getLastError();
  376. else
  377. return NoError;
  378. }
  379. return NoError;
  380. }
  381. void Net::process()
  382. {
  383. sockaddr sa;
  384. PacketReceiveEvent receiveEvent;
  385. for(;;)
  386. {
  387. U32 addrLen = sizeof(sa);
  388. S32 bytesRead = -1;
  389. if(udpSocket != InvalidSocket)
  390. bytesRead = recvfrom(udpSocket, (char *) receiveEvent.data, MaxPacketDataSize, 0, &sa, &addrLen);
  391. if(bytesRead == -1 && ipxSocket != InvalidSocket)
  392. {
  393. addrLen = sizeof(sa);
  394. bytesRead = recvfrom(ipxSocket, (char *) receiveEvent.data, MaxPacketDataSize, 0, &sa, &addrLen);
  395. }
  396. if(bytesRead == -1)
  397. break;
  398. if(sa.sa_family == AF_INET)
  399. IPSocketToNetAddress((sockaddr_in *) &sa, &receiveEvent.sourceAddress);
  400. else
  401. continue;
  402. NetAddress &na = receiveEvent.sourceAddress;
  403. if(na.type == NetAddress::IPAddress &&
  404. na.netNum[0] == 127 &&
  405. na.netNum[1] == 0 &&
  406. na.netNum[2] == 0 &&
  407. na.netNum[3] == 1 &&
  408. na.port == netPort)
  409. continue;
  410. if(bytesRead <= 0)
  411. continue;
  412. receiveEvent.size = PacketReceiveEventHeaderSize + bytesRead;
  413. Game->postEvent(receiveEvent);
  414. }
  415. // process the polled sockets. This blob of code performs functions
  416. // similar to WinsockProc in winNet.cc
  417. if (gPolledSockets.size() == 0)
  418. return;
  419. static ConnectedNotifyEvent notifyEvent;
  420. static ConnectedAcceptEvent acceptEvent;
  421. static ConnectedReceiveEvent cReceiveEvent;
  422. S32 optval;
  423. socklen_t optlen = sizeof(S32);
  424. S32 bytesRead;
  425. Net::Error err;
  426. bool removeSock = false;
  427. Socket *currentSock = NULL;
  428. sockaddr_in ipAddr;
  429. NetSocket incoming = InvalidSocket;
  430. char out_h_addr[1024];
  431. int out_h_length = 0;
  432. for (S32 i = 0; i < gPolledSockets.size();
  433. /* no increment, this is done at end of loop body */)
  434. {
  435. removeSock = false;
  436. currentSock = gPolledSockets[i];
  437. switch (currentSock->state)
  438. {
  439. case InvalidState:
  440. Con::errorf("Error, InvalidState socket in polled sockets list");
  441. break;
  442. case ConnectionPending:
  443. notifyEvent.tag = currentSock->fd;
  444. // see if it is now connected
  445. if (getsockopt(currentSock->fd, SOL_SOCKET, SO_ERROR,
  446. &optval, &optlen) == -1)
  447. {
  448. Con::errorf("Error getting socket options: %s", strerror(errno));
  449. notifyEvent.state = ConnectedNotifyEvent::ConnectFailed;
  450. Game->postEvent(notifyEvent);
  451. removeSock = true;
  452. }
  453. else
  454. {
  455. if (optval == EINPROGRESS)
  456. // still connecting...
  457. break;
  458. if (optval == 0)
  459. {
  460. // poll for writable status to be sure we're connected.
  461. bool ready = netSocketWaitForWritable(currentSock->fd,0);
  462. if(!ready)
  463. break;
  464. // connected.
  465. notifyEvent.state = ConnectedNotifyEvent::Connected;
  466. Game->postEvent(notifyEvent);
  467. currentSock->state = Connected;
  468. }
  469. else
  470. {
  471. // some kind of error
  472. Con::errorf("Error connecting: %s", strerror(errno));
  473. notifyEvent.state = ConnectedNotifyEvent::ConnectFailed;
  474. Game->postEvent(notifyEvent);
  475. removeSock = true;
  476. }
  477. }
  478. break;
  479. case Connected:
  480. bytesRead = 0;
  481. // try to get some data
  482. err = Net::recv(currentSock->fd, cReceiveEvent.data, MaxPacketDataSize, &bytesRead);
  483. if(err == Net::NoError)
  484. {
  485. if (bytesRead > 0)
  486. {
  487. // got some data, post it
  488. cReceiveEvent.tag = currentSock->fd;
  489. cReceiveEvent.size = ConnectedReceiveEventHeaderSize +
  490. bytesRead;
  491. Game->postEvent(cReceiveEvent);
  492. }
  493. else
  494. {
  495. // zero bytes read means EOF
  496. if (bytesRead < 0)
  497. // ack! this shouldn't happen
  498. Con::errorf("Unexpected error on socket: %s",
  499. strerror(errno));
  500. notifyEvent.tag = currentSock->fd;
  501. notifyEvent.state = ConnectedNotifyEvent::Disconnected;
  502. Game->postEvent(notifyEvent);
  503. removeSock = true;
  504. }
  505. }
  506. else if (err != Net::NoError && err != Net::WouldBlock)
  507. {
  508. Con::errorf("Error reading from socket: %s", strerror(errno));
  509. notifyEvent.tag = currentSock->fd;
  510. notifyEvent.state = ConnectedNotifyEvent::Disconnected;
  511. Game->postEvent(notifyEvent);
  512. removeSock = true;
  513. }
  514. break;
  515. case NameLookupRequired:
  516. // is the lookup complete?
  517. if (!gNetAsync.checkLookup(
  518. currentSock->fd, out_h_addr, &out_h_length,
  519. sizeof(out_h_addr)))
  520. break;
  521. notifyEvent.tag = currentSock->fd;
  522. if (out_h_length == -1)
  523. {
  524. Con::errorf("DNS lookup failed: %s", currentSock->remoteAddr);
  525. notifyEvent.state = ConnectedNotifyEvent::DNSFailed;
  526. removeSock = true;
  527. }
  528. else
  529. {
  530. // try to connect
  531. dMemcpy(&(ipAddr.sin_addr.s_addr), out_h_addr, out_h_length);
  532. ipAddr.sin_port = currentSock->remotePort;
  533. ipAddr.sin_family = AF_INET;
  534. if(::connect(currentSock->fd, (struct sockaddr *)&ipAddr,
  535. sizeof(ipAddr)) == -1)
  536. {
  537. if (errno == EINPROGRESS)
  538. {
  539. notifyEvent.state = ConnectedNotifyEvent::DNSResolved;
  540. currentSock->state = ConnectionPending;
  541. }
  542. else
  543. {
  544. Con::errorf("Error connecting to %s: %s",
  545. currentSock->remoteAddr, strerror(errno));
  546. notifyEvent.state = ConnectedNotifyEvent::ConnectFailed;
  547. removeSock = true;
  548. }
  549. }
  550. else
  551. {
  552. notifyEvent.state = ConnectedNotifyEvent::Connected;
  553. currentSock->state = Connected;
  554. }
  555. }
  556. Game->postEvent(notifyEvent);
  557. break;
  558. case Listening:
  559. incoming =
  560. Net::accept(currentSock->fd, &acceptEvent.address);
  561. if(incoming != InvalidSocket)
  562. {
  563. acceptEvent.portTag = currentSock->fd;
  564. acceptEvent.connectionTag = incoming;
  565. setBlocking(incoming, false);
  566. addPolledSocket(incoming, Connected);
  567. Game->postEvent(acceptEvent);
  568. }
  569. break;
  570. }
  571. // only increment index if we're not removing the connection, since
  572. // the removal will shift the indices down by one
  573. if (removeSock)
  574. closeConnectTo(currentSock->fd);
  575. else
  576. i++;
  577. }
  578. }
  579. NetSocket Net::openSocket()
  580. {
  581. int retSocket;
  582. retSocket = socket(AF_INET, SOCK_STREAM, 0);
  583. if(retSocket == InvalidSocket)
  584. return InvalidSocket;
  585. else
  586. return retSocket;
  587. }
  588. Net::Error Net::closeSocket(NetSocket socket)
  589. {
  590. if(socket != InvalidSocket)
  591. {
  592. // if we're quitting, allow the OS to close the sockets.
  593. // this is here to work around a bug in close().
  594. if(platState.quit)
  595. return NoError;
  596. if(!close(socket))
  597. return NoError;
  598. else
  599. return getLastError();
  600. }
  601. else
  602. return NotASocket;
  603. }
  604. Net::Error Net::connect(NetSocket socket, const NetAddress *address)
  605. {
  606. if(address->type != NetAddress::IPAddress)
  607. return WrongProtocolType;
  608. sockaddr_in socketAddress;
  609. netToIPSocketAddress(address, &socketAddress);
  610. if(!::connect(socket, (sockaddr *) &socketAddress, sizeof(socketAddress)))
  611. return NoError;
  612. return getLastError();
  613. }
  614. Net::Error Net::listen(NetSocket socket, S32 backlog)
  615. {
  616. if(!::listen(socket, backlog))
  617. return NoError;
  618. return getLastError();
  619. }
  620. NetSocket Net::accept(NetSocket acceptSocket, NetAddress *remoteAddress)
  621. {
  622. sockaddr_in socketAddress;
  623. U32 addrLen = sizeof(socketAddress);
  624. int retVal = ::accept(acceptSocket, (sockaddr *) &socketAddress, &addrLen);
  625. if(retVal != InvalidSocket)
  626. {
  627. IPSocketToNetAddress(&socketAddress, remoteAddress);
  628. return retVal;
  629. }
  630. return InvalidSocket;
  631. }
  632. Net::Error Net::bind(NetSocket socket, U16 port)
  633. {
  634. S32 error;
  635. sockaddr_in socketAddress;
  636. dMemset((char *)&socketAddress, 0, sizeof(socketAddress));
  637. socketAddress.sin_family = AF_INET;
  638. // It's entirely possible that there are two NIC cards.
  639. // We let the user specify which one the server runs on.
  640. // thanks to [TPG]P1aGu3 for the name
  641. const char* serverIP = Con::getVariable( "Pref::Net::BindAddress" );
  642. // serverIP is guaranteed to be non-0.
  643. AssertFatal( serverIP, "serverIP is NULL!" );
  644. if( serverIP[0] != '\0' ) {
  645. // we're not empty
  646. socketAddress.sin_addr.s_addr = inet_addr( serverIP );
  647. if( socketAddress.sin_addr.s_addr != INADDR_NONE ) {
  648. Con::printf( "Binding server port to %s", serverIP );
  649. } else {
  650. Con::warnf( ConsoleLogEntry::General,
  651. "inet_addr() failed for %s while binding!",
  652. serverIP );
  653. socketAddress.sin_addr.s_addr = INADDR_ANY;
  654. }
  655. } else {
  656. Con::printf( "Binding server port to default IP" );
  657. socketAddress.sin_addr.s_addr = INADDR_ANY;
  658. }
  659. socketAddress.sin_port = htons(port);
  660. error = ::bind(socket, (sockaddr *) &socketAddress, sizeof(socketAddress));
  661. if(!error)
  662. return NoError;
  663. return getLastError();
  664. }
  665. Net::Error Net::setBufferSize(NetSocket socket, S32 bufferSize)
  666. {
  667. S32 error;
  668. error = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *) &bufferSize, sizeof(bufferSize));
  669. if(!error)
  670. error = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *) &bufferSize, sizeof(bufferSize));
  671. if(!error)
  672. return NoError;
  673. return getLastError();
  674. }
  675. Net::Error Net::setBroadcast(NetSocket socket, bool broadcast)
  676. {
  677. S32 bc = broadcast;
  678. S32 error = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc));
  679. if(!error)
  680. return NoError;
  681. return getLastError();
  682. }
  683. Net::Error Net::setBlocking(NetSocket socket, bool blockingIO)
  684. {
  685. int notblock = !blockingIO;
  686. S32 error = ioctl(socket, FIONBIO, &notblock);
  687. if(!error)
  688. return NoError;
  689. return getLastError();
  690. }
  691. Net::Error Net::send(NetSocket socket, const U8 *buffer, S32 bufferSize)
  692. {
  693. errno = 0;
  694. S32 bytesWritten = ::send(socket, (const char*)buffer, bufferSize, 0);
  695. if(bytesWritten == -1)
  696. Con::errorf("Could not write to socket. Error: %s",strerror(errno));
  697. return getLastError();
  698. }
  699. Net::Error Net::recv(NetSocket socket, U8 *buffer, S32 bufferSize, S32 *bytesRead)
  700. {
  701. *bytesRead = ::recv(socket, (char*)buffer, bufferSize, 0);
  702. if(*bytesRead == -1)
  703. return getLastError();
  704. return NoError;
  705. }
  706. bool Net::compareAddresses(const NetAddress *a1, const NetAddress *a2)
  707. {
  708. if((a1->type != a2->type) ||
  709. (*((U32 *)a1->netNum) != *((U32 *)a2->netNum)) ||
  710. (a1->port != a2->port))
  711. return false;
  712. if(a1->type == NetAddress::IPAddress)
  713. return true;
  714. for(S32 i = 0; i < 6; i++)
  715. if(a1->nodeNum[i] != a2->nodeNum[i])
  716. return false;
  717. return true;
  718. }
  719. bool Net::stringToAddress(const char *addressString, NetAddress *address)
  720. {
  721. // assume IP if it doesn't have ipx: at the front.
  722. if(!dStrnicmp(addressString, "ip:", 3))
  723. addressString += 3; // eat off the ip:
  724. sockaddr_in ipAddr;
  725. char remoteAddr[256];
  726. if(strlen(addressString) > 255)
  727. return false;
  728. dStrcpy(remoteAddr, addressString);
  729. char *portString = dStrchr(remoteAddr, ':');
  730. if(portString)
  731. *portString++ = '\0';
  732. struct hostent *hp;
  733. if(!dStricmp(remoteAddr, "broadcast"))
  734. ipAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  735. else
  736. {
  737. if (inet_aton(remoteAddr,&ipAddr.sin_addr) == 0) // error
  738. {
  739. if((hp = gethostbyname(remoteAddr)) == 0)
  740. return false;
  741. else
  742. memcpy(&ipAddr.sin_addr.s_addr, hp->h_addr, sizeof(in_addr));
  743. }
  744. }
  745. if(portString)
  746. ipAddr.sin_port = htons(dAtoi(portString));
  747. else
  748. ipAddr.sin_port = htons(defaultPort);
  749. ipAddr.sin_family = AF_INET;
  750. IPSocketToNetAddress(&ipAddr, address);
  751. return true;
  752. }
  753. void Net::addressToString(const NetAddress *address, char addressString[256])
  754. {
  755. if(address->type == NetAddress::IPAddress)
  756. {
  757. sockaddr_in ipAddr;
  758. netToIPSocketAddress(address, &ipAddr);
  759. if(ipAddr.sin_addr.s_addr == htonl(INADDR_BROADCAST))
  760. dSprintf(addressString, 256, "IP:Broadcast:%d", ntohs(ipAddr.sin_port));
  761. else
  762. dSprintf(addressString, 256, "IP:%s:%d", inet_ntoa(ipAddr.sin_addr),
  763. ntohs(ipAddr.sin_port));
  764. // dSprintf(addressString, 256, "IP:%d:%d", ipAddr.sin_addr.s_addr,
  765. // ntohs(ipAddr.sin_port));
  766. }
  767. else
  768. {
  769. return;
  770. dSprintf(addressString, 256, "IPX:%.2X%.2X%.2X%.2X:%.2X%.2X%.2X%.2X%.2X%.2X:%d",
  771. address->netNum[0], address->netNum[1], address->netNum[2], address->netNum[3],
  772. address->nodeNum[0], address->nodeNum[1], address->nodeNum[2], address->nodeNum[3], address->nodeNum[4], address->nodeNum[5],
  773. address->port);
  774. }
  775. }
  776. Net::Error getLastError()
  777. {
  778. if (errno == EAGAIN)
  779. return Net::WouldBlock;
  780. if (errno == 0)
  781. return Net::NoError;
  782. return Net::UnknownError;
  783. }