console_server.cpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 CE_FATAL("Request unknown.");
  147. }
  148. void ConsoleServer::process_ping(TCPSocket client, const char* /*msg*/)
  149. {
  150. send(client, "{\"type\":\"pong\"}");
  151. }
  152. void ConsoleServer::process_script(TCPSocket /*client*/, const char* msg)
  153. {
  154. JSONParser parser(msg);
  155. JSONElement root = parser.root();
  156. DynamicString script;
  157. root.key("script").to_string(script);
  158. device()->lua_environment()->execute_string(script.c_str());
  159. }
  160. void ConsoleServer::process_command(TCPSocket /*client*/, const char* msg)
  161. {
  162. JSONParser parser(msg);
  163. JSONElement root = parser.root();
  164. JSONElement command = root.key("command");
  165. DynamicString cmd;
  166. command.to_string(cmd);
  167. if (cmd == "reload")
  168. {
  169. JSONElement type = root.key_or_nil("resource_type");
  170. JSONElement name = root.key_or_nil("resource_name");
  171. DynamicString resource_type;
  172. DynamicString resource_name;
  173. type.to_string(resource_type);
  174. name.to_string(resource_name);
  175. char t[256];
  176. char n[256];
  177. strncpy(t, resource_type.c_str(), 256);
  178. strncpy(n, resource_name.c_str(), 256);
  179. device()->reload(t, n);
  180. }
  181. else if (cmd == "pause")
  182. {
  183. device()->pause();
  184. }
  185. else if (cmd == "unpause")
  186. {
  187. device()->unpause();
  188. }
  189. }
  190. namespace console_server_globals
  191. {
  192. char _buffer[sizeof(ConsoleServer)];
  193. ConsoleServer* _console = NULL;
  194. void init(uint16_t port, bool wait)
  195. {
  196. _console = new (_buffer) ConsoleServer(port, wait);
  197. }
  198. void shutdown()
  199. {
  200. _console->~ConsoleServer();
  201. _console = NULL;
  202. }
  203. void update()
  204. {
  205. #if defined(CROWN_DEBUG)
  206. _console->update();
  207. #endif // defined(CROWN_DEBUG)
  208. }
  209. ConsoleServer& console()
  210. {
  211. return *_console;
  212. }
  213. } // namespace console_server
  214. } // namespace crown