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