httpObject.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 "platform/event.h"
  25. #include "core/stream/fileStream.h"
  26. #include "console/simBase.h"
  27. #include "console/consoleInternal.h"
  28. #include "console/engineAPI.h"
  29. IMPLEMENT_CONOBJECT(HTTPObject);
  30. ConsoleDocClass( HTTPObject,
  31. "@brief Allows communications between the game and a server using HTTP.\n\n"
  32. "HTTPObject is derrived from TCPObject and makes use of the same callbacks for dealing with "
  33. "connections and received data. However, the way in which you use HTTPObject to connect "
  34. "with a server is different than TCPObject. Rather than opening a connection, sending data, "
  35. "waiting to receive data, and then closing the connection, you issue a get() or post() and "
  36. "handle the response. The connection is automatically created and destroyed for you.\n\n"
  37. "@tsexample\n"
  38. "// In this example we'll retrieve the weather in Las Vegas using\n"
  39. "// Google's API. The response is in XML which could be processed\n"
  40. "// and used by the game using SimXMLDocument, but we'll just output\n"
  41. "// the results to the console in this example.\n\n"
  42. "// Define callbacks for our specific HTTPObject using our instance's\n"
  43. "// name (WeatherFeed) as the namespace.\n\n"
  44. "// Handle an issue with resolving the server's name\n"
  45. "function WeatherFeed::onDNSFailed(%this)\n"
  46. "{\n"
  47. " // Store this state\n"
  48. " %this.lastState = \"DNSFailed\";\n\n"
  49. " // Handle DNS failure\n"
  50. "}\n\n"
  51. "function WeatherFeed::onConnectFailed(%this)\n"
  52. "{\n"
  53. " // Store this state\n"
  54. " %this.lastState = \"ConnectFailed\";\n\n"
  55. " // Handle connection failure\n"
  56. "}\n\n"
  57. "function WeatherFeed::onDNSResolved(%this)\n"
  58. "{\n"
  59. " // Store this state\n"
  60. " %this.lastState = \"DNSResolved\";\n\n"
  61. "}\n\n"
  62. "function WeatherFeed::onConnected(%this)\n"
  63. "{\n"
  64. " // Store this state\n"
  65. " %this.lastState = \"Connected\";\n\n"
  66. " // Clear our buffer\n"
  67. " %this.buffer = \"\";\n"
  68. "}\n\n"
  69. "function WeatherFeed::onDisconnect(%this)\n"
  70. "{\n"
  71. " // Store this state\n"
  72. " %this.lastState = \"Disconnected\";\n\n"
  73. " // Output the buffer to the console\n"
  74. " echo(\"Google Weather Results:\");\n"
  75. " echo(%this.buffer);\n"
  76. "}\n\n"
  77. "// Handle a line from the server\n"
  78. "function WeatherFeed::onLine(%this, %line)\n"
  79. "{\n"
  80. " // Store this line in out buffer\n"
  81. " %this.buffer = %this.buffer @ %line;\n"
  82. "}\n\n"
  83. "// Create the HTTPObject\n"
  84. "%feed = new HTTPObject(WeatherFeed);\n\n"
  85. "// Define a dynamic field to store the last connection state\n"
  86. "%feed.lastState = \"None\";\n\n"
  87. "// Send the GET command\n"
  88. "%feed.get(\"www.google.com:80\", \"/ig/api\", \"weather=Las-Vegas,US\");\n"
  89. "@endtsexample\n\n"
  90. "@see TCPObject\n"
  91. "@ingroup Networking\n"
  92. );
  93. //--------------------------------------
  94. HTTPObject::HTTPObject()
  95. {
  96. mHostName = 0;
  97. mPath = 0;
  98. mQuery = 0;
  99. mPost = 0;
  100. mBufferSave = 0;
  101. }
  102. HTTPObject::~HTTPObject()
  103. {
  104. dFree(mHostName);
  105. dFree(mPath);
  106. dFree(mQuery);
  107. dFree(mPost);
  108. mHostName = 0;
  109. mPath = 0;
  110. mQuery = 0;
  111. mPost = 0;
  112. dFree(mBufferSave);
  113. }
  114. //--------------------------------------
  115. //--------------------------------------
  116. void HTTPObject::get(const char *host, const char *path, const char *query)
  117. {
  118. if(mHostName)
  119. dFree(mHostName);
  120. if(mPath)
  121. dFree(mPath);
  122. if(mQuery)
  123. dFree(mQuery);
  124. if(mPost)
  125. dFree(mPost);
  126. if(mBufferSave)
  127. dFree(mBufferSave);
  128. mBufferSave = 0;
  129. mHostName = dStrdup(host);
  130. mPath = dStrdup(path);
  131. if(query)
  132. mQuery = dStrdup(query);
  133. else
  134. mQuery = NULL;
  135. mPost = NULL;
  136. connect(host);
  137. }
  138. void HTTPObject::post(const char *host, const char *path, const char *query, const char *post)
  139. {
  140. if(mHostName)
  141. dFree(mHostName);
  142. if(mPath)
  143. dFree(mPath);
  144. if(mQuery)
  145. dFree(mQuery);
  146. if(mPost)
  147. dFree(mPost);
  148. if(mBufferSave)
  149. dFree(mBufferSave);
  150. mBufferSave = 0;
  151. mHostName = dStrdup(host);
  152. mPath = dStrdup(path);
  153. if(query && query[0])
  154. mQuery = dStrdup(query);
  155. else
  156. mQuery = NULL;
  157. mPost = dStrdup(post);
  158. connect(host);
  159. }
  160. static char getHex(char c)
  161. {
  162. if(c <= 9)
  163. return c + '0';
  164. return c - 10 + 'A';
  165. }
  166. static S32 getHexVal(char c)
  167. {
  168. if(c >= '0' && c <= '9')
  169. return c - '0';
  170. else if(c >= 'A' && c <= 'Z')
  171. return c - 'A' + 10;
  172. else if(c >= 'a' && c <= 'z')
  173. return c - 'a' + 10;
  174. return -1;
  175. }
  176. void HTTPObject::expandPath(char *dest, const char *path, U32 destSize)
  177. {
  178. static bool asciiEscapeTableBuilt = false;
  179. static bool asciiEscapeTable[256];
  180. if(!asciiEscapeTableBuilt)
  181. {
  182. asciiEscapeTableBuilt = true;
  183. U32 i;
  184. for(i = 0; i <= ' '; i++)
  185. asciiEscapeTable[i] = true;
  186. for(;i <= 0x7F; i++)
  187. asciiEscapeTable[i] = false;
  188. for(;i <= 0xFF; i++)
  189. asciiEscapeTable[i] = 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>('%')] = true;
  196. asciiEscapeTable[static_cast<U32>('&')] = false;
  197. asciiEscapeTable[static_cast<U32>('+')] = true;
  198. asciiEscapeTable[static_cast<U32>('-')] = true;
  199. asciiEscapeTable[static_cast<U32>('~')] = true;
  200. }
  201. U32 destIndex = 0;
  202. U32 srcIndex = 0;
  203. while(path[srcIndex] && destIndex < destSize - 3)
  204. {
  205. char c = path[srcIndex++];
  206. if(asciiEscapeTable[static_cast<U32>(c)])
  207. {
  208. dest[destIndex++] = '%';
  209. dest[destIndex++] = getHex((c >> 4) & 0xF);
  210. dest[destIndex++] = getHex(c & 0xF);
  211. }
  212. else
  213. dest[destIndex++] = c;
  214. }
  215. dest[destIndex] = 0;
  216. }
  217. //--------------------------------------
  218. void HTTPObject::onConnected()
  219. {
  220. Parent::onConnected();
  221. char expPath[8192];
  222. char buffer[8192];
  223. if(mQuery)
  224. {
  225. dSprintf(buffer, sizeof(buffer), "%s?%s", mPath, mQuery);
  226. expandPath(expPath, buffer, sizeof(expPath));
  227. }
  228. else
  229. expandPath(expPath, mPath, sizeof(expPath));
  230. char *pt = dStrchr(mHostName, ':');
  231. if(pt)
  232. *pt = 0;
  233. dSprintf(buffer, sizeof(buffer), "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", expPath, mHostName);
  234. if(pt)
  235. *pt = ':';
  236. send((U8*)buffer, dStrlen(buffer));
  237. mParseState = ParsingStatusLine;
  238. mChunkedEncoding = false;
  239. }
  240. void HTTPObject::onConnectFailed()
  241. {
  242. dFree(mHostName);
  243. dFree(mPath);
  244. dFree(mQuery);
  245. mHostName = 0;
  246. mPath = 0;
  247. mQuery = 0;
  248. Parent::onConnectFailed();
  249. }
  250. void HTTPObject::onDisconnect()
  251. {
  252. dFree(mHostName);
  253. dFree(mPath);
  254. dFree(mQuery);
  255. mHostName = 0;
  256. mPath = 0;
  257. mQuery = 0;
  258. Parent::onDisconnect();
  259. }
  260. bool HTTPObject::processLine(U8 *line)
  261. {
  262. if(mParseState == ParsingStatusLine)
  263. {
  264. mParseState = ParsingHeader;
  265. }
  266. else if(mParseState == ParsingHeader)
  267. {
  268. if(!dStricmp((char *) line, "transfer-encoding: chunked"))
  269. mChunkedEncoding = true;
  270. if(line[0] == 0)
  271. {
  272. if(mChunkedEncoding)
  273. mParseState = ParsingChunkHeader;
  274. else
  275. mParseState = ProcessingBody;
  276. return true;
  277. }
  278. }
  279. else if(mParseState == ParsingChunkHeader)
  280. {
  281. if(line[0]) // strip off the crlf if necessary
  282. {
  283. mChunkSize = 0;
  284. S32 hexVal;
  285. while((hexVal = getHexVal(*line++)) != -1)
  286. {
  287. mChunkSize *= 16;
  288. mChunkSize += hexVal;
  289. }
  290. if(mBufferSave)
  291. {
  292. mBuffer = mBufferSave;
  293. mBufferSize = mBufferSaveSize;
  294. mBufferSave = 0;
  295. }
  296. if(mChunkSize)
  297. mParseState = ProcessingBody;
  298. else
  299. {
  300. mParseState = ProcessingDone;
  301. finishLastLine();
  302. }
  303. }
  304. }
  305. else
  306. {
  307. return Parent::processLine((UTF8*)line);
  308. }
  309. return true;
  310. }
  311. U32 HTTPObject::onDataReceive(U8 *buffer, U32 bufferLen)
  312. {
  313. U32 start = 0;
  314. parseLine(buffer, &start, bufferLen);
  315. return start;
  316. }
  317. //--------------------------------------
  318. U32 HTTPObject::onReceive(U8 *buffer, U32 bufferLen)
  319. {
  320. if(mParseState == ProcessingBody)
  321. {
  322. if(mChunkedEncoding && bufferLen >= mChunkSize)
  323. {
  324. U32 ret = onDataReceive(buffer, mChunkSize);
  325. mChunkSize -= ret;
  326. if(mChunkSize == 0)
  327. {
  328. if(mBuffer)
  329. {
  330. mBufferSaveSize = mBufferSize;
  331. mBufferSave = mBuffer;
  332. mBuffer = 0;
  333. mBufferSize = 0;
  334. }
  335. mParseState = ParsingChunkHeader;
  336. }
  337. return ret;
  338. }
  339. else
  340. {
  341. U32 ret = onDataReceive(buffer, bufferLen);
  342. mChunkSize -= ret;
  343. return ret;
  344. }
  345. }
  346. else if(mParseState != ProcessingDone)
  347. {
  348. U32 start = 0;
  349. parseLine(buffer, &start, bufferLen);
  350. return start;
  351. }
  352. return bufferLen;
  353. }
  354. //--------------------------------------
  355. DefineEngineMethod( HTTPObject, get, void, ( const char* Address, const char* requirstURI, const char* query ), ( "" ),
  356. "@brief Send a GET command to a server to send or retrieve data.\n\n"
  357. "@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"
  358. "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n"
  359. "@param query Optional. Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. "
  360. "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"
  361. "@tsexample\n"
  362. "// Create an HTTP object for communications\n"
  363. "%httpObj = new HTTPObject();\n\n"
  364. "// Specify a URL to transmit to\n"
  365. "%url = \"www.garagegames.com:80\";\n\n"
  366. "// Specify a URI to communicate with\n"
  367. "%URI = \"/index.php\";\n\n"
  368. "// Specify a query to send.\n"
  369. "%query = \"\";\n\n"
  370. "// Send the GET command to the server\n"
  371. "%httpObj.get(%url,%URI,%query);\n"
  372. "@endtsexample\n\n"
  373. )
  374. {
  375. if( !query || !query[ 0 ] )
  376. object->get(Address, requirstURI, NULL);
  377. else
  378. object->get(Address, requirstURI, query);
  379. }
  380. DefineEngineMethod( HTTPObject, post, void, ( const char* Address, const char* requirstURI, const char* query, const char* post ),,
  381. "@brief Send POST command to a server to send or retrieve data.\n\n"
  382. "@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"
  383. "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n"
  384. "@param query Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. \n"
  385. "@param post Submission data to be processed.\n"
  386. "@note The post() method is currently non-functional.\n"
  387. "@tsexample\n"
  388. "// Create an HTTP object for communications\n"
  389. "%httpObj = new HTTPObject();\n\n"
  390. "// Specify a URL to transmit to\n"
  391. "%url = \"www.garagegames.com:80\";\n\n"
  392. "// Specify a URI to communicate with\n"
  393. "%URI = \"/index.php\";\n\n"
  394. "// Specify a query to send.\n"
  395. "%query = \"\";\n\n"
  396. "// Specify the submission data.\n"
  397. "%post = \"\";\n\n"
  398. "// Send the POST command to the server\n"
  399. "%httpObj.POST(%url,%URI,%query,%post);\n"
  400. "@endtsexample\n\n"
  401. )
  402. {
  403. object->post(Address, requirstURI, query, post);
  404. }