InterfaceWaiter.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "admin/angel/InterfaceWaiter.h"
  16. #include "exception/Except.h"
  17. #include "memory/Allocator.h"
  18. #include "util/events/EventBase.h"
  19. #include "util/log/Log.h"
  20. #include "io/FileWriter.h"
  21. #include "util/events/Timeout.h"
  22. struct Context
  23. {
  24. struct Iface iface;
  25. EventBase_t* eventBase;
  26. Message_t* message;
  27. struct Allocator* alloc;
  28. struct Timeout* timeout;
  29. int timedOut;
  30. int messageReceived;
  31. Identity
  32. };
  33. static void timeout(void* vcontext)
  34. {
  35. struct Context* ctx = vcontext;
  36. ctx->timedOut = 1;
  37. EventBase_endLoop(ctx->eventBase);
  38. }
  39. static Iface_DEFUN receiveMessage(Message_t* message, struct Iface* iface)
  40. {
  41. printf("interfacewaiter got a message\n");
  42. struct Context* ctx = Identity_check((struct Context*) iface);
  43. if (ctx->messageReceived) { return NULL; }
  44. ctx->message = Message_clone(message, ctx->alloc);
  45. Timeout_clearTimeout(ctx->timeout);
  46. EventBase_endLoop(ctx->eventBase);
  47. return NULL;
  48. }
  49. Message_t* InterfaceWaiter_waitForData(struct Iface* iface,
  50. EventBase_t* eventBase,
  51. struct Allocator* alloc,
  52. struct Except* eh)
  53. {
  54. struct Context ctx = {
  55. .iface = { .send = receiveMessage },
  56. .eventBase = eventBase,
  57. .alloc = alloc
  58. };
  59. Identity_set(&ctx);
  60. Iface_plumb(iface, &ctx.iface);
  61. struct Allocator* tempAlloc = Allocator_child(alloc);
  62. ctx.timeout = Timeout_setTimeout(timeout, &ctx, 10000, eventBase, tempAlloc);
  63. EventBase_beginLoop(eventBase);
  64. Iface_unplumb(iface, &ctx.iface);
  65. Allocator_free(tempAlloc);
  66. if (ctx.timedOut) {
  67. Except_throw(eh, "InterfaceWaiter Timed out waiting for data.");
  68. }
  69. Assert_true(!iface->connectedIf);
  70. Assert_true(ctx.message);
  71. return ctx.message;
  72. }