console_server.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Copyright (c) 2012-2021 Daniele Bartolini et al.
  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/filesystem/file_buffer.inl"
  9. #include "core/filesystem/reader_writer.inl"
  10. #include "core/json/json_object.inl"
  11. #include "core/json/sjson.h"
  12. #include "core/memory/temp_allocator.inl"
  13. #include "core/network/ip_address.h"
  14. #include "core/strings/dynamic_string.inl"
  15. #include "core/strings/string_id.inl"
  16. #include "core/strings/string_stream.inl"
  17. #include "core/thread/scoped_mutex.inl"
  18. #include "device/console_server.h"
  19. #include "device/log.h"
  20. LOG_SYSTEM(CONSOLE_SERVER, "console_server")
  21. namespace crown
  22. {
  23. namespace console_server_internal
  24. {
  25. static void message_command(ConsoleServer& cs, u32 client_id, const char* json, void* /*user_data*/)
  26. {
  27. TempAllocator4096 ta;
  28. JsonObject obj(ta);
  29. JsonArray args(ta);
  30. sjson::parse(obj, json);
  31. sjson::parse_array(args, obj["args"]);
  32. DynamicString command_name(ta);
  33. sjson::parse_string(command_name, args[0]);
  34. ConsoleServer::CommandData cmd;
  35. cmd.command_function = NULL;
  36. cmd.user_data = NULL;
  37. cmd = hash_map::get(cs._commands, command_name.to_string_id(), cmd);
  38. if (cmd.command_function != NULL)
  39. cmd.command_function(cs, client_id, args, cmd.user_data);
  40. }
  41. static void command_help(ConsoleServer& cs, u32 client_id, JsonArray& args, void* /*user_data*/)
  42. {
  43. if (array::size(args) != 1)
  44. {
  45. cs.error(client_id, "Usage: help");
  46. return;
  47. }
  48. u32 longest = 0;
  49. auto cur = hash_map::begin(cs._commands);
  50. auto end = hash_map::end(cs._commands);
  51. for (; cur != end; ++cur)
  52. {
  53. HASH_MAP_SKIP_HOLE(cs._commands, cur);
  54. if (longest < strlen32(cur->second.name))
  55. longest = strlen32(cur->second.name);
  56. }
  57. cur = hash_map::begin(cs._commands);
  58. end = hash_map::end(cs._commands);
  59. for (; cur != end; ++cur)
  60. {
  61. HASH_MAP_SKIP_HOLE(cs._commands, cur);
  62. logi(CONSOLE_SERVER, "%s%*s%s"
  63. , cur->second.name
  64. , longest - strlen32(cur->second.name) + 2
  65. , " "
  66. , cur->second.brief
  67. );
  68. }
  69. }
  70. static u32 add_client(ConsoleServer& cs, const TCPSocket& socket)
  71. {
  72. ScopedMutex scoped_mutex(cs._clients_mutex);
  73. ConsoleServer::Client client;
  74. client.socket = socket;
  75. client.id = cs._next_client_id++;
  76. vector::push_back(cs._clients, client);
  77. return client.id;
  78. }
  79. static void remove_client_by_socket(ConsoleServer& cs, const TCPSocket& socket)
  80. {
  81. ScopedMutex scoped_mutex(cs._clients_mutex);
  82. const u32 last = vector::size(cs._clients) - 1;
  83. for (u32 cc = 0; cc < vector::size(cs._clients); ++cc)
  84. {
  85. if (cs._clients[cc].socket == socket)
  86. {
  87. cs._clients[cc] = cs._clients[last];
  88. vector::pop_back(cs._clients);
  89. return;
  90. }
  91. }
  92. }
  93. static u32 get_client_id(ConsoleServer& cs, const TCPSocket& socket)
  94. {
  95. ScopedMutex scoped_mutex(cs._clients_mutex);
  96. const u32 num_clients = vector::size(cs._clients);
  97. for (u32 cc = 0; cc < num_clients; ++cc)
  98. {
  99. if (cs._clients[cc].socket == socket)
  100. return cs._clients[cc].id;
  101. }
  102. return UINT32_MAX;
  103. }
  104. static bool get_socket_by_id(TCPSocket* socket, ConsoleServer& cs, u32 id)
  105. {
  106. ScopedMutex scoped_mutex(cs._clients_mutex);
  107. const u32 num_clients = vector::size(cs._clients);
  108. for (u32 cc = 0; cc < num_clients; ++cc)
  109. {
  110. if (cs._clients[cc].id == id)
  111. {
  112. *socket = cs._clients[cc].socket;
  113. return true;
  114. }
  115. }
  116. return false;
  117. }
  118. } // namespace console_server_internal
  119. ConsoleServer::ConsoleServer(Allocator& a)
  120. : _port(UINT16_MAX)
  121. , _next_client_id(0)
  122. , _clients(a)
  123. , _messages(a)
  124. , _commands(a)
  125. , _thread_exit(false)
  126. , _input_0(a)
  127. , _input_1(a)
  128. , _input_write(&_input_0)
  129. , _input_read(&_input_1)
  130. , _output_0(a)
  131. , _output_1(a)
  132. , _output_write(&_output_0)
  133. , _output_read(&_output_1)
  134. {
  135. this->register_message_type("command", console_server_internal::message_command, this);
  136. this->register_command_name("help", "List all commands", console_server_internal::command_help, this);
  137. }
  138. void ConsoleServer::listen(u16 port, bool wait)
  139. {
  140. const BindResult br = _server.bind(port);
  141. if (br.error != BindResult::SUCCESS)
  142. return;
  143. _port = port;
  144. _server.listen(5);
  145. _active_socket_set.set(&_server);
  146. _input_thread.start([](void* thiz) { return ((ConsoleServer*)thiz)->run_input_thread(); }, this);
  147. _output_thread.start([](void* thiz) { return ((ConsoleServer*)thiz)->run_output_thread(); }, this);
  148. if (wait)
  149. _client_connected.wait();
  150. }
  151. void ConsoleServer::shutdown()
  152. {
  153. _thread_exit = true;
  154. if (_input_thread.is_running())
  155. {
  156. // Unlock input thread if it is stuck waiting for _handlers_semaphore.
  157. execute_message_handlers(false);
  158. // Unlock input thread if it is stuck inside the select().
  159. TCPSocket dummy;
  160. dummy.connect(IP_ADDRESS_LOOPBACK, _port);
  161. _input_thread.stop();
  162. dummy.close();
  163. }
  164. _output_condition.signal();
  165. if (_output_thread.is_running())
  166. _output_thread.stop();
  167. ScopedMutex scoped_mutex(_clients_mutex);
  168. for (u32 i = 0; i < vector::size(_clients); ++i)
  169. _clients[i].socket.close();
  170. _server.close();
  171. }
  172. void ConsoleServer::send(u32 client_id, const char* json)
  173. {
  174. TCPSocket socket;
  175. if (!console_server_internal::get_socket_by_id(&socket, *this, client_id))
  176. return;
  177. const u32 msg_len = strlen32(json);
  178. _output_mutex.lock();
  179. FileBuffer fb(*_output_write);
  180. fb.seek_to_end();
  181. BinaryWriter bw(fb);
  182. bw.write(client_id);
  183. bw.write(msg_len);
  184. bw.write(json, msg_len);
  185. _output_condition.signal();
  186. _output_mutex.unlock();
  187. }
  188. void ConsoleServer::error(u32 client_id, const char* msg)
  189. {
  190. TempAllocator4096 ta;
  191. StringStream ss(ta);
  192. ss << "{\"type\":\"error\",\"message\":\"" << msg << "\"}";
  193. send(client_id, string_stream::c_str(ss));
  194. }
  195. void ConsoleServer::broadcast(const char* json)
  196. {
  197. for (u32 i = 0; i < vector::size(_clients); ++i)
  198. send(_clients[i].id, json);
  199. }
  200. void ConsoleServer::execute_message_handlers(bool sync)
  201. {
  202. bool locked = true;
  203. if (sync)
  204. _input_semaphore.wait();
  205. else
  206. locked = _input_semaphore.try_wait();
  207. if (!locked)
  208. return;
  209. Buffer* temp = _input_read;
  210. _input_read = _input_write;
  211. _input_write = temp;
  212. _handlers_semaphore.post();
  213. // Do not execute message handlers at exit, because when _thread_exit is
  214. // set by shutdown(), handlers may reference stale objects.
  215. if (_thread_exit)
  216. return;
  217. FileBuffer fb(*_input_read);
  218. BinaryReader br(fb);
  219. while (!fb.end_of_file())
  220. {
  221. // Read client, message size and message.
  222. u32 client_id;
  223. u32 msg_len;
  224. br.read(client_id);
  225. br.read(msg_len);
  226. const char* msg = array::begin(*_input_read) + fb.position();
  227. br.skip(msg_len);
  228. // Process message.
  229. JsonObject obj(default_allocator());
  230. sjson::parse(obj, msg);
  231. if (!json_object::has(obj, "type"))
  232. {
  233. error(client_id, "Missing command type");
  234. continue;
  235. }
  236. // Find handler for the message type.
  237. CommandData cmd;
  238. cmd.message_function = NULL;
  239. cmd.user_data = NULL;
  240. cmd = hash_map::get(_messages
  241. , sjson::parse_string_id(obj["type"])
  242. , cmd
  243. );
  244. if (!cmd.message_function)
  245. {
  246. error(client_id, "Unknown command type");
  247. continue;
  248. }
  249. // Call the handler.
  250. cmd.message_function(*this, client_id, msg, cmd.user_data);
  251. }
  252. array::clear(*_input_read);
  253. }
  254. void ConsoleServer::register_command_name(const char* name, const char* brief, CommandTypeFunction function, void* user_data)
  255. {
  256. CE_ENSURE(NULL != name);
  257. CE_ENSURE(NULL != brief);
  258. CE_ENSURE(NULL != function);
  259. CommandData cmd;
  260. cmd.command_function = function;
  261. cmd.user_data = user_data;
  262. strncpy(cmd.name, name, sizeof(cmd.name)-1);
  263. strncpy(cmd.brief, brief, sizeof(cmd.brief)-1);
  264. hash_map::set(_commands, StringId32(name), cmd);
  265. }
  266. void ConsoleServer::register_message_type(const char* type, MessageTypeFunction function, void* user_data)
  267. {
  268. CE_ENSURE(NULL != type);
  269. CE_ENSURE(NULL != function);
  270. CommandData cmd;
  271. cmd.message_function = function;
  272. cmd.user_data = user_data;
  273. hash_map::set(_messages, StringId32(type), cmd);
  274. }
  275. s32 ConsoleServer::run_input_thread()
  276. {
  277. while (!_thread_exit)
  278. {
  279. // Wait for input from one of the sockets in _active_socket_set.
  280. _read_socket_set = _active_socket_set;
  281. SelectResult ret = _read_socket_set.select(UINT32_MAX);
  282. if (ret.error == SelectResult::GENERIC_ERROR)
  283. {
  284. return -1;
  285. }
  286. else if (ret.error == SelectResult::TIMEOUT)
  287. {
  288. continue;
  289. }
  290. FileBuffer fb(*_input_write);
  291. BinaryWriter bw(fb);
  292. // Read data from all clients that are ready.
  293. const u32 num_sockets = _read_socket_set.num();
  294. for (u32 ii = 0; ii < num_sockets; ++ii)
  295. {
  296. TCPSocket cur_socket = _read_socket_set.get(ii);
  297. // Skip if socket is not ready for reading.
  298. if (_read_socket_set.isset(&cur_socket) == false)
  299. continue;
  300. // If ready socket is the one listening for incoming connections.
  301. if (cur_socket == _server)
  302. {
  303. if (_thread_exit)
  304. break;
  305. // Accept the incoming connection.
  306. TCPSocket client;
  307. AcceptResult ar = _server.accept_nonblock(client);
  308. if (ar.error == AcceptResult::SUCCESS)
  309. {
  310. console_server_internal::add_client(*this, client);
  311. _active_socket_set.set(&client);
  312. _client_connected.post();
  313. }
  314. }
  315. else // Check if any other socket is ready for reading.
  316. {
  317. u32 msg_len = 0;
  318. ReadResult rr = cur_socket.read(&msg_len, 4);
  319. if (rr.error != ReadResult::SUCCESS)
  320. {
  321. console_server_internal::remove_client_by_socket(*this, cur_socket);
  322. _active_socket_set.clr(&cur_socket);
  323. cur_socket.close();
  324. continue;
  325. }
  326. const u32 client_id = console_server_internal::get_client_id(*this, cur_socket);
  327. // Add client header and message length.
  328. bw.write(client_id);
  329. bw.write(msg_len);
  330. // Read message.
  331. u32 num_read;
  332. for (num_read = 0; num_read < msg_len;)
  333. {
  334. char buf[4096];
  335. const u32 num_pending = min(u32(sizeof(buf)), msg_len - num_read);
  336. rr = cur_socket.read(buf, num_pending);
  337. if (rr.error != ReadResult::SUCCESS)
  338. {
  339. console_server_internal::remove_client_by_socket(*this, cur_socket);
  340. _active_socket_set.clr(&cur_socket);
  341. cur_socket.close();
  342. break;
  343. }
  344. bw.write(buf, rr.bytes_read);
  345. num_read += rr.bytes_read;
  346. }
  347. if (num_read != msg_len)
  348. {
  349. // Remove partial data that has been written to the input buffer.
  350. for (u32 cc = 0; cc < 4 + 4 + num_read; ++cc)
  351. array::pop_back(*_input_write);
  352. }
  353. }
  354. }
  355. if (array::size(*_input_write) > 0)
  356. {
  357. _input_semaphore.post();
  358. _handlers_semaphore.wait();
  359. }
  360. }
  361. return 0;
  362. }
  363. s32 ConsoleServer::run_output_thread()
  364. {
  365. while (1)
  366. {
  367. _output_mutex.lock();
  368. while (array::size(*_output_write) == 0 && !_thread_exit)
  369. _output_condition.wait(_output_mutex);
  370. if (_thread_exit)
  371. {
  372. _output_mutex.unlock();
  373. break;
  374. }
  375. Buffer* temp = _output_read;
  376. _output_read = _output_write;
  377. _output_write = temp;
  378. _output_mutex.unlock();
  379. FileBuffer fb(*_output_read);
  380. BinaryReader br(fb);
  381. while (!fb.end_of_file())
  382. {
  383. // Read client, message size and message.
  384. u32 client_id;
  385. u32 msg_len;
  386. br.read(client_id);
  387. br.read(msg_len);
  388. const char* msg = array::begin(*_output_read) + fb.position();
  389. br.skip(msg_len);
  390. // Lookup socket by its ID.
  391. TCPSocket socket;
  392. if (console_server_internal::get_socket_by_id(&socket, *this, client_id) != true)
  393. continue;
  394. socket.write(msg-4, msg_len+4);
  395. }
  396. array::clear(*_output_read);
  397. }
  398. return 0;
  399. }
  400. namespace console_server_globals
  401. {
  402. ConsoleServer* _console_server = NULL;
  403. void init()
  404. {
  405. _console_server = CE_NEW(default_allocator(), ConsoleServer)(default_allocator());
  406. }
  407. void shutdown()
  408. {
  409. _console_server->shutdown();
  410. CE_DELETE(default_allocator(), _console_server);
  411. _console_server = NULL;
  412. }
  413. } // namespace console_server_globals
  414. ConsoleServer* console_server()
  415. {
  416. return console_server_globals::_console_server;
  417. }
  418. } // namespace crown