RPCServer.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include "RPCServer.h"
  24. #include "Log.h"
  25. #include "JSONParser.h"
  26. #include "RPCHandler.h"
  27. #include "TempAllocator.h"
  28. #include "StringStream.h"
  29. namespace crown
  30. {
  31. //-----------------------------------------------------------------------------
  32. RPCServer::RPCServer()
  33. : m_num_clients(0)
  34. , m_receive_allocator(default_allocator(), 16 * 1024)
  35. , m_send_allocator(default_allocator(), 16 * 1024)
  36. , m_receive_buffer(m_receive_allocator)
  37. , m_send_buffer(m_send_allocator)
  38. , m_handlers_head(NULL)
  39. , m_receive_callbacks(default_allocator())
  40. , m_send_callbacks(default_allocator())
  41. {
  42. }
  43. //-----------------------------------------------------------------------------
  44. void RPCServer::add_handler(RPCHandler* handler)
  45. {
  46. CE_ASSERT_NOT_NULL(handler);
  47. if (m_handlers_head != NULL)
  48. {
  49. handler->m_next = m_handlers_head;
  50. }
  51. m_handlers_head = handler;
  52. }
  53. //-----------------------------------------------------------------------------
  54. void RPCServer::remove_handler(RPCHandler* handler)
  55. {
  56. CE_ASSERT_NOT_NULL(handler);
  57. RPCHandler* cur = m_handlers_head;
  58. RPCHandler* prev = NULL;
  59. for (; cur != NULL && cur != handler; prev = cur, cur = cur->m_next) ;
  60. if (cur == m_handlers_head)
  61. {
  62. m_handlers_head = cur->m_next;
  63. }
  64. else
  65. {
  66. prev->m_next = cur->m_next;
  67. }
  68. }
  69. //-----------------------------------------------------------------------------
  70. void RPCServer::init(bool wait)
  71. {
  72. m_listener.open(10001);
  73. if (wait)
  74. {
  75. TCPSocket client;
  76. while (!m_listener.listen(client)) ;
  77. add_client(client);
  78. }
  79. }
  80. //-----------------------------------------------------------------------------
  81. void RPCServer::shutdown()
  82. {
  83. for (uint32_t i = 0; i < MAX_RPC_CLIENTS; i++)
  84. {
  85. m_clients[i].close();
  86. }
  87. m_listener.close();
  88. }
  89. //-----------------------------------------------------------------------------
  90. void RPCServer::update()
  91. {
  92. // Check for new clients
  93. TCPSocket client;
  94. if (m_listener.listen(client))
  95. {
  96. add_client(client);
  97. }
  98. // Update all clients
  99. for (uint32_t i = 0; i < MAX_RPC_CLIENTS; i++)
  100. {
  101. ClientId id = *(m_clients_table.begin() + i);
  102. if (id.id != INVALID_ID)
  103. {
  104. update_client(id);
  105. }
  106. }
  107. }
  108. //-----------------------------------------------------------------------------
  109. void RPCServer::log_to_all(const char* message, LogSeverity::Enum severity)
  110. {
  111. TempAllocator2048 alloc;
  112. StringStream json(alloc);
  113. static const char* severity_to_text[] = { "info", "warning", "error", "debug" };
  114. json << "{\"type\":\"message\",";
  115. json << "\"severity\":\"" << severity_to_text[severity] << "\",";
  116. char buf[1024];
  117. string::strncpy(buf, message, 1024);
  118. for (uint32_t i = 0; i < string::strlen(message); i++)
  119. {
  120. if (buf[i] == '"')
  121. buf[i] = '\'';
  122. }
  123. json << "\"message\":\"" << buf << "\"}";
  124. send_message_to_all(json.c_str());
  125. }
  126. //-----------------------------------------------------------------------------
  127. void RPCServer::send_message_to(ClientId client, const char* message)
  128. {
  129. RPCCallback cb;
  130. cb.handler = NULL;
  131. cb.client = client;
  132. cb.message_index = m_send_buffer.size();
  133. m_send_buffer.push(message, string::strlen(message));
  134. m_send_buffer.push_back('\0');
  135. m_send_callbacks.push_back(cb);
  136. }
  137. //-----------------------------------------------------------------------------
  138. void RPCServer::send_message_to_all(const char* message)
  139. {
  140. // Update all clients
  141. for (uint32_t i = 0; i < MAX_RPC_CLIENTS; i++)
  142. {
  143. ClientId id = *(m_clients_table.begin() + i);
  144. if (id.id != INVALID_ID)
  145. {
  146. send_message_to(id, message);
  147. }
  148. }
  149. }
  150. //-----------------------------------------------------------------------------
  151. void RPCServer::execute_callbacks()
  152. {
  153. for (uint32_t i = 0; i < m_receive_callbacks.size(); i++)
  154. {
  155. RPCCallback cb = m_receive_callbacks.front();
  156. m_receive_callbacks.pop_front();
  157. cb.handler->execute_command(this, cb.client, &m_receive_buffer[cb.message_index]);
  158. }
  159. m_receive_callbacks.clear();
  160. m_receive_buffer.clear();
  161. m_receive_allocator.clear();
  162. for (uint32_t i = 0; i < m_send_callbacks.size(); i++)
  163. {
  164. RPCCallback cb = m_send_callbacks.front();
  165. m_send_callbacks.pop_front();
  166. m_clients[cb.client.index].write(&m_send_buffer[cb.message_index], string::strlen(&m_send_buffer[cb.message_index]));
  167. }
  168. m_send_callbacks.clear();
  169. m_send_buffer.clear();
  170. m_send_allocator.clear();
  171. }
  172. //-----------------------------------------------------------------------------
  173. void RPCServer::update_client(ClientId id)
  174. {
  175. size_t total_read = 0;
  176. uint32_t message_index = m_receive_buffer.size();
  177. TCPSocket& client = m_clients[id.index];
  178. char buf[1024];
  179. while (true)
  180. {
  181. ReadResult result = client.read(buf, 32);
  182. if (result.error == ReadResult::NO_ERROR)
  183. {
  184. if (result.received_bytes > 0)
  185. {
  186. m_receive_buffer.push(buf, result.received_bytes);
  187. total_read += result.received_bytes;
  188. continue;
  189. }
  190. break;
  191. }
  192. else
  193. {
  194. // Close remote connection
  195. client.close();
  196. remove_client(id);
  197. return;
  198. }
  199. }
  200. // Ensure NUL-terminated
  201. m_receive_buffer.push_back('\0');
  202. // Process only if received something
  203. // TODO: Bad JSON strings crash
  204. if (total_read > 0)
  205. {
  206. JSONParser parser(&m_receive_buffer[message_index]);
  207. JSONElement root = parser.root();
  208. JSONElement type = root.key_or_nil("type");
  209. if (!type.is_nil())
  210. {
  211. RPCHandler* handler = find_handler(type.string_value());
  212. if (handler != NULL)
  213. {
  214. push_callback(handler, id, message_index);
  215. }
  216. }
  217. else
  218. {
  219. Log::d("Wrong message, type is nil");
  220. }
  221. }
  222. }
  223. //-----------------------------------------------------------------------------
  224. void RPCServer::add_client(TCPSocket& client)
  225. {
  226. if (m_num_clients < MAX_RPC_CLIENTS)
  227. {
  228. ClientId id = m_clients_table.create();
  229. m_clients[id.index] = client;
  230. m_num_clients++;
  231. }
  232. else
  233. {
  234. Log::e("Too many clients, connection denied");
  235. }
  236. }
  237. //-----------------------------------------------------------------------------
  238. void RPCServer::remove_client(ClientId id)
  239. {
  240. CE_ASSERT(m_num_clients > 0, "No client connected");
  241. m_clients[id.index].close();
  242. m_clients_table.destroy(id);
  243. m_num_clients--;
  244. }
  245. //-----------------------------------------------------------------------------
  246. RPCHandler* RPCServer::find_handler(const char* type)
  247. {
  248. const RPCHandler* handler = m_handlers_head;
  249. while (handler != NULL)
  250. {
  251. if (handler->type() == hash::murmur2_32(type, string::strlen(type), 0))
  252. {
  253. return (RPCHandler*)handler;
  254. }
  255. handler = handler->m_next;
  256. }
  257. return NULL;
  258. }
  259. //-----------------------------------------------------------------------------
  260. void RPCServer::push_callback(RPCHandler* handler, ClientId client, uint32_t message_index)
  261. {
  262. RPCCallback cb;
  263. cb.handler = handler;
  264. cb.client = client;
  265. cb.message_index = message_index;
  266. m_receive_callbacks.push_back(cb);
  267. }
  268. } // namespace crown