console_server.cpp 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /*
  2. * Copyright (c) 2012-2020 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. #include "core/containers/array.inl"
  6. #include "core/containers/hash_map.inl"
  7. #include "core/containers/vector.inl"
  8. #include "core/json/json_object.inl"
  9. #include "core/json/sjson.h"
  10. #include "core/memory/temp_allocator.inl"
  11. #include "core/strings/dynamic_string.inl"
  12. #include "core/strings/string_id.inl"
  13. #include "core/strings/string_stream.inl"
  14. #include "device/console_server.h"
  15. namespace crown
  16. {
  17. static void console_server_command(ConsoleServer& cs, TCPSocket& client, const char* json, void* /*user_data*/)
  18. {
  19. TempAllocator4096 ta;
  20. JsonObject obj(ta);
  21. JsonArray args(ta);
  22. sjson::parse(obj, json);
  23. sjson::parse_array(args, obj["args"]);
  24. DynamicString command_name(ta);
  25. sjson::parse_string(command_name, args[0]);
  26. ConsoleServer::CommandData cmd;
  27. cmd.command_function = NULL;
  28. cmd.user_data = NULL;
  29. cmd = hash_map::get(cs._commands, command_name.to_string_id(), cmd);
  30. if (cmd.command_function != NULL)
  31. cmd.command_function(cs, client, args, cmd.user_data);
  32. }
  33. namespace console_server_internal
  34. {
  35. u32 add_client(ConsoleServer& cs, TCPSocket& socket)
  36. {
  37. const u32 id = cs._next_client_id++;
  38. ConsoleServer::Client client;
  39. client.socket = socket;
  40. client.id = id;
  41. vector::push_back(cs._clients, client);
  42. return id;
  43. }
  44. void remove_client(ConsoleServer& cs, u32 id)
  45. {
  46. const u32 last = vector::size(cs._clients) - 1;
  47. for (u32 cc = 0; cc < vector::size(cs._clients); ++cc)
  48. {
  49. if (cs._clients[cc].id == id)
  50. {
  51. cs._clients[cc].socket.close();
  52. cs._clients[cc] = cs._clients[last];
  53. vector::pop_back(cs._clients);
  54. return;
  55. }
  56. }
  57. }
  58. } // namespace console_server_internal
  59. ConsoleServer::ConsoleServer(Allocator& a)
  60. : _next_client_id(0)
  61. , _clients(a)
  62. , _messages(a)
  63. , _commands(a)
  64. {
  65. this->register_message_type("command", console_server_command, this);
  66. }
  67. void ConsoleServer::listen(u16 port, bool wait)
  68. {
  69. _server.bind(port);
  70. _server.listen(5);
  71. if (wait)
  72. {
  73. AcceptResult ar;
  74. TCPSocket client;
  75. do
  76. {
  77. ar = _server.accept(client);
  78. }
  79. while (ar.error != AcceptResult::SUCCESS);
  80. console_server_internal::add_client(*this, client);
  81. }
  82. }
  83. void ConsoleServer::shutdown()
  84. {
  85. for (u32 i = 0; i < vector::size(_clients); ++i)
  86. _clients[i].socket.close();
  87. _server.close();
  88. }
  89. void ConsoleServer::send(TCPSocket& client, const char* json)
  90. {
  91. u32 len = strlen32(json);
  92. client.write(&len, 4);
  93. client.write(json, len);
  94. }
  95. void ConsoleServer::error(TCPSocket& client, const char* msg)
  96. {
  97. TempAllocator4096 ta;
  98. StringStream ss(ta);
  99. ss << "{\"type\":\"error\",\"message\":\"" << msg << "\"}";
  100. send(client, string_stream::c_str(ss));
  101. }
  102. void ConsoleServer::log(LogSeverity::Enum sev, const char* system, const char* msg)
  103. {
  104. const char* severity_map[] = { "info", "warning", "error" };
  105. CE_STATIC_ASSERT(countof(severity_map) == LogSeverity::COUNT);
  106. TempAllocator4096 ta;
  107. StringStream ss(ta);
  108. ss << "{\"type\":\"message\",\"severity\":\"";
  109. ss << severity_map[sev];
  110. ss << "\",\"system\":\"";
  111. ss << system;
  112. ss << "\",\"message\":\"";
  113. // Sanitize msg
  114. const char* ch = msg;
  115. for (; *ch; ch++)
  116. {
  117. if (*ch == '"' || *ch == '\\')
  118. ss << "\\";
  119. ss << *ch;
  120. }
  121. ss << "\"}";
  122. send(string_stream::c_str(ss));
  123. }
  124. void ConsoleServer::send(const char* json)
  125. {
  126. for (u32 i = 0; i < vector::size(_clients); ++i)
  127. send(_clients[i].socket, json);
  128. }
  129. void ConsoleServer::update()
  130. {
  131. TCPSocket client;
  132. AcceptResult ar = _server.accept_nonblock(client);
  133. if (ar.error == AcceptResult::SUCCESS)
  134. console_server_internal::add_client(*this, client);
  135. TempAllocator256 alloc;
  136. Array<u32> to_remove(alloc);
  137. // Update all clients
  138. for (u32 i = 0; i < vector::size(_clients); ++i)
  139. {
  140. for (;;)
  141. {
  142. u32 msg_len = 0;
  143. ReadResult rr = _clients[i].socket.read_nonblock(&msg_len, 4);
  144. if (rr.error == ReadResult::WOULDBLOCK)
  145. break;
  146. if (rr.error != ReadResult::SUCCESS)
  147. {
  148. array::push_back(to_remove, _clients[i].id);
  149. break;
  150. }
  151. // Read message
  152. TempAllocator4096 ta;
  153. Array<char> msg(ta);
  154. array::resize(msg, msg_len + 1);
  155. rr = _clients[i].socket.read(array::begin(msg), msg_len);
  156. msg[msg_len] = '\0';
  157. if (rr.error != ReadResult::SUCCESS)
  158. {
  159. array::push_back(to_remove, _clients[i].id);
  160. break;
  161. }
  162. // Process message
  163. JsonObject obj(ta);
  164. sjson::parse(obj, array::begin(msg));
  165. CommandData cmd;
  166. cmd.message_function = NULL;
  167. cmd.user_data = NULL;
  168. cmd = hash_map::get(_messages
  169. , sjson::parse_string_id(obj["type"])
  170. , cmd
  171. );
  172. if (cmd.message_function)
  173. cmd.message_function(*this, _clients[i].socket, array::begin(msg), cmd.user_data);
  174. else
  175. error(_clients[i].socket, "Unknown command");
  176. }
  177. }
  178. // Remove clients
  179. for (u32 ii = 0; ii < array::size(to_remove); ++ii)
  180. console_server_internal::remove_client(*this, to_remove[ii]);
  181. }
  182. void ConsoleServer::register_command_type(const char* type, CommandTypeFunction function, void* user_data)
  183. {
  184. CE_ENSURE(NULL != type);
  185. CE_ENSURE(NULL != function);
  186. CommandData cmd;
  187. cmd.command_function = function;
  188. cmd.user_data = user_data;
  189. hash_map::set(_commands, StringId32(type), cmd);
  190. }
  191. void ConsoleServer::register_message_type(const char* type, MessageTypeFunction function, void* user_data)
  192. {
  193. CE_ENSURE(NULL != type);
  194. CE_ENSURE(NULL != function);
  195. CommandData cmd;
  196. cmd.message_function = function;
  197. cmd.user_data = user_data;
  198. hash_map::set(_messages, StringId32(type), cmd);
  199. }
  200. namespace console_server_globals
  201. {
  202. ConsoleServer* _console_server = NULL;
  203. void init()
  204. {
  205. _console_server = CE_NEW(default_allocator(), ConsoleServer)(default_allocator());
  206. }
  207. void shutdown()
  208. {
  209. _console_server->shutdown();
  210. CE_DELETE(default_allocator(), _console_server);
  211. _console_server = NULL;
  212. }
  213. } // namespace console_server_globals
  214. ConsoleServer* console_server()
  215. {
  216. return console_server_globals::_console_server;
  217. }
  218. } // namespace crown