Open Source Tomb Raider Engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Network.cpp 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /*!
  2. * \file src/Network.cpp
  3. * \brief Networking Singleton class
  4. *
  5. * \author Mongoose
  6. */
  7. #include <Network.h>
  8. #include <unistd.h>
  9. #include <signal.h>
  10. #include <string.h>
  11. #include <time.h>
  12. #include <sys/time.h>
  13. #include <errno.h>
  14. #include <strings.h>
  15. #include <stdio.h>
  16. #include <sys/types.h>
  17. #include <sys/socket.h>
  18. #include <netinet/in.h>
  19. #include <netdb.h>
  20. #include <arpa/inet.h>
  21. #include <stdlib.h>
  22. #include <MatMath.h> // Random Number
  23. //#define LOCAL_BCAST
  24. #define MAX_CLIENTS 32
  25. typedef struct client_s {
  26. unsigned int uid;
  27. char active;
  28. unsigned int seq;
  29. unsigned int frameExpected;
  30. } client_t;
  31. #ifdef USING_PTHREADS
  32. #include <pthread.h>
  33. pthread_t gPThreadId[3];
  34. #endif
  35. unsigned int gUID;
  36. client_t gClients[MAX_CLIENTS];
  37. unsigned int gNumClients = 0;
  38. network_frame_t gPiggyBack;
  39. ////////////////////////////////////////////////////////////
  40. // Constructors
  41. ////////////////////////////////////////////////////////////
  42. Network *Network::mInstance = 0x0;
  43. Network *Network::Instance()
  44. {
  45. if (mInstance == 0x0)
  46. {
  47. mInstance = new Network();
  48. }
  49. return mInstance;
  50. }
  51. void killNetworkSingleton()
  52. {
  53. printf("Shutting down Network...\n");
  54. // Requires public deconstructor
  55. delete Network::Instance();
  56. }
  57. Network::Network()
  58. {
  59. strncpy(mRemoteHost, "localhost", REMOTE_HOST_STR_SZ);
  60. memset(mBindHost, 0, BIND_HOST_STR_SZ);
  61. setPort(8080);
  62. mPiggyBack = true;
  63. mNetworkReliable = true;
  64. mSpawnedClient = false;
  65. mSpawnedServer = false;
  66. mKillClient = false;
  67. mKillServer = false;
  68. mDebug = false;
  69. gUID = getUID();
  70. printf("UID %u\n", gUID);
  71. for (gNumClients = MAX_CLIENTS; gNumClients > 0;)
  72. {
  73. --gNumClients;
  74. gClients[gNumClients].active = 0;
  75. gClients[gNumClients].uid = 0;
  76. gClients[gNumClients].seq = 0;
  77. }
  78. }
  79. Network::~Network()
  80. {
  81. killServerThread();
  82. killClientThread();
  83. }
  84. ////////////////////////////////////////////////////////////
  85. // Public Accessors
  86. ////////////////////////////////////////////////////////////
  87. network_frame_t &Network::getPiggyBack()
  88. {
  89. return gPiggyBack;
  90. }
  91. unsigned int Network::getUID()
  92. {
  93. struct timeval tv;
  94. struct timezone tz;
  95. gettimeofday(&tv, &tz);
  96. srand(tv.tv_usec);
  97. return ((unsigned int)(tv.tv_sec * helRandomNum(2.0f, 3.3f) -
  98. tv.tv_sec * helRandomNum(1.0f, 2.0f)) +
  99. (unsigned int)(tv.tv_usec * helRandomNum(2.0f, 3.3f) -
  100. tv.tv_usec * helRandomNum(1.0f, 2.0f)) +
  101. (unsigned int)helRandomNum(666.0f, 5000.0f));
  102. }
  103. int Network::getPort()
  104. {
  105. return mPort;
  106. }
  107. ////////////////////////////////////////////////////////////
  108. // Public Mutators
  109. ////////////////////////////////////////////////////////////
  110. void *client_thread(void *v)
  111. {
  112. Network &network = *Network::Instance();
  113. network.runClient();
  114. return NULL;
  115. }
  116. void *server_thread(void *v)
  117. {
  118. Network &network = *Network::Instance();
  119. network.runServer();
  120. return NULL;
  121. }
  122. void Network::setBindHost(char *s)
  123. {
  124. if (!s && !s[0])
  125. return;
  126. strncpy(mBindHost, s, BIND_HOST_STR_SZ);
  127. }
  128. void Network::setRemoteHost(char *s)
  129. {
  130. if (!s && !s[0])
  131. return;
  132. strncpy(mRemoteHost, s, REMOTE_HOST_STR_SZ);
  133. }
  134. void Network::setDebug(bool toggle)
  135. {
  136. mDebug = toggle;
  137. }
  138. void Network::setPort(unsigned int port)
  139. {
  140. mPort = port;
  141. }
  142. void Network::killServerThread()
  143. {
  144. mKillServer = true;
  145. // Remember for mutex
  146. // while (mKillServer)
  147. // {
  148. // }
  149. mSpawnedServer = false;
  150. }
  151. void Network::killClientThread()
  152. {
  153. mKillClient = true;
  154. // Remember for mutex
  155. // while (mKillClient)
  156. // {
  157. // }
  158. mSpawnedClient = false;
  159. }
  160. void Network::spawnServerThread()
  161. {
  162. // For now don't handle shutting down server to start client and vv
  163. if (!mSpawnedServer && !mSpawnedClient)
  164. {
  165. #ifdef USING_PTHREADS
  166. pthread_create(gPThreadId + 0, 0, server_thread, NULL);
  167. #else
  168. printf("Network::spawnServerThread> Build doesn't support threads\n");
  169. #endif
  170. mSpawnedServer = true;
  171. }
  172. }
  173. void Network::spawnClientThread()
  174. {
  175. // For now don't handle shutting down server to start client and vv
  176. if (!mSpawnedServer && !mSpawnedClient)
  177. {
  178. #ifdef USING_PTHREADS
  179. pthread_create(gPThreadId + 1, 0, client_thread, NULL);
  180. #else
  181. printf("Network::spawnClientThread> Build doesn't support threads\n");
  182. #endif
  183. mSpawnedClient = true;
  184. }
  185. }
  186. ////////////////////////////////////////////////////////////
  187. // Protected Mutators
  188. ////////////////////////////////////////////////////////////
  189. int Network::runServer()
  190. {
  191. unsigned int fsize;
  192. int socket_fd, cc, cip;
  193. struct sockaddr_in s_in, from;
  194. char hostid[64];
  195. network_frame_t f;
  196. unsigned int i;
  197. unsigned int packetsRecieved = 0;
  198. socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  199. if (socket_fd < 0)
  200. {
  201. perror("recv_udp:socket");
  202. return -1;
  203. }
  204. if (mBindHost[0])
  205. {
  206. strncpy(hostid, mBindHost, 64);
  207. }
  208. else
  209. {
  210. if (gethostname(hostid, 64) < 0)
  211. {
  212. perror("Server: recv_udp:gethostname");
  213. return -1;
  214. }
  215. printf("Server: gethostname returned '%s'\n", hostid);
  216. fflush(stdout);
  217. }
  218. // Setup for port binding
  219. memset(&s_in, 0, sizeof(s_in));
  220. s_in.sin_family = AF_INET;
  221. #ifdef LOCAL_BCAST
  222. struct hostent *hostptr;
  223. if ((hostptr = gethostbyname(hostid)) == NULL)
  224. {
  225. fprintf(stderr, "Server: recv_udp, Invalid host name '%s'\n", hostid);
  226. return -1;
  227. }
  228. memcpy((void *)(&s_in.sin_addr), hostptr->h_addr, hostptr->h_length);
  229. #else
  230. s_in.sin_addr.s_addr = htonl(INADDR_ANY);
  231. #endif
  232. int port = getPort();
  233. s_in.sin_port = htons(port); // htons new
  234. fflush(stdout);
  235. // Bind
  236. while (bind(socket_fd, (struct sockaddr *)&s_in, sizeof(s_in)) < 0)
  237. {
  238. if (s_in.sin_port++ > (port + 10))
  239. {
  240. perror("Server: recv_udp:bind exhausted");
  241. return -1;
  242. }
  243. }
  244. cip = ntohl(s_in.sin_addr.s_addr);
  245. printf("Server: Started on ( %i.%i.%i.%i:%i )\n",
  246. cip >> 24, cip << 8 >> 24,
  247. cip << 16 >> 24, cip << 24 >> 24, s_in.sin_port);
  248. for (; !mKillClient;)
  249. {
  250. fsize = sizeof(from);
  251. // 1. Wait for event
  252. // 2. Get inbound frame
  253. cc = recvfrom(socket_fd, &f, sizeof(network_frame_t), 0,
  254. (struct sockaddr *)&from, &fsize);
  255. if (cc < 0)
  256. {
  257. perror("Server: recv_udp:recvfrom");
  258. continue;
  259. }
  260. ++packetsRecieved;
  261. if (mDebug)
  262. {
  263. printf("=====================================================\n");
  264. printf("Packet %i\n", packetsRecieved);
  265. printf("Server: Recieved packet from %u\n",
  266. f.uid);
  267. }
  268. // A. Look and see if this client has connected before
  269. for (i = 0; i < gNumClients; ++i)
  270. {
  271. if (gClients[i].uid == f.uid)
  272. {
  273. break;
  274. }
  275. }
  276. // B. Collect client data if it's a new connection
  277. if (!gClients[i].active)
  278. {
  279. for (i = 0; i < gNumClients+1; ++i)
  280. {
  281. if ((i + 1) < MAX_CLIENTS && !gClients[i].active)
  282. {
  283. gClients[i].uid = f.uid;
  284. gClients[i].active = 1;
  285. gClients[i].frameExpected = 0;
  286. ++gNumClients;
  287. printf("Server: %u made connection, as client %i\n",
  288. gClients[i].uid, i);
  289. break;
  290. }
  291. }
  292. if (i == MAX_CLIENTS || !gClients[i].active)
  293. {
  294. if (mDebug)
  295. {
  296. printf("Server: Handshake packet from %u failed?\n",
  297. f.uid);
  298. }
  299. continue;
  300. }
  301. }
  302. cip = ntohl(from.sin_addr.s_addr);
  303. if (mDebug)
  304. {
  305. printf("Server: Client (Famliy %d, Address %i.%i.%i.%i:%d)\n",
  306. ntohs(from.sin_family), cip >> 24, cip << 8 >> 24,
  307. cip << 16 >> 24, cip << 24 >> 24,
  308. ntohs(from.sin_port));
  309. printf("Server: Datalink layer recieved: packet seq %i\n",
  310. f.seq);
  311. }
  312. if (mNetworkReliable)
  313. {
  314. if (f.seq == gClients[i].seq)
  315. {
  316. if (mDebug)
  317. {
  318. printf("SERVER> Msg from %u\n", f.uid);
  319. }
  320. to_network_layer(f.data);
  321. gClients[i].seq = f.seq;
  322. }
  323. else
  324. {
  325. continue;
  326. }
  327. }
  328. //! \fixme Combine with above, duh
  329. // 3. Send to network layer
  330. if (gClients[i].frameExpected == f.header)
  331. {
  332. f.data.cid = i;
  333. to_network_layer(f.data);
  334. gClients[i].frameExpected = !gClients[i].frameExpected;
  335. }
  336. fflush(stdout);
  337. #ifdef UNIT_TEST_NETWORK
  338. if ((rand() % 10 == 0))
  339. {
  340. printf("Server: Simulating a lost ack %i\n", f.seq);
  341. continue;
  342. }
  343. #endif
  344. // 4. Send ACK, w/ piggyback if requested
  345. if (mPiggyBack)
  346. {
  347. gPiggyBack.header = 0;
  348. gPiggyBack.seq = f.seq;
  349. gPiggyBack.uid = gUID;
  350. if (mDebug)
  351. {
  352. printf("SERVER> Sending data by piggyback\n");
  353. }
  354. cc = sendto(socket_fd, &gPiggyBack, sizeof(gPiggyBack), 0,
  355. (struct sockaddr *)&from, sizeof(from));
  356. }
  357. else
  358. {
  359. f.header = 0;
  360. f.seq = 0;
  361. f.uid = gUID;
  362. cc = sendto(socket_fd, &f, sizeof(f), 0,
  363. (struct sockaddr *)&from, sizeof(from));
  364. }
  365. if (cc < 0)
  366. {
  367. perror("Server: send_udp:sendto");
  368. }
  369. else
  370. {
  371. if (mDebug)
  372. {
  373. printf("Server: Ack sent to %u\n", gClients[i].uid);
  374. }
  375. }
  376. }
  377. mKillClient = false;
  378. return 0;
  379. }
  380. void Network::runClient()
  381. {
  382. unsigned int fsize, last_frame_sent = 0;
  383. int socket_fd, cc, done;
  384. struct sockaddr_in dest;
  385. struct hostent *hostptr;
  386. network_frame_t f;
  387. struct timeval timeout;
  388. fd_set readfds;
  389. unsigned int packetsSent = 0;
  390. unsigned int seq = 0;
  391. char timedOut = 1;
  392. if (!mRemoteHost || !mRemoteHost[0])
  393. {
  394. return;
  395. }
  396. memset((char*) &timeout, 0, sizeof(timeout));
  397. timeout.tv_sec = 5;
  398. socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
  399. if (socket_fd == -1)
  400. {
  401. perror("Client: send_udp: socket");
  402. exit(0);
  403. }
  404. if ((hostptr = gethostbyname(mRemoteHost)) == NULL)
  405. {
  406. fprintf(stderr, "Client: send_udp: invalid host name, %s\n",
  407. mRemoteHost);
  408. exit(0);
  409. }
  410. // Setup connection
  411. bzero((char*) &dest, sizeof(dest));
  412. dest.sin_family = AF_INET;
  413. int port = getPort();
  414. dest.sin_port = htons(port);
  415. #ifdef LOCAL_BCAST
  416. memcpy(hostptr->h_addr, (char *) &dest.sin_addr, hostptr->h_length);
  417. #else
  418. if (inet_pton(AF_INET, mRemoteHost, &dest.sin_addr) < 0)
  419. {
  420. perror("inet_pton");
  421. return;
  422. }
  423. #endif
  424. // init
  425. f.data.send = 0;
  426. f.seq = 0;
  427. for (; !mKillServer;)
  428. {
  429. ++packetsSent;
  430. if (mDebug)
  431. {
  432. printf("=====================================================\n");
  433. printf("Packet %i\n", packetsSent);
  434. }
  435. // 1. Get packet to send over wire
  436. if (mNetworkReliable && timedOut && f.seq != seq)
  437. {
  438. if (mDebug)
  439. {
  440. printf("Client: Resending packet\n");
  441. }
  442. }
  443. else
  444. {
  445. from_network_layer(&f.data, &last_frame_sent);
  446. if (!f.data.send)
  447. {
  448. usleep(20);
  449. continue;
  450. }
  451. }
  452. // 2. Copy to frame
  453. f.seq = 0;//seq; // 0 forces all packets to check out
  454. f.uid = gUID;
  455. // 3. Send over the wire
  456. done = 0;
  457. timedOut = 0;
  458. while (!done)
  459. {
  460. if (mDebug)
  461. {
  462. printf("Client: Sending packet %i\n", f.seq);
  463. }
  464. cc = sendto(socket_fd, &f, sizeof(f), 0,
  465. (struct sockaddr *)&dest, sizeof(dest));
  466. if (cc < 0)
  467. {
  468. perror("Client: send_udp:sendto");
  469. if (errno == EMSGSIZE)
  470. {
  471. printf("Client: packet was too large\n");
  472. }
  473. }
  474. else
  475. {
  476. f.data.send = 0;
  477. }
  478. // Comment out this to enable more reliable service
  479. done = 1;
  480. }
  481. // 4. Wait for +ack or resend
  482. FD_ZERO(&readfds);
  483. // Setup socket to listen on here
  484. FD_SET(socket_fd, &readfds);
  485. // Set timeout in milliseconds
  486. timeout.tv_usec = 850;
  487. cc = select(socket_fd + 1, &readfds, NULL, NULL, &timeout);
  488. if ((cc < 0) && (errno != EINTR))
  489. {
  490. // there was an local error with select
  491. }
  492. if (cc == 0)
  493. {
  494. if (mDebug)
  495. {
  496. printf("Client: Timeout detected on packet %i\n", f.seq);
  497. }
  498. timedOut = 1;
  499. continue;
  500. }
  501. // Clear header for recv use
  502. f.header = 0;
  503. fsize = sizeof(dest);
  504. cc = recvfrom(socket_fd, &f, sizeof(f), 0,
  505. (struct sockaddr *)&dest, &fsize);
  506. if (cc < 0)
  507. {
  508. perror("Client: recv_udp:recvfrom");
  509. }
  510. else
  511. {
  512. if (mDebug)
  513. {
  514. printf("Client: Datalink layer recieved: packet seq %i\n", f.seq);
  515. printf("CLIENT> Msg from %u\n", f.uid);
  516. }
  517. to_network_layer(f.data);
  518. }
  519. if (seq == f.seq)
  520. {
  521. if (mDebug)
  522. {
  523. printf("Client: Recieved ack %i\n", f.seq);
  524. }
  525. ++seq;
  526. }
  527. }
  528. mKillServer = false;
  529. }