2 This file is part of GNUnet.
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.
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.
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.
22 * @file rps/gnunet-service-rps.c
23 * @brief rps service implementation
24 * @author Julius Bünger
27 #include "gnunet_util_lib.h"
28 #include "gnunet_cadet_service.h"
29 #include "gnunet_nse_service.h"
32 #include "gnunet-service-rps_sampler.h"
37 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
39 // TODO modify @brief in every file
41 // TODO take care that messages are not longer than 64k
43 // TODO check for overflows
45 // TODO align message structs
47 // (TODO api -- possibility of getting weak random peer immideately)
49 // TODO malicious peer
51 // TODO Change API to accept initialisation peers
53 // TODO Change API to accept good peers 'friends'
55 // TODO store peers somewhere
57 // TODO check that every id we get is valid - is it reachable?
61 // hist_size_init, hist_size_max
66 static const struct GNUNET_CONFIGURATION_Handle *cfg;
71 static struct GNUNET_PeerIdentity *own_identity;
74 struct GNUNET_PeerIdentity *
75 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list, unsigned int size,
76 const struct GNUNET_PeerIdentity *ignore_list, unsigned int ignore_size);
79 /***********************************************************************
80 * Housekeeping with peers
81 ***********************************************************************/
84 * Struct used to store the context of a connected client.
89 * The message queue to communicate with the client.
91 struct GNUNET_MQ_Handle *mq;
95 * Used to keep track in what lists single peerIDs are.
99 PULL_REPLY_PENDING = 0x01,
100 IN_OTHER_GOSSIP_LIST = 0x02, // unneeded?
101 IN_OWN_SAMPLER_LIST = 0x04, // unneeded?
102 IN_OWN_GOSSIP_LIST = 0x08, // unneeded?
105 * We set this bit when we can be sure the other peer is/was live.
112 * Functions of this type can be used to be stored at a peer for later execution.
114 typedef void (* PeerOp) (void *cls, const struct GNUNET_PeerIdentity *peer);
117 * Outstanding operation on peer consisting of callback and closure
119 struct PeerOutstandingOp
134 * Struct used to keep track of other peer's status
136 * This is stored in a multipeermap.
141 * In own gossip/sampler list, in other's gossip/sampler list
146 * Message queue open to client
148 struct GNUNET_MQ_Handle *mq;
151 * Channel open to client.
153 struct GNUNET_CADET_Channel *send_channel;
156 * Channel open from client.
158 struct GNUNET_CADET_Channel *recv_channel; // unneeded?
161 * Array of outstanding operations on this peer.
163 struct PeerOutstandingOp *outstanding_ops;
166 * Number of outstanding operations.
168 unsigned int num_outstanding_ops;
169 //size_t num_outstanding_ops;
172 * Handle to the callback given to cadet_ntfy_tmt_rdy()
174 * To be canceled on shutdown.
176 struct GNUNET_CADET_TransmitHandle *is_live_task;
179 * This is pobably followed by 'statistical' data (when we first saw
180 * him, how did we get his ID, how many pushes (in a timeinterval),
185 /***********************************************************************
186 * /Housekeeping with peers
187 ***********************************************************************/
189 /***********************************************************************
191 ***********************************************************************/
194 * Set of all peers to keep track of them.
196 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
200 * The gossiped list of peers.
202 static struct GNUNET_PeerIdentity *gossip_list;
205 * Size of the gossiped list
207 //static unsigned int gossip_list_size;
208 static uint32_t gossip_list_size;
212 * The actual size of the sampler
214 static unsigned int sampler_size;
215 //size_t sampler_size;
218 * The size of sampler we need to be able to satisfy the client's need of
221 static unsigned int sampler_size_client_need;
224 * The size of sampler we need to be able to satisfy the Brahms protocol's
225 * need of random peers.
227 * This is directly taken as the #gossip_list_size on update of the
230 * This is one minimum size the sampler grows to.
232 static unsigned int sampler_size_est_need;
236 * Percentage of total peer number in the gossip list
237 * to send random PUSHes to
239 * TODO do not read from configuration
244 * Percentage of total peer number in the gossip list
245 * to send random PULLs to
247 * TODO do not read from configuration
252 * The percentage gamma of history updates.
253 * Simply 1 - alpha - beta
258 * Identifier for the main task that runs periodically.
260 static struct GNUNET_SCHEDULER_Task *do_round_task;
263 * Time inverval the do_round task runs in.
265 static struct GNUNET_TIME_Relative round_interval;
270 * List to store peers received through pushes temporary.
272 * TODO -> multipeermap
274 static struct GNUNET_PeerIdentity *push_list;
277 * Size of the push_list;
279 static unsigned int push_list_size;
280 //size_t push_list_size;
283 * List to store peers received through pulls temporary.
285 * TODO -> multipeermap
287 static struct GNUNET_PeerIdentity *pull_list;
290 * Size of the pull_list;
292 static unsigned int pull_list_size;
293 //size_t pull_list_size;
299 static struct GNUNET_NSE_Handle *nse;
304 static struct GNUNET_CADET_Handle *cadet_handle;
310 * Only needed in the beginning to check how many of the 64 deltas
313 static unsigned int req_counter;
316 * Time of the last request we received.
318 * Used to compute the expected request rate.
320 static struct GNUNET_TIME_Absolute last_request;
323 * Size of #request_deltas.
325 #define REQUEST_DELTAS_SIZE 64
326 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
329 * Last 64 deltas between requests
331 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
334 * The prediction of the rate of requests
336 static struct GNUNET_TIME_Relative request_rate;
340 * List with the peers we sent requests to.
342 struct GNUNET_PeerIdentity *pending_pull_reply_list;
345 * Size of #pending_pull_reply_list.
347 uint32_t pending_pull_reply_list_size;
351 * Number of history update tasks.
353 uint32_t num_hist_update_tasks;
356 /***********************************************************************
358 ***********************************************************************/
361 /***********************************************************************
363 ***********************************************************************/
366 * Check if peer is already in peer array.
369 in_arr (const struct GNUNET_PeerIdentity *array,
370 unsigned int arr_size,
371 const struct GNUNET_PeerIdentity *peer)
373 GNUNET_assert (NULL != peer);
378 GNUNET_assert (NULL != array);
383 while (0 != GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer) &&
394 * Remove peer from list.
397 rem_from_list (struct GNUNET_PeerIdentity *peer_list,
398 unsigned int *list_size,
399 const struct GNUNET_PeerIdentity *peer)
403 for ( i = 0 ; i < *list_size ; i++ )
405 if (0 == GNUNET_CRYPTO_cmp_peer_identity (&peer_list[i], peer))
407 if (i < *list_size -1)
408 { /* Not at the last entry -- shift peers left */
409 memcpy (&peer_list[i], &peer_list[i +1],
410 (*list_size - i -1) * sizeof (struct GNUNET_PeerIdentity));
412 /* Remove last entry (should be now useless PeerID) */
413 GNUNET_array_grow (peer_list, *list_size, *list_size -1);
419 * Get random peer from the given list but don't return one from the @a ignore_list.
421 struct GNUNET_PeerIdentity *
422 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
424 const struct GNUNET_PeerIdentity *ignore_list,
425 uint32_t ignore_size)
429 struct GNUNET_PeerIdentity *tmp_peer_list;
430 struct GNUNET_PeerIdentity *peer;
433 tmp_peer_list = NULL;
434 GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
435 memcpy (tmp_peer_list, peer_list, list_size * sizeof (struct GNUNET_PeerIdentity));
436 peer = GNUNET_new (struct GNUNET_PeerIdentity);
437 // FIXME if we have only NULL in gossip list this will block
438 // but then we might have a problem nevertheless
443 * Choose the r_index of the peer we want to return
444 * at random from the interval of the gossip list
446 r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
449 *peer = tmp_peer_list[r_index];
450 if (in_arr (tmp_peer_list, list_size, peer))
452 rem_from_list (tmp_peer_list, &tmp_size, peer);
458 } while (NULL == peer);
460 GNUNET_free (tmp_peer_list);
467 * Get the context of a peer. If not existing, create.
470 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
471 const struct GNUNET_PeerIdentity *peer)
473 struct PeerContext *ctx;
475 if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
477 ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
481 ctx = GNUNET_new (struct PeerContext);
484 ctx->send_channel = NULL;
485 ctx->recv_channel = NULL;
486 ctx->outstanding_ops = NULL;
487 ctx->num_outstanding_ops = 0;
488 (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
489 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
496 * Put random peer from sampler into the gossip list as history update.
499 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
501 GNUNET_assert (1 == num_peers);
503 if (gossip_list_size < sampler_size_est_need)
504 GNUNET_array_append (gossip_list, gossip_list_size, *ids);
506 if (0 < num_hist_update_tasks)
507 num_hist_update_tasks--;
512 * Callback that is called when a channel was effectively established.
513 * This is given to ntfy_tmt_rdy and called when the channel was
514 * successfully established.
517 peer_is_live (void *cls, size_t size, void *buf)
519 struct GNUNET_PeerIdentity *peer;
520 struct PeerContext *peer_ctx;
522 peer = (struct GNUNET_PeerIdentity *) cls;
523 peer_ctx = get_peer_ctx (peer_map, peer);
524 peer_ctx->peer_flags |= LIVING;
526 LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
528 if (0 != peer_ctx->num_outstanding_ops)
529 { /* Call outstanding operations */
532 for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
533 peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
534 GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
545 * Get the channel of a peer. If not existing, create.
547 struct GNUNET_CADET_Channel *
548 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
549 const struct GNUNET_PeerIdentity *peer)
551 struct PeerContext *ctx;
552 struct GNUNET_PeerIdentity *tmp_peer;
554 ctx = get_peer_ctx (peer_map, peer);
555 if (NULL == ctx->send_channel)
557 ctx->send_channel = GNUNET_CADET_channel_create (cadet_handle, NULL, peer,
558 GNUNET_RPS_CADET_PORT,
559 GNUNET_CADET_OPTION_RELIABLE);
561 if (NULL == ctx->recv_channel)
563 tmp_peer = GNUNET_new (struct GNUNET_PeerIdentity);
565 ctx->is_live_task = GNUNET_CADET_notify_transmit_ready (ctx->send_channel, GNUNET_NO,
566 GNUNET_TIME_UNIT_FOREVER_REL,
567 0, peer_is_live, tmp_peer);
570 // do I have to explicitly put it in the peer_map?
571 (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
572 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
574 return ctx->send_channel;
579 * Get the message queue of a specific peer.
581 * If we already have a message queue open to this client,
582 * simply return it, otherways create one.
584 struct GNUNET_MQ_Handle *
585 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
586 const struct GNUNET_PeerIdentity *peer_id)
588 struct PeerContext *ctx;
590 ctx = get_peer_ctx (peer_map, peer_id);
593 (void) get_channel (peer_map, peer_id);
594 ctx->mq = GNUNET_CADET_mq_create (ctx->send_channel);
595 //do I have to explicitly put it in the peer_map?
596 (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, ctx,
597 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
604 * Sum all time relatives of an array.
606 struct GNUNET_TIME_Relative
607 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
609 struct GNUNET_TIME_Relative sum;
612 sum = GNUNET_TIME_UNIT_ZERO;
613 for ( i = 0 ; i < arr_size ; i++ )
615 sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
622 * Compute the average of given time relatives.
624 struct GNUNET_TIME_Relative
625 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
627 return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
632 * Insert PeerID in #pull_list
634 * Called once we know a peer is live.
637 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
639 if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
640 GNUNET_array_append (pull_list, pull_list_size, *peer);
644 * Check whether #insert_in_pull_list was already scheduled
647 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
651 for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
652 if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
659 * Insert PeerID in #gossip_list
661 * Called once we know a peer is live.
664 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
666 if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
667 GNUNET_array_append (gossip_list, gossip_list_size, *peer);
671 * Check whether #insert_in_pull_list was already scheduled
674 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
678 for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
679 if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
686 * Update sampler with given PeerID.
689 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
691 RPS_sampler_update_list (peer);
695 * Check whether #insert_in_sampler was already scheduled
698 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
702 for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
703 if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
711 * Wrapper around #RPS_sampler_resize()
716 uint32_t bigger_size;
720 if (sampler_size_est_need > sampler_size_client_need)
721 bigger_size = sampler_size_client_need;
723 bigger_size = sampler_size_est_need;
725 // TODO respect the request rate, min, max
726 if (sampler_size > bigger_size*4)
728 RPS_sampler_resize (sampler_size/2);
730 else if (sampler_size < bigger_size)
732 RPS_sampler_resize (sampler_size*2);
737 /***********************************************************************
739 ***********************************************************************/
742 * Function called by NSE.
744 * Updates sizes of sampler list and gossip list and adapt those lists
748 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp, double logestimate, double std_dev)
751 //double scale; // TODO this might go gloabal/config
753 LOG (GNUNET_ERROR_TYPE_DEBUG,
754 "Received a ns estimate - logest: %f, std_dev: %f (old_size: %f)\n",
755 logestimate, std_dev, sampler_size);
757 estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
758 // GNUNET_NSE_log_estimate_to_n (logestimate);
759 estimate = pow (estimate, 1./3);
760 // TODO add if std_dev is a number
761 // estimate += (std_dev * scale);
762 if ( 0 < estimate ) {
763 LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
764 sampler_size_est_need = estimate;
766 LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
768 /* If the NSE has changed adapt the lists accordingly */
774 * Callback called once the requested PeerIDs are ready.
776 * Sends those to the requesting client.
778 void client_respond (void *cls,
779 struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
781 LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
782 struct GNUNET_MQ_Envelope *ev;
783 struct GNUNET_RPS_CS_ReplyMessage *out_msg;
784 struct GNUNET_SERVER_Client *client;
785 struct client_ctx *cli_ctx;
787 client = (struct GNUNET_SERVER_Client *) cls;
789 ev = GNUNET_MQ_msg_extra (out_msg,
790 num_peers * sizeof (struct GNUNET_PeerIdentity),
791 GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
792 out_msg->num_peers = htonl (num_peers);
796 num_peers * sizeof (struct GNUNET_PeerIdentity));
799 cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
800 if ( NULL == cli_ctx ) {
801 cli_ctx = GNUNET_new (struct client_ctx);
802 cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
803 GNUNET_SERVER_client_set_user_context (client, cli_ctx);
806 GNUNET_MQ_send (cli_ctx->mq, ev);
811 * Handle RPS request from the client.
814 * @param client identification of the client
815 * @param message the actual message
818 handle_client_request (void *cls,
819 struct GNUNET_SERVER_Client *client,
820 const struct GNUNET_MessageHeader *message)
822 struct GNUNET_RPS_CS_RequestMessage *msg;
824 struct GNUNET_TIME_Relative max_round_duration;
827 /* Estimate request rate */
828 if (request_deltas_size > req_counter)
830 if ( 1 < req_counter)
832 /* Shift last request deltas to the right */
833 memcpy (&request_deltas[1],
835 (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
836 /* Add current delta to beginning */
837 request_deltas[0] = GNUNET_TIME_absolute_get_difference (last_request,
838 GNUNET_TIME_absolute_get ());
839 request_rate = T_relative_avg (request_deltas, req_counter);
841 max_round_duration = GNUNET_TIME_relative_add (round_interval,
842 GNUNET_TIME_relative_divide (round_interval, 2));
843 sampler_size_client_need = max_round_duration.rel_value_us / request_rate.rel_value_us;
847 last_request = GNUNET_TIME_absolute_get ();
850 // TODO check message size
851 msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
853 num_peers = ntohl (msg->num_peers);
855 LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
857 RPS_sampler_get_n_rand_peers (client_respond, client, num_peers, GNUNET_YES);
859 GNUNET_SERVER_receive_done (client,
865 * Handle seed from the client.
868 * @param client identification of the client
869 * @param message the actual message
872 handle_client_seed (void *cls,
873 struct GNUNET_SERVER_Client *client,
874 const struct GNUNET_MessageHeader *message)
876 struct GNUNET_RPS_CS_SeedMessage *in_msg;
877 struct GNUNET_PeerIdentity *peers;
880 if (sizeof (struct GNUNET_RPS_CS_SeedMessage) < ntohs (message->size))
883 GNUNET_SERVER_receive_done (client,
886 in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
887 if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
888 sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
891 GNUNET_SERVER_receive_done (client,
895 in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
896 peers = (struct GNUNET_PeerIdentity *) &message[1];
898 for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
899 RPS_sampler_update_list (&peers[i]);
901 GNUNET_SERVER_receive_done (client,
907 * Handle a PUSH message from another peer.
909 * Check the proof of work and store the PeerID
910 * in the temporary list for pushed PeerIDs.
913 * @param channel The channel the PUSH was received over
914 * @param channel_ctx The context associated with this channel
915 * @param msg The message header
918 handle_peer_push (void *cls,
919 struct GNUNET_CADET_Channel *channel,
921 const struct GNUNET_MessageHeader *msg)
923 const struct GNUNET_PeerIdentity *peer;
925 // (check the proof of work)
927 peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
928 // FIXME wait for cadet to change this function
929 LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
931 /* Add the sending peer to the push_list */
932 if (GNUNET_NO == in_arr (push_list, pull_list_size, peer))
933 GNUNET_array_append (push_list, push_list_size, *peer);
939 * Handle PULL REQUEST request message from another peer.
941 * Reply with the gossip list of PeerIDs.
944 * @param channel The channel the PUSH was received over
945 * @param channel_ctx The context associated with this channel
946 * @param msg The message header
949 handle_peer_pull_request (void *cls,
950 struct GNUNET_CADET_Channel *channel,
952 const struct GNUNET_MessageHeader *msg)
954 struct GNUNET_PeerIdentity *peer;
955 struct GNUNET_MQ_Handle *mq;
956 struct GNUNET_MQ_Envelope *ev;
957 struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
960 peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel,
961 GNUNET_CADET_OPTION_PEER);
962 // FIXME wait for cadet to change this function
963 LOG (GNUNET_ERROR_TYPE_DEBUG,
964 "PULL REQUEST from peer %s received, going to send %u peers\n",
965 GNUNET_i2s (peer), gossip_list_size);
967 mq = get_mq (peer_map, peer);
969 ev = GNUNET_MQ_msg_extra (out_msg,
970 gossip_list_size * sizeof (struct GNUNET_PeerIdentity),
971 GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
972 //out_msg->num_peers = htonl (gossip_list_size);
973 out_msg->num_peers = htonl (gossip_list_size);
974 memcpy (&out_msg[1], gossip_list,
975 gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
977 GNUNET_MQ_send (mq, ev);
983 * Handle PULL REPLY message from another peer.
985 * Check whether we sent a corresponding request and
986 * whether this reply is the first one.
989 * @param channel The channel the PUSH was received over
990 * @param channel_ctx The context associated with this channel
991 * @param msg The message header
994 handle_peer_pull_reply (void *cls,
995 struct GNUNET_CADET_Channel *channel,
997 const struct GNUNET_MessageHeader *msg)
999 LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1001 struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1002 struct GNUNET_PeerIdentity *peers;
1003 struct PeerContext *peer_ctx;
1004 struct GNUNET_PeerIdentity *sender;
1005 struct PeerContext *sender_ctx;
1006 struct PeerOutstandingOp out_op;
1009 if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1011 GNUNET_break_op (0); // At the moment our own implementation seems to break that.
1012 return GNUNET_SYSERR;
1014 in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1015 if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1017 LOG (GNUNET_ERROR_TYPE_ERROR, "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1018 ntohl (in_msg->num_peers),
1019 (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) / sizeof (struct GNUNET_PeerIdentity));
1020 GNUNET_break_op (0);
1021 return GNUNET_SYSERR;
1024 sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1025 (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1026 // Guess simply casting isn't the nicest way...
1027 // FIXME wait for cadet to change this function
1028 sender_ctx = get_peer_ctx (peer_map, sender);
1030 if (0 == (peer_ctx->peer_flags || PULL_REPLY_PENDING))
1032 GNUNET_break_op (0);
1036 peers = (struct GNUNET_PeerIdentity *) &msg[1];
1037 for ( i = 0 ; i < ntohl (in_msg->num_peers) ; i++ )
1039 peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1040 if ((0 != (peer_ctx->peer_flags && LIVING)) ||
1041 NULL != peer_ctx->recv_channel)
1043 if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i]))
1044 GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1046 else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1048 out_op.op = insert_in_pull_list;
1049 GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1053 sender_ctx->peer_flags &= (~PULL_REPLY_PENDING);
1054 rem_from_list (pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1061 * Send out PUSHes and PULLs.
1063 * This is executed regylary.
1066 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1068 LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
1071 //unsigned int *n_arr;
1072 unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1073 struct GNUNET_MQ_Envelope *ev;
1074 const struct GNUNET_PeerIdentity *peer;
1075 struct GNUNET_MQ_Handle *mq;
1077 // TODO log lists, ...
1080 /* Would it make sense to have one shuffeled gossip list and then
1081 * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1082 * use the rest to update sampler?
1083 * in essence get random peers with consumption */
1086 //n_arr = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) gossip_list_size);
1087 if (0 != gossip_list_size)
1089 n_peers = round (alpha * gossip_list_size);
1092 LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pushes to %u (%f * %u) peers.\n",
1093 n_peers, alpha, gossip_list_size);
1094 for ( i = 0 ; i < n_peers ; i++ )
1097 peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1101 if (own_identity != peer) // TODO
1102 { // FIXME if this fails schedule/loop this for later
1103 LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PUSH to peer %s of gossiped list.\n", GNUNET_i2s (peer));
1105 ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1106 // FIXME sometimes it returns a pointer to a freed mq
1107 mq = get_mq (peer_map, peer);
1108 GNUNET_MQ_send (mq, ev);
1115 /* Send PULL requests */
1116 //n_arr = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1117 if (0 != gossip_list_size)
1119 n_peers = round (beta * gossip_list_size);
1122 LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pulls to %u (%f * %u) peers.\n",
1123 n_peers, beta, gossip_list_size);
1124 for ( i = 0 ; i < n_peers ; i++ )
1126 peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1127 pending_pull_reply_list, pending_pull_reply_list_size);
1130 GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, *peer);
1132 if (own_identity != peer)
1133 { // FIXME if this fails schedule/loop this for later
1134 LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PULL request to peer %s of gossiped list.\n", GNUNET_i2s (peer));
1136 ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1138 mq = get_mq (peer_map, peer);
1139 GNUNET_MQ_send (mq, ev);
1146 /* Update gossip list */
1149 if ( push_list_size <= alpha * gossip_list_size &&
1150 push_list_size != 0 &&
1151 pull_list_size != 0 )
1153 LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1155 uint32_t first_border;
1156 uint32_t second_border;
1158 first_border = round (alpha * sampler_size_est_need);
1159 second_border = first_border + round (beta * sampler_size_est_need);
1161 GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1163 for ( i = 0 ; i < first_border ; i++ )
1164 { // TODO use RPS_sampler_get_n_rand_peers
1165 /* Update gossip list with peers received through PUSHes */
1166 r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1168 gossip_list[i] = push_list[r_index];
1169 // TODO change the peer_flags accordingly
1172 for ( i = first_border ; i < second_border ; i++ )
1174 /* Update gossip list with peers received through PULLs */
1175 r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1177 gossip_list[i] = pull_list[r_index];
1178 // TODO change the peer_flags accordingly
1181 for ( i = second_border ; i < gossip_list_size ; i++ )
1183 /* Update gossip list with peers from history */
1184 RPS_sampler_get_n_rand_peers (hist_update, NULL, 1, GNUNET_NO);
1185 num_hist_update_tasks++;
1186 // TODO change the peer_flags accordingly
1192 LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list. ()\n");
1194 // TODO independent of that also get some peers from CADET_get_peers()?
1197 /* Update samplers */
1199 for ( i = 0 ; i < push_list_size ; i++ )
1201 RPS_sampler_update_list (&push_list[i]);
1202 // TODO set in_flag?
1205 for ( i = 0 ; i < pull_list_size ; i++ )
1207 RPS_sampler_update_list (&pull_list[i]);
1208 // TODO set in_flag?
1212 /* Empty push/pull lists */
1213 GNUNET_array_grow (push_list, push_list_size, 0);
1214 GNUNET_array_grow (pull_list, pull_list_size, 0);
1216 struct GNUNET_TIME_Relative time_next_round;
1217 struct GNUNET_TIME_Relative half_round_interval;
1218 unsigned int rand_delay;
1220 /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
1221 half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
1225 * Compute random value between (0 and 1) * round_interval
1226 * via multiplying round_interval with a 'fraction' (0 to value)/value
1228 rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
1229 time_next_round = GNUNET_TIME_relative_multiply (round_interval, rand_delay);
1230 time_next_round = GNUNET_TIME_relative_divide (time_next_round, UINT_MAX/10);
1231 time_next_round = GNUNET_TIME_relative_add (time_next_round, half_round_interval);
1232 } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
1234 /* Schedule next round */
1235 do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1236 LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1241 * Open a connection to given peer and store channel and mq.
1244 insertCB (void *cls, const struct GNUNET_PeerIdentity *id)
1246 // We open a channel to be notified when this peer goes down.
1247 (void) get_channel (peer_map, id);
1252 * Close the connection to given peer and delete channel and mq.
1255 removeCB (void *cls, const struct GNUNET_PeerIdentity *id)
1258 struct PeerContext *ctx;
1260 s = RPS_sampler_count_id (id);
1263 if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, id))
1265 ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, id);
1266 if (NULL != ctx->send_channel)
1268 if (NULL != ctx->mq)
1270 GNUNET_MQ_destroy (ctx->mq);
1272 // may already be freed at shutdown of cadet
1273 //GNUNET_CADET_channel_destroy (ctx->send_channel);
1275 // TODO cleanup peer
1276 (void) GNUNET_CONTAINER_multipeermap_remove_all (peer_map, id);
1282 rps_start (struct GNUNET_SERVER_Handle *server);
1285 * This is called from GNUNET_CADET_get_peers().
1287 * It is called on every peer(ID) that cadet somehow has contact with.
1288 * We use those to initialise the sampler.
1291 init_peer_cb (void *cls,
1292 const struct GNUNET_PeerIdentity *peer,
1293 int tunnel, // "Do we have a tunnel towards this peer?"
1294 unsigned int n_paths, // "Number of known paths towards this peer"
1295 unsigned int best_path) // "How long is the best path?
1296 // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1298 struct GNUNET_SERVER_Handle *server;
1299 struct PeerOutstandingOp out_op;
1300 struct PeerContext *peer_ctx;
1302 server = (struct GNUNET_SERVER_Handle *) cls;
1305 LOG (GNUNET_ERROR_TYPE_DEBUG,
1306 "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1307 GNUNET_i2s (peer), peer, gossip_list_size);
1309 // maybe create a function for that
1310 peer_ctx = get_peer_ctx (peer_map, peer);
1311 if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1313 out_op.op = insert_in_sampler;
1314 GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1317 if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1319 out_op.op = insert_in_gossip_list;
1320 GNUNET_array_append (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, out_op);
1323 /* Issue livelyness test on peer */
1324 (void) get_channel (peer_map, peer);
1326 // send push/pull to each of those peers?
1334 * Callback used to clean the multipeermap.
1337 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1339 struct PeerContext *peer_ctx;
1341 peer_ctx = (struct PeerContext *) value;
1343 if ( NULL != peer_ctx->mq)
1344 GNUNET_MQ_destroy (peer_ctx->mq);
1346 if ( NULL != peer_ctx->is_live_task)
1347 GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
1349 if ( NULL != peer_ctx->send_channel)
1350 GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
1352 if ( NULL != peer_ctx->recv_channel)
1353 GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
1355 if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1356 LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1363 * Task run during shutdown.
1369 shutdown_task (void *cls,
1370 const struct GNUNET_SCHEDULER_TaskContext *tc)
1372 LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1374 if ( NULL != do_round_task )
1376 GNUNET_SCHEDULER_cancel (do_round_task);
1377 do_round_task = NULL;
1381 if (GNUNET_SYSERR == GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1382 LOG (GNUNET_ERROR_TYPE_WARNING,
1383 "Iterating over peers to disconnect from them was cancelled\n");
1385 GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1387 GNUNET_NSE_disconnect (nse);
1388 GNUNET_CADET_disconnect (cadet_handle);
1389 GNUNET_free (own_identity);
1390 RPS_sampler_destroy ();
1391 GNUNET_array_grow (request_deltas, request_deltas_size, 0);
1392 GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1393 GNUNET_array_grow (push_list, push_list_size, 0);
1394 GNUNET_array_grow (pull_list, pull_list_size, 0);
1399 * A client disconnected. Remove all of its data structure entries.
1401 * @param cls closure, NULL
1402 * @param client identification of the client
1405 handle_client_disconnect (void *cls,
1406 struct GNUNET_SERVER_Client * client)
1411 * Handle the channel a peer opens to us.
1413 * @param cls The closure
1414 * @param channel The channel the peer wants to establish
1415 * @param initiator The peer's peer ID
1416 * @param port The port the channel is being established over
1417 * @param options Further options
1420 handle_inbound_channel (void *cls,
1421 struct GNUNET_CADET_Channel *channel,
1422 const struct GNUNET_PeerIdentity *initiator,
1424 enum GNUNET_CADET_ChannelOption options)
1426 struct PeerContext *ctx;
1428 LOG (GNUNET_ERROR_TYPE_DEBUG,
1429 "New channel was established to us (Peer %s).\n",
1430 GNUNET_i2s (initiator));
1432 GNUNET_assert (NULL != channel);
1434 // we might not even store the recv_channel
1436 ctx = get_peer_ctx (peer_map, initiator);
1437 if (NULL != ctx->recv_channel)
1439 ctx->recv_channel = channel;
1442 // FIXME there might already be an established channel
1444 //ctx->peer_flags = IN_OTHER_GOSSIP_LIST;
1445 ctx->mq = NULL; // TODO create mq?
1447 (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, ctx,
1448 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1449 return NULL; // TODO
1453 * This is called when a remote peer destroys a channel.
1455 * @param cls The closure
1456 * @param channel The channel being closed
1457 * @param channel_ctx The context associated with this channel
1460 cleanup_channel (void *cls,
1461 const struct GNUNET_CADET_Channel *channel,
1464 struct GNUNET_PeerIdentity *peer;
1465 struct PeerContext *peer_ctx;
1467 LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel to remote peer was destroyed.\n");
1469 peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1470 (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1471 // Guess simply casting isn't the nicest way...
1472 // FIXME wait for cadet to change this function
1473 RPS_sampler_reinitialise_by_value (peer);
1475 peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
1476 /* Somwewhat {ab,re}use the iterator function */
1477 (void) peer_remove_cb (peer, peer, peer_ctx);
1482 * Actually start the service.
1485 rps_start (struct GNUNET_SERVER_Handle *server)
1487 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1488 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1489 sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1490 {&handle_client_seed, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
1494 GNUNET_SERVER_add_handlers (server, handlers);
1495 GNUNET_SERVER_disconnect_notify (server,
1496 &handle_client_disconnect,
1498 LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1501 num_hist_update_tasks = 0;
1503 do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1504 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1506 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1513 * Process statistics requests.
1515 * @param cls closure
1516 * @param server the initialized server
1517 * @param c configuration to use
1521 struct GNUNET_SERVER_Handle *server,
1522 const struct GNUNET_CONFIGURATION_Handle *c)
1524 // TODO check what this does -- copied from gnunet-boss
1525 // - seems to work as expected
1526 GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1528 LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS started\n");
1535 own_identity = GNUNET_new (struct GNUNET_PeerIdentity);
1536 GNUNET_CRYPTO_get_peer_identity (cfg, own_identity); // TODO check return value
1537 GNUNET_assert (NULL != own_identity);
1538 LOG (GNUNET_ERROR_TYPE_DEBUG, "Own identity is %s (at %p).\n", GNUNET_i2s (own_identity), own_identity);
1541 /* Get time interval from the configuration */
1542 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1546 LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1547 GNUNET_SCHEDULER_shutdown ();
1551 /* Get initial size of sampler/gossip list from the configuration */
1552 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1554 (long long unsigned int *) &sampler_size_est_need))
1556 LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1557 GNUNET_SCHEDULER_shutdown ();
1560 LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
1566 /* connect to NSE */
1567 nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
1568 // TODO check whether that was successful
1569 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1575 peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
1578 /* Initialise cadet */
1579 static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1580 {&handle_peer_push , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH ,
1581 sizeof (struct GNUNET_MessageHeader)},
1582 {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
1583 sizeof (struct GNUNET_MessageHeader)},
1584 {&handle_peer_pull_reply , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY , 0},
1588 const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1589 cadet_handle = GNUNET_CADET_connect (cfg,
1591 &handle_inbound_channel,
1595 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1598 /* Initialise sampler */
1599 struct GNUNET_TIME_Relative half_round_interval;
1600 struct GNUNET_TIME_Relative max_round_interval;
1602 half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
1603 max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
1605 RPS_sampler_init (sampler_size_est_need, max_round_interval,
1606 insertCB, NULL, removeCB, NULL);
1607 sampler_size = sampler_size_est_need;
1609 /* Initialise push and pull maps */
1614 pending_pull_reply_list = NULL;
1615 pending_pull_reply_list_size = 0;
1618 LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1619 GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, server);
1621 // TODO send push/pull to each of those peers?
1626 * The main function for the rps service.
1628 * @param argc number of arguments from the command line
1629 * @param argv command line arguments
1630 * @return 0 ok, 1 on error
1633 main (int argc, char *const *argv)
1635 return (GNUNET_OK ==
1636 GNUNET_SERVICE_run (argc,
1639 GNUNET_SERVICE_OPTION_NONE,
1640 &run, NULL)) ? 0 : 1;
1643 /* end of gnunet-service-rps.c */