rpc.c 17 KB

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