ConsoleServer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 "ConsoleServer.h"
  24. #include "JSONParser.h"
  25. #include "TempAllocator.h"
  26. #include "StringStream.h"
  27. #include "Log.h"
  28. #include "Device.h"
  29. #include "ProxyAllocator.h"
  30. #include "LuaEnvironment.h"
  31. #include "File.h"
  32. #include "Filesystem.h"
  33. #include "MathUtils.h"
  34. namespace crown
  35. {
  36. //-----------------------------------------------------------------------------
  37. ConsoleServer::ConsoleServer(uint16_t port)
  38. : m_port(port)
  39. , m_num_clients(0)
  40. , m_receive_buffer(default_allocator())
  41. , m_receive_callbacks(default_allocator())
  42. {
  43. }
  44. //-----------------------------------------------------------------------------
  45. void ConsoleServer::init(bool wait)
  46. {
  47. m_server.open(m_port);
  48. m_server.listen(5);
  49. if (wait)
  50. {
  51. TCPSocket client;
  52. m_server.accept(client);
  53. add_client(client);
  54. }
  55. }
  56. //-----------------------------------------------------------------------------
  57. void ConsoleServer::shutdown()
  58. {
  59. for (uint32_t i = 0; i < MAX_CONSOLE_CLIENTS; i++)
  60. {
  61. m_clients[i].close();
  62. }
  63. m_server.close();
  64. }
  65. //-----------------------------------------------------------------------------
  66. void ConsoleServer::log_to_all(const char* message, LogSeverity::Enum severity)
  67. {
  68. TempAllocator2048 alloc;
  69. StringStream json(alloc);
  70. static const char* severity_to_text[] = { "info", "warning", "error", "debug" };
  71. json << "{\"type\":\"message\",";
  72. json << "\"severity\":\"" << severity_to_text[severity] << "\",";
  73. char buf[1024];
  74. string::strncpy(buf, message, 1024);
  75. for (uint32_t i = 0; i < string::strlen(message); i++)
  76. {
  77. if (buf[i] == '"')
  78. buf[i] = '\'';
  79. }
  80. json << "\"message\":\"" << buf << "\"}";
  81. send_message_to_all(json.c_str());
  82. }
  83. //-----------------------------------------------------------------------------
  84. void ConsoleServer::send_message_to(ClientId client, const char* message)
  85. {
  86. uint32_t msg_len = string::strlen(message);
  87. m_clients[client.index].write((const char*) &msg_len, 4);
  88. m_clients[client.index].write(message, msg_len);
  89. }
  90. //-----------------------------------------------------------------------------
  91. void ConsoleServer::send_message_to_all(const char* message)
  92. {
  93. // Update all clients
  94. for (uint32_t i = 0; i < MAX_CONSOLE_CLIENTS; i++)
  95. {
  96. ClientId id = *(m_clients_table.begin() + i);
  97. if (id.id != INVALID_ID)
  98. {
  99. send_message_to(id, message);
  100. }
  101. }
  102. }
  103. //-----------------------------------------------------------------------------
  104. void ConsoleServer::update()
  105. {
  106. // Check for new clients
  107. TCPSocket client;
  108. if (m_server.accept_nonblock(client))
  109. {
  110. add_client(client);
  111. }
  112. // Update all clients
  113. for (uint32_t i = 0; i < MAX_CONSOLE_CLIENTS; i++)
  114. {
  115. ClientId id = *(m_clients_table.begin() + i);
  116. if (id.id != INVALID_ID)
  117. {
  118. update_client(id);
  119. }
  120. }
  121. // Process all requests
  122. process_requests();
  123. }
  124. //-----------------------------------------------------------------------------
  125. void ConsoleServer::process_requests()
  126. {
  127. for (uint32_t i = 0; i < m_receive_callbacks.size(); i++)
  128. {
  129. RPCCallback cb = m_receive_callbacks.front();
  130. m_receive_callbacks.pop_front();
  131. const char* request = &m_receive_buffer[cb.message_index];
  132. JSONParser parser(request);
  133. JSONElement request_type = parser.root().key("type");
  134. DynamicString type;
  135. request_type.string_value(type);
  136. // Determine request type
  137. if (type == "ping") process_ping(cb.client, request);
  138. else if (type == "script") process_script(cb.client, request);
  139. else if (type == "stats") process_stats(cb.client, request);
  140. else if (type == "command") process_command(cb.client, request);
  141. else if (type == "filesystem") processs_filesystem(cb.client, request);
  142. else continue;
  143. }
  144. m_receive_callbacks.clear();
  145. m_receive_buffer.clear();
  146. }
  147. //-----------------------------------------------------------------------------
  148. void ConsoleServer::update_client(ClientId id)
  149. {
  150. TCPSocket& client = m_clients[id.index];
  151. uint32_t msg_len = 0;
  152. ReadResult rr = client.read_nonblock(&msg_len, 4);
  153. // If no data received, return
  154. if (rr.error == ReadResult::NO_ERROR && rr.bytes_read == 0) return;
  155. if (rr.error == ReadResult::REMOTE_CLOSED)
  156. {
  157. remove_client(id);
  158. return;
  159. }
  160. // Else read the message
  161. List<char> msg_buf(default_allocator());
  162. msg_buf.resize(msg_len);
  163. ReadResult msg_result = client.read(msg_buf.begin(), msg_len);
  164. uint32_t message_index = m_receive_buffer.size();
  165. m_receive_buffer.push(msg_buf.begin(), msg_result.bytes_read);
  166. m_receive_buffer.push_back('\0');
  167. add_request(id, message_index);
  168. }
  169. //-----------------------------------------------------------------------------
  170. void ConsoleServer::add_client(TCPSocket& client)
  171. {
  172. if (m_num_clients < MAX_CONSOLE_CLIENTS)
  173. {
  174. ClientId id = m_clients_table.create();
  175. m_clients[id.index] = client;
  176. m_num_clients++;
  177. }
  178. else
  179. {
  180. Log::e("Too many clients, connection denied");
  181. }
  182. }
  183. //-----------------------------------------------------------------------------
  184. void ConsoleServer::remove_client(ClientId id)
  185. {
  186. CE_ASSERT(m_num_clients > 0, "No client connected");
  187. m_clients[id.index].close();
  188. m_clients_table.destroy(id);
  189. m_num_clients--;
  190. }
  191. //-----------------------------------------------------------------------------
  192. void ConsoleServer::add_request(ClientId client, uint32_t message_index)
  193. {
  194. RPCCallback cb;
  195. cb.client = client;
  196. cb.message_index = message_index;
  197. m_receive_callbacks.push_back(cb);
  198. }
  199. //-----------------------------------------------------------------------------
  200. void ConsoleServer::process_ping(ClientId client, const char* /*msg*/)
  201. {
  202. send_message_to(client, "{\"type\":\"pong\"}");
  203. }
  204. //-----------------------------------------------------------------------------
  205. void ConsoleServer::process_script(ClientId /*client*/, const char* msg)
  206. {
  207. JSONParser parser(msg);
  208. JSONElement root = parser.root();
  209. DynamicString script;
  210. root.key("script").string_value(script);
  211. device()->lua_environment()->execute_string(script.c_str());
  212. }
  213. //-----------------------------------------------------------------------------
  214. void ConsoleServer::process_stats(ClientId client, const char* /*msg*/)
  215. {
  216. TempAllocator2048 alloc;
  217. StringStream response(alloc);
  218. response << "{\"type\":\"response\",";
  219. response << "{\"allocators\":[";
  220. // Walk all proxy allocators
  221. ProxyAllocator* proxy = ProxyAllocator::begin();
  222. while (proxy != NULL)
  223. {
  224. response << "{";
  225. response << "\"name\":\"" << proxy->name() << "\",";
  226. response << "\"allocated_size\":\"" << proxy->allocated_size() << "\"";
  227. response << "},";
  228. proxy = ProxyAllocator::next(proxy);
  229. }
  230. response << "]" << "}";
  231. send_message_to(client, response.c_str());
  232. }
  233. //-----------------------------------------------------------------------------
  234. void ConsoleServer::process_command(ClientId /*client*/, const char* msg)
  235. {
  236. JSONParser parser(msg);
  237. JSONElement root = parser.root();
  238. JSONElement command = root.key("command");
  239. DynamicString cmd;
  240. command.string_value(cmd);
  241. if (cmd == "reload")
  242. {
  243. JSONElement type = root.key_or_nil("resource_type");
  244. JSONElement name = root.key_or_nil("resource_name");
  245. DynamicString resource_type;
  246. DynamicString resource_name;
  247. type.string_value(resource_type);
  248. name.string_value(resource_name);
  249. char t[256];
  250. char n[256];
  251. string::strncpy(t, resource_type.c_str(), 256);
  252. string::strncpy(n, resource_name.c_str(), 256);
  253. device()->reload(t, n);
  254. }
  255. else if (cmd == "pause")
  256. {
  257. device()->pause();
  258. }
  259. else if (cmd == "unpause")
  260. {
  261. device()->unpause();
  262. }
  263. }
  264. //-----------------------------------------------------------------------------
  265. void ConsoleServer::processs_filesystem(ClientId client, const char* msg)
  266. {
  267. JSONParser parser(msg);
  268. JSONElement root = parser.root();
  269. JSONElement filesystem = root.key("filesystem");
  270. DynamicString cmd;
  271. filesystem.string_value(cmd);
  272. if (cmd == "size")
  273. {
  274. DynamicString file_name;
  275. root.key("file").string_value(file_name);
  276. File* file = device()->filesystem()->open(file_name.c_str(), FOM_READ);
  277. size_t file_size = file->size();
  278. device()->filesystem()->close(file);
  279. TempAllocator64 alloc;
  280. StringStream response(alloc);
  281. response << "{\"type\":\"file\",\"size\":" << file_size << "}";
  282. send_message_to(client, response.c_str());
  283. }
  284. else if (cmd == "read")
  285. {
  286. JSONElement file_position = root.key("position");
  287. JSONElement file_size = root.key("size");
  288. DynamicString file_name;
  289. root.key("file").string_value(file_name);
  290. // Read the file data
  291. File* file = device()->filesystem()->open(file_name.c_str(), FOM_READ);
  292. char* bytes = (char*) default_allocator().allocate((size_t) file_size.int_value());
  293. file->seek((size_t) file_position.int_value());
  294. file->read(bytes, (size_t) file_size.int_value());
  295. device()->filesystem()->close(file);
  296. // Encode data to base64
  297. size_t dummy;
  298. char* bytes_encoded = math::base64_encode((unsigned char*) bytes, (size_t) file_size.int_value(), &dummy);
  299. // Send data
  300. TempAllocator4096 alloc;
  301. StringStream response(alloc);
  302. response << "{\"type\":\"file\",";
  303. response << "\"data\":\"" << bytes_encoded << "\"}";
  304. send_message_to(client, response.c_str());
  305. // Cleanup
  306. default_allocator().deallocate(bytes_encoded);
  307. default_allocator().deallocate(bytes);
  308. }
  309. }
  310. } // namespace crown