console_server.cpp 7.2 KB

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