HTTPConnection2.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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_HTTPConnection2==1 && _RAKNET_SUPPORT_TCPInterface==1
  12. #include "HTTPConnection2.h"
  13. #include "TCPInterface.h"
  14. using namespace RakNet;
  15. STATIC_FACTORY_DEFINITIONS(HTTPConnection2,HTTPConnection2);
  16. HTTPConnection2::HTTPConnection2()
  17. {
  18. }
  19. HTTPConnection2::~HTTPConnection2()
  20. {
  21. }
  22. bool HTTPConnection2::TransmitRequest(const char* stringToTransmit, const char* host, unsigned short port, bool useSSL, int ipVersion, SystemAddress useAddress, void *userData)
  23. {
  24. Request *request = RakNet::OP_NEW<Request>(_FILE_AND_LINE_);
  25. request->host=host;
  26. request->chunked = false;
  27. if (useAddress!=UNASSIGNED_SYSTEM_ADDRESS)
  28. {
  29. request->hostEstimatedAddress=useAddress;
  30. if (IsConnected(useAddress)==false)
  31. {
  32. RakNet::OP_DELETE(request, _FILE_AND_LINE_);
  33. return false;
  34. }
  35. }
  36. else
  37. {
  38. if (request->hostEstimatedAddress.FromString(host, '|', ipVersion)==false)
  39. {
  40. RakNet::OP_DELETE(request, _FILE_AND_LINE_);
  41. return false;
  42. }
  43. }
  44. request->hostEstimatedAddress.SetPortHostOrder(port);
  45. request->port=port;
  46. request->stringToTransmit=stringToTransmit;
  47. request->contentLength=-1;
  48. request->contentOffset=0;
  49. request->useSSL=useSSL;
  50. request->ipVersion=ipVersion;
  51. request->userData=userData;
  52. if (IsConnected(request->hostEstimatedAddress))
  53. {
  54. sentRequestsMutex.Lock();
  55. if (sentRequests.Size()==0)
  56. {
  57. request->hostCompletedAddress=request->hostEstimatedAddress;
  58. sentRequests.Push(request, _FILE_AND_LINE_);
  59. sentRequestsMutex.Unlock();
  60. SendRequest(request);
  61. }
  62. else
  63. {
  64. // Request pending, push it
  65. pendingRequestsMutex.Lock();
  66. pendingRequests.Push(request, _FILE_AND_LINE_);
  67. pendingRequestsMutex.Unlock();
  68. sentRequestsMutex.Unlock();
  69. }
  70. }
  71. else
  72. {
  73. pendingRequestsMutex.Lock();
  74. pendingRequests.Push(request, _FILE_AND_LINE_);
  75. pendingRequestsMutex.Unlock();
  76. if (ipVersion!=6)
  77. {
  78. tcpInterface->Connect(host, port, false, AF_INET);
  79. }
  80. else
  81. {
  82. #if RAKNET_SUPPORT_IPV6
  83. tcpInterface->Connect(host, port, false, AF_INET6);
  84. #else
  85. RakAssert("HTTPConnection2::TransmitRequest needs define RAKNET_SUPPORT_IPV6" && 0);
  86. #endif
  87. }
  88. }
  89. return true;
  90. }
  91. bool HTTPConnection2::GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, int &contentOffset )
  92. {
  93. void *userData;
  94. return GetResponse(stringTransmitted, hostTransmitted, responseReceived, hostReceived, contentOffset, &userData);
  95. }
  96. bool HTTPConnection2::GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, int &contentOffset, void **userData )
  97. {
  98. completedRequestsMutex.Lock();
  99. if (completedRequests.Size()>0)
  100. {
  101. Request *completedRequest = completedRequests[0];
  102. completedRequests.RemoveAtIndexFast(0);
  103. completedRequestsMutex.Unlock();
  104. responseReceived = completedRequest->stringReceived;
  105. hostReceived = completedRequest->hostCompletedAddress;
  106. stringTransmitted = completedRequest->stringToTransmit;
  107. hostTransmitted = completedRequest->host;
  108. contentOffset = completedRequest->contentOffset;
  109. *userData = completedRequest->userData;
  110. RakNet::OP_DELETE(completedRequest, _FILE_AND_LINE_);
  111. return true;
  112. }
  113. else
  114. {
  115. completedRequestsMutex.Unlock();
  116. }
  117. return false;
  118. }
  119. bool HTTPConnection2::IsBusy(void) const
  120. {
  121. return pendingRequests.Size()>0 || sentRequests.Size()>0;
  122. }
  123. bool HTTPConnection2::HasResponse(void) const
  124. {
  125. return completedRequests.Size()>0;
  126. }
  127. int ReadChunkSize( char *txtStart, char **txtEnd )
  128. {
  129. // char lengthStr[32];
  130. // memset(lengthStr, 0, 32);
  131. // memcpy(lengthStr, txtStart, txtEnd - txtStart);
  132. return strtoul(txtStart, txtEnd,16);
  133. // return atoi(lengthStr);
  134. }
  135. void ReadChunkBlock( size_t &currentChunkSize, size_t &bytesReadSoFar, char *txtIn, RakString &txtOut)
  136. {
  137. size_t bytesToRead;
  138. size_t sLen;
  139. do
  140. {
  141. bytesToRead = currentChunkSize - bytesReadSoFar;
  142. sLen = strlen(txtIn);
  143. if (sLen < bytesToRead)
  144. bytesToRead = sLen;
  145. txtOut.AppendBytes(txtIn, bytesToRead);
  146. txtIn += bytesToRead;
  147. bytesReadSoFar += bytesToRead;
  148. if (*txtIn == 0)
  149. {
  150. // currentChunkSize=0;
  151. return;
  152. }
  153. // char *newLine = strstr(txtIn, "\r\n");
  154. if (txtIn[0] && txtIn[0]=='\r' && txtIn[1] && txtIn[1]=='\n' )
  155. txtIn += 2; // Newline
  156. char *newLine;
  157. currentChunkSize = ReadChunkSize(txtIn, &newLine);
  158. RakAssert(currentChunkSize < 50000); // Sanity check
  159. if (currentChunkSize == 0)
  160. return;
  161. if (newLine == 0)
  162. return;
  163. bytesReadSoFar=0;
  164. txtIn = newLine + 2;
  165. } while (txtIn);
  166. }
  167. PluginReceiveResult HTTPConnection2::OnReceive(Packet *packet)
  168. {
  169. unsigned int i;
  170. bool locked=true;
  171. sentRequestsMutex.Lock();
  172. for (i=0; i < sentRequests.Size(); i++)
  173. {
  174. Request *sentRequest = sentRequests[i];
  175. if (sentRequest->hostCompletedAddress==packet->systemAddress)
  176. {
  177. sentRequests.RemoveAtIndexFast(i);
  178. locked=false;
  179. sentRequestsMutex.Unlock();
  180. /*
  181. static FILE * pFile = 0;
  182. if (pFile==0)
  183. {
  184. long lSize;
  185. char * buffer;
  186. size_t result;
  187. pFile = fopen ( "string_received.txt" , "rb" );
  188. if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
  189. // obtain file size:
  190. fseek (pFile , 0 , SEEK_END);
  191. lSize = ftell (pFile);
  192. rewind (pFile);
  193. // allocate memory to contain the whole file:
  194. buffer = (char*) malloc (sizeof(char)*lSize);
  195. if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
  196. // copy the file into the buffer:
  197. result = fread (buffer,1,lSize,pFile);
  198. if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
  199. packet->data=(unsigned char*) buffer;
  200. packet->length=lSize;
  201. }
  202. */
  203. const char *isFirstChunk = strstr((char*) packet->data, "Transfer-Encoding: chunked");
  204. if (isFirstChunk)
  205. {
  206. //printf((char*) packet->data);
  207. locked=false;
  208. sentRequestsMutex.Unlock();
  209. sentRequest->chunked = true;
  210. char *chunkStrStart = strstr((char*) packet->data, "\r\n\r\n");
  211. RakAssert(chunkStrStart);
  212. chunkStrStart += 4; // strlen("\r\n\r\n");
  213. char *body_header; // = strstr(chunkStrStart, "\r\n");
  214. sentRequest->thisChunkSize = ReadChunkSize(chunkStrStart, &body_header);
  215. sentRequest->bytesReadForThisChunk = 0;
  216. sentRequest->contentOffset = 0;
  217. if (sentRequest->thisChunkSize == 0)
  218. {
  219. // Done
  220. completedRequestsMutex.Lock();
  221. completedRequests.Push(sentRequest, _FILE_AND_LINE_);
  222. completedRequestsMutex.Unlock();
  223. // If there is another command waiting for this server, send it
  224. SendPendingRequestToConnectedSystem(packet->systemAddress);
  225. }
  226. else
  227. {
  228. // char *offset = strstr((char*) packet->data+1, "2000");
  229. body_header+=2;
  230. ReadChunkBlock(sentRequest->thisChunkSize, sentRequest->bytesReadForThisChunk, body_header, sentRequest->stringReceived);
  231. if (sentRequest->thisChunkSize==0)
  232. {
  233. // Done
  234. completedRequestsMutex.Lock();
  235. completedRequests.Push(sentRequest, _FILE_AND_LINE_);
  236. completedRequestsMutex.Unlock();
  237. // If there is another command waiting for this server, send it
  238. SendPendingRequestToConnectedSystem(packet->systemAddress);
  239. }
  240. else
  241. {
  242. // Not done
  243. sentRequestsMutex.Lock();
  244. sentRequests.Push(sentRequest, _FILE_AND_LINE_);
  245. sentRequestsMutex.Unlock();
  246. }
  247. }
  248. }
  249. else if (sentRequest->chunked)
  250. {
  251. ReadChunkBlock(sentRequest->thisChunkSize, sentRequest->bytesReadForThisChunk, (char*) packet->data, sentRequest->stringReceived);
  252. if (sentRequest->thisChunkSize==0)
  253. {
  254. // Done
  255. completedRequestsMutex.Lock();
  256. completedRequests.Push(sentRequest, _FILE_AND_LINE_);
  257. completedRequestsMutex.Unlock();
  258. // If there is another command waiting for this server, send it
  259. SendPendingRequestToConnectedSystem(packet->systemAddress);
  260. }
  261. else
  262. {
  263. // Not done
  264. sentRequestsMutex.Lock();
  265. sentRequests.Push(sentRequest, _FILE_AND_LINE_);
  266. sentRequestsMutex.Unlock();
  267. }
  268. }
  269. else
  270. {
  271. sentRequest->stringReceived+=packet->data;
  272. if (sentRequest->contentLength==-1)
  273. {
  274. const char *length_header = strstr(sentRequest->stringReceived.C_String(), "Content-Length: ");
  275. if(length_header)
  276. {
  277. length_header += 16; // strlen("Content-Length: ");
  278. unsigned int clLength;
  279. for (clLength=0; length_header[clLength] && length_header[clLength] >= '0' && length_header[clLength] <= '9'; clLength++)
  280. ;
  281. if (clLength>0 && (length_header[clLength]=='\r' || length_header[clLength]=='\n'))
  282. {
  283. sentRequest->contentLength = RakString::ReadIntFromSubstring(length_header, 0, clLength);
  284. }
  285. }
  286. }
  287. // If we know the content length, find \r\n\r\n
  288. if (sentRequest->contentLength != -1)
  289. {
  290. if (sentRequest->contentLength > 0)
  291. {
  292. const char *body_header = strstr(sentRequest->stringReceived.C_String(), "\r\n\r\n");
  293. if (body_header)
  294. {
  295. body_header += 4; // strlen("\r\n\r\n");
  296. size_t slen = strlen(body_header);
  297. //RakAssert(slen <= (size_t) sentRequest->contentLength);
  298. if (slen >= (size_t) sentRequest->contentLength)
  299. {
  300. sentRequest->contentOffset = body_header - sentRequest->stringReceived.C_String();
  301. completedRequestsMutex.Lock();
  302. completedRequests.Push(sentRequest, _FILE_AND_LINE_);
  303. completedRequestsMutex.Unlock();
  304. // If there is another command waiting for this server, send it
  305. SendPendingRequestToConnectedSystem(packet->systemAddress);
  306. }
  307. else
  308. {
  309. sentRequestsMutex.Lock();
  310. sentRequests.Push(sentRequest, _FILE_AND_LINE_);
  311. sentRequestsMutex.Unlock();
  312. }
  313. }
  314. else
  315. {
  316. sentRequestsMutex.Lock();
  317. sentRequests.Push(sentRequest, _FILE_AND_LINE_);
  318. sentRequestsMutex.Unlock();
  319. }
  320. }
  321. else
  322. {
  323. sentRequest->contentOffset=-1;
  324. completedRequestsMutex.Lock();
  325. completedRequests.Push(sentRequest, _FILE_AND_LINE_);
  326. completedRequestsMutex.Unlock();
  327. // If there is another command waiting for this server, send it
  328. SendPendingRequestToConnectedSystem(packet->systemAddress);
  329. }
  330. }
  331. else
  332. {
  333. const char *firstNewlineSet = strstr(sentRequest->stringReceived.C_String(), "\r\n\r\n");
  334. if (firstNewlineSet!=0)
  335. {
  336. int offset = firstNewlineSet - sentRequest->stringReceived.C_String();
  337. if (sentRequest->stringReceived.C_String()[offset+4]==0)
  338. sentRequest->contentOffset=-1;
  339. else
  340. sentRequest->contentOffset=offset+4;
  341. completedRequestsMutex.Lock();
  342. completedRequests.Push(sentRequest, _FILE_AND_LINE_);
  343. completedRequestsMutex.Unlock();
  344. // If there is another command waiting for this server, send it
  345. SendPendingRequestToConnectedSystem(packet->systemAddress);
  346. }
  347. else
  348. {
  349. sentRequestsMutex.Lock();
  350. sentRequests.Push(sentRequest, _FILE_AND_LINE_);
  351. sentRequestsMutex.Unlock();
  352. }
  353. }
  354. }
  355. break;
  356. }
  357. }
  358. if (locked==true)
  359. sentRequestsMutex.Unlock();
  360. return RR_CONTINUE_PROCESSING;
  361. }
  362. void HTTPConnection2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)
  363. {
  364. (void) rakNetGUID;
  365. (void) isIncoming; // unknown
  366. SendPendingRequestToConnectedSystem(systemAddress);
  367. }
  368. void HTTPConnection2::SendPendingRequestToConnectedSystem(SystemAddress sa)
  369. {
  370. if (sa==UNASSIGNED_SYSTEM_ADDRESS)
  371. return;
  372. unsigned int requestsSent=0;
  373. // Search through requests to find a match for this instance of TCPInterface and SystemAddress
  374. unsigned int i;
  375. i=0;
  376. pendingRequestsMutex.Lock();
  377. while (i < pendingRequests.Size())
  378. {
  379. Request *request = pendingRequests[i];
  380. if (request->hostEstimatedAddress==sa)
  381. {
  382. pendingRequests.RemoveAtIndex(i);
  383. // Send this request
  384. request->hostCompletedAddress=sa;
  385. sentRequestsMutex.Lock();
  386. sentRequests.Push(request, _FILE_AND_LINE_);
  387. sentRequestsMutex.Unlock();
  388. pendingRequestsMutex.Unlock();
  389. #if OPEN_SSL_CLIENT_SUPPORT==1
  390. if (request->useSSL)
  391. tcpInterface->StartSSLClient(sa);
  392. #endif
  393. SendRequest(request);
  394. requestsSent++;
  395. pendingRequestsMutex.Lock();
  396. break;
  397. }
  398. else
  399. {
  400. i++;
  401. }
  402. }
  403. pendingRequestsMutex.Unlock();
  404. if (requestsSent==0)
  405. {
  406. pendingRequestsMutex.Lock();
  407. if (pendingRequests.Size() > 0)
  408. {
  409. // Just assign
  410. Request *request = pendingRequests[0];
  411. pendingRequests.RemoveAtIndex(0);
  412. request->hostCompletedAddress=sa;
  413. sentRequestsMutex.Lock();
  414. sentRequests.Push(request, _FILE_AND_LINE_);
  415. sentRequestsMutex.Unlock();
  416. pendingRequestsMutex.Unlock();
  417. // Send
  418. #if OPEN_SSL_CLIENT_SUPPORT==1
  419. if (request->useSSL)
  420. tcpInterface->StartSSLClient(sa);
  421. #endif
  422. SendRequest(request);
  423. }
  424. else
  425. {
  426. pendingRequestsMutex.Unlock();
  427. }
  428. }
  429. }
  430. void HTTPConnection2::RemovePendingRequest(SystemAddress sa)
  431. {
  432. unsigned int i;
  433. i=0;
  434. pendingRequestsMutex.Lock();
  435. for (i=0; i < pendingRequests.Size(); i++)
  436. {
  437. Request *request = pendingRequests[i];
  438. if (request->hostEstimatedAddress==sa)
  439. {
  440. pendingRequests.RemoveAtIndex(i);
  441. RakNet::OP_DELETE(request, _FILE_AND_LINE_);
  442. }
  443. else
  444. i++;
  445. }
  446. pendingRequestsMutex.Unlock();
  447. }
  448. void HTTPConnection2::SendNextPendingRequest(void)
  449. {
  450. // Send a pending request
  451. pendingRequestsMutex.Lock();
  452. if (pendingRequests.Size()>0)
  453. {
  454. Request *pendingRequest = pendingRequests.Peek();
  455. pendingRequestsMutex.Unlock();
  456. if (pendingRequest->ipVersion!=6)
  457. {
  458. tcpInterface->Connect(pendingRequest->host.C_String(), pendingRequest->port, false, AF_INET);
  459. }
  460. else
  461. {
  462. #if RAKNET_SUPPORT_IPV6
  463. tcpInterface->Connect(pendingRequest->host.C_String(), pendingRequest->port, false, AF_INET6);
  464. #else
  465. RakAssert("HTTPConnection2::TransmitRequest needs define RAKNET_SUPPORT_IPV6" && 0);
  466. #endif
  467. }
  468. }
  469. else
  470. {
  471. pendingRequestsMutex.Unlock();
  472. }
  473. }
  474. void HTTPConnection2::OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason)
  475. {
  476. (void) failedConnectionAttemptReason;
  477. if (packet->systemAddress==UNASSIGNED_SYSTEM_ADDRESS)
  478. return;
  479. RemovePendingRequest(packet->systemAddress);
  480. SendNextPendingRequest();
  481. }
  482. void HTTPConnection2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason )
  483. {
  484. (void) lostConnectionReason;
  485. (void) rakNetGUID;
  486. if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS)
  487. return;
  488. // Update sent requests to completed requests
  489. unsigned int i;
  490. i=0;
  491. sentRequestsMutex.Lock();
  492. while (i < sentRequests.Size())
  493. {
  494. if (sentRequests[i]->hostCompletedAddress==systemAddress)
  495. {
  496. Request *sentRequest = sentRequests[i];
  497. if (sentRequest->chunked==false && sentRequest->stringReceived.IsEmpty()==false)
  498. {
  499. if (strstr(sentRequest->stringReceived.C_String(), "Content-Length: "))
  500. {
  501. char *body_header = strstr((char*) sentRequest->stringReceived.C_String(), "\r\n\r\n");
  502. if (body_header)
  503. {
  504. body_header += 4; // strlen("\r\n\r\n");
  505. sentRequest->contentOffset = body_header - sentRequest->stringReceived.C_String();
  506. }
  507. else
  508. {
  509. sentRequest->contentOffset = 0;
  510. }
  511. }
  512. else
  513. {
  514. sentRequest->contentOffset = 0;
  515. }
  516. }
  517. completedRequestsMutex.Lock();
  518. completedRequests.Push(sentRequests[i], _FILE_AND_LINE_);
  519. completedRequestsMutex.Unlock();
  520. sentRequests.RemoveAtIndexFast(i);
  521. }
  522. else
  523. {
  524. i++;
  525. }
  526. }
  527. sentRequestsMutex.Unlock();
  528. SendNextPendingRequest();
  529. }
  530. bool HTTPConnection2::IsConnected(SystemAddress sa)
  531. {
  532. SystemAddress remoteSystems[64];
  533. unsigned short numberOfSystems=64;
  534. tcpInterface->GetConnectionList(remoteSystems, &numberOfSystems);
  535. for (unsigned int i=0; i < numberOfSystems; i++)
  536. {
  537. if (remoteSystems[i]==sa)
  538. {
  539. return true;
  540. }
  541. }
  542. return false;
  543. }
  544. void HTTPConnection2::SendRequest(Request *request)
  545. {
  546. tcpInterface->Send(request->stringToTransmit.C_String(), (unsigned int) request->stringToTransmit.GetLength(), request->hostCompletedAddress, false);
  547. }
  548. #endif // #if _RAKNET_SUPPORT_HTTPConnection2==1 && _RAKNET_SUPPORT_TCPInterface==1
粤ICP备19079148号