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