console_server.cpp 8.4 KB

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