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