ConsoleServer.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. void ConsoleServer::init(uint16_t port, bool wait)
  38. {
  39. m_server.open(port);
  40. m_server.listen(5);
  41. if (wait)
  42. {
  43. AcceptResult result;
  44. TCPSocket client;
  45. do
  46. {
  47. result = m_server.accept(client);
  48. }
  49. while (result.error != AcceptResult::NO_ERROR);
  50. add_client(client);
  51. }
  52. }
  53. //-----------------------------------------------------------------------------
  54. void ConsoleServer::shutdown()
  55. {
  56. for (uint32_t i = 0; i < m_clients.size(); i++)
  57. {
  58. m_clients[i].close();
  59. }
  60. m_server.close();
  61. }
  62. //-----------------------------------------------------------------------------
  63. void ConsoleServer::log_to_all(const char* message, LogSeverity::Enum severity)
  64. {
  65. using namespace string_stream;
  66. TempAllocator2048 alloc;
  67. StringStream json(alloc);
  68. static const char* severity_to_text[] = { "info", "warning", "error", "debug" };
  69. json << "{\"type\":\"message\",";
  70. json << "\"severity\":\"" << severity_to_text[severity] << "\",";
  71. char buf[1024];
  72. string::strncpy(buf, message, 1024);
  73. for (uint32_t i = 0; i < string::strlen(message); i++)
  74. {
  75. if (buf[i] == '"')
  76. buf[i] = '\'';
  77. }
  78. json << "\"message\":\"" << buf << "\"}";
  79. send_to_all(c_str(json));
  80. }
  81. //-----------------------------------------------------------------------------
  82. void ConsoleServer::send(TCPSocket client, const char* message)
  83. {
  84. uint32_t msg_len = string::strlen(message);
  85. client.write((const char*) &msg_len, 4);
  86. client.write(message, msg_len);
  87. }
  88. //-----------------------------------------------------------------------------
  89. void ConsoleServer::send_to_all(const char* message)
  90. {
  91. for (uint32_t i = 0; i < m_clients.size(); i++)
  92. {
  93. send(m_clients[i].socket, message);
  94. }
  95. }
  96. //-----------------------------------------------------------------------------
  97. void ConsoleServer::update()
  98. {
  99. // Check for new clients only if we have room for them
  100. if (m_clients.size() < CE_MAX_CONSOLE_CLIENTS - 1)
  101. {
  102. TCPSocket client;
  103. AcceptResult result = m_server.accept_nonblock(client);
  104. if (result.error == AcceptResult::NO_ERROR)
  105. {
  106. add_client(client);
  107. }
  108. }
  109. TempAllocator256 alloc;
  110. Array<Id> to_remove(alloc);
  111. // Update all clients
  112. for (uint32_t i = 0; i < m_clients.size(); i++)
  113. {
  114. ReadResult rr = update_client(m_clients[i].socket);
  115. if (rr.error != ReadResult::NO_ERROR) array::push_back(to_remove, m_clients[i].id);
  116. }
  117. // Remove clients
  118. for (uint32_t i = 0; i < array::size(to_remove); i++)
  119. {
  120. m_clients.lookup(to_remove[i]).socket.close();
  121. m_clients.destroy(to_remove[i]);
  122. }
  123. }
  124. //-----------------------------------------------------------------------------
  125. void ConsoleServer::add_client(TCPSocket socket)
  126. {
  127. Client client;
  128. client.socket = socket;
  129. Id id = m_clients.create(client);
  130. m_clients.lookup(id).id = id;
  131. }
  132. //-----------------------------------------------------------------------------
  133. ReadResult ConsoleServer::update_client(TCPSocket client)
  134. {
  135. uint32_t msg_len = 0;
  136. ReadResult rr = client.read_nonblock(&msg_len, 4);
  137. // If no data received, return
  138. if (rr.error == ReadResult::NO_ERROR && rr.bytes_read == 0) return rr;
  139. if (rr.error == ReadResult::REMOTE_CLOSED) return rr;
  140. if (rr.error != ReadResult::NO_ERROR) return rr;
  141. // Else read the message
  142. Array<char> msg_buf(default_allocator());
  143. array::resize(msg_buf, msg_len);
  144. ReadResult msg_result = client.read(array::begin(msg_buf), msg_len);
  145. array::push_back(msg_buf, '\0');
  146. if (msg_result.error == ReadResult::REMOTE_CLOSED) return msg_result;
  147. if (msg_result.error != ReadResult::NO_ERROR) return msg_result;
  148. process(client, array::begin(msg_buf));
  149. return msg_result;
  150. }
  151. //-----------------------------------------------------------------------------
  152. void ConsoleServer::process(TCPSocket client, const char* request)
  153. {
  154. JSONParser parser(request);
  155. DynamicString type;
  156. parser.root().key("type").to_string(type);
  157. // Determine request type
  158. if (type == "ping") process_ping(client, request);
  159. else if (type == "script") process_script(client, request);
  160. else if (type == "stats") process_stats(client, request);
  161. else if (type == "command") process_command(client, request);
  162. else if (type == "filesystem") processs_filesystem(client, request);
  163. else CE_FATAL("Request unknown.");
  164. }
  165. //-----------------------------------------------------------------------------
  166. void ConsoleServer::process_ping(TCPSocket client, const char* /*msg*/)
  167. {
  168. send(client, "{\"type\":\"pong\"}");
  169. }
  170. //-----------------------------------------------------------------------------
  171. void ConsoleServer::process_script(TCPSocket /*client*/, const char* msg)
  172. {
  173. JSONParser parser(msg);
  174. JSONElement root = parser.root();
  175. DynamicString script;
  176. root.key("script").to_string(script);
  177. device()->lua_environment()->execute_string(script.c_str());
  178. }
  179. //-----------------------------------------------------------------------------
  180. void ConsoleServer::process_stats(TCPSocket client, const char* /*msg*/)
  181. {
  182. using namespace string_stream;
  183. TempAllocator2048 alloc;
  184. StringStream response(alloc);
  185. response << "{\"type\":\"response\",";
  186. response << "{\"allocators\":[";
  187. // Walk all proxy allocators
  188. ProxyAllocator* proxy = ProxyAllocator::begin();
  189. while (proxy != NULL)
  190. {
  191. response << "{";
  192. response << "\"name\":\"" << proxy->name() << "\",";
  193. response << "\"allocated_size\":\"" << proxy->allocated_size() << "\"";
  194. response << "},";
  195. proxy = ProxyAllocator::next(proxy);
  196. }
  197. response << "]" << "}";
  198. send(client, c_str(response));
  199. }
  200. //-----------------------------------------------------------------------------
  201. void ConsoleServer::process_command(TCPSocket /*client*/, const char* msg)
  202. {
  203. JSONParser parser(msg);
  204. JSONElement root = parser.root();
  205. JSONElement command = root.key("command");
  206. DynamicString cmd;
  207. command.to_string(cmd);
  208. if (cmd == "reload")
  209. {
  210. JSONElement type = root.key_or_nil("resource_type");
  211. JSONElement name = root.key_or_nil("resource_name");
  212. DynamicString resource_type;
  213. DynamicString resource_name;
  214. type.to_string(resource_type);
  215. name.to_string(resource_name);
  216. char t[256];
  217. char n[256];
  218. string::strncpy(t, resource_type.c_str(), 256);
  219. string::strncpy(n, resource_name.c_str(), 256);
  220. device()->reload(t, n);
  221. }
  222. else if (cmd == "pause")
  223. {
  224. device()->pause();
  225. }
  226. else if (cmd == "unpause")
  227. {
  228. device()->unpause();
  229. }
  230. }
  231. //-----------------------------------------------------------------------------
  232. void ConsoleServer::processs_filesystem(TCPSocket client, const char* msg)
  233. {
  234. using namespace string_stream;
  235. JSONParser parser(msg);
  236. JSONElement root = parser.root();
  237. JSONElement filesystem = root.key("filesystem");
  238. DynamicString cmd;
  239. filesystem.to_string(cmd);
  240. if (cmd == "size")
  241. {
  242. DynamicString file_name;
  243. root.key("file").to_string(file_name);
  244. File* file = device()->filesystem()->open(file_name.c_str(), FOM_READ);
  245. size_t file_size = file->size();
  246. device()->filesystem()->close(file);
  247. TempAllocator64 alloc;
  248. StringStream response(alloc);
  249. response << "{\"type\":\"file\",\"size\":" << file_size << "}";
  250. send(client, c_str(response));
  251. }
  252. else if (cmd == "read")
  253. {
  254. JSONElement file_position = root.key("position");
  255. JSONElement file_size = root.key("size");
  256. DynamicString file_name;
  257. root.key("file").to_string(file_name);
  258. // Read the file data
  259. File* file = device()->filesystem()->open(file_name.c_str(), FOM_READ);
  260. char* bytes = (char*) default_allocator().allocate((size_t) file_size.to_int());
  261. file->seek((size_t) file_position.to_int());
  262. file->read(bytes, (size_t) file_size.to_int());
  263. device()->filesystem()->close(file);
  264. // Encode data to base64
  265. size_t dummy;
  266. char* bytes_encoded = math::base64_encode((unsigned char*) bytes, (size_t) file_size.to_int(), &dummy);
  267. // Send data
  268. TempAllocator4096 alloc;
  269. StringStream response(alloc);
  270. response << "{\"type\":\"file\",";
  271. response << "\"data\":\"" << bytes_encoded << "\"}";
  272. send(client, c_str(response));
  273. // Cleanup
  274. default_allocator().deallocate(bytes_encoded);
  275. default_allocator().deallocate(bytes);
  276. }
  277. }
  278. } // namespace crown