tcpObject.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 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 "tcpObject.h"
  23. #include "platform/platform.h"
  24. #include "platform/event.h"
  25. #include "game/gameInterface.h"
  26. #include "sim/simBase.h"
  27. #include "console/consoleInternal.h"
  28. #include "game/defaultGame.h"
  29. #ifdef TORQUE_OS_IOS
  30. #include "platformiOS/iOSUtil.h"
  31. #endif //TORQUE_OS_IOS
  32. TCPObject *TCPObject::table[TCPObject::TableSize] = {0, };
  33. IMPLEMENT_CONOBJECT(TCPObject);
  34. TCPObject *TCPObject::find(NetSocket tag)
  35. {
  36. for(TCPObject *walk = table[U32(tag) & TableMask]; walk; walk = walk->mNext)
  37. if(walk->mTag == tag)
  38. return walk;
  39. return NULL;
  40. }
  41. void TCPObject::addToTable(NetSocket newTag)
  42. {
  43. removeFromTable();
  44. mTag = newTag;
  45. mNext = table[U32(mTag) & TableMask];
  46. table[U32(mTag) & TableMask] = this;
  47. }
  48. void TCPObject::removeFromTable()
  49. {
  50. for(TCPObject **walk = &table[U32(mTag) & TableMask]; *walk; walk = &((*walk)->mNext))
  51. {
  52. if(*walk == this)
  53. {
  54. *walk = mNext;
  55. return;
  56. }
  57. }
  58. }
  59. TCPObject::TCPObject()
  60. {
  61. mBuffer = NULL;
  62. mBufferSize = 0;
  63. mPort = 0;
  64. mTag = InvalidSocket;
  65. mNext = NULL;
  66. mState = Disconnected;
  67. }
  68. TCPObject::~TCPObject()
  69. {
  70. disconnect();
  71. dFree(mBuffer);
  72. }
  73. bool TCPObject::processArguments(S32 argc, const char **argv)
  74. {
  75. if(argc == 0)
  76. return true;
  77. else if(argc == 1)
  78. {
  79. addToTable(U32(dAtoi(argv[0])));
  80. return true;
  81. }
  82. return false;
  83. }
  84. bool TCPObject::onAdd()
  85. {
  86. if(!Parent::onAdd())
  87. return false;
  88. const char *name = getName();
  89. if(name && name[0] && getClassRep())
  90. {
  91. Namespace *parent = getClassRep()->getNameSpace();
  92. Con::linkNamespaces(parent->mName, name);
  93. mNameSpace = Con::lookupNamespace(name);
  94. }
  95. Sim::getTCPGroup()->addObject(this);
  96. return true;
  97. }
  98. U32 TCPObject::onReceive(U8 *buffer, U32 bufferLen)
  99. {
  100. // we got a raw buffer event
  101. // default action is to split the buffer into lines of text
  102. // and call processLine on each
  103. // for any incomplete lines we have mBuffer
  104. U32 start = 0;
  105. parseLine(buffer, &start, bufferLen);
  106. return start;
  107. }
  108. void TCPObject::parseLine(U8 *buffer, U32 *start, U32 bufferLen)
  109. {
  110. // find the first \n in buffer
  111. U32 i;
  112. U8 *line = buffer + *start;
  113. for(i = *start; i < bufferLen; i++)
  114. if(buffer[i] == '\n' || buffer[i] == 0)
  115. break;
  116. U32 len = i - *start;
  117. if(i == bufferLen || mBuffer)
  118. {
  119. // we've hit the end with no newline
  120. mBuffer = (U8 *) dRealloc(mBuffer, mBufferSize + len + 1);
  121. dMemcpy(mBuffer + mBufferSize, line, len);
  122. mBufferSize += len;
  123. *start = i;
  124. // process the line
  125. if(i != bufferLen)
  126. {
  127. mBuffer[mBufferSize] = 0;
  128. if(mBufferSize && mBuffer[mBufferSize-1] == '\r')
  129. mBuffer[mBufferSize - 1] = 0;
  130. U8 *temp = mBuffer;
  131. mBuffer = 0;
  132. mBufferSize = 0;
  133. processLine(temp);
  134. dFree(temp);
  135. }
  136. }
  137. else if(i != bufferLen)
  138. {
  139. line[len] = 0;
  140. if(len && line[len-1] == '\r')
  141. line[len-1] = 0;
  142. processLine(line);
  143. }
  144. if(i != bufferLen)
  145. *start = i + 1;
  146. }
  147. void TCPObject::onConnectionRequest(const NetAddress *addr, U32 connectId)
  148. {
  149. char idBuf[16];
  150. char addrBuf[256];
  151. Net::addressToString(addr, addrBuf);
  152. dSprintf(idBuf, sizeof(idBuf), "%d", connectId);
  153. Con::executef(this, 3, "onConnectRequest", addrBuf, idBuf);
  154. }
  155. bool TCPObject::processLine(U8 *line)
  156. {
  157. Con::executef(this, 2, "onLine", line);
  158. return true;
  159. }
  160. void TCPObject::onDNSResolved()
  161. {
  162. mState = DNSResolved;
  163. Con::executef(this, 1, "onDNSResolved");
  164. }
  165. void TCPObject::onDNSFailed()
  166. {
  167. mState = Disconnected;
  168. Con::executef(this, 1, "onDNSFailed");
  169. }
  170. void TCPObject::onConnected()
  171. {
  172. mState = Connected;
  173. Con::executef(this, 1, "onConnected");
  174. }
  175. void TCPObject::onConnectFailed()
  176. {
  177. mState = Disconnected;
  178. Con::executef(this, 1, "onConnectFailed");
  179. }
  180. void TCPObject::finishLastLine()
  181. {
  182. if(mBufferSize)
  183. {
  184. mBuffer[mBufferSize] = 0;
  185. processLine(mBuffer);
  186. dFree(mBuffer);
  187. mBuffer = 0;
  188. mBufferSize = 0;
  189. }
  190. }
  191. void TCPObject::onDisconnect()
  192. {
  193. finishLastLine();
  194. mState = Disconnected;
  195. Con::executef(this, 1, "onDisconnect");
  196. }
  197. void TCPObject::listen(U16 port)
  198. {
  199. mState = Listening;
  200. U32 newTag = Net::openListenPort(port);
  201. addToTable(newTag);
  202. }
  203. void TCPObject::connect(const char *address)
  204. {
  205. NetSocket newTag = Net::openConnectTo(address);
  206. addToTable(newTag);
  207. }
  208. //Luma: Used to force networking to be opened before connecting... written specifically to handle GPRS/EDGE/3G situation on iPhone, but can be expanded to other platforms too
  209. void TCPObject::openAndConnect(const char *address)
  210. {
  211. #ifdef TORQUE_OS_IOS
  212. if(IsDeviceiPhone())
  213. {
  214. //on the iPhone, we need to make sure that the radio is "open" first, then call the connect CB
  215. OpeniOSNetworkingAndConnectToTCPObject(this, address);
  216. }
  217. else
  218. #endif //TORQUE_OS_IOS
  219. {
  220. //just do straight connect on non-iPhone builds for now
  221. connect(address);
  222. }
  223. }
  224. void TCPObject::disconnect()
  225. {
  226. if( mTag != InvalidSocket ) {
  227. Net::closeConnectTo(mTag);
  228. }
  229. removeFromTable();
  230. mTag = InvalidSocket;
  231. }
  232. //Luma: Encode data before sending via TCP so that only valid URL characters are sent
  233. U8 *TCPObject::URLEncodeData(U8 *pData, U32 iDataSize, U32 *piNewDataSize)
  234. {
  235. U8 szValidChars[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:/.?=_-$(){}~&";
  236. U8 *pEncodedData;
  237. U32 iCurEncodedCharacter = 0;
  238. //set initial new data size
  239. *piNewDataSize = iDataSize;
  240. //the maximum size of our encoded data is 3x the base data!
  241. pEncodedData = (U8 *)dMalloc(sizeof(U8) * iDataSize * 3);
  242. for(U32 i=0;i<iDataSize;i++)
  243. {
  244. if(!dStrchr((char *)szValidChars, pData[i]))
  245. {
  246. if(pData[i] == ' ')
  247. {
  248. //spaces become '+'
  249. pEncodedData[iCurEncodedCharacter++] = '+';
  250. }
  251. else
  252. {
  253. char szHexVal[3];
  254. dSprintf(szHexVal, 3, "%X", pData[i]);
  255. if(dStrlen(szHexVal) == 1)
  256. {
  257. //if only 1 digit was turned into text, we need to manually place the preceeding '0'
  258. szHexVal[2] = '\0';
  259. szHexVal[1] = szHexVal[0];
  260. szHexVal[0] = '0';
  261. }
  262. //invalid character... need to encode it!
  263. pEncodedData[iCurEncodedCharacter++] = '%';
  264. pEncodedData[iCurEncodedCharacter++] = szHexVal[0];
  265. pEncodedData[iCurEncodedCharacter++] = szHexVal[1];
  266. //add on 2 more to the length of the data
  267. *piNewDataSize += 2;
  268. }
  269. }
  270. else
  271. {
  272. //valid character, so leave it!
  273. pEncodedData[iCurEncodedCharacter++] = pData[i];
  274. }
  275. }
  276. return pEncodedData;
  277. }
  278. void TCPObject::send(const U8 *buffer, U32 len)
  279. {
  280. Net::sendtoSocket(mTag, buffer, S32(len));
  281. }
  282. ConsoleMethod( TCPObject, send, void, 3, 0, "( ... ) Use the send method to send any number of parameters, as strings, one at a time to the agent at the other end of the connection.\n"
  283. "@param ... Any number of arguments, as strings. Each string is sent separately. i.e. The arguments are not concatenated.\n"
  284. "@return No return value")
  285. {
  286. for(S32 i = 2; i < argc; i++)
  287. object->send((const U8 *) argv[i], dStrlen(argv[i]));
  288. }
  289. ConsoleMethod( TCPObject, listen, void, 3, 3, "( port ) Use the listen method to allow this TCPObject to accept connections on the specified port.\n"
  290. "@param port A value between 1000 and 65536.\n"
  291. "@return No return value")
  292. {
  293. object->listen(U32(dAtoi(argv[2])));
  294. }
  295. ConsoleMethod( TCPObject, connect, void, 3, 3, "( addr ) Use the connect method to request a connection to a remote agent at the address addr.\n"
  296. "@param addr A string containing an address of the form: ìA.B.C.D:Portî, where A .. B are standard IP numbers between 0 and 255 and Port can be between 1000 and 65536.\n"
  297. "@return No return value.\n"
  298. "@sa disconnect")
  299. {
  300. object->connect(argv[2]);
  301. }
  302. //Luma: Used to force networking to be opened before connecting... written specifically to handle GPRS/EDGE/3G situation on iPhone, but can be expanded to other platforms too
  303. ConsoleMethod( TCPObject, openAndConnect, void, 3, 3, "(string addr)"
  304. "Connect to the given address, making sure that the connection is open first.")
  305. {
  306. object->openAndConnect(argv[2]);
  307. }
  308. ConsoleMethod( TCPObject, disconnect, void, 2, 2, "() Use the disconnect method to close a previously opened connection without destroying the requesting TCPOpbject.\n"
  309. "This will close any open connection, but not destroy this object. Thus, the object can be used to open a new connection.\n"
  310. "@return No return value.\n"
  311. "@sa connect")
  312. {
  313. object->disconnect();
  314. }
  315. //Luma: Encode data before sending via TCP so that only valid URL characters are sent
  316. ConsoleMethod(TCPObject, URLEncodeString, const char*, 3, 3, "(string data) Performs URLEncoding on a single string.\n\n")
  317. {
  318. U8 *pEncodedString;
  319. U32 iNewBufferLen;
  320. pEncodedString = object->URLEncodeData((U8 *)argv[2], dStrlen(argv[2]) + 1, &iNewBufferLen);
  321. //copy string to return buffer
  322. char *pcReturnBuffer = Con::getReturnBuffer(iNewBufferLen);
  323. dMemcpy(pcReturnBuffer, pEncodedString, iNewBufferLen);
  324. //free encoded data pointer
  325. dFree((void *)pEncodedString);
  326. return pcReturnBuffer;
  327. }
  328. void DefaultGame::processConnectedReceiveEvent(ConnectedReceiveEvent* event )
  329. {
  330. TCPObject *tcpo = TCPObject::find(event->tag);
  331. if(!tcpo)
  332. {
  333. Con::printf("Got bad connected receive event.");
  334. return;
  335. }
  336. U32 size = U32(event->size - ConnectedReceiveEventHeaderSize);
  337. U8 *buffer = event->data;
  338. while(size)
  339. {
  340. U32 ret = tcpo->onReceive(buffer, size);
  341. AssertFatal(ret <= size, "Invalid return size");
  342. size -= ret;
  343. buffer += ret;
  344. }
  345. }
  346. void DefaultGame::processConnectedAcceptEvent( ConnectedAcceptEvent* event )
  347. {
  348. TCPObject *tcpo = TCPObject::find(event->portTag);
  349. if(!tcpo)
  350. return;
  351. tcpo->onConnectionRequest(&event->address, event->connectionTag);
  352. }
  353. void DefaultGame::processConnectedNotifyEvent( ConnectedNotifyEvent* event )
  354. {
  355. TCPObject *tcpo = TCPObject::find(event->tag);
  356. if(!tcpo)
  357. return;
  358. switch(event->state)
  359. {
  360. case ConnectedNotifyEvent::DNSResolved:
  361. tcpo->onDNSResolved();
  362. break;
  363. case ConnectedNotifyEvent::DNSFailed:
  364. tcpo->onDNSFailed();
  365. break;
  366. case ConnectedNotifyEvent::Connected:
  367. tcpo->onConnected();
  368. break;
  369. case ConnectedNotifyEvent::ConnectFailed:
  370. tcpo->onConnectFailed();
  371. break;
  372. case ConnectedNotifyEvent::Disconnected:
  373. tcpo->onDisconnect();
  374. break;
  375. }
  376. }