InterfaceWaiter.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 <http://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. struct EventBase* eventBase;
  26. struct Message* 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(struct Message* message, struct Iface* iface)
  40. {
  41. struct Context* ctx = Identity_check((struct Context*) iface);
  42. if (ctx->messageReceived) { return 0; }
  43. ctx->message = Message_clone(message, ctx->alloc);
  44. Timeout_clearTimeout(ctx->timeout);
  45. EventBase_endLoop(ctx->eventBase);
  46. return 0;
  47. }
  48. struct Message* InterfaceWaiter_waitForData(struct Iface* iface,
  49. struct EventBase* eventBase,
  50. struct Allocator* alloc,
  51. struct Except* eh)
  52. {
  53. struct Context ctx = {
  54. .iface = { .send = receiveMessage },
  55. .eventBase = eventBase,
  56. .alloc = alloc
  57. };
  58. Identity_set(&ctx);
  59. Iface_plumb(iface, &ctx.iface);
  60. struct Allocator* tempAlloc = Allocator_child(alloc);
  61. ctx.timeout = Timeout_setTimeout(timeout, &ctx, 10000, eventBase, tempAlloc);
  62. EventBase_beginLoop(eventBase);
  63. Iface_unplumb(iface, &ctx.iface);
  64. Allocator_free(tempAlloc);
  65. if (ctx.timedOut) {
  66. Except_throw(eh, "InterfaceWaiter Timed out waiting for data.");
  67. }
  68. Assert_true(!iface->connectedIf);
  69. Assert_true(ctx.message);
  70. return ctx.message;
  71. }