7d443e5d110fac67b73ceb8b1711886b89a0cab8
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      (C)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file rps/gnunet-service-rps.c
23  * @brief rps service implementation
24  * @author Julius Bünger
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_cadet_service.h"
29 #include "gnunet_nse_service.h"
30 #include "rps.h"
31
32 #include "gnunet-service-rps_sampler.h"
33
34 #include <math.h>
35 #include <inttypes.h>
36
37 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
38
39 // TODO modify @brief in every file
40
41 // TODO check for overflows
42
43 // TODO align message structs
44
45 // (TODO api -- possibility of getting weak random peer immideately)
46
47 // TODO malicious peer
48
49 // TODO connect to friends
50
51 // TODO store peers somewhere
52
53 // TODO ignore list?
54
55 // hist_size_init, hist_size_max
56
57 /**
58  * Our configuration.
59  */
60 static const struct GNUNET_CONFIGURATION_Handle *cfg;
61
62 /**
63  * Our own identity.
64  */
65 static struct GNUNET_PeerIdentity own_identity;
66
67
68   struct GNUNET_PeerIdentity *
69 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list, unsigned int size,
70                            const struct GNUNET_PeerIdentity *ignore_list, unsigned int ignore_size);
71
72
73 /***********************************************************************
74  * Housekeeping with peers
75 ***********************************************************************/
76
77 /**
78  * Struct used to store the context of a connected client.
79  */
80 struct client_ctx
81 {
82   /**
83    * The message queue to communicate with the client.
84    */
85   struct GNUNET_MQ_Handle *mq;
86 };
87
88 /**
89  * Used to keep track in what lists single peerIDs are.
90  */
91 enum PeerFlags
92 {
93   PULL_REPLY_PENDING   = 0x01,
94   IN_OTHER_GOSSIP_LIST = 0x02, // unneeded?
95   IN_OWN_SAMPLER_LIST  = 0x04, // unneeded?
96   IN_OWN_GOSSIP_LIST   = 0x08, // unneeded?
97
98   /**
99    * We set this bit when we can be sure the other peer is/was live.
100    */
101   LIVING               = 0x10
102 };
103
104
105 /**
106  * Functions of this type can be used to be stored at a peer for later execution.
107  */
108 typedef void (* PeerOp) (void *cls, const struct GNUNET_PeerIdentity *peer);
109
110 /**
111  * Outstanding operation on peer consisting of callback and closure
112  */
113 struct PeerOutstandingOp
114 {
115   /**
116    * Callback
117    */
118   PeerOp op;
119
120   /**
121    * Closure
122    */
123   void *op_cls;
124 };
125
126
127 /**
128  * Struct used to keep track of other peer's status
129  *
130  * This is stored in a multipeermap.
131  */
132 struct PeerContext
133 {
134   /**
135    * In own gossip/sampler list, in other's gossip/sampler list
136    */
137   uint32_t peer_flags;
138
139   /**
140    * Message queue open to client
141    */
142   struct GNUNET_MQ_Handle *mq;
143
144   /**
145    * Channel open to client.
146    */
147   struct GNUNET_CADET_Channel *send_channel;
148
149   /**
150    * Channel open from client.
151    */
152   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
153
154   /**
155    * Array of outstanding operations on this peer.
156    */
157   struct PeerOutstandingOp *outstanding_ops;
158
159   /**
160    * Number of outstanding operations.
161    */
162   unsigned int num_outstanding_ops;
163   //size_t num_outstanding_ops;
164
165   /**
166    * Handle to the callback given to cadet_ntfy_tmt_rdy()
167    *
168    * To be canceled on shutdown.
169    */
170   struct GNUNET_CADET_TransmitHandle *is_live_task;
171
172   /**
173    * Identity of the peer
174    */
175   struct GNUNET_PeerIdentity peer_id;
176
177   /**
178    * This is pobably followed by 'statistical' data (when we first saw
179    * him, how did we get his ID, how many pushes (in a timeinterval),
180    * ...)
181    */
182 };
183
184 /***********************************************************************
185  * /Housekeeping with peers
186 ***********************************************************************/
187
188 /***********************************************************************
189  * Globals
190 ***********************************************************************/
191
192 /**
193  * Set of all peers to keep track of them.
194  */
195 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
196
197
198 /**
199  * The gossiped list of peers.
200  */
201 static struct GNUNET_PeerIdentity *gossip_list;
202
203 /**
204  * Size of the gossiped list
205  */
206 //static unsigned int gossip_list_size;
207 static uint32_t gossip_list_size;
208
209
210 /**
211  * The size of sampler we need to be able to satisfy the client's need of
212  * random peers.
213  */
214 static unsigned int sampler_size_client_need;
215
216 /**
217  * The size of sampler we need to be able to satisfy the Brahms protocol's
218  * need of random peers.
219  *
220  * This is directly taken as the #gossip_list_size on update of the
221  * #gossip_list
222  *
223  * This is one minimum size the sampler grows to.
224  */
225 static unsigned int sampler_size_est_need;
226
227
228 /**
229  * Percentage of total peer number in the gossip list
230  * to send random PUSHes to
231  */
232 static float alpha;
233
234 /**
235  * Percentage of total peer number in the gossip list
236  * to send random PULLs to
237  */
238 static float beta;
239
240 /**
241  * The percentage gamma of history updates.
242  * Simply 1 - alpha - beta
243  */
244
245
246 /**
247  * Identifier for the main task that runs periodically.
248  */
249 static struct GNUNET_SCHEDULER_Task *do_round_task;
250
251 /**
252  * Time inverval the do_round task runs in.
253  */
254 static struct GNUNET_TIME_Relative round_interval;
255
256
257
258 /**
259  * List to store peers received through pushes temporary.
260  *
261  * TODO -> multipeermap
262  */
263 static struct GNUNET_PeerIdentity *push_list;
264
265 /**
266  * Size of the push_list;
267  */
268 static unsigned int push_list_size;
269 //size_t push_list_size;
270
271 /**
272  * List to store peers received through pulls temporary.
273  *
274  * TODO -> multipeermap
275  */
276 static struct GNUNET_PeerIdentity *pull_list;
277
278 /**
279  * Size of the pull_list;
280  */
281 static unsigned int pull_list_size;
282 //size_t pull_list_size;
283
284
285 /**
286  * Handler to NSE.
287  */
288 static struct GNUNET_NSE_Handle *nse;
289
290 /**
291  * Handler to CADET.
292  */
293 static struct GNUNET_CADET_Handle *cadet_handle;
294
295
296 /**
297  * Request counter.
298  *
299  * Only needed in the beginning to check how many of the 64 deltas
300  * we already have
301  */
302 static unsigned int req_counter;
303
304 /**
305  * Time of the last request we received.
306  *
307  * Used to compute the expected request rate.
308  */
309 static struct GNUNET_TIME_Absolute last_request;
310
311 /**
312  * Size of #request_deltas.
313  */
314 #define REQUEST_DELTAS_SIZE 64
315 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
316
317 /**
318  * Last 64 deltas between requests
319  */
320 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
321
322 /**
323  * The prediction of the rate of requests
324  */
325 static struct GNUNET_TIME_Relative  request_rate;
326
327
328 /**
329  * List with the peers we sent requests to.
330  */
331 struct GNUNET_PeerIdentity *pending_pull_reply_list;
332
333 /**
334  * Size of #pending_pull_reply_list.
335  */
336 uint32_t pending_pull_reply_list_size;
337
338
339 /**
340  * Number of history update tasks.
341  */
342 uint32_t num_hist_update_tasks;
343
344
345 /***********************************************************************
346  * /Globals
347 ***********************************************************************/
348
349
350 /***********************************************************************
351  * Util functions
352 ***********************************************************************/
353
354 /**
355  * Check if peer is already in peer array.
356  */
357   int
358 in_arr (const struct GNUNET_PeerIdentity *array,
359         unsigned int arr_size,
360         const struct GNUNET_PeerIdentity *peer)
361 {
362   GNUNET_assert (NULL != peer);
363
364   if (0 == arr_size)
365     return GNUNET_NO;
366
367   GNUNET_assert (NULL != array);
368
369   unsigned int i;
370
371   i = 0;
372   while (0 != GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer) &&
373          i < arr_size)
374     i++;
375
376   if (i == arr_size)
377     return GNUNET_NO;
378   else
379     return GNUNET_YES;
380 }
381
382 /**
383  * Remove peer from list.
384  */
385   void
386 rem_from_list (struct GNUNET_PeerIdentity *peer_list,
387                unsigned int *list_size,
388                const struct GNUNET_PeerIdentity *peer)
389 {
390   unsigned int i;
391
392   for ( i = 0 ; i < *list_size ; i++ )
393   {
394     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&peer_list[i], peer))
395     {
396       if (i < *list_size -1)
397       { /* Not at the last entry -- shift peers left */
398         memcpy (&peer_list[i], &peer_list[i +1],
399                 (*list_size - i -1) * sizeof (struct GNUNET_PeerIdentity));
400       }
401       /* Remove last entry (should be now useless PeerID) */
402       GNUNET_array_grow (peer_list, *list_size, *list_size -1);
403     }
404   }
405 }
406
407 /**
408  * Get random peer from the given list but don't return one from the @a ignore_list.
409  */
410   struct GNUNET_PeerIdentity *
411 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
412                            uint32_t list_size,
413                            const struct GNUNET_PeerIdentity *ignore_list,
414                            uint32_t ignore_size)
415 {
416   uint32_t r_index;
417   uint32_t tmp_size;
418   struct GNUNET_PeerIdentity *tmp_peer_list;
419   struct GNUNET_PeerIdentity *peer;
420
421   GNUNET_assert (NULL != peer_list);
422   if (0 == list_size)
423     return NULL;
424
425   tmp_size = 0;
426   tmp_peer_list = NULL;
427   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
428   memcpy (tmp_peer_list, peer_list, list_size * sizeof (struct GNUNET_PeerIdentity));
429   peer = GNUNET_new (struct GNUNET_PeerIdentity);
430
431   /**;
432    * Choose the r_index of the peer we want to return
433    * at random from the interval of the gossip list
434    */
435   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
436                                       tmp_size);
437   *peer = tmp_peer_list[r_index];
438
439   while (in_arr (ignore_list, ignore_size, peer))
440   {
441     rem_from_list (tmp_peer_list, &tmp_size, peer);
442
443     if (0 == tmp_size)
444     {
445       GNUNET_free (peer);
446       return NULL;
447     }
448
449     /**;
450      * Choose the r_index of the peer we want to return
451      * at random from the interval of the gossip list
452      */
453     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
454                                         tmp_size);
455     *peer = tmp_peer_list[r_index];
456   }
457
458
459   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
460
461   return peer;
462 }
463
464
465 /**
466  * Get the context of a peer. If not existing, create.
467  */
468   struct PeerContext *
469 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
470               const struct GNUNET_PeerIdentity *peer)
471 {
472   struct PeerContext *ctx;
473
474   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
475   {
476     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
477   }
478   else
479   {
480     ctx = GNUNET_new (struct PeerContext);
481     ctx->peer_flags = 0;
482     ctx->mq = NULL;
483     ctx->send_channel = NULL;
484     ctx->recv_channel = NULL;
485     ctx->outstanding_ops = NULL;
486     ctx->num_outstanding_ops = 0;
487     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
488                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
489   }
490   return ctx;
491 }
492
493
494 /**
495  * Put random peer from sampler into the gossip list as history update.
496  */
497   void
498 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
499 {
500   GNUNET_assert (1 == num_peers);
501
502   if (gossip_list_size < sampler_size_est_need)
503     GNUNET_array_append (gossip_list, gossip_list_size, *ids);
504
505   if (0 < num_hist_update_tasks)
506     num_hist_update_tasks--;
507 }
508
509
510 /**
511  * Callback that is called when a channel was effectively established.
512  * This is given to ntfy_tmt_rdy and called when the channel was
513  * successfully established.
514  */
515 static size_t
516 peer_is_live (void *cls, size_t size, void *buf)
517 {
518   struct PeerContext *ctx = cls;
519   struct GNUNET_PeerIdentity *peer;
520   struct PeerContext *peer_ctx;
521
522   //if (NULL == buf ||
523   //    0 == size)
524   // TODO check
525
526   ctx->is_live_task = NULL;
527   peer = &ctx->peer_id;
528   peer_ctx = get_peer_ctx (peer_map, peer);
529   peer_ctx->peer_flags |= LIVING;
530
531   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
532
533   if (0 != peer_ctx->num_outstanding_ops)
534   { /* Call outstanding operations */
535     unsigned int i;
536
537     for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
538       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
539     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
540   }
541
542   //if (NULL != peer_ctx->is_live_task)
543   //{
544   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
545   //  peer_ctx->is_live_task = NULL; // needed?
546   //}
547   return 0;
548 }
549
550
551 /**
552  * Get the channel of a peer. If not existing, create.
553  */
554   struct GNUNET_CADET_Channel *
555 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
556              const struct GNUNET_PeerIdentity *peer)
557 {
558   struct PeerContext *ctx;
559
560   ctx = get_peer_ctx (peer_map, peer);
561   if (NULL == ctx->send_channel)
562   {
563     ctx->send_channel = GNUNET_CADET_channel_create (cadet_handle, NULL, peer,
564                                                      GNUNET_RPS_CADET_PORT,
565                                                      GNUNET_CADET_OPTION_RELIABLE);
566
567     if (NULL == ctx->recv_channel)
568     {
569       ctx->peer_id = *peer;
570       ctx->is_live_task =
571           GNUNET_CADET_notify_transmit_ready (ctx->send_channel, GNUNET_NO,
572                                               GNUNET_TIME_UNIT_FOREVER_REL,
573                                               sizeof (struct GNUNET_MessageHeader),
574                                               peer_is_live, ctx);
575     }
576
577     // do I have to explicitly put it in the peer_map?
578     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
579                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
580   }
581   return ctx->send_channel;
582 }
583
584
585 /**
586  * Get the message queue of a specific peer.
587  *
588  * If we already have a message queue open to this client,
589  * simply return it, otherways create one.
590  */
591   struct GNUNET_MQ_Handle *
592 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
593         const struct GNUNET_PeerIdentity *peer_id)
594 {
595   struct PeerContext *ctx;
596
597   ctx = get_peer_ctx (peer_map, peer_id);
598   if (NULL == ctx->mq)
599   {
600     (void) get_channel (peer_map, peer_id);
601     ctx->mq = GNUNET_CADET_mq_create (ctx->send_channel);
602     //do I have to explicitly put it in the peer_map?
603     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, ctx,
604                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
605   }
606   return ctx->mq;
607 }
608
609
610 /**
611  * Sum all time relatives of an array.
612   */
613   struct GNUNET_TIME_Relative
614 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
615 {
616   struct GNUNET_TIME_Relative sum;
617   uint32_t i;
618
619   sum = GNUNET_TIME_UNIT_ZERO;
620   for ( i = 0 ; i < arr_size ; i++ )
621   {
622     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
623   }
624   return sum;
625 }
626
627
628 /**
629  * Compute the average of given time relatives.
630  */
631   struct GNUNET_TIME_Relative
632 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
633 {
634   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
635 }
636
637
638 /**
639  * Insert PeerID in #pull_list
640  *
641  * Called once we know a peer is live.
642  */
643   void
644 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
645 {
646   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
647     GNUNET_array_append (pull_list, pull_list_size, *peer);
648 }
649
650 /**
651  * Check whether #insert_in_pull_list was already scheduled
652  */
653   int
654 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
655 {
656   unsigned int i;
657
658   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
659     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
660       return GNUNET_YES;
661   return GNUNET_NO;
662 }
663
664
665 /**
666  * Insert PeerID in #gossip_list
667  *
668  * Called once we know a peer is live.
669  */
670   void
671 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
672 {
673   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
674     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
675 }
676
677 /**
678  * Check whether #insert_in_pull_list was already scheduled
679  */
680   int
681 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
682 {
683   unsigned int i;
684
685   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
686     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
687       return GNUNET_YES;
688   return GNUNET_NO;
689 }
690
691
692 /**
693  * Update sampler with given PeerID.
694  */
695   void
696 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
697 {
698   RPS_sampler_update_list (peer);
699 }
700
701
702 /**
703  * Check whether #insert_in_sampler was already scheduled
704  */
705   int
706 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
707 {
708   unsigned int i;
709
710   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
711     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
712       return GNUNET_YES;
713   return GNUNET_NO;
714 }
715
716
717 /**
718  * Wrapper around #RPS_sampler_resize()
719  */
720   void
721 resize_wrapper ()
722 {
723   uint32_t bigger_size;
724   unsigned int sampler_size;
725
726   // TODO statistics
727
728   if (sampler_size_est_need > sampler_size_client_need)
729     bigger_size = sampler_size_est_need;
730   else
731     bigger_size = sampler_size_client_need;
732
733   // TODO respect the min, max
734   sampler_size = RPS_sampler_get_size ();
735   if (sampler_size > bigger_size * 4)
736   { /* Shrinking */
737     RPS_sampler_resize (sampler_size / 2);
738   }
739   else if (sampler_size < bigger_size)
740   { /* Growing */
741     RPS_sampler_resize (sampler_size * 2);
742   }
743   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
744 }
745
746
747 /**
748  * Estimate request rate
749  *
750  * Called every time we receive a request from the client.
751  */
752   void
753 est_request_rate()
754 {
755   struct GNUNET_TIME_Relative max_round_duration;
756
757   if (request_deltas_size > req_counter)
758     req_counter++;
759   if ( 1 < req_counter)
760   {
761     /* Shift last request deltas to the right */
762     memcpy (&request_deltas[1],
763         request_deltas,
764         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
765
766     /* Add current delta to beginning */
767     request_deltas[0] =
768         GNUNET_TIME_absolute_get_difference (last_request,
769                                              GNUNET_TIME_absolute_get ());
770     request_rate = T_relative_avg (request_deltas, req_counter);
771
772     /* Compute the duration a round will maximally take */
773     max_round_duration =
774         GNUNET_TIME_relative_add (round_interval,
775                                   GNUNET_TIME_relative_divide (round_interval, 2));
776
777     /* Set the estimated size the sampler has to have to
778      * satisfy the current client request rate */
779     sampler_size_client_need =
780         max_round_duration.rel_value_us / request_rate.rel_value_us;
781
782     /* Resize the sampler */
783     resize_wrapper ();
784   }
785   last_request = GNUNET_TIME_absolute_get ();
786 }
787
788
789 /***********************************************************************
790  * /Util functions
791 ***********************************************************************/
792
793 /**
794  * Function called by NSE.
795  *
796  * Updates sizes of sampler list and gossip list and adapt those lists
797  * accordingly.
798  */
799   void
800 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
801               double logestimate, double std_dev)
802 {
803   double estimate;
804   //double scale; // TODO this might go gloabal/config
805
806   LOG (GNUNET_ERROR_TYPE_DEBUG,
807        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
808        logestimate, std_dev, RPS_sampler_get_size ());
809   //scale = .01;
810   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
811   // GNUNET_NSE_log_estimate_to_n (logestimate);
812   estimate = pow (estimate, 1.0 / 3);
813   // TODO add if std_dev is a number
814   // estimate += (std_dev * scale);
815   if (2 < ceil (estimate))
816   {
817     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
818     sampler_size_est_need = estimate;
819   } else
820     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
821
822   /* If the NSE has changed adapt the lists accordingly */
823   resize_wrapper ();
824 }
825
826
827 /**
828  * Callback called once the requested PeerIDs are ready.
829  *
830  * Sends those to the requesting client.
831  */
832 void client_respond (void *cls,
833     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
834 {
835   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
836   struct GNUNET_MQ_Envelope *ev;
837   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
838   struct GNUNET_SERVER_Client *client;
839   uint32_t size_needed;
840   struct client_ctx *cli_ctx;
841
842   client = (struct GNUNET_SERVER_Client *) cls;
843
844   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
845                 num_peers * sizeof (struct GNUNET_PeerIdentity);
846
847   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
848
849   ev = GNUNET_MQ_msg_extra (out_msg,
850                             num_peers * sizeof (struct GNUNET_PeerIdentity),
851                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
852   out_msg->num_peers = htonl (num_peers);
853
854   memcpy (&out_msg[1],
855       ids,
856       num_peers * sizeof (struct GNUNET_PeerIdentity));
857   GNUNET_free (ids);
858
859   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
860   if ( NULL == cli_ctx ) {
861     cli_ctx = GNUNET_new (struct client_ctx);
862     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
863     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
864   }
865
866   GNUNET_MQ_send (cli_ctx->mq, ev);
867 }
868
869
870 /**
871  * Handle RPS request from the client.
872  *
873  * @param cls closure
874  * @param client identification of the client
875  * @param message the actual message
876  */
877 static void
878 handle_client_request (void *cls,
879             struct GNUNET_SERVER_Client *client,
880             const struct GNUNET_MessageHeader *message)
881 {
882   struct GNUNET_RPS_CS_RequestMessage *msg;
883   uint32_t num_peers;
884   uint32_t size_needed;
885   uint32_t i;
886
887   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
888
889   num_peers = ntohl (msg->num_peers);
890   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
891                 num_peers * sizeof (struct GNUNET_PeerIdentity);
892
893   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
894   {
895     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
896     return;
897   }
898
899   for (i = 0 ; i < num_peers ; i++)
900     est_request_rate();
901
902   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
903
904   RPS_sampler_get_n_rand_peers (client_respond, client, num_peers, GNUNET_YES);
905
906   GNUNET_SERVER_receive_done (client,
907                               GNUNET_OK);
908 }
909
910
911 /**
912  * Handle seed from the client.
913  *
914  * @param cls closure
915  * @param client identification of the client
916  * @param message the actual message
917  */
918   static void
919 handle_client_seed (void *cls,
920             struct GNUNET_SERVER_Client *client,
921             const struct GNUNET_MessageHeader *message)
922 {
923   struct GNUNET_RPS_CS_SeedMessage *in_msg;
924   struct GNUNET_PeerIdentity *peers;
925   uint32_t i;
926
927   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) < ntohs (message->size))
928   {
929     GNUNET_break_op (0);
930     GNUNET_SERVER_receive_done (client,
931               GNUNET_SYSERR);
932   }
933   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
934   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
935       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
936   {
937     GNUNET_break_op (0);
938     GNUNET_SERVER_receive_done (client,
939               GNUNET_SYSERR);
940   }
941
942   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
943   peers = (struct GNUNET_PeerIdentity *) &message[1];
944
945   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
946     RPS_sampler_update_list (&peers[i]);
947
948   GNUNET_SERVER_receive_done (client,
949                               GNUNET_OK);
950 }
951
952
953 /**
954  * Handle a PUSH message from another peer.
955  *
956  * Check the proof of work and store the PeerID
957  * in the temporary list for pushed PeerIDs.
958  *
959  * @param cls Closure
960  * @param channel The channel the PUSH was received over
961  * @param channel_ctx The context associated with this channel
962  * @param msg The message header
963  */
964 static int
965 handle_peer_push (void *cls,
966     struct GNUNET_CADET_Channel *channel,
967     void **channel_ctx,
968     const struct GNUNET_MessageHeader *msg)
969 {
970   const struct GNUNET_PeerIdentity *peer;
971
972   // (check the proof of work)
973
974   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
975   // FIXME wait for cadet to change this function
976   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
977
978   /* Add the sending peer to the push_list */
979   if (GNUNET_NO == in_arr (push_list, pull_list_size, peer))
980     GNUNET_array_append (push_list, push_list_size, *peer);
981
982   return GNUNET_OK;
983 }
984
985 /**
986  * Handle PULL REQUEST request message from another peer.
987  *
988  * Reply with the gossip list of PeerIDs.
989  *
990  * @param cls Closure
991  * @param channel The channel the PUSH was received over
992  * @param channel_ctx The context associated with this channel
993  * @param msg The message header
994  */
995 static int
996 handle_peer_pull_request (void *cls,
997     struct GNUNET_CADET_Channel *channel,
998     void **channel_ctx,
999     const struct GNUNET_MessageHeader *msg)
1000 {
1001   struct GNUNET_PeerIdentity *peer;
1002   uint32_t send_size;
1003   struct GNUNET_MQ_Handle *mq;
1004   struct GNUNET_MQ_Envelope *ev;
1005   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1006
1007
1008   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel,
1009                                                                        GNUNET_CADET_OPTION_PEER);
1010   // FIXME wait for cadet to change this function
1011
1012   /* Compute actual size */
1013   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1014               gossip_list_size * sizeof (struct GNUNET_PeerIdentity);
1015
1016   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1017     /* Compute number of peers to send
1018      * If too long, simply truncate */
1019     send_size = (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1020                  sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1021                  sizeof (struct GNUNET_PeerIdentity);
1022   else
1023     send_size = gossip_list_size;
1024
1025   LOG (GNUNET_ERROR_TYPE_DEBUG,
1026       "PULL REQUEST from peer %s received, going to send %u peers\n",
1027       GNUNET_i2s (peer), send_size);
1028
1029   mq = get_mq (peer_map, peer);
1030
1031   ev = GNUNET_MQ_msg_extra (out_msg,
1032                            send_size * sizeof (struct GNUNET_PeerIdentity),
1033                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1034   //out_msg->num_peers = htonl (gossip_list_size);
1035   out_msg->num_peers = htonl (send_size);
1036   memcpy (&out_msg[1], gossip_list,
1037          send_size * sizeof (struct GNUNET_PeerIdentity));
1038
1039   GNUNET_MQ_send (mq, ev);
1040
1041   return GNUNET_OK;
1042 }
1043
1044 /**
1045  * Handle PULL REPLY message from another peer.
1046  *
1047  * Check whether we sent a corresponding request and
1048  * whether this reply is the first one.
1049  *
1050  * @param cls Closure
1051  * @param channel The channel the PUSH was received over
1052  * @param channel_ctx The context associated with this channel
1053  * @param msg The message header
1054  */
1055   static int
1056 handle_peer_pull_reply (void *cls,
1057     struct GNUNET_CADET_Channel *channel,
1058     void **channel_ctx,
1059     const struct GNUNET_MessageHeader *msg)
1060 {
1061   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1062
1063   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1064   struct GNUNET_PeerIdentity *peers;
1065   struct PeerContext *peer_ctx;
1066   struct GNUNET_PeerIdentity *sender;
1067   struct PeerContext *sender_ctx;
1068   struct PeerOutstandingOp out_op;
1069   uint32_t i;
1070
1071   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1072   {
1073     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
1074     return GNUNET_SYSERR;
1075   }
1076   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1077   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1078   {
1079     LOG (GNUNET_ERROR_TYPE_ERROR, "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1080         ntohl (in_msg->num_peers),
1081         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity));
1082     GNUNET_break_op (0);
1083     return GNUNET_SYSERR;
1084   }
1085
1086   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1087       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1088        // Guess simply casting isn't the nicest way...
1089        // FIXME wait for cadet to change this function
1090   sender_ctx = get_peer_ctx (peer_map, sender);
1091
1092   if (0 == (sender_ctx->peer_flags || PULL_REPLY_PENDING))
1093   {
1094     GNUNET_break_op (0);
1095     return GNUNET_OK;
1096   }
1097
1098   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1099   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
1100   {
1101     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1102     if ((0 != (peer_ctx->peer_flags && LIVING)) ||
1103         NULL != peer_ctx->recv_channel)
1104     {
1105       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i]))
1106         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1107     }
1108     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1109     {
1110       out_op.op = insert_in_pull_list;
1111       out_op.op_cls = NULL;
1112       GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1113     }
1114   }
1115
1116   sender_ctx->peer_flags &= (~PULL_REPLY_PENDING);
1117   rem_from_list (pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1118
1119   return GNUNET_OK;
1120 }
1121
1122
1123 /**
1124  * Send out PUSHes and PULLs.
1125  *
1126  * This is executed regylary.
1127  */
1128 static void
1129 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1130 {
1131   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
1132
1133   uint32_t i;
1134   unsigned int *permut;
1135   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1136   struct GNUNET_MQ_Envelope *ev;
1137   struct GNUNET_PeerIdentity peer;
1138   struct GNUNET_PeerIdentity *tmp_peer;
1139   struct GNUNET_MQ_Handle *mq;
1140
1141   LOG (GNUNET_ERROR_TYPE_DEBUG,
1142        "Printing gossip list:\n");
1143   for (i = 0 ; i < gossip_list_size ; i++)
1144     LOG (GNUNET_ERROR_TYPE_DEBUG,
1145          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
1146   // TODO log lists, ...
1147
1148   /* Would it make sense to have one shuffeled gossip list and then
1149    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1150    * use the rest to update sampler?
1151    * in essence get random peers with consumption */
1152
1153   /* Send PUSHes */
1154   if (0 < gossip_list_size)
1155   {
1156     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
1157                                            (unsigned int) gossip_list_size);
1158     n_peers = ceil (alpha * gossip_list_size);
1159     LOG (GNUNET_ERROR_TYPE_DEBUG,
1160          "Going to send pushes to %u ceil (%f * %u) peers.\n",
1161          n_peers, alpha, gossip_list_size);
1162     for (i = 0 ; i < n_peers ; i++)
1163     {
1164       peer = gossip_list[permut[i]];
1165       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
1166       { // FIXME if this fails schedule/loop this for later
1167         LOG (GNUNET_ERROR_TYPE_DEBUG,
1168              "Sending PUSH to peer %s of gossiped list.\n",
1169              GNUNET_i2s (&peer));
1170
1171         ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1172         mq = get_mq (peer_map, &peer);
1173         GNUNET_MQ_send (mq, ev);
1174       }
1175     }
1176     GNUNET_free (permut);
1177   }
1178
1179
1180   /* Send PULL requests */
1181   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1182   n_peers = ceil (beta * gossip_list_size);
1183   LOG (GNUNET_ERROR_TYPE_DEBUG,
1184        "Going to send pulls to %u ceil (%f * %u) peers.\n",
1185        n_peers, beta, gossip_list_size);
1186   for (i = 0 ; i < n_peers ; i++)
1187   {
1188     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1189         pending_pull_reply_list, pending_pull_reply_list_size);
1190     if (NULL != tmp_peer)
1191     {
1192       peer = *tmp_peer;
1193       GNUNET_free (tmp_peer);
1194
1195       GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, peer);
1196
1197       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
1198       { // FIXME if this fails schedule/loop this for later
1199         LOG (GNUNET_ERROR_TYPE_DEBUG,
1200              "Sending PULL request to peer %s of gossiped list.\n",
1201              GNUNET_i2s (&peer));
1202
1203         ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1204         mq = get_mq (peer_map, &peer);
1205         GNUNET_MQ_send (mq, ev);
1206       }
1207     }
1208   }
1209
1210
1211   /* Update gossip list */
1212   uint32_t r_index;
1213
1214   if ( push_list_size <= alpha * gossip_list_size &&
1215        push_list_size != 0 &&
1216        pull_list_size != 0 )
1217   {
1218     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1219
1220     uint32_t first_border;
1221     uint32_t second_border;
1222
1223     first_border  =                ceil (alpha * sampler_size_est_need);
1224     second_border = first_border + ceil (beta  * sampler_size_est_need);
1225
1226     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1227
1228     for (i = 0 ; i < first_border ; i++)
1229     { // TODO use RPS_sampler_get_n_rand_peers
1230       /* Update gossip list with peers received through PUSHes */
1231       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1232                                        push_list_size);
1233       gossip_list[i] = push_list[r_index];
1234       // TODO change the peer_flags accordingly
1235     }
1236
1237     for (i = first_border ; i < second_border ; i++)
1238     {
1239       /* Update gossip list with peers received through PULLs */
1240       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1241                                        pull_list_size);
1242       gossip_list[i] = pull_list[r_index];
1243       // TODO change the peer_flags accordingly
1244     }
1245
1246     for (i = second_border ; i < sampler_size_est_need ; i++)
1247     {
1248       /* Update gossip list with peers from history */
1249       RPS_sampler_get_n_rand_peers (hist_update, NULL, 1, GNUNET_NO);
1250       num_hist_update_tasks++;
1251       // TODO change the peer_flags accordingly
1252     }
1253
1254   }
1255   else
1256   {
1257     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
1258   }
1259   // TODO independent of that also get some peers from CADET_get_peers()?
1260
1261
1262   /* Update samplers */
1263
1264   for ( i = 0 ; i < push_list_size ; i++ )
1265   {
1266     RPS_sampler_update_list (&push_list[i]);
1267     // TODO set in_flag?
1268   }
1269
1270   for ( i = 0 ; i < pull_list_size ; i++ )
1271   {
1272     RPS_sampler_update_list (&pull_list[i]);
1273     // TODO set in_flag?
1274   }
1275
1276
1277   /* Empty push/pull lists */
1278   GNUNET_array_grow (push_list, push_list_size, 0);
1279   GNUNET_array_grow (pull_list, pull_list_size, 0);
1280
1281   struct GNUNET_TIME_Relative time_next_round;
1282   struct GNUNET_TIME_Relative half_round_interval;
1283   unsigned int rand_delay;
1284
1285   /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
1286   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
1287   do
1288   {
1289   /*
1290    * Compute random value between (0 and 1) * round_interval
1291    * via multiplying round_interval with a 'fraction' (0 to value)/value
1292    */
1293   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
1294   time_next_round = GNUNET_TIME_relative_multiply (round_interval,  rand_delay);
1295   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
1296   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
1297   } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
1298
1299   /* Schedule next round */
1300   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1301   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1302 }
1303
1304
1305 /**
1306  * Open a connection to given peer and store channel and mq.
1307  */
1308   void
1309 insertCB (void *cls, const struct GNUNET_PeerIdentity *id)
1310 {
1311   // We open a channel to be notified when this peer goes down.
1312   (void) get_channel (peer_map, id);
1313 }
1314
1315
1316 /**
1317  * Close the connection to given peer and delete channel and mq.
1318  */
1319   void
1320 removeCB (void *cls, const struct GNUNET_PeerIdentity *id)
1321 {
1322   size_t s;
1323   struct PeerContext *ctx;
1324
1325   s = RPS_sampler_count_id (id);
1326   if ( 1 >= s )
1327   {
1328     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, id))
1329     {
1330       ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, id);
1331       if (NULL != ctx->send_channel)
1332       {
1333         if (NULL != ctx->mq)
1334         {
1335           GNUNET_MQ_destroy (ctx->mq);
1336         }
1337         // may already be freed at shutdown of cadet
1338         //GNUNET_CADET_channel_destroy (ctx->send_channel);
1339       }
1340       // TODO cleanup peer
1341       (void) GNUNET_CONTAINER_multipeermap_remove_all (peer_map, id);
1342     }
1343   }
1344 }
1345
1346 static void
1347 rps_start (struct GNUNET_SERVER_Handle *server);
1348
1349 /**
1350  * This is called from GNUNET_CADET_get_peers().
1351  *
1352  * It is called on every peer(ID) that cadet somehow has contact with.
1353  * We use those to initialise the sampler.
1354  */
1355 void
1356 init_peer_cb (void *cls,
1357               const struct GNUNET_PeerIdentity *peer,
1358               int tunnel, // "Do we have a tunnel towards this peer?"
1359               unsigned int n_paths, // "Number of known paths towards this peer"
1360               unsigned int best_path) // "How long is the best path?
1361                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1362 {
1363   struct GNUNET_SERVER_Handle *server;
1364   struct PeerOutstandingOp out_op;
1365   struct PeerContext *peer_ctx;
1366
1367   server = (struct GNUNET_SERVER_Handle *) cls;
1368   if ( NULL != peer )
1369   {
1370     LOG (GNUNET_ERROR_TYPE_DEBUG,
1371         "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1372         GNUNET_i2s (peer), peer, gossip_list_size);
1373
1374     // maybe create a function for that
1375     peer_ctx = get_peer_ctx (peer_map, peer);
1376     if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1377     {
1378       out_op.op = insert_in_sampler;
1379       GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1380     }
1381
1382     if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1383     {
1384       out_op.op = insert_in_gossip_list;
1385       out_op.op_cls = NULL;
1386       GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1387     }
1388
1389     /* Issue livelyness test on peer */
1390     (void) get_channel (peer_map, peer);
1391
1392     // send push/pull to each of those peers?
1393   }
1394   else
1395     rps_start (server);
1396 }
1397
1398
1399 /**
1400  * Callback used to clean the multipeermap.
1401  */
1402   int
1403 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1404 {
1405   struct PeerContext *peer_ctx;
1406   const struct GNUNET_CADET_Channel *ch = (const struct GNUNET_CADET_Channel *) cls;
1407   struct GNUNET_CADET_Channel *recv;
1408   struct GNUNET_CADET_Channel *send;
1409
1410   peer_ctx = (struct PeerContext *) value;
1411
1412   if (0 != peer_ctx->num_outstanding_ops)
1413     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
1414
1415   if (NULL != peer_ctx->mq)
1416     GNUNET_MQ_destroy (peer_ctx->mq);
1417
1418   if (NULL != peer_ctx->is_live_task)
1419   {
1420     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
1421     peer_ctx->is_live_task = NULL;
1422   }
1423
1424   send = peer_ctx->send_channel;
1425   peer_ctx->send_channel = NULL;
1426   recv = peer_ctx->send_channel;
1427   peer_ctx->recv_channel = NULL;
1428
1429   if (NULL  != send
1430       && ch != send)
1431   {
1432     GNUNET_CADET_channel_destroy (send);
1433   }
1434
1435   if (NULL  != recv
1436       && ch != recv)
1437   {
1438     GNUNET_CADET_channel_destroy (recv);
1439   }
1440
1441   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1442     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1443   else
1444     GNUNET_free (peer_ctx);
1445
1446   return GNUNET_YES;
1447 }
1448
1449
1450 /**
1451  * Task run during shutdown.
1452  *
1453  * @param cls unused
1454  * @param tc unused
1455  */
1456 static void
1457 shutdown_task (void *cls,
1458                const struct GNUNET_SCHEDULER_TaskContext *tc)
1459 {
1460   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1461
1462   if ( NULL != do_round_task )
1463   {
1464     GNUNET_SCHEDULER_cancel (do_round_task);
1465     do_round_task = NULL;
1466   }
1467
1468
1469   {
1470   if (GNUNET_SYSERR == GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1471     LOG (GNUNET_ERROR_TYPE_WARNING,
1472         "Iterating over peers to disconnect from them was cancelled\n");
1473   }
1474
1475   GNUNET_NSE_disconnect (nse);
1476   GNUNET_CADET_disconnect (cadet_handle);
1477   RPS_sampler_destroy ();
1478   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
1479   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1480   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1481   GNUNET_array_grow (push_list, push_list_size, 0);
1482   GNUNET_array_grow (pull_list, pull_list_size, 0);
1483 }
1484
1485
1486 /**
1487  * A client disconnected.  Remove all of its data structure entries.
1488  *
1489  * @param cls closure, NULL
1490  * @param client identification of the client
1491  */
1492 static void
1493 handle_client_disconnect (void *cls,
1494                           struct GNUNET_SERVER_Client * client)
1495 {
1496 }
1497
1498
1499 /**
1500  * Handle the channel a peer opens to us.
1501  *
1502  * @param cls The closure
1503  * @param channel The channel the peer wants to establish
1504  * @param initiator The peer's peer ID
1505  * @param port The port the channel is being established over
1506  * @param options Further options
1507  */
1508   static void *
1509 handle_inbound_channel (void *cls,
1510                         struct GNUNET_CADET_Channel *channel,
1511                         const struct GNUNET_PeerIdentity *initiator,
1512                         uint32_t port,
1513                         enum GNUNET_CADET_ChannelOption options)
1514 {
1515   struct PeerContext *ctx;
1516
1517   LOG (GNUNET_ERROR_TYPE_DEBUG,
1518       "New channel was established to us (Peer %s).\n",
1519       GNUNET_i2s (initiator));
1520
1521   GNUNET_assert (NULL != channel);
1522
1523   // we might not even store the recv_channel
1524
1525   ctx = get_peer_ctx (peer_map, initiator);
1526   if (NULL != ctx->recv_channel)
1527   {
1528     ctx->recv_channel = channel;
1529   }
1530
1531   ctx->peer_flags |= LIVING;
1532
1533   //ctx->peer_flags = IN_OTHER_GOSSIP_LIST;
1534   ctx->mq = NULL;
1535
1536   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, ctx,
1537       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1538
1539   return NULL; // TODO
1540 }
1541
1542
1543 /**
1544  * This is called when a remote peer destroys a channel.
1545  *
1546  * @param cls The closure
1547  * @param channel The channel being closed
1548  * @param channel_ctx The context associated with this channel
1549  */
1550   static void
1551 cleanup_channel (void *cls,
1552                 const struct GNUNET_CADET_Channel *channel,
1553                 void *channel_ctx)
1554 {
1555   struct GNUNET_PeerIdentity *peer;
1556   struct PeerContext *peer_ctx;
1557
1558   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1559       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1560        // Guess simply casting isn't the nicest way...
1561        // FIXME wait for cadet to change this function
1562   LOG (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up channel to peer %s\n",
1563        GNUNET_i2s (peer));
1564
1565   RPS_sampler_reinitialise_by_value (peer);
1566
1567   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1568   {
1569     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
1570
1571     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
1572       return;
1573
1574     /* Somwewhat {ab,re}use the iterator function */
1575     /* Cast to void is ok, because it's used as void in peer_remove_cb */
1576     (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
1577   }
1578 }
1579
1580
1581 /**
1582  * Actually start the service.
1583  */
1584   static void
1585 rps_start (struct GNUNET_SERVER_Handle *server)
1586 {
1587   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1588     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1589       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1590     {&handle_client_seed,    NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
1591     {NULL, NULL, 0, 0}
1592   };
1593
1594   GNUNET_SERVER_add_handlers (server, handlers);
1595   GNUNET_SERVER_disconnect_notify (server,
1596                                    &handle_client_disconnect,
1597                                    NULL);
1598   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1599
1600
1601   num_hist_update_tasks = 0;
1602
1603   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1604   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1605
1606   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1607                                 &shutdown_task,
1608                                 NULL);
1609 }
1610
1611
1612 /**
1613  * Process statistics requests.
1614  *
1615  * @param cls closure
1616  * @param server the initialized server
1617  * @param c configuration to use
1618  */
1619   static void
1620 run (void *cls,
1621      struct GNUNET_SERVER_Handle *server,
1622      const struct GNUNET_CONFIGURATION_Handle *c)
1623 {
1624   // TODO check what this does -- copied from gnunet-boss
1625   // - seems to work as expected
1626   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1627   cfg = c;
1628
1629
1630   /* Get own ID */
1631   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
1632   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1633               "STARTING SERVICE (rps) for peer [%s]\n",
1634               GNUNET_i2s (&own_identity));
1635
1636
1637   /* Get time interval from the configuration */
1638   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1639                                                         "ROUNDINTERVAL",
1640                                                         &round_interval))
1641   {
1642     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1643     GNUNET_SCHEDULER_shutdown ();
1644     return;
1645   }
1646
1647   /* Get initial size of sampler/gossip list from the configuration */
1648   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1649                                                          "INITSIZE",
1650                                                          (long long unsigned int *) &sampler_size_est_need))
1651   {
1652     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1653     GNUNET_SCHEDULER_shutdown ();
1654     return;
1655   }
1656   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
1657
1658
1659   gossip_list = NULL;
1660
1661
1662   /* connect to NSE */
1663   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
1664   // TODO check whether that was successful
1665   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1666
1667
1668   alpha = 0.45;
1669   beta  = 0.45;
1670
1671   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
1672
1673
1674   /* Initialise cadet */
1675   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1676     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
1677       sizeof (struct GNUNET_MessageHeader)},
1678     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
1679       sizeof (struct GNUNET_MessageHeader)},
1680     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1681     {NULL, 0, 0}
1682   };
1683
1684   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1685   cadet_handle = GNUNET_CADET_connect (cfg,
1686                                        cls,
1687                                        &handle_inbound_channel,
1688                                        &cleanup_channel,
1689                                        cadet_handlers,
1690                                        ports);
1691   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1692
1693
1694   /* Initialise sampler */
1695   struct GNUNET_TIME_Relative half_round_interval;
1696   struct GNUNET_TIME_Relative  max_round_interval;
1697
1698   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
1699   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
1700
1701   RPS_sampler_init (sampler_size_est_need, max_round_interval,
1702       insertCB, NULL, removeCB, NULL);
1703
1704   /* Initialise push and pull maps */
1705   push_list = NULL;
1706   push_list_size = 0;
1707   pull_list = NULL;
1708   pull_list_size = 0;
1709   pending_pull_reply_list = NULL;
1710   pending_pull_reply_list_size = 0;
1711
1712
1713   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1714   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, server);
1715
1716   // TODO send push/pull to each of those peers?
1717 }
1718
1719
1720 /**
1721  * The main function for the rps service.
1722  *
1723  * @param argc number of arguments from the command line
1724  * @param argv command line arguments
1725  * @return 0 ok, 1 on error
1726  */
1727   int
1728 main (int argc, char *const *argv)
1729 {
1730   return (GNUNET_OK ==
1731           GNUNET_SERVICE_run (argc,
1732                               argv,
1733                               "rps",
1734                               GNUNET_SERVICE_OPTION_NONE,
1735                               &run, NULL)) ? 0 : 1;
1736 }
1737
1738 /* end of gnunet-service-rps.c */