console_server.cpp 9.4 KB

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