AndroidNet.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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 "platformAndroid/platformAndroid.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. S32 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(U32);
  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,
  447. (S32*)&optlen) == -1)
  448. {
  449. Con::errorf("Error getting socket options: %s", strerror(errno));
  450. notifyEvent.state = ConnectedNotifyEvent::ConnectFailed;
  451. Game->postEvent(notifyEvent);
  452. removeSock = true;
  453. }
  454. else
  455. {
  456. if (optval == EINPROGRESS)
  457. // still connecting...
  458. break;
  459. if (optval == 0)
  460. {
  461. // poll for writable status to be sure we're connected.
  462. bool ready = netSocketWaitForWritable(currentSock->fd,0);
  463. if(!ready)
  464. break;
  465. // connected.
  466. notifyEvent.state = ConnectedNotifyEvent::Connected;
  467. Game->postEvent(notifyEvent);
  468. currentSock->state = Connected;
  469. }
  470. else
  471. {
  472. // some kind of error
  473. Con::errorf("Error connecting: %s", strerror(errno));
  474. notifyEvent.state = ConnectedNotifyEvent::ConnectFailed;
  475. Game->postEvent(notifyEvent);
  476. removeSock = true;
  477. }
  478. }
  479. break;
  480. case Connected:
  481. bytesRead = 0;
  482. // try to get some data
  483. err = Net::recv(currentSock->fd, cReceiveEvent.data, MaxPacketDataSize, &bytesRead);
  484. if(err == Net::NoError)
  485. {
  486. if (bytesRead > 0)
  487. {
  488. // got some data, post it
  489. cReceiveEvent.tag = currentSock->fd;
  490. cReceiveEvent.size = ConnectedReceiveEventHeaderSize +
  491. bytesRead;
  492. Game->postEvent(cReceiveEvent);
  493. }
  494. else
  495. {
  496. // zero bytes read means EOF
  497. if (bytesRead < 0)
  498. // ack! this shouldn't happen
  499. Con::errorf("Unexpected error on socket: %s",
  500. strerror(errno));
  501. notifyEvent.tag = currentSock->fd;
  502. notifyEvent.state = ConnectedNotifyEvent::Disconnected;
  503. Game->postEvent(notifyEvent);
  504. removeSock = true;
  505. }
  506. }
  507. else if (err != Net::NoError && err != Net::WouldBlock)
  508. {
  509. Con::errorf("Error reading from socket: %s", strerror(errno));
  510. notifyEvent.tag = currentSock->fd;
  511. notifyEvent.state = ConnectedNotifyEvent::Disconnected;
  512. Game->postEvent(notifyEvent);
  513. removeSock = true;
  514. }
  515. break;
  516. case NameLookupRequired:
  517. // is the lookup complete?
  518. if (!gNetAsync.checkLookup(
  519. currentSock->fd, out_h_addr, &out_h_length,
  520. sizeof(out_h_addr)))
  521. break;
  522. notifyEvent.tag = currentSock->fd;
  523. if (out_h_length == -1)
  524. {
  525. Con::errorf("DNS lookup failed: %s", currentSock->remoteAddr);
  526. notifyEvent.state = ConnectedNotifyEvent::DNSFailed;
  527. removeSock = true;
  528. }
  529. else
  530. {
  531. // try to connect
  532. dMemcpy(&(ipAddr.sin_addr.s_addr), out_h_addr, out_h_length);
  533. ipAddr.sin_port = currentSock->remotePort;
  534. ipAddr.sin_family = AF_INET;
  535. if(::connect(currentSock->fd, (struct sockaddr *)&ipAddr,
  536. sizeof(ipAddr)) == -1)
  537. {
  538. if (errno == EINPROGRESS)
  539. {
  540. notifyEvent.state = ConnectedNotifyEvent::DNSResolved;
  541. currentSock->state = ConnectionPending;
  542. }
  543. else
  544. {
  545. Con::errorf("Error connecting to %s: %s",
  546. currentSock->remoteAddr, strerror(errno));
  547. notifyEvent.state = ConnectedNotifyEvent::ConnectFailed;
  548. removeSock = true;
  549. }
  550. }
  551. else
  552. {
  553. notifyEvent.state = ConnectedNotifyEvent::Connected;
  554. currentSock->state = Connected;
  555. }
  556. }
  557. Game->postEvent(notifyEvent);
  558. break;
  559. case Listening:
  560. incoming =
  561. Net::accept(currentSock->fd, &acceptEvent.address);
  562. if(incoming != InvalidSocket)
  563. {
  564. acceptEvent.portTag = currentSock->fd;
  565. acceptEvent.connectionTag = incoming;
  566. setBlocking(incoming, false);
  567. addPolledSocket(incoming, Connected);
  568. Game->postEvent(acceptEvent);
  569. }
  570. break;
  571. }
  572. // only increment index if we're not removing the connection, since
  573. // the removal will shift the indices down by one
  574. if (removeSock)
  575. closeConnectTo(currentSock->fd);
  576. else
  577. i++;
  578. }
  579. }
  580. NetSocket Net::openSocket()
  581. {
  582. int retSocket;
  583. retSocket = socket(AF_INET, SOCK_STREAM, 0);
  584. if(retSocket == InvalidSocket)
  585. return InvalidSocket;
  586. else
  587. return retSocket;
  588. }
  589. Net::Error Net::closeSocket(NetSocket socket)
  590. {
  591. if(socket != InvalidSocket)
  592. {
  593. // if we're quitting, allow the OS to close the sockets.
  594. // this is here to work around a bug in close().
  595. if(platState.quit)
  596. return NoError;
  597. if(!close(socket))
  598. return NoError;
  599. else
  600. return getLastError();
  601. }
  602. else
  603. return NotASocket;
  604. }
  605. Net::Error Net::connect(NetSocket socket, const NetAddress *address)
  606. {
  607. if(address->type != NetAddress::IPAddress)
  608. return WrongProtocolType;
  609. sockaddr_in socketAddress;
  610. netToIPSocketAddress(address, &socketAddress);
  611. if(!::connect(socket, (sockaddr *) &socketAddress, sizeof(socketAddress)))
  612. return NoError;
  613. return getLastError();
  614. }
  615. Net::Error Net::listen(NetSocket socket, S32 backlog)
  616. {
  617. if(!::listen(socket, backlog))
  618. return NoError;
  619. return getLastError();
  620. }
  621. NetSocket Net::accept(NetSocket acceptSocket, NetAddress *remoteAddress)
  622. {
  623. sockaddr_in socketAddress;
  624. S32 addrLen = sizeof(socketAddress);
  625. int retVal = ::accept(acceptSocket, (sockaddr *) &socketAddress, &addrLen);
  626. if(retVal != InvalidSocket)
  627. {
  628. IPSocketToNetAddress(&socketAddress, remoteAddress);
  629. return retVal;
  630. }
  631. return InvalidSocket;
  632. }
  633. Net::Error Net::bind(NetSocket socket, U16 port)
  634. {
  635. S32 error;
  636. sockaddr_in socketAddress;
  637. dMemset((char *)&socketAddress, 0, sizeof(socketAddress));
  638. socketAddress.sin_family = AF_INET;
  639. // It's entirely possible that there are two NIC cards.
  640. // We let the user specify which one the server runs on.
  641. // thanks to [TPG]P1aGu3 for the name
  642. const char* serverIP = Con::getVariable( "Pref::Net::BindAddress" );
  643. // serverIP is guaranteed to be non-0.
  644. AssertFatal( serverIP, "serverIP is NULL!" );
  645. if( serverIP[0] != '\0' ) {
  646. // we're not empty
  647. socketAddress.sin_addr.s_addr = inet_addr( serverIP );
  648. if( socketAddress.sin_addr.s_addr != INADDR_NONE ) {
  649. Con::printf( "Binding server port to %s", serverIP );
  650. } else {
  651. Con::warnf( ConsoleLogEntry::General,
  652. "inet_addr() failed for %s while binding!",
  653. serverIP );
  654. socketAddress.sin_addr.s_addr = INADDR_ANY;
  655. }
  656. } else {
  657. Con::printf( "Binding server port to default IP" );
  658. socketAddress.sin_addr.s_addr = INADDR_ANY;
  659. }
  660. socketAddress.sin_port = htons(port);
  661. error = ::bind(socket, (sockaddr *) &socketAddress, sizeof(socketAddress));
  662. if(!error)
  663. return NoError;
  664. return getLastError();
  665. }
  666. Net::Error Net::setBufferSize(NetSocket socket, S32 bufferSize)
  667. {
  668. S32 error;
  669. error = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *) &bufferSize, sizeof(bufferSize));
  670. if(!error)
  671. error = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *) &bufferSize, sizeof(bufferSize));
  672. if(!error)
  673. return NoError;
  674. return getLastError();
  675. }
  676. Net::Error Net::setBroadcast(NetSocket socket, bool broadcast)
  677. {
  678. S32 bc = broadcast;
  679. S32 error = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc));
  680. if(!error)
  681. return NoError;
  682. return getLastError();
  683. }
  684. Net::Error Net::setBlocking(NetSocket socket, bool blockingIO)
  685. {
  686. int notblock = !blockingIO;
  687. S32 error = ioctl(socket, FIONBIO, &notblock);
  688. if(!error)
  689. return NoError;
  690. return getLastError();
  691. }
  692. Net::Error Net::send(NetSocket socket, const U8 *buffer, S32 bufferSize)
  693. {
  694. errno = 0;
  695. S32 bytesWritten = ::send(socket, (const char*)buffer, bufferSize, 0);
  696. if(bytesWritten == -1)
  697. Con::errorf("Could not write to socket. Error: %s",strerror(errno));
  698. return getLastError();
  699. }
  700. Net::Error Net::recv(NetSocket socket, U8 *buffer, S32 bufferSize, S32 *bytesRead)
  701. {
  702. *bytesRead = ::recv(socket, (char*)buffer, bufferSize, 0);
  703. if(*bytesRead == -1)
  704. return getLastError();
  705. return NoError;
  706. }
  707. bool Net::compareAddresses(const NetAddress *a1, const NetAddress *a2)
  708. {
  709. if((a1->type != a2->type) ||
  710. (*((U32 *)a1->netNum) != *((U32 *)a2->netNum)) ||
  711. (a1->port != a2->port))
  712. return false;
  713. if(a1->type == NetAddress::IPAddress)
  714. return true;
  715. for(S32 i = 0; i < 6; i++)
  716. if(a1->nodeNum[i] != a2->nodeNum[i])
  717. return false;
  718. return true;
  719. }
  720. bool Net::stringToAddress(const char *addressString, NetAddress *address)
  721. {
  722. // assume IP if it doesn't have ipx: at the front.
  723. if(!dStrnicmp(addressString, "ip:", 3))
  724. addressString += 3; // eat off the ip:
  725. sockaddr_in ipAddr;
  726. char remoteAddr[256];
  727. if(strlen(addressString) > 255)
  728. return false;
  729. dStrcpy(remoteAddr, addressString);
  730. char *portString = dStrchr(remoteAddr, ':');
  731. if(portString)
  732. *portString++ = '\0';
  733. struct hostent *hp;
  734. if(!dStricmp(remoteAddr, "broadcast"))
  735. ipAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  736. else
  737. {
  738. if (inet_aton(remoteAddr,&ipAddr.sin_addr) == 0) // error
  739. {
  740. if((hp = gethostbyname(remoteAddr)) == 0)
  741. return false;
  742. else
  743. memcpy(&ipAddr.sin_addr.s_addr, hp->h_addr, sizeof(in_addr));
  744. }
  745. }
  746. if(portString)
  747. ipAddr.sin_port = htons(dAtoi(portString));
  748. else
  749. ipAddr.sin_port = htons(defaultPort);
  750. ipAddr.sin_family = AF_INET;
  751. IPSocketToNetAddress(&ipAddr, address);
  752. return true;
  753. }
  754. void Net::addressToString(const NetAddress *address, char addressString[256])
  755. {
  756. if(address->type == NetAddress::IPAddress)
  757. {
  758. sockaddr_in ipAddr;
  759. netToIPSocketAddress(address, &ipAddr);
  760. if(ipAddr.sin_addr.s_addr == htonl(INADDR_BROADCAST))
  761. dSprintf(addressString, 256, "IP:Broadcast:%d", ntohs(ipAddr.sin_port));
  762. else
  763. dSprintf(addressString, 256, "IP:%s:%d", inet_ntoa(ipAddr.sin_addr),
  764. ntohs(ipAddr.sin_port));
  765. // dSprintf(addressString, 256, "IP:%d:%d", ipAddr.sin_addr.s_addr,
  766. // ntohs(ipAddr.sin_port));
  767. }
  768. else
  769. {
  770. return;
  771. dSprintf(addressString, 256, "IPX:%.2X%.2X%.2X%.2X:%.2X%.2X%.2X%.2X%.2X%.2X:%d",
  772. address->netNum[0], address->netNum[1], address->netNum[2], address->netNum[3],
  773. address->nodeNum[0], address->nodeNum[1], address->nodeNum[2], address->nodeNum[3], address->nodeNum[4], address->nodeNum[5],
  774. address->port);
  775. }
  776. }
  777. Net::Error getLastError()
  778. {
  779. if (errno == EAGAIN)
  780. return Net::WouldBlock;
  781. if (errno == 0)
  782. return Net::NoError;
  783. return Net::UnknownError;
  784. }