request_response.c 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "app_manager_export.h"
  6. #include "coap_ext.h"
  7. #include "wasm_export.h"
  8. #include "bh_assert.h"
  9. extern void module_request_handler(request_t *request, void *user_data);
  10. bool
  11. wasm_response_send(wasm_exec_env_t exec_env,
  12. int32 buffer_offset, int size)
  13. {
  14. wasm_module_inst_t module_inst = get_module_inst(exec_env);
  15. char *buffer = NULL;
  16. if (!validate_app_addr(buffer_offset, size))
  17. return false;
  18. buffer = addr_app_to_native(buffer_offset);
  19. if (buffer != NULL) {
  20. response_t response[1];
  21. if (NULL == unpack_response(buffer, size, response))
  22. return false;
  23. am_send_response(response);
  24. return true;
  25. }
  26. return false;
  27. }
  28. void
  29. wasm_register_resource(wasm_exec_env_t exec_env, int32 url_offset)
  30. {
  31. wasm_module_inst_t module_inst = get_module_inst(exec_env);
  32. char *url = NULL;
  33. if (!validate_app_str_addr(url_offset))
  34. return;
  35. url = addr_app_to_native(url_offset);
  36. if (url != NULL) {
  37. unsigned int mod_id = app_manager_get_module_id(Module_WASM_App,
  38. module_inst);
  39. bh_assert(mod_id != ID_NONE);
  40. am_register_resource(url, module_request_handler, mod_id);
  41. }
  42. }
  43. void
  44. wasm_post_request(wasm_exec_env_t exec_env,
  45. int32 buffer_offset, int size)
  46. {
  47. wasm_module_inst_t module_inst = get_module_inst(exec_env);
  48. char *buffer = NULL;
  49. if (!validate_app_addr(buffer_offset, size))
  50. return;
  51. buffer = addr_app_to_native(buffer_offset);
  52. if (buffer != NULL) {
  53. request_t req[1];
  54. if (!unpack_request(buffer, size, req))
  55. return;
  56. // TODO: add permission check, ensure app can't do harm
  57. // set sender to help dispatch the response to the sender ap
  58. unsigned int mod_id = app_manager_get_module_id(Module_WASM_App,
  59. module_inst);
  60. bh_assert(mod_id != ID_NONE);
  61. req->sender = mod_id;
  62. if (req->action == COAP_EVENT) {
  63. am_publish_event(req);
  64. return;
  65. }
  66. am_dispatch_request(req);
  67. }
  68. }
  69. void
  70. wasm_sub_event(wasm_exec_env_t exec_env, int32 url_offset)
  71. {
  72. wasm_module_inst_t module_inst = get_module_inst(exec_env);
  73. char *url = NULL;
  74. if (!validate_app_str_addr(url_offset))
  75. return;
  76. url = addr_app_to_native(url_offset);
  77. if (url != NULL) {
  78. unsigned int mod_id = app_manager_get_module_id(Module_WASM_App,
  79. module_inst);
  80. bh_assert(mod_id != ID_NONE);
  81. am_register_event(url, mod_id);
  82. }
  83. }