TCPInterface.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. #include "NativeFeatureIncludes.h"
  11. #if _RAKNET_SUPPORT_TCPInterface==1
  12. /// \file
  13. /// \brief A simple TCP based server allowing sends and receives. Can be connected to by a telnet client.
  14. ///
  15. #include "TCPInterface.h"
  16. #ifdef _WIN32
  17. #if !defined (WINDOWS_STORE_RT)
  18. typedef int socklen_t;
  19. #endif
  20. #else
  21. #include <sys/time.h>
  22. #include <unistd.h>
  23. #include <pthread.h>
  24. #endif
  25. #include <string.h>
  26. #include "RakAssert.h"
  27. #include <stdio.h>
  28. #include "RakAssert.h"
  29. #include "RakSleep.h"
  30. #include "StringCompressor.h"
  31. #include "StringTable.h"
  32. #include "Itoa.h"
  33. #include "SocketLayer.h"
  34. #include "SocketDefines.h"
  35. #if (defined(__GNUC__) || defined(__GCCXML__)) && !defined(__WIN32__)
  36. #include <netdb.h>
  37. #endif
  38. #ifdef _DO_PRINTF
  39. #endif
  40. #ifdef _WIN32
  41. #include "WSAStartupSingleton.h"
  42. #endif
  43. namespace RakNet
  44. {
  45. RAK_THREAD_DECLARATION(UpdateTCPInterfaceLoop);
  46. RAK_THREAD_DECLARATION(ConnectionAttemptLoop);
  47. }
  48. #ifdef _MSC_VER
  49. #pragma warning( push )
  50. #endif
  51. using namespace RakNet;
  52. STATIC_FACTORY_DEFINITIONS(TCPInterface,TCPInterface);
  53. TCPInterface::TCPInterface()
  54. {
  55. #if !defined(WINDOWS_STORE_RT)
  56. listenSocket=0;
  57. #endif
  58. remoteClients=0;
  59. remoteClientsLength=0;
  60. StringCompressor::AddReference();
  61. RakNet::StringTable::AddReference();
  62. #if OPEN_SSL_CLIENT_SUPPORT==1
  63. ctx=0;
  64. meth=0;
  65. #endif
  66. #ifdef _WIN32
  67. WSAStartupSingleton::AddRef();
  68. #endif
  69. }
  70. TCPInterface::~TCPInterface()
  71. {
  72. Stop();
  73. #ifdef _WIN32
  74. WSAStartupSingleton::Deref();
  75. #endif
  76. RakNet::OP_DELETE_ARRAY(remoteClients,_FILE_AND_LINE_);
  77. StringCompressor::RemoveReference();
  78. RakNet::StringTable::RemoveReference();
  79. }
  80. #if !defined(WINDOWS_STORE_RT)
  81. bool TCPInterface::CreateListenSocket(unsigned short port, unsigned short maxIncomingConnections, unsigned short socketFamily, const char *bindAddress)
  82. {
  83. (void) maxIncomingConnections;
  84. (void) socketFamily;
  85. #if RAKNET_SUPPORT_IPV6!=1
  86. listenSocket = socket__(AF_INET, SOCK_STREAM, 0);
  87. if ((int)listenSocket ==-1)
  88. return false;
  89. struct sockaddr_in serverAddress;
  90. memset(&serverAddress,0,sizeof(sockaddr_in));
  91. serverAddress.sin_family = AF_INET;
  92. if ( bindAddress && bindAddress[0] )
  93. {
  94. serverAddress.sin_addr.s_addr = inet_addr__(bindAddress );
  95. }
  96. else
  97. serverAddress.sin_addr.s_addr = INADDR_ANY;
  98. serverAddress.sin_port = htons(port);
  99. SocketLayer::SetSocketOptions(listenSocket, false, false);
  100. if (bind__(listenSocket,(struct sockaddr *) &serverAddress,sizeof(serverAddress)) < 0)
  101. return false;
  102. listen__(listenSocket, maxIncomingConnections);
  103. #else
  104. struct addrinfo hints;
  105. memset(&hints, 0, sizeof (addrinfo)); // make sure the struct is empty
  106. hints.ai_family = socketFamily; // don't care IPv4 or IPv6
  107. hints.ai_socktype = SOCK_STREAM; // TCP sockets
  108. hints.ai_flags = AI_PASSIVE; // fill in my IP for me
  109. struct addrinfo *servinfo=0, *aip; // will point to the results
  110. char portStr[32];
  111. Itoa(port,portStr,10);
  112. getaddrinfo(0, portStr, &hints, &servinfo);
  113. for (aip = servinfo; aip != NULL; aip = aip->ai_next)
  114. {
  115. // Open socket. The address type depends on what
  116. // getaddrinfo() gave us.
  117. listenSocket = socket__(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
  118. if (listenSocket != 0)
  119. {
  120. int ret = bind__( listenSocket, aip->ai_addr, (int) aip->ai_addrlen );
  121. if (ret>=0)
  122. {
  123. break;
  124. }
  125. else
  126. {
  127. closesocket__(listenSocket);
  128. listenSocket=0;
  129. }
  130. }
  131. }
  132. if (listenSocket==0)
  133. return false;
  134. SocketLayer::SetSocketOptions(listenSocket, false, false);
  135. listen__(listenSocket, maxIncomingConnections);
  136. #endif // #if RAKNET_SUPPORT_IPV6!=1
  137. return true;
  138. }
  139. #endif
  140. #if defined(WINDOWS_STORE_RT)
  141. bool TCPInterface::CreateListenSocket_WinStore8(unsigned short port, unsigned short maxIncomingConnections, unsigned short socketFamily, const char *bindAddress)
  142. {
  143. listenSocket = WinRTCreateStreamSocket(AF_INET, SOCK_STREAM, 0);
  144. return true;
  145. }
  146. #endif
  147. bool TCPInterface::Start(unsigned short port, unsigned short maxIncomingConnections, unsigned short maxConnections, int _threadPriority, unsigned short socketFamily, const char *bindAddress)
  148. {
  149. #ifdef __native_client__
  150. return false;
  151. #else
  152. (void) socketFamily;
  153. if (isStarted.GetValue()>0)
  154. return false;
  155. threadPriority=_threadPriority;
  156. if (threadPriority==-99999)
  157. {
  158. #if defined(_WIN32)
  159. threadPriority=0;
  160. #else
  161. threadPriority=1000;
  162. #endif
  163. }
  164. isStarted.Increment();
  165. if (maxConnections==0)
  166. maxConnections=maxIncomingConnections;
  167. if (maxConnections==0)
  168. maxConnections=1;
  169. remoteClientsLength=maxConnections;
  170. remoteClients=RakNet::OP_NEW_ARRAY<RemoteClient>(maxConnections,_FILE_AND_LINE_);
  171. listenSocket=0;
  172. if (maxIncomingConnections>0)
  173. {
  174. #if defined(WINDOWS_STORE_RT)
  175. CreateListenSocket_WinStore8(port, maxIncomingConnections, socketFamily, bindAddress);
  176. #else
  177. CreateListenSocket(port, maxIncomingConnections, socketFamily, bindAddress);
  178. #endif
  179. }
  180. // Start the update thread
  181. int errorCode;
  182. errorCode = RakNet::RakThread::Create(UpdateTCPInterfaceLoop, this, threadPriority);
  183. if (errorCode!=0)
  184. return false;
  185. while (threadRunning.GetValue()==0)
  186. RakSleep(0);
  187. unsigned int i;
  188. for (i=0; i < messageHandlerList.Size(); i++)
  189. messageHandlerList[i]->OnRakPeerStartup();
  190. return true;
  191. #endif // __native_client__
  192. }
  193. void TCPInterface::Stop(void)
  194. {
  195. unsigned int i;
  196. for (i=0; i < messageHandlerList.Size(); i++)
  197. messageHandlerList[i]->OnRakPeerShutdown();
  198. #ifndef __native_client__
  199. if (isStarted.GetValue()==0)
  200. return;
  201. #if OPEN_SSL_CLIENT_SUPPORT==1
  202. for (i=0; i < remoteClientsLength; i++)
  203. remoteClients[i].DisconnectSSL();
  204. #endif
  205. isStarted.Decrement();
  206. #if !defined(WINDOWS_STORE_RT)
  207. if (listenSocket!=0)
  208. #endif
  209. {
  210. #ifdef _WIN32
  211. shutdown__(listenSocket, SD_BOTH);
  212. #else
  213. shutdown__(listenSocket, SHUT_RDWR);
  214. #endif
  215. closesocket__(listenSocket);
  216. }
  217. // Abort waiting connect calls
  218. blockingSocketListMutex.Lock();
  219. for (i=0; i < blockingSocketList.Size(); i++)
  220. {
  221. closesocket__(blockingSocketList[i]);
  222. }
  223. blockingSocketListMutex.Unlock();
  224. // Wait for the thread to stop
  225. while ( threadRunning.GetValue()>0 )
  226. RakSleep(15);
  227. RakSleep(100);
  228. #if !defined(WINDOWS_STORE_RT)
  229. listenSocket=0;
  230. #endif
  231. // Stuff from here on to the end of the function is not threadsafe
  232. for (i=0; i < (unsigned int) remoteClientsLength; i++)
  233. {
  234. closesocket__(remoteClients[i].socket);
  235. #if OPEN_SSL_CLIENT_SUPPORT==1
  236. remoteClients[i].FreeSSL();
  237. #endif
  238. }
  239. remoteClientsLength=0;
  240. RakNet::OP_DELETE_ARRAY(remoteClients,_FILE_AND_LINE_);
  241. remoteClients=0;
  242. incomingMessages.Clear(_FILE_AND_LINE_);
  243. newIncomingConnections.Clear(_FILE_AND_LINE_);
  244. newRemoteClients.Clear(_FILE_AND_LINE_);
  245. lostConnections.Clear(_FILE_AND_LINE_);
  246. requestedCloseConnections.Clear(_FILE_AND_LINE_);
  247. failedConnectionAttempts.Clear(_FILE_AND_LINE_);
  248. completedConnectionAttempts.Clear(_FILE_AND_LINE_);
  249. failedConnectionAttempts.Clear(_FILE_AND_LINE_);
  250. for (i=0; i < headPush.Size(); i++)
  251. DeallocatePacket(headPush[i]);
  252. headPush.Clear(_FILE_AND_LINE_);
  253. for (i=0; i < tailPush.Size(); i++)
  254. DeallocatePacket(tailPush[i]);
  255. tailPush.Clear(_FILE_AND_LINE_);
  256. #if OPEN_SSL_CLIENT_SUPPORT==1
  257. SSL_CTX_free (ctx);
  258. startSSL.Clear(_FILE_AND_LINE_);
  259. activeSSLConnections.Clear(false, _FILE_AND_LINE_);
  260. #endif
  261. #endif // __native_client__
  262. }
  263. SystemAddress TCPInterface::Connect(const char* host, unsigned short remotePort, bool block, unsigned short socketFamily, const char *bindAddress)
  264. {
  265. if (threadRunning.GetValue()==0)
  266. return UNASSIGNED_SYSTEM_ADDRESS;
  267. int newRemoteClientIndex=-1;
  268. for (newRemoteClientIndex=0; newRemoteClientIndex < remoteClientsLength; newRemoteClientIndex++)
  269. {
  270. remoteClients[newRemoteClientIndex].isActiveMutex.Lock();
  271. if (remoteClients[newRemoteClientIndex].isActive==false)
  272. {
  273. remoteClients[newRemoteClientIndex].SetActive(true);
  274. remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();
  275. break;
  276. }
  277. remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();
  278. }
  279. if (newRemoteClientIndex==-1)
  280. return UNASSIGNED_SYSTEM_ADDRESS;
  281. if (block)
  282. {
  283. SystemAddress systemAddress;
  284. systemAddress.FromString(host);
  285. systemAddress.SetPortHostOrder(remotePort);
  286. systemAddress.systemIndex=(SystemIndex) newRemoteClientIndex;
  287. char buffout[128];
  288. systemAddress.ToString(false,buffout);
  289. __TCPSOCKET__ sockfd = SocketConnect(buffout, remotePort, socketFamily, bindAddress);
  290. // Windows RT TODO
  291. #if !defined(WINDOWS_STORE_RT)
  292. if (sockfd==0)
  293. #endif
  294. {
  295. remoteClients[newRemoteClientIndex].isActiveMutex.Lock();
  296. remoteClients[newRemoteClientIndex].SetActive(false);
  297. remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();
  298. failedConnectionAttemptMutex.Lock();
  299. failedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ );
  300. failedConnectionAttemptMutex.Unlock();
  301. return UNASSIGNED_SYSTEM_ADDRESS;
  302. }
  303. remoteClients[newRemoteClientIndex].socket=sockfd;
  304. remoteClients[newRemoteClientIndex].systemAddress=systemAddress;
  305. completedConnectionAttemptMutex.Lock();
  306. completedConnectionAttempts.Push(remoteClients[newRemoteClientIndex].systemAddress, _FILE_AND_LINE_ );
  307. completedConnectionAttemptMutex.Unlock();
  308. return remoteClients[newRemoteClientIndex].systemAddress;
  309. }
  310. else
  311. {
  312. ThisPtrPlusSysAddr *s = RakNet::OP_NEW<ThisPtrPlusSysAddr>( _FILE_AND_LINE_ );
  313. s->systemAddress.FromStringExplicitPort(host,remotePort);
  314. s->systemAddress.systemIndex=(SystemIndex) newRemoteClientIndex;
  315. if (bindAddress)
  316. strcpy(s->bindAddress, bindAddress);
  317. else
  318. s->bindAddress[0]=0;
  319. s->tcpInterface=this;
  320. s->socketFamily=socketFamily;
  321. // Start the connection thread
  322. int errorCode;
  323. errorCode = RakNet::RakThread::Create(ConnectionAttemptLoop, s, threadPriority);
  324. if (errorCode!=0)
  325. {
  326. RakNet::OP_DELETE(s, _FILE_AND_LINE_);
  327. failedConnectionAttempts.Push(s->systemAddress, _FILE_AND_LINE_ );
  328. }
  329. return UNASSIGNED_SYSTEM_ADDRESS;
  330. }
  331. }
  332. #if OPEN_SSL_CLIENT_SUPPORT==1
  333. void TCPInterface::StartSSLClient(SystemAddress systemAddress)
  334. {
  335. if (ctx==0)
  336. {
  337. sharedSslMutex.Lock();
  338. SSLeay_add_ssl_algorithms();
  339. meth = (SSL_METHOD*) SSLv23_client_method();
  340. SSL_load_error_strings();
  341. ctx = SSL_CTX_new (meth);
  342. RakAssert(ctx!=0);
  343. sharedSslMutex.Unlock();
  344. }
  345. SystemAddress *id = startSSL.Allocate( _FILE_AND_LINE_ );
  346. *id=systemAddress;
  347. startSSL.Push(id);
  348. unsigned index = activeSSLConnections.GetIndexOf(systemAddress);
  349. if (index==(unsigned)-1)
  350. activeSSLConnections.Insert(systemAddress,_FILE_AND_LINE_);
  351. }
  352. bool TCPInterface::IsSSLActive(SystemAddress systemAddress)
  353. {
  354. return activeSSLConnections.GetIndexOf(systemAddress)!=-1;
  355. }
  356. #endif
  357. void TCPInterface::Send( const char *data, unsigned length, const SystemAddress &systemAddress, bool broadcast )
  358. {
  359. SendList( &data, &length, 1, systemAddress,broadcast );
  360. }
  361. bool TCPInterface::SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast )
  362. {
  363. if (isStarted.GetValue()==0)
  364. return false;
  365. if (data==0)
  366. return false;
  367. if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS && broadcast==false)
  368. return false;
  369. unsigned int totalLength=0;
  370. int i;
  371. for (i=0; i < numParameters; i++)
  372. {
  373. if (lengths[i]>0)
  374. totalLength+=lengths[i];
  375. }
  376. if (totalLength==0)
  377. return false;
  378. if (broadcast)
  379. {
  380. // Send to all, possible exception system
  381. for (i=0; i < remoteClientsLength; i++)
  382. {
  383. if (remoteClients[i].systemAddress!=systemAddress)
  384. {
  385. remoteClients[i].SendOrBuffer(data, lengths, numParameters);
  386. }
  387. }
  388. }
  389. else
  390. {
  391. // Send to this player
  392. if (systemAddress.systemIndex<remoteClientsLength &&
  393. remoteClients[systemAddress.systemIndex].systemAddress==systemAddress)
  394. {
  395. remoteClients[systemAddress.systemIndex].SendOrBuffer(data, lengths, numParameters);
  396. }
  397. else
  398. {
  399. for (i=0; i < remoteClientsLength; i++)
  400. {
  401. if (remoteClients[i].systemAddress==systemAddress )
  402. {
  403. remoteClients[i].SendOrBuffer(data, lengths, numParameters);
  404. }
  405. }
  406. }
  407. }
  408. return true;
  409. }
  410. bool TCPInterface::ReceiveHasPackets( void )
  411. {
  412. return headPush.IsEmpty()==false || incomingMessages.IsEmpty()==false || tailPush.IsEmpty()==false;
  413. }
  414. Packet* TCPInterface::Receive( void )
  415. {
  416. unsigned int i;
  417. for (i=0; i < messageHandlerList.Size(); i++)
  418. messageHandlerList[i]->Update();
  419. Packet* outgoingPacket = ReceiveInt();
  420. if (outgoingPacket)
  421. {
  422. PluginReceiveResult pluginResult;
  423. for (i=0; i < messageHandlerList.Size(); i++)
  424. {
  425. pluginResult=messageHandlerList[i]->OnReceive(outgoingPacket);
  426. if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE)
  427. {
  428. DeallocatePacket( outgoingPacket );
  429. outgoingPacket=0; // Will do the loop again and get another packet
  430. break; // break out of the enclosing for
  431. }
  432. else if (pluginResult==RR_STOP_PROCESSING)
  433. {
  434. outgoingPacket=0;
  435. break;
  436. }
  437. }
  438. }
  439. return outgoingPacket;
  440. }
  441. Packet* TCPInterface::ReceiveInt( void )
  442. {
  443. if (isStarted.GetValue()==0)
  444. return 0;
  445. if (headPush.IsEmpty()==false)
  446. return headPush.Pop();
  447. Packet *p = incomingMessages.PopInaccurate();
  448. if (p)
  449. return p;
  450. if (tailPush.IsEmpty()==false)
  451. return tailPush.Pop();
  452. return 0;
  453. }
  454. void TCPInterface::AttachPlugin( PluginInterface2 *plugin )
  455. {
  456. if (messageHandlerList.GetIndexOf(plugin)==MAX_UNSIGNED_LONG)
  457. {
  458. messageHandlerList.Insert(plugin, _FILE_AND_LINE_);
  459. plugin->SetTCPInterface(this);
  460. plugin->OnAttach();
  461. }
  462. }
  463. void TCPInterface::DetachPlugin( PluginInterface2 *plugin )
  464. {
  465. if (plugin==0)
  466. return;
  467. unsigned int index;
  468. index = messageHandlerList.GetIndexOf(plugin);
  469. if (index!=MAX_UNSIGNED_LONG)
  470. {
  471. messageHandlerList[index]->OnDetach();
  472. // Unordered list so delete from end for speed
  473. messageHandlerList[index]=messageHandlerList[messageHandlerList.Size()-1];
  474. messageHandlerList.RemoveFromEnd();
  475. plugin->SetTCPInterface(0);
  476. }
  477. }
  478. void TCPInterface::CloseConnection( SystemAddress systemAddress )
  479. {
  480. if (isStarted.GetValue()==0)
  481. return;
  482. if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS)
  483. return;
  484. unsigned int i;
  485. for (i=0; i < messageHandlerList.Size(); i++)
  486. messageHandlerList[i]->OnClosedConnection(systemAddress, UNASSIGNED_RAKNET_GUID, LCR_CLOSED_BY_USER);
  487. if (systemAddress.systemIndex<remoteClientsLength && remoteClients[systemAddress.systemIndex].systemAddress==systemAddress)
  488. {
  489. remoteClients[systemAddress.systemIndex].isActiveMutex.Lock();
  490. remoteClients[systemAddress.systemIndex].SetActive(false);
  491. remoteClients[systemAddress.systemIndex].isActiveMutex.Unlock();
  492. }
  493. else
  494. {
  495. for (int i=0; i < remoteClientsLength; i++)
  496. {
  497. remoteClients[i].isActiveMutex.Lock();
  498. if (remoteClients[i].isActive && remoteClients[i].systemAddress==systemAddress)
  499. {
  500. remoteClients[systemAddress.systemIndex].SetActive(false);
  501. remoteClients[i].isActiveMutex.Unlock();
  502. break;
  503. }
  504. remoteClients[i].isActiveMutex.Unlock();
  505. }
  506. }
  507. #if OPEN_SSL_CLIENT_SUPPORT==1
  508. unsigned index = activeSSLConnections.GetIndexOf(systemAddress);
  509. if (index!=(unsigned)-1)
  510. activeSSLConnections.RemoveAtIndex(index);
  511. #endif
  512. }
  513. void TCPInterface::DeallocatePacket( Packet *packet )
  514. {
  515. if (packet==0)
  516. return;
  517. if (packet->deleteData)
  518. {
  519. rakFree_Ex(packet->data, _FILE_AND_LINE_ );
  520. incomingMessages.Deallocate(packet, _FILE_AND_LINE_);
  521. }
  522. else
  523. {
  524. // Came from userspace AllocatePacket
  525. rakFree_Ex(packet->data, _FILE_AND_LINE_ );
  526. RakNet::OP_DELETE(packet, _FILE_AND_LINE_);
  527. }
  528. }
  529. Packet* TCPInterface::AllocatePacket(unsigned dataSize)
  530. {
  531. Packet*p = RakNet::OP_NEW<Packet>(_FILE_AND_LINE_);
  532. p->data=(unsigned char*) rakMalloc_Ex(dataSize,_FILE_AND_LINE_);
  533. p->length=dataSize;
  534. p->bitSize=BYTES_TO_BITS(dataSize);
  535. p->deleteData=false;
  536. p->guid=UNASSIGNED_RAKNET_GUID;
  537. p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS;
  538. p->systemAddress.systemIndex=(SystemIndex)-1;
  539. return p;
  540. }
  541. void TCPInterface::PushBackPacket( Packet *packet, bool pushAtHead )
  542. {
  543. if (pushAtHead)
  544. headPush.Push(packet, _FILE_AND_LINE_ );
  545. else
  546. tailPush.Push(packet, _FILE_AND_LINE_ );
  547. }
  548. bool TCPInterface::WasStarted(void) const
  549. {
  550. return threadRunning.GetValue()>0;
  551. }
  552. SystemAddress TCPInterface::HasCompletedConnectionAttempt(void)
  553. {
  554. SystemAddress sysAddr=UNASSIGNED_SYSTEM_ADDRESS;
  555. completedConnectionAttemptMutex.Lock();
  556. if (completedConnectionAttempts.IsEmpty()==false)
  557. sysAddr=completedConnectionAttempts.Pop();
  558. completedConnectionAttemptMutex.Unlock();
  559. if (sysAddr!=UNASSIGNED_SYSTEM_ADDRESS)
  560. {
  561. unsigned int i;
  562. for (i=0; i < messageHandlerList.Size(); i++)
  563. messageHandlerList[i]->OnNewConnection(sysAddr, UNASSIGNED_RAKNET_GUID, true);
  564. }
  565. return sysAddr;
  566. }
  567. SystemAddress TCPInterface::HasFailedConnectionAttempt(void)
  568. {
  569. SystemAddress sysAddr=UNASSIGNED_SYSTEM_ADDRESS;
  570. failedConnectionAttemptMutex.Lock();
  571. if (failedConnectionAttempts.IsEmpty()==false)
  572. sysAddr=failedConnectionAttempts.Pop();
  573. failedConnectionAttemptMutex.Unlock();
  574. if (sysAddr!=UNASSIGNED_SYSTEM_ADDRESS)
  575. {
  576. unsigned int i;
  577. for (i=0; i < messageHandlerList.Size(); i++)
  578. {
  579. Packet p;
  580. p.systemAddress=sysAddr;
  581. p.data=0;
  582. p.length=0;
  583. p.bitSize=0;
  584. messageHandlerList[i]->OnFailedConnectionAttempt(&p, FCAR_CONNECTION_ATTEMPT_FAILED);
  585. }
  586. }
  587. return sysAddr;
  588. }
  589. SystemAddress TCPInterface::HasNewIncomingConnection(void)
  590. {
  591. SystemAddress *out, out2;
  592. out = newIncomingConnections.PopInaccurate();
  593. if (out)
  594. {
  595. out2=*out;
  596. newIncomingConnections.Deallocate(out, _FILE_AND_LINE_);
  597. unsigned int i;
  598. for (i=0; i < messageHandlerList.Size(); i++)
  599. messageHandlerList[i]->OnNewConnection(out2, UNASSIGNED_RAKNET_GUID, true);
  600. return *out;
  601. }
  602. else
  603. {
  604. return UNASSIGNED_SYSTEM_ADDRESS;
  605. }
  606. }
  607. SystemAddress TCPInterface::HasLostConnection(void)
  608. {
  609. SystemAddress *out, out2;
  610. out = lostConnections.PopInaccurate();
  611. if (out)
  612. {
  613. out2=*out;
  614. lostConnections.Deallocate(out, _FILE_AND_LINE_);
  615. unsigned int i;
  616. for (i=0; i < messageHandlerList.Size(); i++)
  617. messageHandlerList[i]->OnClosedConnection(out2, UNASSIGNED_RAKNET_GUID, LCR_DISCONNECTION_NOTIFICATION);
  618. return *out;
  619. }
  620. else
  621. {
  622. return UNASSIGNED_SYSTEM_ADDRESS;
  623. }
  624. }
  625. void TCPInterface::GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const
  626. {
  627. unsigned short systemCount=0;
  628. unsigned short maxToWrite=*numberOfSystems;
  629. for (int i=0; i < remoteClientsLength; i++)
  630. {
  631. if (remoteClients[i].isActive)
  632. {
  633. if (systemCount < maxToWrite)
  634. remoteSystems[systemCount]=remoteClients[i].systemAddress;
  635. systemCount++;
  636. }
  637. }
  638. *numberOfSystems=systemCount;
  639. }
  640. unsigned short TCPInterface::GetConnectionCount(void) const
  641. {
  642. unsigned short systemCount=0;
  643. for (int i=0; i < remoteClientsLength; i++)
  644. {
  645. if (remoteClients[i].isActive)
  646. systemCount++;
  647. }
  648. return systemCount;
  649. }
  650. unsigned int TCPInterface::GetOutgoingDataBufferSize(SystemAddress systemAddress) const
  651. {
  652. unsigned bytesWritten=0;
  653. if (systemAddress.systemIndex<remoteClientsLength &&
  654. remoteClients[systemAddress.systemIndex].isActive &&
  655. remoteClients[systemAddress.systemIndex].systemAddress==systemAddress)
  656. {
  657. remoteClients[systemAddress.systemIndex].outgoingDataMutex.Lock();
  658. bytesWritten=remoteClients[systemAddress.systemIndex].outgoingData.GetBytesWritten();
  659. remoteClients[systemAddress.systemIndex].outgoingDataMutex.Unlock();
  660. return bytesWritten;
  661. }
  662. for (int i=0; i < remoteClientsLength; i++)
  663. {
  664. if (remoteClients[i].isActive && remoteClients[i].systemAddress==systemAddress)
  665. {
  666. remoteClients[i].outgoingDataMutex.Lock();
  667. bytesWritten+=remoteClients[i].outgoingData.GetBytesWritten();
  668. remoteClients[i].outgoingDataMutex.Unlock();
  669. }
  670. }
  671. return bytesWritten;
  672. }
  673. __TCPSOCKET__ TCPInterface::SocketConnect(const char* host, unsigned short remotePort, unsigned short socketFamily, const char *bindAddress)
  674. {
  675. #ifdef __native_client__
  676. return 0;
  677. #else
  678. int connectResult;
  679. (void) connectResult;
  680. (void) socketFamily;
  681. #if RAKNET_SUPPORT_IPV6!=1
  682. sockaddr_in serverAddress;
  683. struct hostent * server;
  684. server = gethostbyname(host);
  685. if (server == NULL)
  686. return 0;
  687. #if defined(WINDOWS_STORE_RT)
  688. __TCPSOCKET__ sockfd = WinRTCreateStreamSocket(AF_INET, SOCK_STREAM, 0);
  689. #else
  690. __TCPSOCKET__ sockfd = socket__(AF_INET, SOCK_STREAM, 0);
  691. if (sockfd < 0)
  692. return 0;
  693. #endif
  694. memset(&serverAddress, 0, sizeof(serverAddress));
  695. serverAddress.sin_family = AF_INET;
  696. serverAddress.sin_port = htons( remotePort );
  697. if ( bindAddress && bindAddress[0] )
  698. {
  699. serverAddress.sin_addr.s_addr = inet_addr__( bindAddress );
  700. }
  701. else
  702. serverAddress.sin_addr.s_addr = INADDR_ANY;
  703. int sock_opt=1024*256;
  704. setsockopt__(sockfd, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) );
  705. memcpy((char *)&serverAddress.sin_addr.s_addr, (char *)server->h_addr, server->h_length);
  706. blockingSocketListMutex.Lock();
  707. blockingSocketList.Insert(sockfd, _FILE_AND_LINE_);
  708. blockingSocketListMutex.Unlock();
  709. // This is blocking
  710. connectResult = connect__( sockfd, ( struct sockaddr * ) &serverAddress, sizeof( struct sockaddr ) );
  711. #else
  712. struct addrinfo hints, *res;
  713. int sockfd;
  714. memset(&hints, 0, sizeof hints);
  715. hints.ai_family = socketFamily;
  716. hints.ai_socktype = SOCK_STREAM;
  717. char portStr[32];
  718. Itoa(remotePort,portStr,10);
  719. getaddrinfo(host, portStr, &hints, &res);
  720. sockfd = socket__(res->ai_family, res->ai_socktype, res->ai_protocol);
  721. blockingSocketListMutex.Lock();
  722. blockingSocketList.Insert(sockfd, _FILE_AND_LINE_);
  723. blockingSocketListMutex.Unlock();
  724. connectResult=connect__(sockfd, res->ai_addr, res->ai_addrlen);
  725. freeaddrinfo(res); // free the linked-list
  726. #endif // #if RAKNET_SUPPORT_IPV6!=1
  727. if (connectResult==-1)
  728. {
  729. unsigned sockfdIndex;
  730. blockingSocketListMutex.Lock();
  731. sockfdIndex=blockingSocketList.GetIndexOf(sockfd);
  732. if (sockfdIndex!=(unsigned)-1)
  733. blockingSocketList.RemoveAtIndexFast(sockfdIndex);
  734. blockingSocketListMutex.Unlock();
  735. closesocket__(sockfd);
  736. return 0;
  737. }
  738. return sockfd;
  739. #endif // __native_client__
  740. }
  741. RAK_THREAD_DECLARATION(RakNet::ConnectionAttemptLoop)
  742. {
  743. TCPInterface::ThisPtrPlusSysAddr *s = (TCPInterface::ThisPtrPlusSysAddr *) arguments;
  744. SystemAddress systemAddress = s->systemAddress;
  745. TCPInterface *tcpInterface = s->tcpInterface;
  746. int newRemoteClientIndex=systemAddress.systemIndex;
  747. unsigned short socketFamily = s->socketFamily;
  748. RakNet::OP_DELETE(s, _FILE_AND_LINE_);
  749. char str1[64];
  750. systemAddress.ToString(false, str1);
  751. __TCPSOCKET__ sockfd = tcpInterface->SocketConnect(str1, systemAddress.GetPort(), socketFamily, s->bindAddress);
  752. if (sockfd==0)
  753. {
  754. tcpInterface->remoteClients[newRemoteClientIndex].isActiveMutex.Lock();
  755. tcpInterface->remoteClients[newRemoteClientIndex].SetActive(false);
  756. tcpInterface->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();
  757. tcpInterface->failedConnectionAttemptMutex.Lock();
  758. tcpInterface->failedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ );
  759. tcpInterface->failedConnectionAttemptMutex.Unlock();
  760. return 0;
  761. }
  762. tcpInterface->remoteClients[newRemoteClientIndex].socket=sockfd;
  763. tcpInterface->remoteClients[newRemoteClientIndex].systemAddress=systemAddress;
  764. // Notify user that the connection attempt has completed.
  765. if (tcpInterface->threadRunning.GetValue()>0)
  766. {
  767. tcpInterface->completedConnectionAttemptMutex.Lock();
  768. tcpInterface->completedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ );
  769. tcpInterface->completedConnectionAttemptMutex.Unlock();
  770. }
  771. return 0;
  772. }
  773. RAK_THREAD_DECLARATION(RakNet::UpdateTCPInterfaceLoop)
  774. {
  775. TCPInterface * sts = ( TCPInterface * ) arguments;
  776. // const int BUFF_SIZE=8096;
  777. const unsigned int BUFF_SIZE=1048576;
  778. //char data[ BUFF_SIZE ];
  779. char * data = (char*) rakMalloc_Ex(BUFF_SIZE,_FILE_AND_LINE_);
  780. Packet *incomingMessage;
  781. fd_set readFD, exceptionFD, writeFD;
  782. sts->threadRunning.Increment();
  783. #if RAKNET_SUPPORT_IPV6!=1
  784. sockaddr_in sockAddr;
  785. int sockAddrSize = sizeof(sockAddr);
  786. #else
  787. struct sockaddr_storage sockAddr;
  788. socklen_t sockAddrSize = sizeof(sockAddr);
  789. #endif
  790. int len;
  791. __TCPSOCKET__ newSock;
  792. int selectResult;
  793. timeval tv;
  794. tv.tv_sec=0;
  795. tv.tv_usec=30000;
  796. while (sts->isStarted.GetValue()>0)
  797. {
  798. #if OPEN_SSL_CLIENT_SUPPORT==1
  799. SystemAddress *sslSystemAddress;
  800. sslSystemAddress = sts->startSSL.PopInaccurate();
  801. if (sslSystemAddress)
  802. {
  803. if (sslSystemAddress->systemIndex>=0 &&
  804. sslSystemAddress->systemIndex<sts->remoteClientsLength &&
  805. sts->remoteClients[sslSystemAddress->systemIndex].systemAddress==*sslSystemAddress)
  806. {
  807. sts->remoteClients[sslSystemAddress->systemIndex].InitSSL(sts->ctx,sts->meth);
  808. }
  809. else
  810. {
  811. for (int i=0; i < sts->remoteClientsLength; i++)
  812. {
  813. sts->remoteClients[i].isActiveMutex.Lock();
  814. if (sts->remoteClients[i].isActive && sts->remoteClients[i].systemAddress==*sslSystemAddress)
  815. {
  816. if (sts->remoteClients[i].ssl==0)
  817. sts->remoteClients[i].InitSSL(sts->ctx,sts->meth);
  818. }
  819. sts->remoteClients[i].isActiveMutex.Unlock();
  820. }
  821. }
  822. sts->startSSL.Deallocate(sslSystemAddress,_FILE_AND_LINE_);
  823. }
  824. #endif
  825. __TCPSOCKET__ largestDescriptor=0; // see select__()'s first parameter's documentation under linux
  826. // Linux' select__() implementation changes the timeout
  827. tv.tv_sec=0;
  828. tv.tv_usec=30000;
  829. #ifdef _MSC_VER
  830. #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant
  831. #endif
  832. while (1)
  833. {
  834. // Reset readFD, writeFD, and exceptionFD since select seems to clear it
  835. FD_ZERO(&readFD);
  836. FD_ZERO(&exceptionFD);
  837. FD_ZERO(&writeFD);
  838. largestDescriptor=0;
  839. if (sts->listenSocket!=0)
  840. {
  841. FD_SET(sts->listenSocket, &readFD);
  842. FD_SET(sts->listenSocket, &exceptionFD);
  843. largestDescriptor = sts->listenSocket; // @see largestDescriptor def
  844. }
  845. unsigned i;
  846. for (i=0; i < (unsigned int) sts->remoteClientsLength; i++)
  847. {
  848. sts->remoteClients[i].isActiveMutex.Lock();
  849. if (sts->remoteClients[i].isActive)
  850. {
  851. // calling FD_ISSET with -1 as socket (that’s what 0 is set to) produces a bus error under Linux 64-Bit
  852. __TCPSOCKET__ socketCopy = sts->remoteClients[i].socket;
  853. if (socketCopy != 0)
  854. {
  855. FD_SET(socketCopy, &readFD);
  856. FD_SET(socketCopy, &exceptionFD);
  857. if (sts->remoteClients[i].outgoingData.GetBytesWritten()>0)
  858. FD_SET(socketCopy, &writeFD);
  859. if(socketCopy > largestDescriptor) // @see largestDescriptorDef
  860. largestDescriptor = socketCopy;
  861. }
  862. }
  863. sts->remoteClients[i].isActiveMutex.Unlock();
  864. }
  865. #ifdef _MSC_VER
  866. #pragma warning( disable : 4244 ) // warning C4127: conditional expression is constant
  867. #endif
  868. selectResult=(int) select__(largestDescriptor+1, &readFD, &writeFD, &exceptionFD, &tv);
  869. if (selectResult<=0)
  870. break;
  871. if (sts->listenSocket!=0 && FD_ISSET(sts->listenSocket, &readFD))
  872. {
  873. newSock = accept__(sts->listenSocket, (sockaddr*)&sockAddr, (socklen_t*)&sockAddrSize);
  874. if (newSock != 0)
  875. {
  876. int newRemoteClientIndex=-1;
  877. for (newRemoteClientIndex=0; newRemoteClientIndex < sts->remoteClientsLength; newRemoteClientIndex++)
  878. {
  879. sts->remoteClients[newRemoteClientIndex].isActiveMutex.Lock();
  880. if (sts->remoteClients[newRemoteClientIndex].isActive==false)
  881. {
  882. sts->remoteClients[newRemoteClientIndex].socket=newSock;
  883. #if RAKNET_SUPPORT_IPV6!=1
  884. sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_addr.s_addr=sockAddr.sin_addr.s_addr;
  885. sts->remoteClients[newRemoteClientIndex].systemAddress.SetPortNetworkOrder( sockAddr.sin_port);
  886. sts->remoteClients[newRemoteClientIndex].systemAddress.systemIndex=newRemoteClientIndex;
  887. #else
  888. if (sockAddr.ss_family==AF_INET)
  889. {
  890. memcpy(&sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4,(sockaddr_in *)&sockAddr,sizeof(sockaddr_in));
  891. // sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_port=ntohs( sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_port );
  892. }
  893. else
  894. {
  895. memcpy(&sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6,(sockaddr_in6 *)&sockAddr,sizeof(sockaddr_in6));
  896. // sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6.sin6_port=ntohs( sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6.sin6_port );
  897. }
  898. #endif // #if RAKNET_SUPPORT_IPV6!=1
  899. sts->remoteClients[newRemoteClientIndex].SetActive(true);
  900. sts->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();
  901. SystemAddress *newConnectionSystemAddress=sts->newIncomingConnections.Allocate( _FILE_AND_LINE_ );
  902. *newConnectionSystemAddress=sts->remoteClients[newRemoteClientIndex].systemAddress;
  903. sts->newIncomingConnections.Push(newConnectionSystemAddress);
  904. break;
  905. }
  906. sts->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock();
  907. }
  908. if (newRemoteClientIndex==-1)
  909. {
  910. closesocket__(sts->listenSocket);
  911. }
  912. }
  913. else
  914. {
  915. #ifdef _DO_PRINTF
  916. RAKNET_DEBUG_PRINTF("Error: connection failed\n");
  917. #endif
  918. }
  919. }
  920. else if (sts->listenSocket!=0 && FD_ISSET(sts->listenSocket, &exceptionFD))
  921. {
  922. #ifdef _DO_PRINTF
  923. int err;
  924. int errlen = sizeof(err);
  925. getsockopt__(sts->listenSocket, SOL_SOCKET, SO_ERROR,(char*)&err, &errlen);
  926. RAKNET_DEBUG_PRINTF("Socket error %s on listening socket\n", err);
  927. #endif
  928. }
  929. {
  930. i=0;
  931. while (i < (unsigned int) sts->remoteClientsLength)
  932. {
  933. if (sts->remoteClients[i].isActive==false)
  934. {
  935. i++;
  936. continue;
  937. }
  938. // calling FD_ISSET with -1 as socket (that’s what 0 is set to) produces a bus error under Linux 64-Bit
  939. __TCPSOCKET__ socketCopy = sts->remoteClients[i].socket;
  940. if (socketCopy == 0)
  941. {
  942. i++;
  943. continue;
  944. }
  945. if (FD_ISSET(socketCopy, &exceptionFD))
  946. {
  947. // #ifdef _DO_PRINTF
  948. // if (sts->listenSocket!=-1)
  949. // {
  950. // int err;
  951. // int errlen = sizeof(err);
  952. // getsockopt__(sts->listenSocket, SOL_SOCKET, SO_ERROR,(char*)&err, &errlen);
  953. // in_addr in;
  954. // in.s_addr = sts->remoteClients[i].systemAddress.binaryAddress;
  955. // RAKNET_DEBUG_PRINTF("Socket error %i on %s:%i\n", err,inet_ntoa( in ), sts->remoteClients[i].systemAddress.GetPort() );
  956. // }
  957. //
  958. // #endif
  959. // Connection lost abruptly
  960. SystemAddress *lostConnectionSystemAddress=sts->lostConnections.Allocate( _FILE_AND_LINE_ );
  961. *lostConnectionSystemAddress=sts->remoteClients[i].systemAddress;
  962. sts->lostConnections.Push(lostConnectionSystemAddress);
  963. sts->remoteClients[i].isActiveMutex.Lock();
  964. sts->remoteClients[i].SetActive(false);
  965. sts->remoteClients[i].isActiveMutex.Unlock();
  966. }
  967. else
  968. {
  969. if (FD_ISSET(socketCopy, &readFD))
  970. {
  971. // if recv returns 0 this was a graceful close
  972. len = sts->remoteClients[i].Recv(data,BUFF_SIZE);
  973. // removeme
  974. // data[len]=0;
  975. // printf(data);
  976. if (len>0)
  977. {
  978. incomingMessage=sts->incomingMessages.Allocate( _FILE_AND_LINE_ );
  979. incomingMessage->data = (unsigned char*) rakMalloc_Ex( len+1, _FILE_AND_LINE_ );
  980. memcpy(incomingMessage->data, data, len);
  981. incomingMessage->data[len]=0; // Null terminate this so we can print it out as regular strings. This is different from RakNet which does not do this.
  982. // printf("RECV: %s\n",incomingMessage->data);
  983. /*
  984. if (1)
  985. {
  986. static FILE *fp=0;
  987. if (fp==0)
  988. {
  989. fp = fopen("tcpRcv.txt", "wb");
  990. }
  991. fwrite(data,1,len,fp);
  992. }
  993. */
  994. incomingMessage->length=len;
  995. incomingMessage->deleteData=true; // actually means came from SPSC, rather than AllocatePacket
  996. incomingMessage->systemAddress=sts->remoteClients[i].systemAddress;
  997. sts->incomingMessages.Push(incomingMessage);
  998. }
  999. else
  1000. {
  1001. // Connection lost gracefully
  1002. SystemAddress *lostConnectionSystemAddress=sts->lostConnections.Allocate( _FILE_AND_LINE_ );
  1003. *lostConnectionSystemAddress=sts->remoteClients[i].systemAddress;
  1004. sts->lostConnections.Push(lostConnectionSystemAddress);
  1005. sts->remoteClients[i].isActiveMutex.Lock();
  1006. sts->remoteClients[i].SetActive(false);
  1007. sts->remoteClients[i].isActiveMutex.Unlock();
  1008. continue;
  1009. }
  1010. }
  1011. if (FD_ISSET(socketCopy, &writeFD))
  1012. {
  1013. RemoteClient *rc = &sts->remoteClients[i];
  1014. unsigned int bytesInBuffer;
  1015. int bytesAvailable;
  1016. int bytesSent;
  1017. rc->outgoingDataMutex.Lock();
  1018. bytesInBuffer=rc->outgoingData.GetBytesWritten();
  1019. if (bytesInBuffer>0)
  1020. {
  1021. unsigned int contiguousLength;
  1022. char* contiguousBytesPointer = rc->outgoingData.PeekContiguousBytes(&contiguousLength);
  1023. if (contiguousLength < (unsigned int) BUFF_SIZE && contiguousLength<bytesInBuffer)
  1024. {
  1025. if (bytesInBuffer > BUFF_SIZE)
  1026. bytesAvailable=BUFF_SIZE;
  1027. else
  1028. bytesAvailable=bytesInBuffer;
  1029. rc->outgoingData.ReadBytes(data,bytesAvailable,true);
  1030. bytesSent=rc->Send(data,bytesAvailable);
  1031. }
  1032. else
  1033. {
  1034. bytesSent=rc->Send(contiguousBytesPointer,contiguousLength);
  1035. }
  1036. if (bytesSent>0)
  1037. rc->outgoingData.IncrementReadOffset(bytesSent);
  1038. bytesInBuffer=rc->outgoingData.GetBytesWritten();
  1039. }
  1040. rc->outgoingDataMutex.Unlock();
  1041. }
  1042. i++; // Nothing deleted so increment the index
  1043. }
  1044. }
  1045. }
  1046. }
  1047. // Sleep 0 on Linux monopolizes the CPU
  1048. RakSleep(30);
  1049. }
  1050. sts->threadRunning.Decrement();
  1051. rakFree_Ex(data,_FILE_AND_LINE_);
  1052. return 0;
  1053. }
  1054. void RemoteClient::SetActive(bool a)
  1055. {
  1056. if (isActive != a)
  1057. {
  1058. isActive=a;
  1059. Reset();
  1060. if (isActive==false && socket!=0)
  1061. {
  1062. closesocket__(socket);
  1063. socket=0;
  1064. }
  1065. }
  1066. }
  1067. void RemoteClient::SendOrBuffer(const char **data, const unsigned int *lengths, const int numParameters)
  1068. {
  1069. // True can save memory and buffer copies, but gives worse performance overall
  1070. // Do not use true for the XBOX, as it just locks up
  1071. const bool ALLOW_SEND_FROM_USER_THREAD=false;
  1072. int parameterIndex;
  1073. if (isActive==false)
  1074. return;
  1075. parameterIndex=0;
  1076. for (; parameterIndex < numParameters; parameterIndex++)
  1077. {
  1078. outgoingDataMutex.Lock();
  1079. if (ALLOW_SEND_FROM_USER_THREAD && outgoingData.GetBytesWritten()==0)
  1080. {
  1081. outgoingDataMutex.Unlock();
  1082. int bytesSent = Send(data[parameterIndex],lengths[parameterIndex]);
  1083. if (bytesSent<(int) lengths[parameterIndex])
  1084. {
  1085. // Push remainder
  1086. outgoingDataMutex.Lock();
  1087. outgoingData.WriteBytes(data[parameterIndex]+bytesSent,lengths[parameterIndex]-bytesSent,_FILE_AND_LINE_);
  1088. outgoingDataMutex.Unlock();
  1089. }
  1090. }
  1091. else
  1092. {
  1093. outgoingData.WriteBytes(data[parameterIndex],lengths[parameterIndex],_FILE_AND_LINE_);
  1094. outgoingDataMutex.Unlock();
  1095. }
  1096. }
  1097. }
  1098. #if OPEN_SSL_CLIENT_SUPPORT==1
  1099. bool RemoteClient::InitSSL(SSL_CTX* ctx, SSL_METHOD *meth)
  1100. {
  1101. (void) meth;
  1102. ssl = SSL_new (ctx);
  1103. RakAssert(ssl);
  1104. int res;
  1105. res = SSL_set_fd (ssl, socket);
  1106. if (res!=1)
  1107. {
  1108. printf("SSL_set_fd error: %s\n", ERR_reason_error_string(ERR_get_error()));
  1109. SSL_free(ssl);
  1110. ssl=0;
  1111. return false;
  1112. }
  1113. RakAssert(res==1);
  1114. res = SSL_connect (ssl);
  1115. if (res<0)
  1116. {
  1117. unsigned long err = ERR_get_error();
  1118. printf("SSL_connect error: %s\n", ERR_reason_error_string(err));
  1119. SSL_free(ssl);
  1120. ssl=0;
  1121. return false;
  1122. }
  1123. else if (res==0)
  1124. {
  1125. // The TLS/SSL handshake was not successful but was shut down controlled and by the specifications of the TLS/SSL protocol. Call SSL_get_error() with the return value ret to find out the reason.
  1126. int err = SSL_get_error(ssl, res);
  1127. switch (err)
  1128. {
  1129. case SSL_ERROR_NONE:
  1130. printf("SSL_ERROR_NONE\n");
  1131. break;
  1132. case SSL_ERROR_ZERO_RETURN:
  1133. printf("SSL_ERROR_ZERO_RETURN\n");
  1134. break;
  1135. case SSL_ERROR_WANT_READ:
  1136. printf("SSL_ERROR_WANT_READ\n");
  1137. break;
  1138. case SSL_ERROR_WANT_WRITE:
  1139. printf("SSL_ERROR_WANT_WRITE\n");
  1140. break;
  1141. case SSL_ERROR_WANT_CONNECT:
  1142. printf("SSL_ERROR_WANT_CONNECT\n");
  1143. break;
  1144. case SSL_ERROR_WANT_ACCEPT:
  1145. printf("SSL_ERROR_WANT_ACCEPT\n");
  1146. break;
  1147. case SSL_ERROR_WANT_X509_LOOKUP:
  1148. printf("SSL_ERROR_WANT_X509_LOOKUP\n");
  1149. break;
  1150. case SSL_ERROR_SYSCALL:
  1151. {
  1152. // http://www.openssl.org/docs/ssl/SSL_get_error.html
  1153. char buff[1024];
  1154. unsigned long ege = ERR_get_error();
  1155. if (ege==0 && res==0)
  1156. printf("SSL_ERROR_SYSCALL EOF in violation of the protocol\n");
  1157. else if (ege==0 && res==-1)
  1158. printf("SSL_ERROR_SYSCALL %s\n", strerror(errno));
  1159. else
  1160. printf("SSL_ERROR_SYSCALL %s\n", ERR_error_string(ege, buff));
  1161. }
  1162. break;
  1163. case SSL_ERROR_SSL:
  1164. printf("SSL_ERROR_SSL\n");
  1165. break;
  1166. }
  1167. }
  1168. if (res!=1)
  1169. {
  1170. SSL_free(ssl);
  1171. ssl=0;
  1172. return false;
  1173. }
  1174. return true;
  1175. }
  1176. void RemoteClient::DisconnectSSL(void)
  1177. {
  1178. if (ssl)
  1179. SSL_shutdown (ssl); /* send SSL/TLS close_notify */
  1180. }
  1181. void RemoteClient::FreeSSL(void)
  1182. {
  1183. if (ssl)
  1184. SSL_free (ssl);
  1185. }
  1186. int RemoteClient::Send(const char *data, unsigned int length)
  1187. {
  1188. if (ssl)
  1189. return SSL_write (ssl, data, length);
  1190. else
  1191. return send__(socket, data, length, 0);
  1192. }
  1193. int RemoteClient::Recv(char *data, const int dataSize)
  1194. {
  1195. if (ssl)
  1196. return SSL_read (ssl, data, dataSize);
  1197. else
  1198. return recv__(socket, data, dataSize, 0);
  1199. }
  1200. #else
  1201. int RemoteClient::Send(const char *data, unsigned int length)
  1202. {
  1203. #ifdef __native_client__
  1204. return -1;
  1205. #else
  1206. return send__(socket, data, length, 0);
  1207. #endif
  1208. }
  1209. int RemoteClient::Recv(char *data, const int dataSize)
  1210. {
  1211. #ifdef __native_client__
  1212. return -1;
  1213. #else
  1214. return recv__(socket, data, dataSize, 0);
  1215. #endif
  1216. }
  1217. #endif
  1218. #ifdef _MSC_VER
  1219. #pragma warning( pop )
  1220. #endif
  1221. #endif // _RAKNET_SUPPORT_*
粤ICP备19079148号