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