httpObject.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "app/net/httpObject.h"
  23. #include "platform/platform.h"
  24. #include "core/stream/fileStream.h"
  25. #include "console/simBase.h"
  26. #include "console/consoleInternal.h"
  27. #include "console/engineAPI.h"
  28. IMPLEMENT_CONOBJECT(HTTPObject);
  29. ConsoleDocClass( HTTPObject,
  30. "@brief Allows communications between the game and a server using HTTP.\n\n"
  31. "HTTPObject is derrived from TCPObject and makes use of the same callbacks for dealing with "
  32. "connections and received data. However, the way in which you use HTTPObject to connect "
  33. "with a server is different than TCPObject. Rather than opening a connection, sending data, "
  34. "waiting to receive data, and then closing the connection, you issue a get() or post() and "
  35. "handle the response. The connection is automatically created and destroyed for you.\n\n"
  36. "@tsexample\n"
  37. "// In this example we'll retrieve the weather in Las Vegas using\n"
  38. "// Google's API. The response is in XML which could be processed\n"
  39. "// and used by the game using SimXMLDocument, but we'll just output\n"
  40. "// the results to the console in this example.\n\n"
  41. "// Define callbacks for our specific HTTPObject using our instance's\n"
  42. "// name (WeatherFeed) as the namespace.\n\n"
  43. "// Handle an issue with resolving the server's name\n"
  44. "function WeatherFeed::onDNSFailed(%this)\n"
  45. "{\n"
  46. " // Store this state\n"
  47. " %this.lastState = \"DNSFailed\";\n\n"
  48. " // Handle DNS failure\n"
  49. "}\n\n"
  50. "function WeatherFeed::onConnectFailed(%this)\n"
  51. "{\n"
  52. " // Store this state\n"
  53. " %this.lastState = \"ConnectFailed\";\n\n"
  54. " // Handle connection failure\n"
  55. "}\n\n"
  56. "function WeatherFeed::onDNSResolved(%this)\n"
  57. "{\n"
  58. " // Store this state\n"
  59. " %this.lastState = \"DNSResolved\";\n\n"
  60. "}\n\n"
  61. "function WeatherFeed::onConnected(%this)\n"
  62. "{\n"
  63. " // Store this state\n"
  64. " %this.lastState = \"Connected\";\n\n"
  65. " // Clear our buffer\n"
  66. " %this.buffer = \"\";\n"
  67. "}\n\n"
  68. "function WeatherFeed::onDisconnect(%this)\n"
  69. "{\n"
  70. " // Store this state\n"
  71. " %this.lastState = \"Disconnected\";\n\n"
  72. " // Output the buffer to the console\n"
  73. " echo(\"Google Weather Results:\");\n"
  74. " echo(%this.buffer);\n"
  75. "}\n\n"
  76. "// Handle a line from the server\n"
  77. "function WeatherFeed::onLine(%this, %line)\n"
  78. "{\n"
  79. " // Store this line in out buffer\n"
  80. " %this.buffer = %this.buffer @ %line;\n"
  81. "}\n\n"
  82. "// Create the HTTPObject\n"
  83. "%feed = new HTTPObject(WeatherFeed);\n\n"
  84. "// Define a dynamic field to store the last connection state\n"
  85. "%feed.lastState = \"None\";\n\n"
  86. "// Send the GET command\n"
  87. "%feed.get(\"www.google.com:80\", \"/ig/api\", \"weather=Las-Vegas,US\");\n"
  88. "@endtsexample\n\n"
  89. "@see TCPObject\n"
  90. "@ingroup Networking\n"
  91. );
  92. //--------------------------------------
  93. HTTPObject::HTTPObject()
  94. {
  95. mHostName = 0;
  96. mPath = 0;
  97. mQuery = 0;
  98. mPost = 0;
  99. mBufferSave = 0;
  100. }
  101. HTTPObject::~HTTPObject()
  102. {
  103. dFree(mHostName);
  104. dFree(mPath);
  105. dFree(mQuery);
  106. dFree(mPost);
  107. mHostName = 0;
  108. mPath = 0;
  109. mQuery = 0;
  110. mPost = 0;
  111. dFree(mBufferSave);
  112. }
  113. //--------------------------------------
  114. //--------------------------------------
  115. void HTTPObject::get(const char *host, const char *path, const char *query)
  116. {
  117. if(mHostName)
  118. dFree(mHostName);
  119. if(mPath)
  120. dFree(mPath);
  121. if(mQuery)
  122. dFree(mQuery);
  123. if(mPost)
  124. dFree(mPost);
  125. if(mBufferSave)
  126. dFree(mBufferSave);
  127. mBufferSave = 0;
  128. mHostName = dStrdup(host);
  129. mPath = dStrdup(path);
  130. if(query)
  131. mQuery = dStrdup(query);
  132. else
  133. mQuery = NULL;
  134. mPost = NULL;
  135. connect(host);
  136. }
  137. void HTTPObject::post(const char *host, const char *path, const char *query, const char *post)
  138. {
  139. if(mHostName)
  140. dFree(mHostName);
  141. if(mPath)
  142. dFree(mPath);
  143. if(mQuery)
  144. dFree(mQuery);
  145. if(mPost)
  146. dFree(mPost);
  147. if(mBufferSave)
  148. dFree(mBufferSave);
  149. mBufferSave = 0;
  150. mHostName = dStrdup(host);
  151. mPath = dStrdup(path);
  152. if(query && query[0])
  153. mQuery = dStrdup(query);
  154. else
  155. mQuery = NULL;
  156. mPost = dStrdup(post);
  157. connect(host);
  158. }
  159. static char getHex(char c)
  160. {
  161. if(c <= 9)
  162. return c + '0';
  163. return c - 10 + 'A';
  164. }
  165. static S32 getHexVal(char c)
  166. {
  167. if(c >= '0' && c <= '9')
  168. return c - '0';
  169. else if(c >= 'A' && c <= 'Z')
  170. return c - 'A' + 10;
  171. else if(c >= 'a' && c <= 'z')
  172. return c - 'a' + 10;
  173. return -1;
  174. }
  175. void HTTPObject::expandPath(char *dest, const char *path, U32 destSize)
  176. {
  177. static bool asciiEscapeTableBuilt = false;
  178. static bool asciiEscapeTable[256];
  179. if(!asciiEscapeTableBuilt)
  180. {
  181. asciiEscapeTableBuilt = true;
  182. U32 i;
  183. for(i = 0; i <= ' '; i++)
  184. asciiEscapeTable[i] = true;
  185. for(;i <= 0x7F; i++)
  186. asciiEscapeTable[i] = false;
  187. for(;i <= 0xFF; i++)
  188. asciiEscapeTable[i] = true;
  189. asciiEscapeTable[static_cast<U32>('\"')] = true;
  190. asciiEscapeTable[static_cast<U32>('_')] = true;
  191. asciiEscapeTable[static_cast<U32>('\'')] = true;
  192. asciiEscapeTable[static_cast<U32>('#')] = true;
  193. asciiEscapeTable[static_cast<U32>('$')] = true;
  194. asciiEscapeTable[static_cast<U32>('%')] = true;
  195. asciiEscapeTable[static_cast<U32>('&')] = false;
  196. asciiEscapeTable[static_cast<U32>('+')] = true;
  197. asciiEscapeTable[static_cast<U32>('-')] = true;
  198. asciiEscapeTable[static_cast<U32>('~')] = true;
  199. }
  200. U32 destIndex = 0;
  201. U32 srcIndex = 0;
  202. while(path[srcIndex] && destIndex < destSize - 3)
  203. {
  204. char c = path[srcIndex++];
  205. if(asciiEscapeTable[static_cast<U32>(c)])
  206. {
  207. dest[destIndex++] = '%';
  208. dest[destIndex++] = getHex((c >> 4) & 0xF);
  209. dest[destIndex++] = getHex(c & 0xF);
  210. }
  211. else
  212. dest[destIndex++] = c;
  213. }
  214. dest[destIndex] = 0;
  215. }
  216. //--------------------------------------
  217. void HTTPObject::onConnected()
  218. {
  219. Parent::onConnected();
  220. char expPath[8192];
  221. char buffer[8192];
  222. if(mQuery)
  223. {
  224. dSprintf(buffer, sizeof(buffer), "%s?%s", mPath, mQuery);
  225. expandPath(expPath, buffer, sizeof(expPath));
  226. }
  227. else
  228. expandPath(expPath, mPath, sizeof(expPath));
  229. char *pt = dStrchr(mHostName, ':');
  230. if(pt)
  231. *pt = 0;
  232. //If we want to do a get request
  233. if(mPost == NULL)
  234. {
  235. dSprintf(buffer, sizeof(buffer), "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", expPath, mHostName);
  236. }
  237. //Else we want to do a post request
  238. else
  239. {
  240. dSprintf(buffer, sizeof(buffer), "POST %s HTTP/1.1\r\nHost: %s\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: %i\r\n\r\n%s\r\n\r\n",
  241. expPath, mHostName, dStrlen(mPost), mPost);
  242. }
  243. if(pt)
  244. *pt = ':';
  245. send((U8*)buffer, dStrlen(buffer));
  246. mParseState = ParsingStatusLine;
  247. mChunkedEncoding = false;
  248. }
  249. void HTTPObject::onConnectFailed()
  250. {
  251. dFree(mHostName);
  252. dFree(mPath);
  253. dFree(mQuery);
  254. mHostName = 0;
  255. mPath = 0;
  256. mQuery = 0;
  257. Parent::onConnectFailed();
  258. }
  259. void HTTPObject::onDisconnect()
  260. {
  261. dFree(mHostName);
  262. dFree(mPath);
  263. dFree(mQuery);
  264. mHostName = 0;
  265. mPath = 0;
  266. mQuery = 0;
  267. Parent::onDisconnect();
  268. }
  269. bool HTTPObject::processLine(UTF8 *line)
  270. {
  271. if(mParseState == ParsingStatusLine)
  272. {
  273. mParseState = ParsingHeader;
  274. }
  275. else if(mParseState == ParsingHeader)
  276. {
  277. if(!dStricmp((char *) line, "transfer-encoding: chunked"))
  278. mChunkedEncoding = true;
  279. if(line[0] == 0)
  280. {
  281. if(mChunkedEncoding)
  282. mParseState = ParsingChunkHeader;
  283. else
  284. mParseState = ProcessingBody;
  285. return true;
  286. }
  287. }
  288. else if(mParseState == ParsingChunkHeader)
  289. {
  290. if(line[0]) // strip off the crlf if necessary
  291. {
  292. mChunkSize = 0;
  293. S32 hexVal;
  294. while((hexVal = getHexVal(*line++)) != -1)
  295. {
  296. mChunkSize *= 16;
  297. mChunkSize += hexVal;
  298. }
  299. if(mBufferSave)
  300. {
  301. mBuffer = mBufferSave;
  302. mBufferSize = mBufferSaveSize;
  303. mBufferSave = 0;
  304. }
  305. if(mChunkSize)
  306. mParseState = ProcessingBody;
  307. else
  308. {
  309. mParseState = ProcessingDone;
  310. finishLastLine();
  311. }
  312. }
  313. }
  314. else
  315. {
  316. return Parent::processLine((UTF8*)line);
  317. }
  318. return true;
  319. }
  320. U32 HTTPObject::onDataReceive(U8 *buffer, U32 bufferLen)
  321. {
  322. U32 start = 0;
  323. parseLine(buffer, &start, bufferLen);
  324. return start;
  325. }
  326. //--------------------------------------
  327. U32 HTTPObject::onReceive(U8 *buffer, U32 bufferLen)
  328. {
  329. if(mParseState == ProcessingBody)
  330. {
  331. if(mChunkedEncoding && bufferLen >= mChunkSize)
  332. {
  333. U32 ret = onDataReceive(buffer, mChunkSize);
  334. mChunkSize -= ret;
  335. if(mChunkSize == 0)
  336. {
  337. if(mBuffer)
  338. {
  339. mBufferSaveSize = mBufferSize;
  340. mBufferSave = mBuffer;
  341. mBuffer = 0;
  342. mBufferSize = 0;
  343. }
  344. mParseState = ParsingChunkHeader;
  345. }
  346. return ret;
  347. }
  348. else
  349. {
  350. U32 ret = onDataReceive(buffer, bufferLen);
  351. mChunkSize -= ret;
  352. return ret;
  353. }
  354. }
  355. else if(mParseState != ProcessingDone)
  356. {
  357. U32 start = 0;
  358. parseLine(buffer, &start, bufferLen);
  359. return start;
  360. }
  361. return bufferLen;
  362. }
  363. //--------------------------------------
  364. DefineEngineMethod( HTTPObject, get, void, ( const char* Address, const char* requirstURI, const char* query ), ( "" ),
  365. "@brief Send a GET command to a server to send or retrieve data.\n\n"
  366. "@param Address HTTP web address to send this get call to. Be sure to include the port at the end (IE: \"www.garagegames.com:80\").\n"
  367. "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n"
  368. "@param query Optional. Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. "
  369. "If you were building the URL manually, this is the text that follows the question mark. For example: http://www.google.com/ig/api?<b>weather=Las-Vegas,US</b>\n"
  370. "@tsexample\n"
  371. "// Create an HTTP object for communications\n"
  372. "%httpObj = new HTTPObject();\n\n"
  373. "// Specify a URL to transmit to\n"
  374. "%url = \"www.garagegames.com:80\";\n\n"
  375. "// Specify a URI to communicate with\n"
  376. "%URI = \"/index.php\";\n\n"
  377. "// Specify a query to send.\n"
  378. "%query = \"\";\n\n"
  379. "// Send the GET command to the server\n"
  380. "%httpObj.get(%url,%URI,%query);\n"
  381. "@endtsexample\n\n"
  382. )
  383. {
  384. if( !query || !query[ 0 ] )
  385. object->get(Address, requirstURI, NULL);
  386. else
  387. object->get(Address, requirstURI, query);
  388. }
  389. DefineEngineMethod( HTTPObject, post, void, ( const char* Address, const char* requirstURI, const char* query, const char* post ),,
  390. "@brief Send POST command to a server to send or retrieve data.\n\n"
  391. "@param Address HTTP web address to send this get call to. Be sure to include the port at the end (IE: \"www.garagegames.com:80\").\n"
  392. "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n"
  393. "@param query Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. \n"
  394. "@param post Submission data to be processed.\n"
  395. "@tsexample\n"
  396. "// Create an HTTP object for communications\n"
  397. "%httpObj = new HTTPObject();\n\n"
  398. "// Specify a URL to transmit to\n"
  399. "%url = \"www.garagegames.com:80\";\n\n"
  400. "// Specify a URI to communicate with\n"
  401. "%URI = \"/index.php\";\n\n"
  402. "// Specify a query to send.\n"
  403. "%query = \"\";\n\n"
  404. "// Specify the submission data.\n"
  405. "%post = \"\";\n\n"
  406. "// Send the POST command to the server\n"
  407. "%httpObj.POST(%url,%URI,%query,%post);\n"
  408. "@endtsexample\n\n"
  409. )
  410. {
  411. object->post(Address, requirstURI, query, post);
  412. }