1
0

AddrInterfaceAdapter.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 "interface/Interface.h"
  16. #include "interface/addressable/AddrInterfaceAdapter.h"
  17. #include "memory/Allocator.h"
  18. #include "util/platform/Sockaddr.h"
  19. #include "util/Assert.h"
  20. #include "util/Identity.h"
  21. #include "wire/Message.h"
  22. /**
  23. * Convert a normal Interface to an AddrInterface, all incoming messages
  24. * will have the same address (Sockaddr_LOOPBACK).
  25. */
  26. struct AddrInterfaceAdapter_pvt
  27. {
  28. struct AddrInterface pub;
  29. struct Interface* wrapped;
  30. Identity
  31. };
  32. static uint8_t sendMessage(struct Message* message, struct Interface* iface)
  33. {
  34. struct AddrInterfaceAdapter_pvt* context =
  35. Identity_cast((struct AddrInterfaceAdapter_pvt*) iface);
  36. Message_shift(message, -(context->pub.addr->addrLen), NULL);
  37. return Interface_sendMessage(context->wrapped, message);
  38. }
  39. static uint8_t receiveMessage(struct Message* message, struct Interface* iface)
  40. {
  41. struct AddrInterfaceAdapter_pvt* context =
  42. Identity_cast((struct AddrInterfaceAdapter_pvt*) iface->receiverContext);
  43. Message_push(message, context->pub.addr, context->pub.addr->addrLen, NULL);
  44. return Interface_receiveMessage(&context->pub.generic, message);
  45. }
  46. struct AddrInterface* AddrInterfaceAdapter_new(struct Interface* toWrap, struct Allocator* alloc)
  47. {
  48. struct AddrInterfaceAdapter_pvt* context =
  49. Allocator_malloc(alloc, sizeof(struct AddrInterfaceAdapter_pvt));
  50. Bits_memcpyConst(context, (&(struct AddrInterfaceAdapter_pvt) {
  51. .pub = {
  52. .generic = {
  53. .sendMessage = sendMessage,
  54. .senderContext = context,
  55. .allocator = alloc
  56. }
  57. },
  58. .wrapped = toWrap
  59. }), sizeof(struct AddrInterfaceAdapter_pvt));
  60. Identity_set(context);
  61. context->pub.addr = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
  62. toWrap->receiveMessage = receiveMessage;
  63. toWrap->receiverContext = context;
  64. return &context->pub;
  65. }