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