2762339aef643060b6d63401b6fca49d3f3995b4
[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
423   tmp_size = 0;
424   tmp_peer_list = NULL;
425   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
426   memcpy (tmp_peer_list, peer_list, list_size * sizeof (struct GNUNET_PeerIdentity));
427   peer = GNUNET_new (struct GNUNET_PeerIdentity);
428
429   do
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
438     *peer = tmp_peer_list[r_index];
439     if (in_arr (tmp_peer_list, list_size, peer))
440     {
441       rem_from_list (tmp_peer_list, &tmp_size, peer);
442       if (0 == tmp_size)
443         return NULL;
444       continue;
445     }
446
447   } while (NULL == peer);
448
449   GNUNET_free (tmp_peer_list);
450
451   return peer;
452 }
453
454
455 /**
456  * Get the context of a peer. If not existing, create.
457  */
458   struct PeerContext *
459 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
460               const struct GNUNET_PeerIdentity *peer)
461 {
462   struct PeerContext *ctx;
463
464   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
465   {
466     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
467   }
468   else
469   {
470     ctx = GNUNET_new (struct PeerContext);
471     ctx->peer_flags = 0;
472     ctx->mq = NULL;
473     ctx->send_channel = NULL;
474     ctx->recv_channel = NULL;
475     ctx->outstanding_ops = NULL;
476     ctx->num_outstanding_ops = 0;
477     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
478                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
479   }
480   return ctx;
481 }
482
483
484 /**
485  * Put random peer from sampler into the gossip list as history update.
486  */
487   void
488 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
489 {
490   GNUNET_assert (1 == num_peers);
491
492   if (gossip_list_size < sampler_size_est_need)
493     GNUNET_array_append (gossip_list, gossip_list_size, *ids);
494
495   if (0 < num_hist_update_tasks)
496     num_hist_update_tasks--;
497 }
498
499
500 /**
501  * Callback that is called when a channel was effectively established.
502  * This is given to ntfy_tmt_rdy and called when the channel was
503  * successfully established.
504  */
505 static size_t
506 peer_is_live (void *cls, size_t size, void *buf)
507 {
508   struct PeerContext *ctx = cls;
509   struct GNUNET_PeerIdentity *peer;
510   struct PeerContext *peer_ctx;
511
512   //if (NULL == buf ||
513   //    0 == size)
514   // TODO check
515
516   ctx->is_live_task = NULL;
517   peer = &ctx->peer_id;
518   peer_ctx = get_peer_ctx (peer_map, peer);
519   peer_ctx->peer_flags |= LIVING;
520
521   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
522
523   if (0 != peer_ctx->num_outstanding_ops)
524   { /* Call outstanding operations */
525     unsigned int i;
526
527     for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
528       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
529     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
530   }
531
532   //if (NULL != peer_ctx->is_live_task)
533   //{
534   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
535   //  peer_ctx->is_live_task = NULL; // needed?
536   //}
537   return 0;
538 }
539
540
541 /**
542  * Get the channel of a peer. If not existing, create.
543  */
544   struct GNUNET_CADET_Channel *
545 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
546              const struct GNUNET_PeerIdentity *peer)
547 {
548   struct PeerContext *ctx;
549
550   ctx = get_peer_ctx (peer_map, peer);
551   if (NULL == ctx->send_channel)
552   {
553     ctx->send_channel = GNUNET_CADET_channel_create (cadet_handle, NULL, peer,
554                                                      GNUNET_RPS_CADET_PORT,
555                                                      GNUNET_CADET_OPTION_RELIABLE);
556
557     if (NULL == ctx->recv_channel)
558     {
559       ctx->peer_id = *peer;
560       ctx->is_live_task =
561           GNUNET_CADET_notify_transmit_ready (ctx->send_channel, GNUNET_NO,
562                                               GNUNET_TIME_UNIT_FOREVER_REL,
563                                               sizeof (struct GNUNET_MessageHeader),
564                                               peer_is_live, ctx);
565     }
566
567     // do I have to explicitly put it in the peer_map?
568     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
569                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
570   }
571   return ctx->send_channel;
572 }
573
574
575 /**
576  * Get the message queue of a specific peer.
577  *
578  * If we already have a message queue open to this client,
579  * simply return it, otherways create one.
580  */
581   struct GNUNET_MQ_Handle *
582 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
583         const struct GNUNET_PeerIdentity *peer_id)
584 {
585   struct PeerContext *ctx;
586
587   ctx = get_peer_ctx (peer_map, peer_id);
588   if (NULL == ctx->mq)
589   {
590     (void) get_channel (peer_map, peer_id);
591     ctx->mq = GNUNET_CADET_mq_create (ctx->send_channel);
592     //do I have to explicitly put it in the peer_map?
593     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, ctx,
594                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
595   }
596   return ctx->mq;
597 }
598
599
600 /**
601  * Sum all time relatives of an array.
602   */
603   struct GNUNET_TIME_Relative
604 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
605 {
606   struct GNUNET_TIME_Relative sum;
607   uint32_t i;
608
609   sum = GNUNET_TIME_UNIT_ZERO;
610   for ( i = 0 ; i < arr_size ; i++ )
611   {
612     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
613   }
614   return sum;
615 }
616
617
618 /**
619  * Compute the average of given time relatives.
620  */
621   struct GNUNET_TIME_Relative
622 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
623 {
624   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
625 }
626
627
628 /**
629  * Insert PeerID in #pull_list
630  *
631  * Called once we know a peer is live.
632  */
633   void
634 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
635 {
636   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
637     GNUNET_array_append (pull_list, pull_list_size, *peer);
638 }
639
640 /**
641  * Check whether #insert_in_pull_list was already scheduled
642  */
643   int
644 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
645 {
646   unsigned int i;
647
648   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
649     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
650       return GNUNET_YES;
651   return GNUNET_NO;
652 }
653
654
655 /**
656  * Insert PeerID in #gossip_list
657  *
658  * Called once we know a peer is live.
659  */
660   void
661 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
662 {
663   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
664     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
665 }
666
667 /**
668  * Check whether #insert_in_pull_list was already scheduled
669  */
670   int
671 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
672 {
673   unsigned int i;
674
675   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
676     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
677       return GNUNET_YES;
678   return GNUNET_NO;
679 }
680
681
682 /**
683  * Update sampler with given PeerID.
684  */
685   void
686 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
687 {
688   RPS_sampler_update_list (peer);
689 }
690
691
692 /**
693  * Check whether #insert_in_sampler was already scheduled
694  */
695   int
696 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
697 {
698   unsigned int i;
699
700   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
701     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
702       return GNUNET_YES;
703   return GNUNET_NO;
704 }
705
706
707 /**
708  * Wrapper around #RPS_sampler_resize()
709  */
710   void
711 resize_wrapper ()
712 {
713   uint32_t bigger_size;
714   unsigned int sampler_size;
715
716   // TODO statistics
717
718   if (sampler_size_est_need > sampler_size_client_need)
719     bigger_size = sampler_size_est_need;
720   else
721     bigger_size = sampler_size_client_need;
722
723   // TODO respect the min, max
724   sampler_size = RPS_sampler_get_size ();
725   if (sampler_size > bigger_size * 4)
726   { /* Shrinking */
727     RPS_sampler_resize (sampler_size / 2);
728   }
729   else if (sampler_size < bigger_size)
730   { /* Growing */
731     RPS_sampler_resize (sampler_size * 2);
732   }
733   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
734 }
735
736
737 /**
738  * Estimate request rate
739  *
740  * Called every time we receive a request from the client.
741  */
742   void
743 est_request_rate()
744 {
745   struct GNUNET_TIME_Relative max_round_duration;
746
747   if (request_deltas_size > req_counter)
748     req_counter++;
749   if ( 1 < req_counter)
750   {
751     /* Shift last request deltas to the right */
752     memcpy (&request_deltas[1],
753         request_deltas,
754         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
755
756     /* Add current delta to beginning */
757     request_deltas[0] =
758         GNUNET_TIME_absolute_get_difference (last_request,
759                                              GNUNET_TIME_absolute_get ());
760     request_rate = T_relative_avg (request_deltas, req_counter);
761
762     /* Compute the duration a round will maximally take */
763     max_round_duration =
764         GNUNET_TIME_relative_add (round_interval,
765                                   GNUNET_TIME_relative_divide (round_interval, 2));
766
767     /* Set the estimated size the sampler has to have to
768      * satisfy the current client request rate */
769     sampler_size_client_need =
770         max_round_duration.rel_value_us / request_rate.rel_value_us;
771
772     /* Resize the sampler */
773     resize_wrapper ();
774   }
775   last_request = GNUNET_TIME_absolute_get ();
776 }
777
778
779 /***********************************************************************
780  * /Util functions
781 ***********************************************************************/
782
783 /**
784  * Function called by NSE.
785  *
786  * Updates sizes of sampler list and gossip list and adapt those lists
787  * accordingly.
788  */
789   void
790 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
791               double logestimate, double std_dev)
792 {
793   double estimate;
794   //double scale; // TODO this might go gloabal/config
795
796   LOG (GNUNET_ERROR_TYPE_DEBUG,
797        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
798        logestimate, std_dev, RPS_sampler_get_size ());
799   //scale = .01;
800   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
801   // GNUNET_NSE_log_estimate_to_n (logestimate);
802   estimate = pow (estimate, 1.0 / 3);
803   // TODO add if std_dev is a number
804   // estimate += (std_dev * scale);
805   if (0 < ceil (estimate))
806   {
807     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
808     sampler_size_est_need = estimate;
809   } else
810     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
811
812   /* If the NSE has changed adapt the lists accordingly */
813   resize_wrapper ();
814 }
815
816
817 /**
818  * Callback called once the requested PeerIDs are ready.
819  *
820  * Sends those to the requesting client.
821  */
822 void client_respond (void *cls,
823     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
824 {
825   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
826   struct GNUNET_MQ_Envelope *ev;
827   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
828   struct GNUNET_SERVER_Client *client;
829   uint32_t size_needed;
830   struct client_ctx *cli_ctx;
831
832   client = (struct GNUNET_SERVER_Client *) cls;
833
834   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
835                 num_peers * sizeof (struct GNUNET_PeerIdentity);
836
837   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
838
839   ev = GNUNET_MQ_msg_extra (out_msg,
840                             num_peers * sizeof (struct GNUNET_PeerIdentity),
841                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
842   out_msg->num_peers = htonl (num_peers);
843
844   memcpy (&out_msg[1],
845       ids,
846       num_peers * sizeof (struct GNUNET_PeerIdentity));
847   GNUNET_free (ids);
848
849   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
850   if ( NULL == cli_ctx ) {
851     cli_ctx = GNUNET_new (struct client_ctx);
852     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
853     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
854   }
855
856   GNUNET_MQ_send (cli_ctx->mq, ev);
857 }
858
859
860 /**
861  * Handle RPS request from the client.
862  *
863  * @param cls closure
864  * @param client identification of the client
865  * @param message the actual message
866  */
867 static void
868 handle_client_request (void *cls,
869             struct GNUNET_SERVER_Client *client,
870             const struct GNUNET_MessageHeader *message)
871 {
872   struct GNUNET_RPS_CS_RequestMessage *msg;
873   uint32_t num_peers;
874   uint32_t size_needed;
875   uint32_t i;
876
877   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
878
879   num_peers = ntohl (msg->num_peers);
880   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
881                 num_peers * sizeof (struct GNUNET_PeerIdentity);
882
883   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
884   {
885     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
886     return;
887   }
888
889   for (i = 0 ; i < num_peers ; i++)
890     est_request_rate();
891
892   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
893
894   RPS_sampler_get_n_rand_peers (client_respond, client, num_peers, GNUNET_YES);
895
896   GNUNET_SERVER_receive_done (client,
897                               GNUNET_OK);
898 }
899
900
901 /**
902  * Handle seed from the client.
903  *
904  * @param cls closure
905  * @param client identification of the client
906  * @param message the actual message
907  */
908   static void
909 handle_client_seed (void *cls,
910             struct GNUNET_SERVER_Client *client,
911             const struct GNUNET_MessageHeader *message)
912 {
913   struct GNUNET_RPS_CS_SeedMessage *in_msg;
914   struct GNUNET_PeerIdentity *peers;
915   uint32_t i;
916
917   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) < ntohs (message->size))
918   {
919     GNUNET_break_op (0);
920     GNUNET_SERVER_receive_done (client,
921               GNUNET_SYSERR);
922   }
923   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
924   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
925       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
926   {
927     GNUNET_break_op (0);
928     GNUNET_SERVER_receive_done (client,
929               GNUNET_SYSERR);
930   }
931
932   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
933   peers = (struct GNUNET_PeerIdentity *) &message[1];
934
935   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
936     RPS_sampler_update_list (&peers[i]);
937
938   GNUNET_SERVER_receive_done (client,
939                               GNUNET_OK);
940 }
941
942
943 /**
944  * Handle a PUSH message from another peer.
945  *
946  * Check the proof of work and store the PeerID
947  * in the temporary list for pushed PeerIDs.
948  *
949  * @param cls Closure
950  * @param channel The channel the PUSH was received over
951  * @param channel_ctx The context associated with this channel
952  * @param msg The message header
953  */
954 static int
955 handle_peer_push (void *cls,
956     struct GNUNET_CADET_Channel *channel,
957     void **channel_ctx,
958     const struct GNUNET_MessageHeader *msg)
959 {
960   const struct GNUNET_PeerIdentity *peer;
961
962   // (check the proof of work)
963
964   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
965   // FIXME wait for cadet to change this function
966   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
967
968   /* Add the sending peer to the push_list */
969   if (GNUNET_NO == in_arr (push_list, pull_list_size, peer))
970     GNUNET_array_append (push_list, push_list_size, *peer);
971
972   return GNUNET_OK;
973 }
974
975 /**
976  * Handle PULL REQUEST request message from another peer.
977  *
978  * Reply with the gossip list of PeerIDs.
979  *
980  * @param cls Closure
981  * @param channel The channel the PUSH was received over
982  * @param channel_ctx The context associated with this channel
983  * @param msg The message header
984  */
985 static int
986 handle_peer_pull_request (void *cls,
987     struct GNUNET_CADET_Channel *channel,
988     void **channel_ctx,
989     const struct GNUNET_MessageHeader *msg)
990 {
991   struct GNUNET_PeerIdentity *peer;
992   uint32_t send_size;
993   struct GNUNET_MQ_Handle *mq;
994   struct GNUNET_MQ_Envelope *ev;
995   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
996
997
998   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel,
999                                                                        GNUNET_CADET_OPTION_PEER);
1000   // FIXME wait for cadet to change this function
1001
1002   /* Compute actual size */
1003   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1004               gossip_list_size * sizeof (struct GNUNET_PeerIdentity);
1005
1006   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1007     /* Compute number of peers to send
1008      * If too long, simply truncate */
1009     send_size = (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1010                  sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1011                  sizeof (struct GNUNET_PeerIdentity);
1012   else
1013     send_size = gossip_list_size;
1014
1015   LOG (GNUNET_ERROR_TYPE_DEBUG,
1016       "PULL REQUEST from peer %s received, going to send %u peers\n",
1017       GNUNET_i2s (peer), send_size);
1018
1019   mq = get_mq (peer_map, peer);
1020
1021   ev = GNUNET_MQ_msg_extra (out_msg,
1022                            send_size * sizeof (struct GNUNET_PeerIdentity),
1023                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1024   //out_msg->num_peers = htonl (gossip_list_size);
1025   out_msg->num_peers = htonl (send_size);
1026   memcpy (&out_msg[1], gossip_list,
1027          send_size * sizeof (struct GNUNET_PeerIdentity));
1028
1029   GNUNET_MQ_send (mq, ev);
1030
1031   return GNUNET_OK;
1032 }
1033
1034 /**
1035  * Handle PULL REPLY message from another peer.
1036  *
1037  * Check whether we sent a corresponding request and
1038  * whether this reply is the first one.
1039  *
1040  * @param cls Closure
1041  * @param channel The channel the PUSH was received over
1042  * @param channel_ctx The context associated with this channel
1043  * @param msg The message header
1044  */
1045   static int
1046 handle_peer_pull_reply (void *cls,
1047     struct GNUNET_CADET_Channel *channel,
1048     void **channel_ctx,
1049     const struct GNUNET_MessageHeader *msg)
1050 {
1051   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1052
1053   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1054   struct GNUNET_PeerIdentity *peers;
1055   struct PeerContext *peer_ctx;
1056   struct GNUNET_PeerIdentity *sender;
1057   struct PeerContext *sender_ctx;
1058   struct PeerOutstandingOp out_op;
1059   uint32_t i;
1060
1061   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1062   {
1063     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
1064     return GNUNET_SYSERR;
1065   }
1066   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1067   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1068   {
1069     LOG (GNUNET_ERROR_TYPE_ERROR, "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1070         ntohl (in_msg->num_peers),
1071         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity));
1072     GNUNET_break_op (0);
1073     return GNUNET_SYSERR;
1074   }
1075
1076   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1077       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1078        // Guess simply casting isn't the nicest way...
1079        // FIXME wait for cadet to change this function
1080   sender_ctx = get_peer_ctx (peer_map, sender);
1081
1082   if (0 == (peer_ctx->peer_flags || PULL_REPLY_PENDING))
1083   {
1084     GNUNET_break_op (0);
1085     return GNUNET_OK;
1086   }
1087
1088   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1089   for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
1090   {
1091     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1092     if ((0 != (peer_ctx->peer_flags && LIVING)) ||
1093         NULL != peer_ctx->recv_channel)
1094     {
1095       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i]))
1096         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1097     }
1098     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1099     {
1100       out_op.op = insert_in_pull_list;
1101       GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1102     }
1103   }
1104
1105   sender_ctx->peer_flags &= (~PULL_REPLY_PENDING);
1106   rem_from_list (pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1107
1108   return GNUNET_OK;
1109 }
1110
1111
1112 /**
1113  * Send out PUSHes and PULLs.
1114  *
1115  * This is executed regylary.
1116  */
1117 static void
1118 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1119 {
1120   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
1121
1122   uint32_t i;
1123   unsigned int *permut;
1124   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1125   struct GNUNET_MQ_Envelope *ev;
1126   const struct GNUNET_PeerIdentity *peer;
1127   struct GNUNET_MQ_Handle *mq;
1128
1129   // TODO log lists, ...
1130
1131
1132   /* Would it make sense to have one shuffeled gossip list and then
1133    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1134    * use the rest to update sampler?
1135    * in essence get random peers with consumption */
1136
1137   /* Send PUSHes */
1138   if (0 < gossip_list_size)
1139   {
1140     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
1141                                            (unsigned int) gossip_list_size);
1142     if (0 != gossip_list_size)
1143     {
1144       n_peers = round (alpha * gossip_list_size);
1145       if (0 == n_peers)
1146         n_peers = 1;
1147       LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pushes to %u (%f * %u) peers.\n",
1148           n_peers, alpha, gossip_list_size);
1149       for ( i = 0 ; i < n_peers ; i++ )
1150       {
1151         peer = &gossip_list[permut[i]];
1152         if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer)) // TODO
1153         { // FIXME if this fails schedule/loop this for later
1154           LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PUSH to peer %s of gossiped list.\n", GNUNET_i2s (peer));
1155
1156           ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1157           mq = get_mq (peer_map, peer);
1158           GNUNET_MQ_send (mq, ev);
1159         }
1160       }
1161     }
1162     GNUNET_free (permut);
1163   }
1164
1165
1166   /* Send PULL requests */
1167   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1168   if (0 != gossip_list_size)
1169   {
1170     n_peers = round (beta * gossip_list_size);
1171     if (0 == n_peers)
1172       n_peers = 1;
1173     LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pulls to %u (%f * %u) peers.\n",
1174         n_peers, beta, gossip_list_size);
1175     for ( i = 0 ; i < n_peers ; i++ )
1176     {
1177       peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1178                                         pending_pull_reply_list, pending_pull_reply_list_size);
1179       if (NULL != peer)
1180       {
1181         GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, *peer);
1182
1183         if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer))
1184         { // FIXME if this fails schedule/loop this for later
1185           LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PULL request to peer %s of gossiped list.\n", GNUNET_i2s (peer));
1186
1187           ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1188           //pull_msg = NULL;
1189           mq = get_mq (peer_map, peer);
1190           GNUNET_MQ_send (mq, ev);
1191         }
1192       }
1193     }
1194   }
1195
1196
1197   /* Update gossip list */
1198   uint32_t r_index;
1199
1200   if ( push_list_size <= alpha * gossip_list_size &&
1201        push_list_size != 0 &&
1202        pull_list_size != 0 )
1203   {
1204     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1205
1206     uint32_t first_border;
1207     uint32_t second_border;
1208
1209     first_border = round (alpha * sampler_size_est_need);
1210     second_border = first_border + round (beta * sampler_size_est_need);
1211
1212     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1213
1214     for ( i = 0 ; i < first_border ; i++ )
1215     { // TODO use RPS_sampler_get_n_rand_peers
1216       /* Update gossip list with peers received through PUSHes */
1217       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1218                                        push_list_size);
1219       gossip_list[i] = push_list[r_index];
1220       // TODO change the peer_flags accordingly
1221     }
1222
1223     for ( i = first_border ; i < second_border ; i++ )
1224     {
1225       /* Update gossip list with peers received through PULLs */
1226       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1227                                        pull_list_size);
1228       gossip_list[i] = pull_list[r_index];
1229       // TODO change the peer_flags accordingly
1230     }
1231
1232     for ( i = second_border ; i < gossip_list_size ; i++ )
1233     {
1234       /* Update gossip list with peers from history */
1235       RPS_sampler_get_n_rand_peers (hist_update, NULL, 1, GNUNET_NO);
1236       num_hist_update_tasks++;
1237       // TODO change the peer_flags accordingly
1238     }
1239
1240   }
1241   else
1242   {
1243     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list. ()\n");
1244   }
1245   // TODO independent of that also get some peers from CADET_get_peers()?
1246
1247
1248   /* Update samplers */
1249
1250   for ( i = 0 ; i < push_list_size ; i++ )
1251   {
1252     RPS_sampler_update_list (&push_list[i]);
1253     // TODO set in_flag?
1254   }
1255
1256   for ( i = 0 ; i < pull_list_size ; i++ )
1257   {
1258     RPS_sampler_update_list (&pull_list[i]);
1259     // TODO set in_flag?
1260   }
1261
1262
1263   /* Empty push/pull lists */
1264   GNUNET_array_grow (push_list, push_list_size, 0);
1265   GNUNET_array_grow (pull_list, pull_list_size, 0);
1266
1267   struct GNUNET_TIME_Relative time_next_round;
1268   struct GNUNET_TIME_Relative half_round_interval;
1269   unsigned int rand_delay;
1270
1271   /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
1272   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
1273   do
1274   {
1275   /*
1276    * Compute random value between (0 and 1) * round_interval
1277    * via multiplying round_interval with a 'fraction' (0 to value)/value
1278    */
1279   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
1280   time_next_round = GNUNET_TIME_relative_multiply (round_interval,  rand_delay);
1281   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
1282   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
1283   } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
1284
1285   /* Schedule next round */
1286   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1287   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1288 }
1289
1290
1291 /**
1292  * Open a connection to given peer and store channel and mq.
1293  */
1294   void
1295 insertCB (void *cls, const struct GNUNET_PeerIdentity *id)
1296 {
1297   // We open a channel to be notified when this peer goes down.
1298   (void) get_channel (peer_map, id);
1299 }
1300
1301
1302 /**
1303  * Close the connection to given peer and delete channel and mq.
1304  */
1305   void
1306 removeCB (void *cls, const struct GNUNET_PeerIdentity *id)
1307 {
1308   size_t s;
1309   struct PeerContext *ctx;
1310
1311   s = RPS_sampler_count_id (id);
1312   if ( 1 >= s )
1313   {
1314     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, id))
1315     {
1316       ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, id);
1317       if (NULL != ctx->send_channel)
1318       {
1319         if (NULL != ctx->mq)
1320         {
1321           GNUNET_MQ_destroy (ctx->mq);
1322         }
1323         // may already be freed at shutdown of cadet
1324         //GNUNET_CADET_channel_destroy (ctx->send_channel);
1325       }
1326       // TODO cleanup peer
1327       (void) GNUNET_CONTAINER_multipeermap_remove_all (peer_map, id);
1328     }
1329   }
1330 }
1331
1332 static void
1333 rps_start (struct GNUNET_SERVER_Handle *server);
1334
1335 /**
1336  * This is called from GNUNET_CADET_get_peers().
1337  *
1338  * It is called on every peer(ID) that cadet somehow has contact with.
1339  * We use those to initialise the sampler.
1340  */
1341 void
1342 init_peer_cb (void *cls,
1343               const struct GNUNET_PeerIdentity *peer,
1344               int tunnel, // "Do we have a tunnel towards this peer?"
1345               unsigned int n_paths, // "Number of known paths towards this peer"
1346               unsigned int best_path) // "How long is the best path?
1347                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1348 {
1349   struct GNUNET_SERVER_Handle *server;
1350   struct PeerOutstandingOp out_op;
1351   struct PeerContext *peer_ctx;
1352
1353   server = (struct GNUNET_SERVER_Handle *) cls;
1354   if ( NULL != peer )
1355   {
1356     LOG (GNUNET_ERROR_TYPE_DEBUG,
1357         "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1358         GNUNET_i2s (peer), peer, gossip_list_size);
1359
1360     // maybe create a function for that
1361     peer_ctx = get_peer_ctx (peer_map, peer);
1362     if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1363     {
1364       out_op.op = insert_in_sampler;
1365       GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1366     }
1367
1368     if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1369     {
1370       out_op.op = insert_in_gossip_list;
1371       GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1372     }
1373
1374     /* Issue livelyness test on peer */
1375     (void) get_channel (peer_map, peer);
1376
1377     // send push/pull to each of those peers?
1378   }
1379   else
1380     rps_start (server);
1381 }
1382
1383
1384 /**
1385  * Callback used to clean the multipeermap.
1386  */
1387   int
1388 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1389 {
1390   struct PeerContext *peer_ctx;
1391   const struct GNUNET_CADET_Channel *ch = (const struct GNUNET_CADET_Channel *) cls;
1392   struct GNUNET_CADET_Channel *destroy;
1393
1394   peer_ctx = (struct PeerContext *) value;
1395
1396   if (NULL != peer_ctx->mq)
1397     GNUNET_MQ_destroy (peer_ctx->mq);
1398
1399   if (NULL != peer_ctx->is_live_task)
1400   {
1401     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
1402     peer_ctx->is_live_task = NULL;
1403   }
1404
1405   if (NULL  != peer_ctx->send_channel
1406       && ch != peer_ctx->send_channel)
1407   {
1408     destroy = peer_ctx->send_channel;
1409     peer_ctx->send_channel = NULL;
1410     GNUNET_CADET_channel_destroy (destroy);
1411   }
1412
1413   if (NULL  != peer_ctx->recv_channel
1414       && ch != peer_ctx->recv_channel)
1415   {
1416     destroy = peer_ctx->recv_channel;
1417     peer_ctx->recv_channel = NULL;
1418     GNUNET_CADET_channel_destroy (destroy);
1419   }
1420
1421   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1422     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1423
1424   GNUNET_free (peer_ctx);
1425   return GNUNET_YES;
1426 }
1427
1428
1429 /**
1430  * Task run during shutdown.
1431  *
1432  * @param cls unused
1433  * @param tc unused
1434  */
1435 static void
1436 shutdown_task (void *cls,
1437                const struct GNUNET_SCHEDULER_TaskContext *tc)
1438 {
1439   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1440
1441   if ( NULL != do_round_task )
1442   {
1443     GNUNET_SCHEDULER_cancel (do_round_task);
1444     do_round_task = NULL;
1445   }
1446
1447
1448   /* FIXME instead of this, destroy every known channel */
1449   {
1450   if (GNUNET_SYSERR == GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1451     LOG (GNUNET_ERROR_TYPE_WARNING,
1452         "Iterating over peers to disconnect from them was cancelled\n");
1453   }
1454
1455   GNUNET_NSE_disconnect (nse);
1456   GNUNET_CADET_disconnect (cadet_handle);
1457   RPS_sampler_destroy ();
1458   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
1459   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1460   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1461   GNUNET_array_grow (push_list, push_list_size, 0);
1462   GNUNET_array_grow (pull_list, pull_list_size, 0);
1463 }
1464
1465
1466 /**
1467  * A client disconnected.  Remove all of its data structure entries.
1468  *
1469  * @param cls closure, NULL
1470  * @param client identification of the client
1471  */
1472 static void
1473 handle_client_disconnect (void *cls,
1474                           struct GNUNET_SERVER_Client * client)
1475 {
1476 }
1477
1478
1479 /**
1480  * Handle the channel a peer opens to us.
1481  *
1482  * @param cls The closure
1483  * @param channel The channel the peer wants to establish
1484  * @param initiator The peer's peer ID
1485  * @param port The port the channel is being established over
1486  * @param options Further options
1487  */
1488   static void *
1489 handle_inbound_channel (void *cls,
1490                         struct GNUNET_CADET_Channel *channel,
1491                         const struct GNUNET_PeerIdentity *initiator,
1492                         uint32_t port,
1493                         enum GNUNET_CADET_ChannelOption options)
1494 {
1495   struct PeerContext *ctx;
1496
1497   LOG (GNUNET_ERROR_TYPE_DEBUG,
1498       "New channel was established to us (Peer %s).\n",
1499       GNUNET_i2s (initiator));
1500
1501   GNUNET_assert (NULL != channel);
1502
1503   // we might not even store the recv_channel
1504
1505   ctx = get_peer_ctx (peer_map, initiator);
1506   if (NULL != ctx->recv_channel)
1507   {
1508     ctx->recv_channel = channel;
1509   }
1510
1511   ctx->peer_flags |= LIVING;
1512
1513   //ctx->peer_flags = IN_OTHER_GOSSIP_LIST;
1514   ctx->mq = NULL;
1515
1516   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, ctx,
1517       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1518
1519   return NULL; // TODO
1520 }
1521
1522
1523 /**
1524  * This is called when a remote peer destroys a channel.
1525  *
1526  * @param cls The closure
1527  * @param channel The channel being closed
1528  * @param channel_ctx The context associated with this channel
1529  */
1530   static void
1531 cleanup_channel (void *cls,
1532                 const struct GNUNET_CADET_Channel *channel,
1533                 void *channel_ctx)
1534 {
1535   struct GNUNET_PeerIdentity *peer;
1536   struct PeerContext *peer_ctx;
1537
1538   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel to remote peer was destroyed.\n");
1539
1540   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1541       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1542        // Guess simply casting isn't the nicest way...
1543        // FIXME wait for cadet to change this function
1544   RPS_sampler_reinitialise_by_value (peer);
1545
1546   peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
1547
1548   if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
1549     return;
1550
1551   /* Somwewhat {ab,re}use the iterator function */
1552   /* Cast to void is ok, because it's used as void in peer_remove_cb */
1553   (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
1554 }
1555
1556
1557 /**
1558  * Actually start the service.
1559  */
1560   static void
1561 rps_start (struct GNUNET_SERVER_Handle *server)
1562 {
1563   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1564     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1565       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1566     {&handle_client_seed,    NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
1567     {NULL, NULL, 0, 0}
1568   };
1569
1570   GNUNET_SERVER_add_handlers (server, handlers);
1571   GNUNET_SERVER_disconnect_notify (server,
1572                                    &handle_client_disconnect,
1573                                    NULL);
1574   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1575
1576
1577   num_hist_update_tasks = 0;
1578
1579   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1580   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1581
1582   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1583                                 &shutdown_task,
1584                                 NULL);
1585 }
1586
1587
1588 /**
1589  * Process statistics requests.
1590  *
1591  * @param cls closure
1592  * @param server the initialized server
1593  * @param c configuration to use
1594  */
1595   static void
1596 run (void *cls,
1597      struct GNUNET_SERVER_Handle *server,
1598      const struct GNUNET_CONFIGURATION_Handle *c)
1599 {
1600   // TODO check what this does -- copied from gnunet-boss
1601   // - seems to work as expected
1602   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1603   cfg = c;
1604
1605
1606   /* Get own ID */
1607   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
1608   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1609               "STARTING SERVICE (rps) for peer [%s]\n",
1610               GNUNET_i2s (&own_identity));
1611
1612
1613   /* Get time interval from the configuration */
1614   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1615                                                         "ROUNDINTERVAL",
1616                                                         &round_interval))
1617   {
1618     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1619     GNUNET_SCHEDULER_shutdown ();
1620     return;
1621   }
1622
1623   /* Get initial size of sampler/gossip list from the configuration */
1624   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1625                                                          "INITSIZE",
1626                                                          (long long unsigned int *) &sampler_size_est_need))
1627   {
1628     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1629     GNUNET_SCHEDULER_shutdown ();
1630     return;
1631   }
1632   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
1633
1634
1635   gossip_list = NULL;
1636
1637
1638   /* connect to NSE */
1639   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
1640   // TODO check whether that was successful
1641   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1642
1643
1644   alpha = 0.45;
1645   beta  = 0.45;
1646
1647   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
1648
1649
1650   /* Initialise cadet */
1651   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1652     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
1653       sizeof (struct GNUNET_MessageHeader)},
1654     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
1655       sizeof (struct GNUNET_MessageHeader)},
1656     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1657     {NULL, 0, 0}
1658   };
1659
1660   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1661   cadet_handle = GNUNET_CADET_connect (cfg,
1662                                        cls,
1663                                        &handle_inbound_channel,
1664                                        &cleanup_channel,
1665                                        cadet_handlers,
1666                                        ports);
1667   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1668
1669
1670   /* Initialise sampler */
1671   struct GNUNET_TIME_Relative half_round_interval;
1672   struct GNUNET_TIME_Relative  max_round_interval;
1673
1674   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
1675   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
1676
1677   RPS_sampler_init (sampler_size_est_need, max_round_interval,
1678       insertCB, NULL, removeCB, NULL);
1679
1680   /* Initialise push and pull maps */
1681   push_list = NULL;
1682   push_list_size = 0;
1683   pull_list = NULL;
1684   pull_list_size = 0;
1685   pending_pull_reply_list = NULL;
1686   pending_pull_reply_list_size = 0;
1687
1688
1689   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1690   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, server);
1691
1692   // TODO send push/pull to each of those peers?
1693 }
1694
1695
1696 /**
1697  * The main function for the rps service.
1698  *
1699  * @param argc number of arguments from the command line
1700  * @param argv command line arguments
1701  * @return 0 ok, 1 on error
1702  */
1703   int
1704 main (int argc, char *const *argv)
1705 {
1706   return (GNUNET_OK ==
1707           GNUNET_SERVICE_run (argc,
1708                               argv,
1709                               "rps",
1710                               GNUNET_SERVICE_OPTION_NONE,
1711                               &run, NULL)) ? 0 : 1;
1712 }
1713
1714 /* end of gnunet-service-rps.c */