summaryrefslogtreecommitdiff
path: root/src/rps/rps_api.c
blob: e4f4db506a1d02044112263bd5501ecb1a572518 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
/*
     This file is part of GNUnet.
     Copyright (C)

     GNUnet is free software: you can redistribute it and/or modify it
     under the terms of the GNU Affero General Public License as published
     by the Free Software Foundation, either version 3 of the License,
     or (at your option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     Affero General Public License for more details.
    
     You should have received a copy of the GNU Affero General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * @file rps/rps_api.c
 * @brief API for rps
 * @author Julius Bünger
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "rps.h"
#include "gnunet_rps_service.h"
#include "gnunet-service-rps_sampler.h"

#include <inttypes.h>

#define LOG(kind,...) GNUNET_log_from (kind, "rps-api",__VA_ARGS__)

/**
 * Handle for a request to get peers from biased stream of ids
 */
struct GNUNET_RPS_StreamRequestHandle
{
  /**
   * The client issuing the request.
   */
  struct GNUNET_RPS_Handle *rps_handle;

  /**
   * The number of requested peers.
   */
  uint32_t num_peers_left;

  /**
   * The callback to be called when we receive an answer.
   */
  GNUNET_RPS_NotifyReadyCB ready_cb;

  /**
   * The closure for the callback.
   */
  void *ready_cb_cls;

  /**
   * @brief Next element of the DLL
   */
  struct GNUNET_RPS_StreamRequestHandle *next;

  /**
   * @brief Previous element of the DLL
   */
  struct GNUNET_RPS_StreamRequestHandle *prev;
};


/**
 * Handler to handle requests from a client.
 */
struct GNUNET_RPS_Handle
{
  /**
   * The handle to the client configuration.
   */
  const struct GNUNET_CONFIGURATION_Handle *cfg;

  /**
   * The message queue to the client.
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * Array of Request_Handles.
   */
  struct GNUNET_CONTAINER_MultiHashMap32 *req_handlers;

  /**
   * The id of the last request.
   */
  uint32_t current_request_id;

  /**
   * @brief Callback called on each update of the view
   */
  GNUNET_RPS_NotifyReadyCB view_update_cb;

  /**
   * @brief Closure to each requested update of the view
   */
  void *view_update_cls;

  /**
   * @brief Closure to each requested peer from the biased stream
   */
  void *stream_input_cls;

  /**
   * @brief Head of the DLL of stream requests
   */
  struct GNUNET_RPS_StreamRequestHandle *stream_requests_head;

  /**
   * @brief Tail of the DLL of stream requests
   */
  struct GNUNET_RPS_StreamRequestHandle *stream_requests_tail;
};


/**
 * Handler for a single request from a client.
 */
struct GNUNET_RPS_Request_Handle
{
  /**
   * The client issuing the request.
   */
  struct GNUNET_RPS_Handle *rps_handle;

  /**
   * The id of the request.
   */
  uint32_t id;

  /**
   * The number of requested peers.
   */
  uint32_t num_requests;

  /**
   * @brief The Sampler for the client request
   */
  struct RPS_Sampler *sampler;

  /**
   * The callback to be called when we receive an answer.
   */
  GNUNET_RPS_NotifyReadyCB ready_cb;

  /**
   * The closure for the callback.
   */
  void *ready_cb_cls;
};


/**
 * Struct used to pack the callback, its closure (provided by the caller)
 * and the connection handler to the service to pass it to a callback function.
 */
struct cb_cls_pack
{
  /**
   * Callback provided by the client
   */
  GNUNET_RPS_NotifyReadyCB cb;

  /**
   * Closure provided by the client
   */
  void *cls;

  /**
   * Handle to the service connection
   */
 struct GNUNET_CLIENT_Connection *service_conn;
};


/**
 * @brief Create a new handle for a stream request
 *
 * @param rps_handle The rps handle
 * @param num_peers The number of desired peers
 * @param ready_cb The callback to be called, once all peers are ready
 * @param cls The colsure to provide to the callback
 *
 * @return The handle to the stream request
 */
static struct GNUNET_RPS_StreamRequestHandle *
new_stream_request (struct GNUNET_RPS_Handle *rps_handle,
                    uint64_t num_peers,
                    GNUNET_RPS_NotifyReadyCB ready_cb,
                    void *cls)
{
  struct GNUNET_RPS_StreamRequestHandle *srh;

  srh = GNUNET_new (struct GNUNET_RPS_StreamRequestHandle);

  srh->rps_handle = rps_handle;
  srh->num_peers_left = num_peers;
  srh->ready_cb = ready_cb;
  srh->ready_cb_cls = cls;
  GNUNET_CONTAINER_DLL_insert (rps_handle->stream_requests_head,
                               rps_handle->stream_requests_tail,
                               srh);

  return srh;
}


/**
 * @brief Remove the given stream request from the list of requests and memory
 *
 * @param srh The request to be removed
 * @param srh_head Head of the DLL to remove request from
 * @param srh_tail Tail of the DLL to remove request from
 */
static void
remove_stream_request (struct GNUNET_RPS_StreamRequestHandle *srh,
                       struct GNUNET_RPS_StreamRequestHandle *srh_head,
                       struct GNUNET_RPS_StreamRequestHandle *srh_tail)
{
  GNUNET_CONTAINER_DLL_remove (srh_head,
                               srh_tail,
                               srh);

  GNUNET_free (srh);
}


/**
 * @brief Create new request handle
 *
 * @param rps_handle Handle to the service
 * @param num_requests Number of requests
 * @param ready_cb Callback
 * @param cls Closure
 *
 * @return The newly created request handle
 */
static struct GNUNET_RPS_Request_Handle *
new_request_handle (struct GNUNET_RPS_Handle *rps_handle,
                    uint64_t num_requests,
                    struct RPS_Sampler *sampler,
                    GNUNET_RPS_NotifyReadyCB ready_cb,
                    void *cls)
{
  struct GNUNET_RPS_Request_Handle *rh;

  rh = GNUNET_new (struct GNUNET_RPS_Request_Handle);
  rh->rps_handle = rps_handle;
  rh->id = rps_handle->current_request_id++;
  rh->num_requests = num_requests;
  rh->sampler = sampler;
  rh->ready_cb = ready_cb;
  rh->ready_cb_cls = cls;
  GNUNET_CONTAINER_multihashmap32_put (rps_handle->req_handlers, rh->id, rh,
      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);

  return rh;
}


/**
 * @brief Send a request to the service.
 *
 * @param h rps handle
 * @param id id of the request
 * @param num_req_peers number of peers
 */
void
send_request (const struct GNUNET_RPS_Handle *h,
              uint32_t id,
              uint32_t num_req_peers)
{
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_RPS_CS_RequestMessage *msg;

  ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST);
  msg->num_peers = htonl (num_req_peers);
  msg->id = htonl (id);
  GNUNET_MQ_send (h->mq, ev);
}

/**
 * @brief Iterator function over pending requests
 *
 * Implements #GNUNET_CONTAINER_HashMapIterator32
 *
 * @param cls rps handle
 * @param key id of the request
 * @param value request handle
 *
 * @return GNUNET_YES to continue iteration
 */
int
resend_requests_iterator (void *cls, uint32_t key, void *value)
{
  const struct GNUNET_RPS_Handle *h = cls;
  const struct GNUNET_RPS_Request_Handle *req_handle = value;
  (void) key;

  send_request (h, req_handle->id, req_handle->num_requests);
  return GNUNET_YES; /* continue iterating */
}

/**
 * @brief Resend all pending requests
 *
 * This is used to resend all pending requests after the client
 * reconnected to the service, because the service cancels all
 * pending requests after reconnection.
 *
 * @param h rps handle
 */
void
resend_requests (struct GNUNET_RPS_Handle *h)
{
  GNUNET_CONTAINER_multihashmap32_iterate (h->req_handlers,
                                           resend_requests_iterator,
                                           h);
}


/**
 * This function is called, when the service replies to our request.
 * It verifies that @a msg is well-formed.
 *
 * @param cls the closure
 * @param msg the message
 * @return #GNUNET_OK if @a msg is well-formed
 */
static int
check_reply (void *cls,
             const struct GNUNET_RPS_CS_ReplyMessage *msg)
{
  uint16_t msize = ntohs (msg->header.size);
  uint32_t num_peers = ntohl (msg->num_peers);
  (void) cls;

  msize -= sizeof (struct GNUNET_RPS_CS_ReplyMessage);
  if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
       (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * This function is called, when the service replies to our request.
 * It calls the callback the caller gave us with the provided closure
 * and disconnects afterwards.
 *
 * @param cls the closure
 * @param msg the message
 */
static void
handle_reply (void *cls,
              const struct GNUNET_RPS_CS_ReplyMessage *msg)
{
  struct GNUNET_RPS_Handle *h = cls;
  struct GNUNET_PeerIdentity *peers;
  struct GNUNET_RPS_Request_Handle *rh;
  uint32_t id;

  /* Give the peers back */
  id = ntohl (msg->id);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Service replied with %" PRIu32 " peers for id %" PRIu32 "\n",
       ntohl (msg->num_peers),
       id);

  peers = (struct GNUNET_PeerIdentity *) &msg[1];
  GNUNET_assert (GNUNET_YES ==
      GNUNET_CONTAINER_multihashmap32_contains (h->req_handlers, id));
  rh = GNUNET_CONTAINER_multihashmap32_get (h->req_handlers, id);
  GNUNET_assert (NULL != rh);
  GNUNET_assert (rh->num_requests == ntohl (msg->num_peers));
  GNUNET_CONTAINER_multihashmap32_remove_all (h->req_handlers, id);
  rh->ready_cb (rh->ready_cb_cls,
                ntohl (msg->num_peers),
                peers);
}


/* Get internals for debugging/profiling purposes */

/**
 * Request updates of view
 *
 * @param rps_handle handle to the rps service
 * @param num_req_peers number of peers we want to receive
 *        (0 for infinite updates)
 * @param cls a closure that will be given to the callback
 * @param ready_cb the callback called when the peers are available
 */
void
GNUNET_RPS_view_request (struct GNUNET_RPS_Handle *rps_handle,
                         uint32_t num_updates,
                         GNUNET_RPS_NotifyReadyCB view_update_cb,
                         void *cls)
{
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_RPS_CS_DEBUG_ViewRequest *msg;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Client requests %" PRIu32 " view updates\n",
       num_updates);
  rps_handle->view_update_cb = view_update_cb;
  rps_handle->view_update_cls = cls;

  ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REQUEST);
  msg->num_updates = htonl (num_updates);
  GNUNET_MQ_send (rps_handle->mq, ev);
}


/**
 * Request biased stream of peers that are being put into the sampler
 *
 * @param rps_handle handle to the rps service
 * @param num_req_peers number of peers we want to receive
 *        (0 for infinite updates)
 * @param cls a closure that will be given to the callback
 * @param ready_cb the callback called when the peers are available
 */
struct GNUNET_RPS_StreamRequestHandle *
GNUNET_RPS_stream_request (struct GNUNET_RPS_Handle *rps_handle,
                           uint32_t num_peers,
                           GNUNET_RPS_NotifyReadyCB stream_input_cb,
                           void *cls)
{
  struct GNUNET_RPS_StreamRequestHandle *srh;
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_RPS_CS_DEBUG_StreamRequest *msg;

  srh = new_stream_request (rps_handle,
                            num_peers, /* num requests */
                            stream_input_cb,
                            cls);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Client requests %" PRIu32 " biased stream updates\n",
       num_peers);

  ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_REQUEST);
  GNUNET_MQ_send (rps_handle->mq, ev);
  return srh;
}


/**
 * This function is called, when the service updates the view.
 * It verifies that @a msg is well-formed.
 *
 * @param cls the closure
 * @param msg the message
 * @return #GNUNET_OK if @a msg is well-formed
 */
static int
check_view_update (void *cls,
                   const struct GNUNET_RPS_CS_DEBUG_ViewReply *msg)
{
  uint16_t msize = ntohs (msg->header.size);
  uint32_t num_peers = ntohl (msg->num_peers);
  (void) cls;

  msize -= sizeof (struct GNUNET_RPS_CS_DEBUG_ViewReply);
  if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
       (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * This function is called, when the service updated its view.
 * It calls the callback the caller provided
 * and disconnects afterwards.
 *
 * @param msg the message
 */
static void
handle_view_update (void *cls,
                    const struct GNUNET_RPS_CS_DEBUG_ViewReply *msg)
{
  struct GNUNET_RPS_Handle *h = cls;
  struct GNUNET_PeerIdentity *peers;

  /* Give the peers back */
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "New view of %" PRIu32 " peers:\n",
       ntohl (msg->num_peers));

  peers = (struct GNUNET_PeerIdentity *) &msg[1];
  GNUNET_assert (NULL != h);
  GNUNET_assert (NULL != h->view_update_cb);
  h->view_update_cb (h->view_update_cls, ntohl (msg->num_peers), peers);
}


/**
 * @brief Send message to service that this client does not want to receive
 * further updates from the biased peer stream
 *
 * @param rps_handle The handle representing the service to the client
 */
static void
cancel_stream (struct GNUNET_RPS_Handle *rps_handle)
{
  struct GNUNET_MQ_Envelope *ev;

  ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_CANCEL);
  GNUNET_MQ_send (rps_handle->mq, ev);
}


/**
 * @brief Cancel a specific request for updates from the biased peer stream
 *
 * @param srh The request handle to cancel
 */
void
GNUNET_RPS_stream_cancel (struct GNUNET_RPS_StreamRequestHandle *srh)
{
  struct GNUNET_RPS_Handle *rps_handle;

  rps_handle = srh->rps_handle;
  GNUNET_CONTAINER_DLL_remove (rps_handle->stream_requests_head,
                               rps_handle->stream_requests_tail,
                               srh);
  GNUNET_free (srh);
  if (NULL == rps_handle->stream_requests_head) cancel_stream (rps_handle);
}


/**
 * This function is called, when the service sends another peer from the biased
 * stream.
 * It calls the callback the caller provided
 * and disconnects afterwards.
 *
 * TODO merge with check_view_update
 *
 * @param msg the message
 */
static int
check_stream_input (void *cls,
                    const struct GNUNET_RPS_CS_DEBUG_StreamReply *msg)
{
  uint16_t msize = ntohs (msg->header.size);
  uint32_t num_peers = ntohl (msg->num_peers);
  (void) cls;

  msize -= sizeof (struct GNUNET_RPS_CS_DEBUG_StreamReply);
  if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
       (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}

/**
 * This function is called, when the service sends another peer from the biased
 * stream.
 * It calls the callback the caller provided
 * and disconnects afterwards.
 *
 * @param msg the message
 */
static void
handle_stream_input (void *cls,
                     const struct GNUNET_RPS_CS_DEBUG_StreamReply *msg)
{
  struct GNUNET_RPS_Handle *h = cls;
  const struct GNUNET_PeerIdentity *peers;
  /* The following two pointers are used to prevent that new handles are
   * inserted into the DLL, that is currently iterated over, from within a call
   * to that handler_cb, are executed and in turn again add themselves to the
   * iterated DLL infinitely */
  struct GNUNET_RPS_StreamRequestHandle *srh_head_tmp;
  struct GNUNET_RPS_StreamRequestHandle *srh_tail_tmp;
  uint64_t num_peers;
  uint64_t num_peers_return;

  peers = (struct GNUNET_PeerIdentity *) &msg[1];
  num_peers = ntohl (msg->num_peers);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received %" PRIu64 " peer(s) from stream input.\n",
       num_peers);
  srh_head_tmp = h->stream_requests_head;
  srh_tail_tmp = h->stream_requests_tail;
  h->stream_requests_head = NULL;
  h->stream_requests_tail = NULL;
  for (struct GNUNET_RPS_StreamRequestHandle *srh_iter = srh_head_tmp;
       NULL != srh_iter;
       srh_iter = srh_iter->next)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Calling srh - left: %" PRIu64 "\n",
        srh_iter->num_peers_left);
    if (0 == srh_iter->num_peers_left) /* infinite updates */
    {
      num_peers_return = num_peers;
    }
    else if (num_peers > srh_iter->num_peers_left)
    {
      num_peers_return = num_peers - srh_iter->num_peers_left;
    }
    else /* num_peers <= srh_iter->num_peers_left */
    {
      num_peers_return = srh_iter->num_peers_left - num_peers;
    }
    srh_iter->ready_cb (srh_iter->ready_cb_cls,
                        num_peers_return,
                        peers);
    if (0 == srh_iter->num_peers_left) ;
    else if (num_peers_return >= srh_iter->num_peers_left)
    {
      remove_stream_request (srh_iter,
                             srh_head_tmp,
                             srh_tail_tmp);
    }
    else
    {
      srh_iter->num_peers_left -= num_peers_return;
    }
  }
  for (struct GNUNET_RPS_StreamRequestHandle *srh_iter = srh_head_tmp;
       NULL != srh_iter;
       srh_iter = srh_iter->next)
  {
      GNUNET_CONTAINER_DLL_insert (h->stream_requests_head,
                                   h->stream_requests_tail,
                                   srh_iter);
  }

  if (NULL == h->stream_requests_head)
  {
    cancel_stream (h);
  }
}


/**
 * Reconnect to the service
 */
static void
reconnect (struct GNUNET_RPS_Handle *h);


/**
 * Error handler for mq.
 *
 * This function is called whan mq encounters an error.
 * Until now mq doesn't provide useful error messages.
 *
 * @param cls the closure
 * @param error error code without specyfied meaning
 */
static void
mq_error_handler (void *cls,
                  enum GNUNET_MQ_Error error)
{
  struct GNUNET_RPS_Handle *h = cls;
  //TODO LOG
  LOG (GNUNET_ERROR_TYPE_WARNING, "Problem with message queue. error: %i\n\
       1: READ,\n\
       2: WRITE,\n\
       4: TIMEOUT\n",
       error);
  reconnect (h);
  /* Resend all pending request as the service destroyed its knowledge
   * about them */
  resend_requests (h);
}


/**
 * Reconnect to the service
 */
static void
reconnect (struct GNUNET_RPS_Handle *h)
{
  struct GNUNET_MQ_MessageHandler mq_handlers[] = {
    GNUNET_MQ_hd_var_size (reply,
                           GNUNET_MESSAGE_TYPE_RPS_CS_REPLY,
                           struct GNUNET_RPS_CS_ReplyMessage,
                           h),
    GNUNET_MQ_hd_var_size (view_update,
                           GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REPLY,
                           struct GNUNET_RPS_CS_DEBUG_ViewReply,
                           h),
    GNUNET_MQ_hd_var_size (stream_input,
                           GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_STREAM_REPLY,
                           struct GNUNET_RPS_CS_DEBUG_StreamReply,
                           h),
    GNUNET_MQ_handler_end ()
  };

  if (NULL != h->mq)
    GNUNET_MQ_destroy (h->mq);
  h->mq = GNUNET_CLIENT_connect (h->cfg,
                                 "rps",
                                 mq_handlers,
                                 &mq_error_handler,
                                 h);
}


/**
 * Connect to the rps service
 *
 * @param cfg configuration to use
 * @return a handle to the service
 */
struct GNUNET_RPS_Handle *
GNUNET_RPS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
{
  struct GNUNET_RPS_Handle *h;

  h = GNUNET_new (struct GNUNET_RPS_Handle);
  h->current_request_id = 0;
  h->cfg = cfg;
  reconnect (h);
  if (NULL == h->mq)
  {
    GNUNET_free (h);
    return NULL;
  }
  h->req_handlers = GNUNET_CONTAINER_multihashmap32_create (4);
  return h;
}


/**
 * Request n random peers.
 *
 * @param rps_handle handle to the rps service
 * @param num_req_peers number of peers we want to receive
 * @param ready_cb the callback called when the peers are available
 * @param cls closure given to the callback
 * @return a handle to cancel this request
 */
struct GNUNET_RPS_Request_Handle *
GNUNET_RPS_request_peers_2 (struct GNUNET_RPS_Handle *rps_handle,
                          uint32_t num_req_peers,
                          GNUNET_RPS_NotifyReadyCB ready_cb,
                          void *cls)
{
  struct GNUNET_RPS_Request_Handle *rh;

  rh = new_request_handle (rps_handle,
                           num_req_peers,
                           NULL, /* no sampler needed */
                           ready_cb,
                           cls);

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Requesting %" PRIu32 " peers with id %" PRIu32 "\n",
       num_req_peers,
       rh->id);

  send_request (rps_handle, rh->id, num_req_peers);
  return rh;
}


/**
 * @brief Callback to collect the peers from the biased stream and put those
 * into the sampler.
 *
 * @param cls The #GNUNET_RPS_Request_Handle
 * @param num_peers The number of peer that have been returned
 * @param peers The array of @a num_peers that have been returned
 */
void
collect_peers_cb (void *cls,
                  uint64_t num_peers,
                  const struct GNUNET_PeerIdentity *peers)
{
  struct GNUNET_RPS_Request_Handle *rh = cls;

  for (uint64_t i = 0; i < num_peers; i++)
  {
    RPS_sampler_update (rh->sampler, &peers[i]);
  }
}


/**
 * @brief Called once the sampler has collected all requested peers.
 *
 * Calls the callback provided by the client with the corresponding cls.
 *
 * @param peers The array of @a num_peers that has been returned.
 * @param num_peers The number of peers that have been returned
 * @param cls The #GNUNET_RPS_Request_Handle
 */
void
peers_ready_cb (const struct GNUNET_PeerIdentity *peers,
                uint32_t num_peers,
                void *cls)
{
  struct GNUNET_RPS_Request_Handle *rh = cls;

  rh->ready_cb (rh->ready_cb_cls,
                num_peers,
                peers);
  // TODO cleanup, sampler, rh, cancel stuff
  // TODO screw this function. We can give the cb,cls directly to the sampler.
}

/**
 * Request n random peers.
 *
 * @param rps_handle handle to the rps service
 * @param num_req_peers number of peers we want to receive
 * @param ready_cb the callback called when the peers are available
 * @param cls closure given to the callback
 * @return a handle to cancel this request
 */
struct GNUNET_RPS_Request_Handle *
GNUNET_RPS_request_peers (struct GNUNET_RPS_Handle *rps_handle,
                          uint32_t num_req_peers,
                          GNUNET_RPS_NotifyReadyCB ready_cb,
                          void *cls)
{
  struct GNUNET_RPS_Request_Handle *rh;

  rh = new_request_handle (rps_handle,
                           num_req_peers,
                           RPS_sampler_mod_init (num_req_peers,
                                                 GNUNET_TIME_UNIT_SECONDS), // TODO remove this time-stuff
                           ready_cb,
                           cls);
  RPS_sampler_get_n_rand_peers (rh->sampler,
                                num_req_peers,
                                peers_ready_cb,
                                rh);

  GNUNET_RPS_stream_request (rps_handle,
                             0, /* infinite updates */
                             collect_peers_cb,
                             rh); /* cls */

  return rh;
}


/**
 * Seed rps service with peerIDs.
 *
 * @param h handle to the rps service
 * @param n number of peers to seed
 * @param ids the ids of the peers seeded
 */
void
GNUNET_RPS_seed_ids (struct GNUNET_RPS_Handle *h,
                     uint32_t n,
                     const struct GNUNET_PeerIdentity *ids)
{
  size_t size_needed;
  uint32_t num_peers_max;
  const struct GNUNET_PeerIdentity *tmp_peer_pointer;
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_RPS_CS_SeedMessage *msg;

  unsigned int i;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Client wants to seed %" PRIu32 " peers:\n",
       n);
  for (i = 0 ; i < n ; i++)
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%u. peer: %s\n",
         i,
         GNUNET_i2s (&ids[i]));

  /* The actual size the message occupies */
  size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
    n * sizeof (struct GNUNET_PeerIdentity);
  /* The number of peers that fits in one message together with
   * the respective header */
  num_peers_max = (GNUNET_MAX_MESSAGE_SIZE -
      sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
    sizeof (struct GNUNET_PeerIdentity);
  tmp_peer_pointer = ids;

  while (GNUNET_MAX_MESSAGE_SIZE < size_needed)
  {
    ev = GNUNET_MQ_msg_extra (msg, num_peers_max * sizeof (struct GNUNET_PeerIdentity),
        GNUNET_MESSAGE_TYPE_RPS_CS_SEED);
    msg->num_peers = htonl (num_peers_max);
    GNUNET_memcpy (&msg[1], tmp_peer_pointer, num_peers_max * sizeof (struct GNUNET_PeerIdentity));
    GNUNET_MQ_send (h->mq, ev);

    n -= num_peers_max;
    size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
                  n * sizeof (struct GNUNET_PeerIdentity);
    /* Set pointer to beginning of next block of num_peers_max peers */
    tmp_peer_pointer = &ids[num_peers_max];
  }

  ev = GNUNET_MQ_msg_extra (msg, n * sizeof (struct GNUNET_PeerIdentity),
                            GNUNET_MESSAGE_TYPE_RPS_CS_SEED);
  msg->num_peers = htonl (n);
  GNUNET_memcpy (&msg[1], tmp_peer_pointer, n * sizeof (struct GNUNET_PeerIdentity));

  GNUNET_MQ_send (h->mq, ev);
}


#ifdef ENABLE_MALICIOUS
/**
 * Turn RPS service to act malicious.
 *
 * @param h handle to the rps service
 * @param type which type of malicious peer to turn to.
 *             0 Don't act malicious at all
 *             1 Try to maximise representation
 *             2 Try to partition the network
 *               (isolate one peer from the rest)
 * @param n number of @a ids
 * @param ids the ids of the malicious peers
 *            if @type is 2 the last id is the id of the
 *            peer to be isolated from the rest
 */
void
GNUNET_RPS_act_malicious (struct GNUNET_RPS_Handle *h,
                          uint32_t type,
                          uint32_t num_peers,
                          const struct GNUNET_PeerIdentity *peer_ids,
                          const struct GNUNET_PeerIdentity *target_peer)
{
  size_t size_needed;
  uint32_t num_peers_max;
  const struct GNUNET_PeerIdentity *tmp_peer_pointer;
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_RPS_CS_ActMaliciousMessage *msg;

  unsigned int i;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Client turns malicious (type %" PRIu32 ") with %" PRIu32 " other peers:\n",
       type,
       num_peers);
  for (i = 0 ; i < num_peers ; i++)
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%u. peer: %s\n",
         i,
         GNUNET_i2s (&peer_ids[i]));

  /* The actual size the message would occupy */
  size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
    num_peers * sizeof (struct GNUNET_PeerIdentity);
  /* The number of peers that fit in one message together with
   * the respective header */
  num_peers_max = (GNUNET_MAX_MESSAGE_SIZE -
      sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
    sizeof (struct GNUNET_PeerIdentity);
  tmp_peer_pointer = peer_ids;

  while (GNUNET_MAX_MESSAGE_SIZE < size_needed)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Too many peers to send at once, sending %" PRIu32 " (all we can so far)\n",
         num_peers_max);
    ev = GNUNET_MQ_msg_extra (msg,
                              num_peers_max * sizeof (struct GNUNET_PeerIdentity),
                              GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS);
    msg->type = htonl (type);
    msg->num_peers = htonl (num_peers_max);
    if ( (2 == type) ||
         (3 == type) )
      msg->attacked_peer = peer_ids[num_peers];
    GNUNET_memcpy (&msg[1],
            tmp_peer_pointer,
            num_peers_max * sizeof (struct GNUNET_PeerIdentity));

    GNUNET_MQ_send (h->mq, ev);

    num_peers -= num_peers_max;
    size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
                  num_peers * sizeof (struct GNUNET_PeerIdentity);
    /* Set pointer to beginning of next block of num_peers_max peers */
    tmp_peer_pointer = &peer_ids[num_peers_max];
  }

  ev = GNUNET_MQ_msg_extra (msg,
                            num_peers * sizeof (struct GNUNET_PeerIdentity),
                            GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS);
  msg->type = htonl (type);
  msg->num_peers = htonl (num_peers);
  if ( (2 == type) ||
       (3 == type) )
    msg->attacked_peer = *target_peer;
  GNUNET_memcpy (&msg[1], tmp_peer_pointer, num_peers * sizeof (struct GNUNET_PeerIdentity));

  GNUNET_MQ_send (h->mq, ev);
}
#endif /* ENABLE_MALICIOUS */


/**
 * Cancle an issued request.
 *
 * @param rh request handle of request to cancle
 */
void
GNUNET_RPS_request_cancel (struct GNUNET_RPS_Request_Handle *rh)
{
  struct GNUNET_RPS_Handle *h;
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_RPS_CS_RequestCancelMessage*msg;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Cancelling request with id %" PRIu32 "\n",
       rh->id);

  h = rh->rps_handle;
  GNUNET_assert (GNUNET_CONTAINER_multihashmap32_contains (h->req_handlers,
        rh->id));
  GNUNET_CONTAINER_multihashmap32_remove_all (h->req_handlers, rh->id);
  ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST_CANCEL);
  msg->id = htonl (rh->id);
  GNUNET_MQ_send (rh->rps_handle->mq, ev);
}


/**
 * Disconnect from the rps service
 *
 * @param h the handle to the rps service
 */
void
GNUNET_RPS_disconnect (struct GNUNET_RPS_Handle *h)
{
  GNUNET_MQ_destroy (h->mq);
  if (0 < GNUNET_CONTAINER_multihashmap32_size (h->req_handlers))
    LOG (GNUNET_ERROR_TYPE_WARNING,
        "Still waiting for requests\n");
  GNUNET_CONTAINER_multihashmap32_destroy (h->req_handlers);
  GNUNET_free (h);
}


/* end of rps_api.c */