RandomPacketSink.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @file RandomPacketSink.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. #ifndef _RANDOMPACKETSINK_H
  23. #define _RANDOMPACKETSINK_H
  24. #include <stdio.h>
  25. #include <misc/brandom.h>
  26. #include <system/BReactor.h>
  27. #include <flow/PacketPassInterface.h>
  28. typedef struct {
  29. BReactor *reactor;
  30. PacketPassInterface input;
  31. BTimer timer;
  32. } RandomPacketSink;
  33. static int _RandomPacketSink_input_handler_send (RandomPacketSink *s, uint8_t *data, int data_len)
  34. {
  35. printf("sink: send '");
  36. fwrite(data, data_len, 1, stdout);
  37. uint8_t r;
  38. brandom_randomize(&r, sizeof(r));
  39. if (r&(uint8_t)1) {
  40. printf("' accepting\n");
  41. return 1;
  42. }
  43. printf("' delaying\n");
  44. BReactor_SetTimer(s->reactor, &s->timer);
  45. return 0;
  46. }
  47. static void _RandomPacketSink_input_handler_cancel (RandomPacketSink *s)
  48. {
  49. printf("sink: cancelled\n");
  50. BReactor_RemoveTimer(s->reactor, &s->timer);
  51. }
  52. static void _RandomPacketSink_timer_handler (RandomPacketSink *s)
  53. {
  54. PacketPassInterface_Done(&s->input);
  55. }
  56. static void RandomPacketSink_Init (RandomPacketSink *s, BReactor *reactor, int mtu, int ms)
  57. {
  58. s->reactor = reactor;
  59. PacketPassInterface_Init(&s->input, mtu, (PacketPassInterface_handler_send)_RandomPacketSink_input_handler_send, s);
  60. PacketPassInterface_EnableCancel(&s->input, (PacketPassInterface_handler_cancel)_RandomPacketSink_input_handler_cancel);
  61. BTimer_Init(&s->timer, ms, (BTimer_handler)_RandomPacketSink_timer_handler, s);
  62. }
  63. static void RandomPacketSink_Free (RandomPacketSink *s)
  64. {
  65. BReactor_RemoveTimer(s->reactor, &s->timer);
  66. PacketPassInterface_Free(&s->input);
  67. }
  68. static PacketPassInterface * RandomPacketSink_GetInput (RandomPacketSink *s)
  69. {
  70. return &s->input;
  71. }
  72. #endif