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