rpc.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. #include "rpc_i.h"
  2. #include <pb.h>
  3. #include <pb_decode.h>
  4. #include <pb_encode.h>
  5. #include <status.pb.h>
  6. #include <storage.pb.h>
  7. #include <flipper.pb.h>
  8. #include <cmsis_os.h>
  9. #include <cmsis_os2.h>
  10. #include <portmacro.h>
  11. #include <furi.h>
  12. #include <cli/cli.h>
  13. #include <stdint.h>
  14. #include <stdio.h>
  15. #include <stream_buffer.h>
  16. #include <m-string.h>
  17. #include <m-dict.h>
  18. #define TAG "RpcSrv"
  19. #define RPC_EVENT_NEW_DATA (1 << 0)
  20. #define RPC_EVENT_DISCONNECT (1 << 1)
  21. #define RPC_EVENTS_ALL (RPC_EVENT_DISCONNECT | RPC_EVENT_NEW_DATA)
  22. DICT_DEF2(RpcHandlerDict, pb_size_t, M_DEFAULT_OPLIST, RpcHandler, M_POD_OPLIST)
  23. typedef struct {
  24. RpcSystemAlloc alloc;
  25. RpcSystemFree free;
  26. void* context;
  27. } RpcSystemCallbacks;
  28. static RpcSystemCallbacks rpc_systems[] = {
  29. {
  30. .alloc = rpc_system_status_alloc,
  31. .free = NULL,
  32. },
  33. {
  34. .alloc = rpc_system_storage_alloc,
  35. .free = rpc_system_storage_free,
  36. },
  37. {
  38. .alloc = rpc_system_app_alloc,
  39. .free = NULL,
  40. },
  41. {
  42. .alloc = rpc_system_gui_alloc,
  43. .free = rpc_system_gui_free,
  44. },
  45. };
  46. struct RpcSession {
  47. RpcSendBytesCallback send_bytes_callback;
  48. RpcBufferIsEmptyCallback buffer_is_empty_callback;
  49. RpcSessionClosedCallback closed_callback;
  50. void* context;
  51. osMutexId_t callbacks_mutex;
  52. Rpc* rpc;
  53. bool terminate;
  54. void** system_contexts;
  55. };
  56. struct Rpc {
  57. bool busy;
  58. osMutexId_t busy_mutex;
  59. RpcSession session;
  60. osEventFlagsId_t events;
  61. StreamBufferHandle_t stream;
  62. RpcHandlerDict_t handlers;
  63. PB_Main* decoded_message;
  64. };
  65. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg);
  66. static void rpc_close_session_process(const PB_Main* msg_request, void* context) {
  67. furi_assert(msg_request);
  68. furi_assert(context);
  69. Rpc* rpc = context;
  70. rpc_send_and_release_empty(rpc, msg_request->command_id, PB_CommandStatus_OK);
  71. osMutexAcquire(rpc->session.callbacks_mutex, osWaitForever);
  72. if(rpc->session.closed_callback) {
  73. rpc->session.closed_callback(rpc->session.context);
  74. }
  75. osMutexRelease(rpc->session.callbacks_mutex);
  76. }
  77. static size_t rpc_sprintf_msg_file(
  78. string_t str,
  79. const char* prefix,
  80. const PB_Storage_File* msg_file,
  81. size_t msg_files_size) {
  82. size_t cnt = 0;
  83. for(int i = 0; i < msg_files_size; ++i, ++msg_file) {
  84. string_cat_printf(
  85. str,
  86. "%s[%c] size: %5ld",
  87. prefix,
  88. msg_file->type == PB_Storage_File_FileType_DIR ? 'd' : 'f',
  89. msg_file->size);
  90. if(msg_file->name) {
  91. string_cat_printf(str, " \'%s\'", msg_file->name);
  92. }
  93. if(msg_file->data && msg_file->data->size) {
  94. string_cat_printf(
  95. str,
  96. " (%d):\'%.*s%s\'",
  97. msg_file->data->size,
  98. MIN(msg_file->data->size, 30),
  99. msg_file->data->bytes,
  100. msg_file->data->size > 30 ? "..." : "");
  101. }
  102. string_cat_printf(str, "\r\n");
  103. }
  104. return cnt;
  105. }
  106. void rpc_print_data(const char* prefix, uint8_t* buffer, size_t size) {
  107. string_t str;
  108. string_init(str);
  109. string_reserve(str, 100 + size * 5);
  110. string_cat_printf(str, "\r\n%s DEC(%d): {", prefix, size);
  111. for(int i = 0; i < size; ++i) {
  112. string_cat_printf(str, "%d, ", buffer[i]);
  113. }
  114. string_cat_printf(str, "}\r\n");
  115. printf("%s", string_get_cstr(str));
  116. string_reset(str);
  117. string_reserve(str, 100 + size * 3);
  118. string_cat_printf(str, "%s HEX(%d): {", prefix, size);
  119. for(int i = 0; i < size; ++i) {
  120. string_cat_printf(str, "%02X", buffer[i]);
  121. }
  122. string_cat_printf(str, "}\r\n\r\n");
  123. printf("%s", string_get_cstr(str));
  124. string_clear(str);
  125. }
  126. void rpc_print_message(const PB_Main* message) {
  127. string_t str;
  128. string_init(str);
  129. string_cat_printf(
  130. str,
  131. "PB_Main: {\r\n\tresult: %d cmd_id: %ld (%s)\r\n",
  132. message->command_status,
  133. message->command_id,
  134. message->has_next ? "has_next" : "last");
  135. switch(message->which_content) {
  136. default:
  137. /* not implemented yet */
  138. string_cat_printf(str, "\tNOT_IMPLEMENTED (%d) {\r\n", message->which_content);
  139. break;
  140. case PB_Main_stop_session_tag:
  141. string_cat_printf(str, "\tstop_session {\r\n");
  142. break;
  143. case PB_Main_app_start_request_tag: {
  144. string_cat_printf(str, "\tapp_start {\r\n");
  145. const char* name = message->content.app_start_request.name;
  146. const char* args = message->content.app_start_request.args;
  147. if(name) {
  148. string_cat_printf(str, "\t\tname: %s\r\n", name);
  149. }
  150. if(args) {
  151. string_cat_printf(str, "\t\targs: %s\r\n", args);
  152. }
  153. break;
  154. }
  155. case PB_Main_app_lock_status_request_tag: {
  156. string_cat_printf(str, "\tapp_lock_status_request {\r\n");
  157. break;
  158. }
  159. case PB_Main_app_lock_status_response_tag: {
  160. string_cat_printf(str, "\tapp_lock_status_response {\r\n");
  161. bool lock_status = message->content.app_lock_status_response.locked;
  162. string_cat_printf(str, "\t\tlocked: %s\r\n", lock_status ? "true" : "false");
  163. break;
  164. }
  165. case PB_Main_storage_md5sum_request_tag: {
  166. string_cat_printf(str, "\tmd5sum_request {\r\n");
  167. const char* path = message->content.storage_md5sum_request.path;
  168. if(path) {
  169. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  170. }
  171. break;
  172. }
  173. case PB_Main_storage_md5sum_response_tag: {
  174. string_cat_printf(str, "\tmd5sum_response {\r\n");
  175. const char* path = message->content.storage_md5sum_response.md5sum;
  176. if(path) {
  177. string_cat_printf(str, "\t\tmd5sum: %s\r\n", path);
  178. }
  179. break;
  180. }
  181. case PB_Main_ping_request_tag:
  182. string_cat_printf(str, "\tping_request {\r\n");
  183. break;
  184. case PB_Main_ping_response_tag:
  185. string_cat_printf(str, "\tping_response {\r\n");
  186. break;
  187. case PB_Main_storage_mkdir_request_tag:
  188. string_cat_printf(str, "\tmkdir {\r\n");
  189. break;
  190. case PB_Main_storage_delete_request_tag: {
  191. string_cat_printf(str, "\tdelete {\r\n");
  192. const char* path = message->content.storage_delete_request.path;
  193. if(path) {
  194. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  195. }
  196. break;
  197. }
  198. case PB_Main_empty_tag:
  199. string_cat_printf(str, "\tempty {\r\n");
  200. break;
  201. case PB_Main_storage_list_request_tag: {
  202. string_cat_printf(str, "\tlist_request {\r\n");
  203. const char* path = message->content.storage_list_request.path;
  204. if(path) {
  205. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  206. }
  207. break;
  208. }
  209. case PB_Main_storage_read_request_tag: {
  210. string_cat_printf(str, "\tread_request {\r\n");
  211. const char* path = message->content.storage_read_request.path;
  212. if(path) {
  213. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  214. }
  215. break;
  216. }
  217. case PB_Main_storage_write_request_tag: {
  218. string_cat_printf(str, "\twrite_request {\r\n");
  219. const char* path = message->content.storage_write_request.path;
  220. if(path) {
  221. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  222. }
  223. if(message->content.storage_write_request.has_file) {
  224. const PB_Storage_File* msg_file = &message->content.storage_write_request.file;
  225. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  226. }
  227. break;
  228. }
  229. case PB_Main_storage_read_response_tag:
  230. string_cat_printf(str, "\tread_response {\r\n");
  231. if(message->content.storage_read_response.has_file) {
  232. const PB_Storage_File* msg_file = &message->content.storage_read_response.file;
  233. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  234. }
  235. break;
  236. case PB_Main_storage_list_response_tag: {
  237. const PB_Storage_File* msg_file = message->content.storage_list_response.file;
  238. size_t msg_file_count = message->content.storage_list_response.file_count;
  239. string_cat_printf(str, "\tlist_response {\r\n");
  240. rpc_sprintf_msg_file(str, "\t\t", msg_file, msg_file_count);
  241. break;
  242. }
  243. case PB_Main_gui_start_screen_stream_request_tag:
  244. string_cat_printf(str, "\tstart_screen_stream {\r\n");
  245. break;
  246. case PB_Main_gui_stop_screen_stream_request_tag:
  247. string_cat_printf(str, "\tstop_screen_stream {\r\n");
  248. break;
  249. case PB_Main_gui_screen_frame_tag:
  250. string_cat_printf(str, "\tscreen_frame {\r\n");
  251. break;
  252. case PB_Main_gui_send_input_event_request_tag:
  253. string_cat_printf(str, "\tsend_input_event {\r\n");
  254. string_cat_printf(
  255. str, "\t\tkey: %d\r\n", message->content.gui_send_input_event_request.key);
  256. string_cat_printf(
  257. str, "\t\type: %d\r\n", message->content.gui_send_input_event_request.type);
  258. break;
  259. case PB_Main_gui_start_virtual_display_request_tag:
  260. string_cat_printf(str, "\tstart_virtual_display {\r\n");
  261. break;
  262. case PB_Main_gui_stop_virtual_display_request_tag:
  263. string_cat_printf(str, "\tstop_virtual_display {\r\n");
  264. break;
  265. }
  266. string_cat_printf(str, "\t}\r\n}\r\n");
  267. printf("%s", string_get_cstr(str));
  268. string_clear(str);
  269. }
  270. static Rpc* rpc_alloc(void) {
  271. Rpc* rpc = furi_alloc(sizeof(Rpc));
  272. rpc->busy_mutex = osMutexNew(NULL);
  273. rpc->busy = false;
  274. rpc->events = osEventFlagsNew(NULL);
  275. rpc->stream = xStreamBufferCreate(RPC_BUFFER_SIZE, 1);
  276. rpc->decoded_message = furi_alloc(sizeof(PB_Main));
  277. rpc->decoded_message->cb_content.funcs.decode = content_callback;
  278. rpc->decoded_message->cb_content.arg = rpc;
  279. RpcHandlerDict_init(rpc->handlers);
  280. return rpc;
  281. }
  282. RpcSession* rpc_session_open(Rpc* rpc) {
  283. furi_assert(rpc);
  284. bool result = false;
  285. furi_check(osMutexAcquire(rpc->busy_mutex, osWaitForever) == osOK);
  286. if(rpc->busy) {
  287. result = false;
  288. } else {
  289. rpc->busy = true;
  290. result = true;
  291. }
  292. furi_check(osMutexRelease(rpc->busy_mutex) == osOK);
  293. if(result) {
  294. RpcSession* session = &rpc->session;
  295. session->callbacks_mutex = osMutexNew(NULL);
  296. session->rpc = rpc;
  297. session->terminate = false;
  298. xStreamBufferReset(rpc->stream);
  299. session->system_contexts = furi_alloc(COUNT_OF(rpc_systems) * sizeof(void*));
  300. for(int i = 0; i < COUNT_OF(rpc_systems); ++i) {
  301. session->system_contexts[i] = rpc_systems[i].alloc(rpc);
  302. }
  303. RpcHandler rpc_handler = {
  304. .message_handler = rpc_close_session_process,
  305. .decode_submessage = NULL,
  306. .context = rpc,
  307. };
  308. rpc_add_handler(rpc, PB_Main_stop_session_tag, &rpc_handler);
  309. FURI_LOG_D(TAG, "Session started\r\n");
  310. }
  311. return result ? &rpc->session : NULL; /* support 1 open session for now */
  312. }
  313. void rpc_session_close(RpcSession* session) {
  314. furi_assert(session);
  315. furi_assert(session->rpc);
  316. furi_assert(session->rpc->busy);
  317. rpc_session_set_send_bytes_callback(session, NULL);
  318. rpc_session_set_close_callback(session, NULL);
  319. rpc_session_set_buffer_is_empty_callback(session, NULL);
  320. osEventFlagsSet(session->rpc->events, RPC_EVENT_DISCONNECT);
  321. }
  322. static void rpc_free_session(RpcSession* session) {
  323. furi_assert(session);
  324. for(int i = 0; i < COUNT_OF(rpc_systems); ++i) {
  325. if(rpc_systems[i].free) {
  326. rpc_systems[i].free(session->system_contexts[i]);
  327. }
  328. }
  329. free(session->system_contexts);
  330. osMutexDelete(session->callbacks_mutex);
  331. RpcHandlerDict_reset(session->rpc->handlers);
  332. session->context = NULL;
  333. session->closed_callback = NULL;
  334. session->send_bytes_callback = NULL;
  335. session->buffer_is_empty_callback = NULL;
  336. }
  337. void rpc_session_set_context(RpcSession* session, void* context) {
  338. furi_assert(session);
  339. furi_assert(session->rpc);
  340. furi_assert(session->rpc->busy);
  341. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  342. session->context = context;
  343. osMutexRelease(session->callbacks_mutex);
  344. }
  345. void rpc_session_set_close_callback(RpcSession* session, RpcSessionClosedCallback callback) {
  346. furi_assert(session);
  347. furi_assert(session->rpc);
  348. furi_assert(session->rpc->busy);
  349. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  350. session->closed_callback = callback;
  351. osMutexRelease(session->callbacks_mutex);
  352. }
  353. void rpc_session_set_send_bytes_callback(RpcSession* session, RpcSendBytesCallback callback) {
  354. furi_assert(session);
  355. furi_assert(session->rpc);
  356. furi_assert(session->rpc->busy);
  357. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  358. session->send_bytes_callback = callback;
  359. osMutexRelease(session->callbacks_mutex);
  360. }
  361. void rpc_session_set_buffer_is_empty_callback(
  362. RpcSession* session,
  363. RpcBufferIsEmptyCallback callback) {
  364. furi_assert(session);
  365. furi_assert(session->rpc->busy);
  366. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  367. session->buffer_is_empty_callback = callback;
  368. osMutexRelease(session->callbacks_mutex);
  369. }
  370. /* Doesn't forbid using rpc_feed_bytes() after session close - it's safe.
  371. * Because any bytes received in buffer will be flushed before next session.
  372. * If bytes get into stream buffer before it's get epmtified and this
  373. * command is gets processed - it's safe either. But case of it is quite
  374. * odd: client sends close request and sends command after.
  375. */
  376. size_t
  377. rpc_session_feed(RpcSession* session, uint8_t* encoded_bytes, size_t size, TickType_t timeout) {
  378. furi_assert(session);
  379. Rpc* rpc = session->rpc;
  380. furi_assert(rpc->busy);
  381. size_t bytes_sent = xStreamBufferSend(rpc->stream, encoded_bytes, size, timeout);
  382. osEventFlagsSet(rpc->events, RPC_EVENT_NEW_DATA);
  383. return bytes_sent;
  384. }
  385. size_t rpc_session_get_available_size(RpcSession* session) {
  386. furi_assert(session);
  387. Rpc* rpc = session->rpc;
  388. return xStreamBufferSpacesAvailable(rpc->stream);
  389. }
  390. bool rpc_pb_stream_read(pb_istream_t* istream, pb_byte_t* buf, size_t count) {
  391. Rpc* rpc = istream->state;
  392. uint32_t flags = 0;
  393. size_t bytes_received = 0;
  394. furi_assert(istream->bytes_left);
  395. while(1) {
  396. bytes_received +=
  397. xStreamBufferReceive(rpc->stream, buf + bytes_received, count - bytes_received, 0);
  398. if(xStreamBufferIsEmpty(rpc->stream)) {
  399. if(rpc->session.buffer_is_empty_callback) {
  400. rpc->session.buffer_is_empty_callback(rpc->session.context);
  401. }
  402. }
  403. if(count == bytes_received) {
  404. break;
  405. } else {
  406. flags = osEventFlagsWait(rpc->events, RPC_EVENTS_ALL, 0, osWaitForever);
  407. if(flags & RPC_EVENT_DISCONNECT) {
  408. if(xStreamBufferIsEmpty(rpc->stream)) {
  409. rpc->session.terminate = true;
  410. istream->bytes_left = 0;
  411. bytes_received = 0;
  412. break;
  413. } else {
  414. /* Save disconnect flag and continue reading buffer */
  415. osEventFlagsSet(rpc->events, RPC_EVENT_DISCONNECT);
  416. }
  417. }
  418. }
  419. }
  420. #if SRV_RPC_DEBUG
  421. rpc_print_data("INPUT", buf, bytes_received);
  422. #endif
  423. return (count == bytes_received);
  424. }
  425. void rpc_send_and_release(Rpc* rpc, PB_Main* message) {
  426. furi_assert(rpc);
  427. furi_assert(message);
  428. RpcSession* session = &rpc->session;
  429. pb_ostream_t ostream = PB_OSTREAM_SIZING;
  430. #if SRV_RPC_DEBUG
  431. FURI_LOG_I(TAG, "OUTPUT:");
  432. rpc_print_message(message);
  433. #endif
  434. bool result = pb_encode_ex(&ostream, &PB_Main_msg, message, PB_ENCODE_DELIMITED);
  435. furi_check(result && ostream.bytes_written);
  436. uint8_t* buffer = furi_alloc(ostream.bytes_written);
  437. ostream = pb_ostream_from_buffer(buffer, ostream.bytes_written);
  438. pb_encode_ex(&ostream, &PB_Main_msg, message, PB_ENCODE_DELIMITED);
  439. #if SRV_RPC_DEBUG
  440. rpc_print_data("OUTPUT", buffer, ostream.bytes_written);
  441. #endif
  442. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  443. if(session->send_bytes_callback) {
  444. session->send_bytes_callback(session->context, buffer, ostream.bytes_written);
  445. }
  446. osMutexRelease(session->callbacks_mutex);
  447. free(buffer);
  448. pb_release(&PB_Main_msg, message);
  449. }
  450. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg) {
  451. furi_assert(stream);
  452. Rpc* rpc = *arg;
  453. RpcHandler* handler = RpcHandlerDict_get(rpc->handlers, field->tag);
  454. if(handler && handler->decode_submessage) {
  455. handler->decode_submessage(stream, field, arg);
  456. }
  457. return true;
  458. }
  459. int32_t rpc_srv(void* p) {
  460. Rpc* rpc = rpc_alloc();
  461. furi_record_create("rpc", rpc);
  462. Cli* cli = furi_record_open("cli");
  463. cli_add_command(
  464. cli, "start_rpc_session", CliCommandFlagParallelSafe, rpc_cli_command_start_session, rpc);
  465. while(1) {
  466. pb_istream_t istream = {
  467. .callback = rpc_pb_stream_read,
  468. .state = rpc,
  469. .errmsg = NULL,
  470. .bytes_left = RPC_MAX_MESSAGE_SIZE, /* max incoming message size */
  471. };
  472. if(pb_decode_ex(&istream, &PB_Main_msg, rpc->decoded_message, PB_DECODE_DELIMITED)) {
  473. #if SRV_RPC_DEBUG
  474. FURI_LOG_I(TAG, "INPUT:");
  475. rpc_print_message(rpc->decoded_message);
  476. #endif
  477. RpcHandler* handler =
  478. RpcHandlerDict_get(rpc->handlers, rpc->decoded_message->which_content);
  479. if(handler && handler->message_handler) {
  480. handler->message_handler(rpc->decoded_message, handler->context);
  481. } else if(!handler && !rpc->session.terminate) {
  482. FURI_LOG_E(TAG, "Unhandled message, tag: %d", rpc->decoded_message->which_content);
  483. }
  484. } else {
  485. xStreamBufferReset(rpc->stream);
  486. if(!rpc->session.terminate) {
  487. FURI_LOG_E(TAG, "Decode failed, error: \'%.128s\'", PB_GET_ERROR(&istream));
  488. }
  489. }
  490. pb_release(&PB_Main_msg, rpc->decoded_message);
  491. if(rpc->session.terminate) {
  492. FURI_LOG_D(TAG, "Session terminated");
  493. osEventFlagsClear(rpc->events, RPC_EVENTS_ALL);
  494. rpc_free_session(&rpc->session);
  495. rpc->busy = false;
  496. }
  497. }
  498. return 0;
  499. }
  500. void rpc_add_handler(Rpc* rpc, pb_size_t message_tag, RpcHandler* handler) {
  501. furi_assert(RpcHandlerDict_get(rpc->handlers, message_tag) == NULL);
  502. RpcHandlerDict_set_at(rpc->handlers, message_tag, *handler);
  503. }
  504. void rpc_send_and_release_empty(Rpc* rpc, uint32_t command_id, PB_CommandStatus status) {
  505. PB_Main message = {
  506. .command_id = command_id,
  507. .command_status = status,
  508. .has_next = false,
  509. .which_content = PB_Main_empty_tag,
  510. };
  511. rpc_send_and_release(rpc, &message);
  512. pb_release(&PB_Main_msg, &message);
  513. }