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

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