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