console_server.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 == "command") process_command(client, request);
  159. else if (type == "filesystem") processs_filesystem(client, request);
  160. else CE_FATAL("Request unknown.");
  161. }
  162. void ConsoleServer::process_ping(TCPSocket client, const char* /*msg*/)
  163. {
  164. send(client, "{\"type\":\"pong\"}");
  165. }
  166. void ConsoleServer::process_script(TCPSocket /*client*/, const char* msg)
  167. {
  168. JSONParser parser(msg);
  169. JSONElement root = parser.root();
  170. DynamicString script;
  171. root.key("script").to_string(script);
  172. device()->lua_environment()->execute_string(script.c_str());
  173. }
  174. void ConsoleServer::process_command(TCPSocket /*client*/, const char* msg)
  175. {
  176. JSONParser parser(msg);
  177. JSONElement root = parser.root();
  178. JSONElement command = root.key("command");
  179. DynamicString cmd;
  180. command.to_string(cmd);
  181. if (cmd == "reload")
  182. {
  183. JSONElement type = root.key_or_nil("resource_type");
  184. JSONElement name = root.key_or_nil("resource_name");
  185. DynamicString resource_type;
  186. DynamicString resource_name;
  187. type.to_string(resource_type);
  188. name.to_string(resource_name);
  189. char t[256];
  190. char n[256];
  191. strncpy(t, resource_type.c_str(), 256);
  192. strncpy(n, resource_name.c_str(), 256);
  193. device()->reload(t, n);
  194. }
  195. else if (cmd == "pause")
  196. {
  197. device()->pause();
  198. }
  199. else if (cmd == "unpause")
  200. {
  201. device()->unpause();
  202. }
  203. }
  204. void ConsoleServer::processs_filesystem(TCPSocket client, const char* msg)
  205. {
  206. /*
  207. using namespace string_stream;
  208. JSONParser parser(msg);
  209. JSONElement root = parser.root();
  210. JSONElement filesystem = root.key("filesystem");
  211. DynamicString cmd;
  212. filesystem.to_string(cmd);
  213. if (cmd == "size")
  214. {
  215. DynamicString file_name;
  216. root.key("file").to_string(file_name);
  217. File* file = crown::filesystem()->open(file_name.c_str(), FOM_READ);
  218. size_t file_size = file->size();
  219. crown::filesystem()->close(file);
  220. TempAllocator64 alloc;
  221. StringStream response(alloc);
  222. response << "{\"type\":\"file\",\"size\":" << file_size << "}";
  223. send(client, c_str(response));
  224. }
  225. else if (cmd == "read")
  226. {
  227. JSONElement file_position = root.key("position");
  228. JSONElement file_size = root.key("size");
  229. DynamicString file_name;
  230. root.key("file").to_string(file_name);
  231. // Read the file data
  232. File* file = crown::filesystem()->open(file_name.c_str(), FOM_READ);
  233. char* bytes = (char*) default_allocator().allocate((size_t) file_size.to_int());
  234. file->seek((size_t) file_position.to_int());
  235. file->read(bytes, (size_t) file_size.to_int());
  236. crown::filesystem()->close(file);
  237. // Encode data to base64
  238. size_t dummy;
  239. char* bytes_encoded = base64_encode((unsigned char*) bytes, (size_t) file_size.to_int(), &dummy);
  240. // Send data
  241. TempAllocator4096 alloc;
  242. StringStream response(alloc);
  243. response << "{\"type\":\"file\",";
  244. response << "\"data\":\"" << bytes_encoded << "\"}";
  245. send(client, c_str(response));
  246. // Cleanup
  247. default_allocator().deallocate(bytes_encoded);
  248. default_allocator().deallocate(bytes);
  249. }
  250. */
  251. }
  252. namespace console_server_globals
  253. {
  254. char _buffer[sizeof(ConsoleServer)];
  255. ConsoleServer* _console = NULL;
  256. void init(uint16_t port, bool wait)
  257. {
  258. _console = new (_buffer) ConsoleServer(port, wait);
  259. }
  260. void shutdown()
  261. {
  262. _console->~ConsoleServer();
  263. _console = NULL;
  264. }
  265. void update()
  266. {
  267. #if defined(CROWN_DEBUG)
  268. _console->update();
  269. #endif // defined(CROWN_DEBUG)
  270. }
  271. ConsoleServer& console()
  272. {
  273. return *_console;
  274. }
  275. } // namespace console_server
  276. } // namespace crown