RPCServer.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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_buffer(default_allocator())
  35. , m_send_buffer(default_allocator())
  36. , m_handlers_head(NULL)
  37. , m_receive_callbacks(default_allocator())
  38. , m_send_callbacks(default_allocator())
  39. {
  40. }
  41. //-----------------------------------------------------------------------------
  42. void RPCServer::add_handler(RPCHandler* handler)
  43. {
  44. CE_ASSERT_NOT_NULL(handler);
  45. if (m_handlers_head != NULL)
  46. {
  47. handler->m_next = m_handlers_head;
  48. }
  49. m_handlers_head = handler;
  50. }
  51. //-----------------------------------------------------------------------------
  52. void RPCServer::remove_handler(RPCHandler* handler)
  53. {
  54. CE_ASSERT_NOT_NULL(handler);
  55. RPCHandler* cur = m_handlers_head;
  56. RPCHandler* prev = NULL;
  57. for (; cur != NULL && cur != handler; prev = cur, cur = cur->m_next) ;
  58. if (cur == m_handlers_head)
  59. {
  60. m_handlers_head = cur->m_next;
  61. }
  62. else
  63. {
  64. prev->m_next = cur->m_next;
  65. }
  66. }
  67. //-----------------------------------------------------------------------------
  68. void RPCServer::init(bool wait)
  69. {
  70. m_listener.open(10001);
  71. if (wait)
  72. {
  73. TCPSocket client;
  74. while (!m_listener.listen(client)) ;
  75. add_client(client);
  76. }
  77. }
  78. //-----------------------------------------------------------------------------
  79. void RPCServer::shutdown()
  80. {
  81. for (uint32_t i = 0; i < MAX_RPC_CLIENTS; i++)
  82. {
  83. m_clients[i].close();
  84. }
  85. m_listener.close();
  86. }
  87. //-----------------------------------------------------------------------------
  88. void RPCServer::update()
  89. {
  90. // Check for new clients
  91. TCPSocket client;
  92. if (m_listener.listen(client))
  93. {
  94. add_client(client);
  95. }
  96. // Update all clients
  97. for (uint32_t i = 0; i < MAX_RPC_CLIENTS; i++)
  98. {
  99. ClientId id = *(m_clients_table.begin() + i);
  100. if (id.id != INVALID_ID)
  101. {
  102. update_client(id);
  103. }
  104. }
  105. }
  106. //-----------------------------------------------------------------------------
  107. void RPCServer::log_to_all(const char* message, LogSeverity::Enum severity)
  108. {
  109. TempAllocator2048 alloc;
  110. StringStream json(alloc);
  111. static const char* severity_to_text[] = { "info", "warning", "error", "debug" };
  112. json << "{\"type\":\"message\",";
  113. json << "\"severity\":\"" << severity_to_text[severity] << "\",";
  114. char buf[1024];
  115. string::strncpy(buf, message, 1024);
  116. for (uint32_t i = 0; i < string::strlen(message); i++)
  117. {
  118. if (buf[i] == '"')
  119. buf[i] = '\'';
  120. }
  121. json << "\"message\":\"" << buf << "\"}";
  122. send_message_to_all(json.c_str());
  123. }
  124. //-----------------------------------------------------------------------------
  125. void RPCServer::send_message_to(ClientId client, const char* message)
  126. {
  127. RPCCallback cb;
  128. cb.handler = NULL;
  129. cb.client = client;
  130. cb.message_index = m_send_buffer.size();
  131. m_send_buffer.push(message, string::strlen(message));
  132. m_send_buffer.push_back('\0');
  133. m_send_callbacks.push_back(cb);
  134. }
  135. //-----------------------------------------------------------------------------
  136. void RPCServer::send_message_to_all(const char* message)
  137. {
  138. // Update all clients
  139. for (uint32_t i = 0; i < MAX_RPC_CLIENTS; i++)
  140. {
  141. ClientId id = *(m_clients_table.begin() + i);
  142. if (id.id != INVALID_ID)
  143. {
  144. send_message_to(id, message);
  145. }
  146. }
  147. }
  148. //-----------------------------------------------------------------------------
  149. void RPCServer::execute_callbacks()
  150. {
  151. for (uint32_t i = 0; i < m_receive_callbacks.size(); i++)
  152. {
  153. RPCCallback cb = m_receive_callbacks.front();
  154. m_receive_callbacks.pop_front();
  155. cb.handler->execute_command(this, cb.client, &m_receive_buffer[cb.message_index]);
  156. }
  157. m_receive_callbacks.clear();
  158. m_receive_buffer.clear();
  159. for (uint32_t i = 0; i < m_send_callbacks.size(); i++)
  160. {
  161. RPCCallback cb = m_send_callbacks.front();
  162. m_send_callbacks.pop_front();
  163. m_clients[cb.client.index].write(&m_send_buffer[cb.message_index], string::strlen(&m_send_buffer[cb.message_index]));
  164. }
  165. m_send_callbacks.clear();
  166. m_send_buffer.clear();
  167. }
  168. //-----------------------------------------------------------------------------
  169. void RPCServer::update_client(ClientId id)
  170. {
  171. size_t total_read = 0;
  172. uint32_t message_index = m_receive_buffer.size();
  173. TCPSocket& client = m_clients[id.index];
  174. char buf[1024];
  175. while (true)
  176. {
  177. ReadResult result = client.read(buf, 32);
  178. if (result.error == ReadResult::NO_ERROR)
  179. {
  180. if (result.received_bytes > 0)
  181. {
  182. for (uint32_t i = 0; i < result.received_bytes; i++)
  183. {
  184. printf("%c", buf[i]);
  185. }
  186. printf("\n");
  187. m_receive_buffer.push(buf, result.received_bytes);
  188. total_read += result.received_bytes;
  189. continue;
  190. }
  191. break;
  192. }
  193. else
  194. {
  195. // Close remote connection
  196. client.close();
  197. remove_client(id);
  198. return;
  199. }
  200. }
  201. // Ensure NUL-terminated
  202. m_receive_buffer.push_back('\0');
  203. // Process only if received something
  204. // TODO: Bad JSON strings crash
  205. if (total_read > 0)
  206. {
  207. JSONParser parser(&m_receive_buffer[message_index]);
  208. Log::d("%s", &m_receive_buffer[message_index]);
  209. JSONElement root = parser.root();
  210. JSONElement type = root.key_or_nil("type");
  211. if (!type.is_nil())
  212. {
  213. RPCHandler* handler = find_handler(type.string_value());
  214. if (handler != NULL)
  215. {
  216. push_callback(handler, id, message_index);
  217. }
  218. }
  219. else
  220. {
  221. Log::d("Wrong message, type is nil");
  222. }
  223. }
  224. }
  225. //-----------------------------------------------------------------------------
  226. void RPCServer::add_client(TCPSocket& client)
  227. {
  228. if (m_num_clients < MAX_RPC_CLIENTS)
  229. {
  230. ClientId id = m_clients_table.create();
  231. m_clients[id.index] = client;
  232. m_num_clients++;
  233. }
  234. else
  235. {
  236. Log::e("Too many clients, connection denied");
  237. }
  238. }
  239. //-----------------------------------------------------------------------------
  240. void RPCServer::remove_client(ClientId id)
  241. {
  242. CE_ASSERT(m_num_clients > 0, "No client connected");
  243. m_clients[id.index].close();
  244. m_clients_table.destroy(id);
  245. m_num_clients--;
  246. }
  247. //-----------------------------------------------------------------------------
  248. RPCHandler* RPCServer::find_handler(const char* type)
  249. {
  250. const RPCHandler* handler = m_handlers_head;
  251. while (handler != NULL)
  252. {
  253. if (handler->type() == hash::murmur2_32(type, string::strlen(type), 0))
  254. {
  255. return (RPCHandler*)handler;
  256. }
  257. handler = handler->m_next;
  258. }
  259. return NULL;
  260. }
  261. //-----------------------------------------------------------------------------
  262. void RPCServer::push_callback(RPCHandler* handler, ClientId client, uint32_t message_index)
  263. {
  264. RPCCallback cb;
  265. cb.handler = handler;
  266. cb.client = client;
  267. cb.message_index = message_index;
  268. m_receive_callbacks.push_back(cb);
  269. }
  270. } // namespace crown