tcpObject.cc 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. #include "tcpObject_ScriptBinding.h"
  33. TCPObject *TCPObject::table[TCPObject::TableSize] = {0, };
  34. IMPLEMENT_CONOBJECT(TCPObject);
  35. TCPObject *TCPObject::find(NetSocket tag)
  36. {
  37. for(TCPObject *walk = table[U32(tag) & TableMask]; walk; walk = walk->mNext)
  38. if(walk->mTag == tag)
  39. return walk;
  40. return NULL;
  41. }
  42. void TCPObject::addToTable(NetSocket newTag)
  43. {
  44. removeFromTable();
  45. mTag = newTag;
  46. mNext = table[U32(mTag) & TableMask];
  47. table[U32(mTag) & TableMask] = this;
  48. }
  49. void TCPObject::removeFromTable()
  50. {
  51. for(TCPObject **walk = &table[U32(mTag) & TableMask]; *walk; walk = &((*walk)->mNext))
  52. {
  53. if(*walk == this)
  54. {
  55. *walk = mNext;
  56. return;
  57. }
  58. }
  59. }
  60. TCPObject::TCPObject()
  61. {
  62. mBuffer = NULL;
  63. mBufferSize = 0;
  64. mPort = 0;
  65. mTag = InvalidSocket;
  66. mNext = NULL;
  67. mState = Disconnected;
  68. }
  69. TCPObject::~TCPObject()
  70. {
  71. disconnect();
  72. dFree(mBuffer);
  73. }
  74. bool TCPObject::processArguments(S32 argc, const char **argv)
  75. {
  76. if(argc == 0)
  77. return true;
  78. else if(argc == 1)
  79. {
  80. addToTable(U32(dAtoi(argv[0])));
  81. return true;
  82. }
  83. return false;
  84. }
  85. bool TCPObject::onAdd()
  86. {
  87. if(!Parent::onAdd())
  88. return false;
  89. const char *name = getName();
  90. if(name && name[0] && getClassRep())
  91. {
  92. Namespace *parent = getClassRep()->getNameSpace();
  93. Con::linkNamespaces(parent->mName, name);
  94. mNameSpace = Con::lookupNamespace(name);
  95. }
  96. Sim::getTCPGroup()->addObject(this);
  97. return true;
  98. }
  99. U32 TCPObject::onReceive(U8 *buffer, U32 bufferLen)
  100. {
  101. // we got a raw buffer event
  102. // default action is to split the buffer into lines of text
  103. // and call processLine on each
  104. // for any incomplete lines we have mBuffer
  105. U32 start = 0;
  106. parseLine(buffer, &start, bufferLen);
  107. return start;
  108. }
  109. void TCPObject::parseLine(U8 *buffer, U32 *start, U32 bufferLen)
  110. {
  111. // find the first \n in buffer
  112. U32 i;
  113. U8 *line = buffer + *start;
  114. for(i = *start; i < bufferLen; i++)
  115. if(buffer[i] == '\n' || buffer[i] == 0)
  116. break;
  117. U32 len = i - *start;
  118. if(i == bufferLen || mBuffer)
  119. {
  120. // we've hit the end with no newline
  121. mBuffer = (U8 *) dRealloc(mBuffer, mBufferSize + len + 1);
  122. dMemcpy(mBuffer + mBufferSize, line, len);
  123. mBufferSize += len;
  124. *start = i;
  125. // process the line
  126. if(i != bufferLen)
  127. {
  128. mBuffer[mBufferSize] = 0;
  129. if(mBufferSize && mBuffer[mBufferSize-1] == '\r')
  130. mBuffer[mBufferSize - 1] = 0;
  131. U8 *temp = mBuffer;
  132. mBuffer = 0;
  133. mBufferSize = 0;
  134. processLine(temp);
  135. dFree(temp);
  136. }
  137. }
  138. else if(i != bufferLen)
  139. {
  140. line[len] = 0;
  141. if(len && line[len-1] == '\r')
  142. line[len-1] = 0;
  143. processLine(line);
  144. }
  145. if(i != bufferLen)
  146. *start = i + 1;
  147. }
  148. void TCPObject::onConnectionRequest(const NetAddress *addr, U32 connectId)
  149. {
  150. char idBuf[16];
  151. char addrBuf[256];
  152. Net::addressToString(addr, addrBuf);
  153. dSprintf(idBuf, sizeof(idBuf), "%d", connectId);
  154. Con::executef(this, 3, "onConnectRequest", addrBuf, idBuf);
  155. }
  156. bool TCPObject::processLine(U8 *line)
  157. {
  158. Con::executef(this, 2, "onLine", line);
  159. return true;
  160. }
  161. void TCPObject::onDNSResolved()
  162. {
  163. mState = DNSResolved;
  164. Con::executef(this, 1, "onDNSResolved");
  165. }
  166. void TCPObject::onDNSFailed()
  167. {
  168. mState = Disconnected;
  169. Con::executef(this, 1, "onDNSFailed");
  170. }
  171. void TCPObject::onConnected()
  172. {
  173. mState = Connected;
  174. Con::executef(this, 1, "onConnected");
  175. }
  176. void TCPObject::onConnectFailed()
  177. {
  178. mState = Disconnected;
  179. Con::executef(this, 1, "onConnectFailed");
  180. }
  181. void TCPObject::finishLastLine()
  182. {
  183. if(mBufferSize)
  184. {
  185. mBuffer[mBufferSize] = 0;
  186. processLine(mBuffer);
  187. dFree(mBuffer);
  188. mBuffer = 0;
  189. mBufferSize = 0;
  190. }
  191. }
  192. void TCPObject::onDisconnect()
  193. {
  194. finishLastLine();
  195. mState = Disconnected;
  196. Con::executef(this, 1, "onDisconnect");
  197. }
  198. void TCPObject::listen(U16 port)
  199. {
  200. mState = Listening;
  201. U32 newTag = Net::openListenPort(port);
  202. addToTable(newTag);
  203. }
  204. void TCPObject::connect(const char *address)
  205. {
  206. NetSocket newTag = Net::openConnectTo(address);
  207. addToTable(newTag);
  208. }
  209. //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
  210. void TCPObject::openAndConnect(const char *address)
  211. {
  212. #ifdef TORQUE_OS_IOS
  213. if(IsDeviceiPhone())
  214. {
  215. //on the iPhone, we need to make sure that the radio is "open" first, then call the connect CB
  216. OpeniOSNetworkingAndConnectToTCPObject(this, address);
  217. }
  218. else
  219. #endif //TORQUE_OS_IOS
  220. {
  221. //just do straight connect on non-iPhone builds for now
  222. connect(address);
  223. }
  224. }
  225. void TCPObject::disconnect()
  226. {
  227. if( mTag != InvalidSocket ) {
  228. Net::closeConnectTo(mTag);
  229. }
  230. removeFromTable();
  231. mTag = InvalidSocket;
  232. }
  233. //Luma: Encode data before sending via TCP so that only valid URL characters are sent
  234. U8 *TCPObject::URLEncodeData(U8 *pData, U32 iDataSize, U32 *piNewDataSize)
  235. {
  236. U8 szValidChars[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:/.?=_-$(){}~&";
  237. U8 *pEncodedData;
  238. U32 iCurEncodedCharacter = 0;
  239. //set initial new data size
  240. *piNewDataSize = iDataSize;
  241. //the maximum size of our encoded data is 3x the base data!
  242. pEncodedData = (U8 *)dMalloc(sizeof(U8) * iDataSize * 3);
  243. for(U32 i=0;i<iDataSize;i++)
  244. {
  245. if(!dStrchr((char *)szValidChars, pData[i]))
  246. {
  247. if(pData[i] == ' ')
  248. {
  249. //spaces become '+'
  250. pEncodedData[iCurEncodedCharacter++] = '+';
  251. }
  252. else
  253. {
  254. char szHexVal[3];
  255. dSprintf(szHexVal, 3, "%X", pData[i]);
  256. if(dStrlen(szHexVal) == 1)
  257. {
  258. //if only 1 digit was turned into text, we need to manually place the preceeding '0'
  259. szHexVal[2] = '\0';
  260. szHexVal[1] = szHexVal[0];
  261. szHexVal[0] = '0';
  262. }
  263. //invalid character... need to encode it!
  264. pEncodedData[iCurEncodedCharacter++] = '%';
  265. pEncodedData[iCurEncodedCharacter++] = szHexVal[0];
  266. pEncodedData[iCurEncodedCharacter++] = szHexVal[1];
  267. //add on 2 more to the length of the data
  268. *piNewDataSize += 2;
  269. }
  270. }
  271. else
  272. {
  273. //valid character, so leave it!
  274. pEncodedData[iCurEncodedCharacter++] = pData[i];
  275. }
  276. }
  277. return pEncodedData;
  278. }
  279. void TCPObject::send(const U8 *buffer, U32 len)
  280. {
  281. Net::sendtoSocket(mTag, buffer, S32(len));
  282. }
  283. void DefaultGame::processConnectedReceiveEvent(ConnectedReceiveEvent* event )
  284. {
  285. TCPObject *tcpo = TCPObject::find(event->tag);
  286. if(!tcpo)
  287. {
  288. Con::printf("Got bad connected receive event.");
  289. return;
  290. }
  291. U32 size = U32(event->size - ConnectedReceiveEventHeaderSize);
  292. U8 *buffer = event->data;
  293. while(size)
  294. {
  295. U32 ret = tcpo->onReceive(buffer, size);
  296. AssertFatal(ret <= size, "Invalid return size");
  297. size -= ret;
  298. buffer += ret;
  299. }
  300. }
  301. void DefaultGame::processConnectedAcceptEvent( ConnectedAcceptEvent* event )
  302. {
  303. TCPObject *tcpo = TCPObject::find(event->portTag);
  304. if(!tcpo)
  305. return;
  306. tcpo->onConnectionRequest(&event->address, event->connectionTag);
  307. }
  308. void DefaultGame::processConnectedNotifyEvent( ConnectedNotifyEvent* event )
  309. {
  310. TCPObject *tcpo = TCPObject::find(event->tag);
  311. if(!tcpo)
  312. return;
  313. switch(event->state)
  314. {
  315. case ConnectedNotifyEvent::DNSResolved:
  316. tcpo->onDNSResolved();
  317. break;
  318. case ConnectedNotifyEvent::DNSFailed:
  319. tcpo->onDNSFailed();
  320. break;
  321. case ConnectedNotifyEvent::Connected:
  322. tcpo->onConnected();
  323. break;
  324. case ConnectedNotifyEvent::ConnectFailed:
  325. tcpo->onConnectFailed();
  326. break;
  327. case ConnectedNotifyEvent::Disconnected:
  328. tcpo->onDisconnect();
  329. break;
  330. }
  331. }