httpObject.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. dSprintf(buffer, sizeof(buffer), "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", expPath, mHostName);
  233. if(pt)
  234. *pt = ':';
  235. send((U8*)buffer, dStrlen(buffer));
  236. mParseState = ParsingStatusLine;
  237. mChunkedEncoding = false;
  238. }
  239. void HTTPObject::onConnectFailed()
  240. {
  241. dFree(mHostName);
  242. dFree(mPath);
  243. dFree(mQuery);
  244. mHostName = 0;
  245. mPath = 0;
  246. mQuery = 0;
  247. Parent::onConnectFailed();
  248. }
  249. void HTTPObject::onDisconnect()
  250. {
  251. dFree(mHostName);
  252. dFree(mPath);
  253. dFree(mQuery);
  254. mHostName = 0;
  255. mPath = 0;
  256. mQuery = 0;
  257. Parent::onDisconnect();
  258. }
  259. bool HTTPObject::processLine(UTF8 *line)
  260. {
  261. if(mParseState == ParsingStatusLine)
  262. {
  263. mParseState = ParsingHeader;
  264. }
  265. else if(mParseState == ParsingHeader)
  266. {
  267. if(!dStricmp((char *) line, "transfer-encoding: chunked"))
  268. mChunkedEncoding = true;
  269. if(line[0] == 0)
  270. {
  271. if(mChunkedEncoding)
  272. mParseState = ParsingChunkHeader;
  273. else
  274. mParseState = ProcessingBody;
  275. return true;
  276. }
  277. }
  278. else if(mParseState == ParsingChunkHeader)
  279. {
  280. if(line[0]) // strip off the crlf if necessary
  281. {
  282. mChunkSize = 0;
  283. S32 hexVal;
  284. while((hexVal = getHexVal(*line++)) != -1)
  285. {
  286. mChunkSize *= 16;
  287. mChunkSize += hexVal;
  288. }
  289. if(mBufferSave)
  290. {
  291. mBuffer = mBufferSave;
  292. mBufferSize = mBufferSaveSize;
  293. mBufferSave = 0;
  294. }
  295. if(mChunkSize)
  296. mParseState = ProcessingBody;
  297. else
  298. {
  299. mParseState = ProcessingDone;
  300. finishLastLine();
  301. }
  302. }
  303. }
  304. else
  305. {
  306. return Parent::processLine((UTF8*)line);
  307. }
  308. return true;
  309. }
  310. U32 HTTPObject::onDataReceive(U8 *buffer, U32 bufferLen)
  311. {
  312. U32 start = 0;
  313. parseLine(buffer, &start, bufferLen);
  314. return start;
  315. }
  316. //--------------------------------------
  317. U32 HTTPObject::onReceive(U8 *buffer, U32 bufferLen)
  318. {
  319. if(mParseState == ProcessingBody)
  320. {
  321. if(mChunkedEncoding && bufferLen >= mChunkSize)
  322. {
  323. U32 ret = onDataReceive(buffer, mChunkSize);
  324. mChunkSize -= ret;
  325. if(mChunkSize == 0)
  326. {
  327. if(mBuffer)
  328. {
  329. mBufferSaveSize = mBufferSize;
  330. mBufferSave = mBuffer;
  331. mBuffer = 0;
  332. mBufferSize = 0;
  333. }
  334. mParseState = ParsingChunkHeader;
  335. }
  336. return ret;
  337. }
  338. else
  339. {
  340. U32 ret = onDataReceive(buffer, bufferLen);
  341. mChunkSize -= ret;
  342. return ret;
  343. }
  344. }
  345. else if(mParseState != ProcessingDone)
  346. {
  347. U32 start = 0;
  348. parseLine(buffer, &start, bufferLen);
  349. return start;
  350. }
  351. return bufferLen;
  352. }
  353. //--------------------------------------
  354. DefineEngineMethod( HTTPObject, get, void, ( const char* Address, const char* requirstURI, const char* query ), ( "" ),
  355. "@brief Send a GET command to a server to send or retrieve data.\n\n"
  356. "@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"
  357. "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n"
  358. "@param query Optional. Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. "
  359. "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"
  360. "@tsexample\n"
  361. "// Create an HTTP object for communications\n"
  362. "%httpObj = new HTTPObject();\n\n"
  363. "// Specify a URL to transmit to\n"
  364. "%url = \"www.garagegames.com:80\";\n\n"
  365. "// Specify a URI to communicate with\n"
  366. "%URI = \"/index.php\";\n\n"
  367. "// Specify a query to send.\n"
  368. "%query = \"\";\n\n"
  369. "// Send the GET command to the server\n"
  370. "%httpObj.get(%url,%URI,%query);\n"
  371. "@endtsexample\n\n"
  372. )
  373. {
  374. if( !query || !query[ 0 ] )
  375. object->get(Address, requirstURI, NULL);
  376. else
  377. object->get(Address, requirstURI, query);
  378. }
  379. DefineEngineMethod( HTTPObject, post, void, ( const char* Address, const char* requirstURI, const char* query, const char* post ),,
  380. "@brief Send POST command to a server to send or retrieve data.\n\n"
  381. "@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"
  382. "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n"
  383. "@param query Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. \n"
  384. "@param post Submission data to be processed.\n"
  385. "@note The post() method is currently non-functional.\n"
  386. "@tsexample\n"
  387. "// Create an HTTP object for communications\n"
  388. "%httpObj = new HTTPObject();\n\n"
  389. "// Specify a URL to transmit to\n"
  390. "%url = \"www.garagegames.com:80\";\n\n"
  391. "// Specify a URI to communicate with\n"
  392. "%URI = \"/index.php\";\n\n"
  393. "// Specify a query to send.\n"
  394. "%query = \"\";\n\n"
  395. "// Specify the submission data.\n"
  396. "%post = \"\";\n\n"
  397. "// Send the POST command to the server\n"
  398. "%httpObj.POST(%url,%URI,%query,%post);\n"
  399. "@endtsexample\n\n"
  400. )
  401. {
  402. object->post(Address, requirstURI, query, post);
  403. }