rps: record more statistic values
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013-2015 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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_applications.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_cadet_service.h"
30 #include "gnunet_peerinfo_service.h"
31 #include "gnunet_nse_service.h"
32 #include "gnunet_statistics_service.h"
33 #include "rps.h"
34 #include "rps-test_util.h"
35 #include "gnunet-service-rps_sampler.h"
36 #include "gnunet-service-rps_custommap.h"
37 #include "gnunet-service-rps_view.h"
38
39 #include <math.h>
40 #include <inttypes.h>
41
42 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
43
44 // TODO modify @brief in every file
45
46 // TODO check for overflows
47
48 // TODO align message structs
49
50 // TODO connect to friends
51
52 // TODO store peers somewhere persistent
53
54 // TODO blacklist? (-> mal peer detection on top of brahms)
55
56 // hist_size_init, hist_size_max
57
58 /**
59  * Our configuration.
60  */
61 static const struct GNUNET_CONFIGURATION_Handle *cfg;
62
63 /**
64  * Handle to the statistics service.
65  */
66 static struct GNUNET_STATISTICS_Handle *stats;
67
68 /**
69  * Our own identity.
70  */
71 static struct GNUNET_PeerIdentity own_identity;
72
73
74
75 /***********************************************************************
76  * Old gnunet-service-rps_peers.c
77 ***********************************************************************/
78
79 /**
80  * Set a peer flag of given peer context.
81  */
82 #define set_peer_flag(peer_ctx, mask) ((peer_ctx->peer_flags) |= (mask))
83
84 /**
85  * Get peer flag of given peer context.
86  */
87 #define check_peer_flag_set(peer_ctx, mask)\
88   ((peer_ctx->peer_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
89
90 /**
91  * Unset flag of given peer context.
92  */
93 #define unset_peer_flag(peer_ctx, mask) ((peer_ctx->peer_flags) &= ~(mask))
94
95 /**
96  * Set a channel flag of given channel context.
97  */
98 #define set_channel_flag(channel_flags, mask) ((*channel_flags) |= (mask))
99
100 /**
101  * Get channel flag of given channel context.
102  */
103 #define check_channel_flag_set(channel_flags, mask)\
104   ((*channel_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
105
106 /**
107  * Unset flag of given channel context.
108  */
109 #define unset_channel_flag(channel_flags, mask) ((*channel_flags) &= ~(mask))
110
111
112
113 /**
114  * Pending operation on peer consisting of callback and closure
115  *
116  * When an operation cannot be executed right now this struct is used to store
117  * the callback and closure for later execution.
118  */
119 struct PeerPendingOp
120 {
121   /**
122    * Callback
123    */
124   PeerOp op;
125
126   /**
127    * Closure
128    */
129   void *op_cls;
130 };
131
132 /**
133  * List containing all messages that are yet to be send
134  *
135  * This is used to keep track of all messages that have not been sent yet. When
136  * a peer is to be removed the pending messages can be removed properly.
137  */
138 struct PendingMessage
139 {
140   /**
141    * DLL next, prev
142    */
143   struct PendingMessage *next;
144   struct PendingMessage *prev;
145
146   /**
147    * The envelope to the corresponding message
148    */
149   struct GNUNET_MQ_Envelope *ev;
150
151   /**
152    * The corresponding context
153    */
154   struct PeerContext *peer_ctx;
155
156   /**
157    * The message type
158    */
159   const char *type;
160 };
161
162 /**
163  * Struct used to keep track of other peer's status
164  *
165  * This is stored in a multipeermap.
166  * It contains information such as cadet channels, a message queue for sending,
167  * status about the channels, the pending operations on this peer and some flags
168  * about the status of the peer itself. (live, valid, ...)
169  */
170 struct PeerContext
171 {
172   /**
173    * Message queue open to client
174    */
175   struct GNUNET_MQ_Handle *mq;
176
177   /**
178    * Channel open to client.
179    */
180   struct GNUNET_CADET_Channel *send_channel;
181
182   /**
183    * Flags to the sending channel
184    */
185   uint32_t *send_channel_flags;
186
187   /**
188    * Channel open from client.
189    */
190   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
191
192   /**
193    * Flags to the receiving channel
194    */
195   uint32_t *recv_channel_flags;
196
197   /**
198    * Array of pending operations on this peer.
199    */
200   struct PeerPendingOp *pending_ops;
201
202   /**
203    * Handle to the callback given to cadet_ntfy_tmt_rdy()
204    *
205    * To be canceled on shutdown.
206    */
207   struct PendingMessage *liveliness_check_pending;
208
209   /**
210    * Number of pending operations.
211    */
212   unsigned int num_pending_ops;
213
214   /**
215    * Identity of the peer
216    */
217   struct GNUNET_PeerIdentity peer_id;
218
219   /**
220    * Flags indicating status of peer
221    */
222   uint32_t peer_flags;
223
224   /**
225    * Last time we received something from that peer.
226    */
227   struct GNUNET_TIME_Absolute last_message_recv;
228
229   /**
230    * Last time we received a keepalive message.
231    */
232   struct GNUNET_TIME_Absolute last_keepalive;
233
234   /**
235    * DLL with all messages that are yet to be sent
236    */
237   struct PendingMessage *pending_messages_head;
238   struct PendingMessage *pending_messages_tail;
239
240   /**
241    * This is pobably followed by 'statistical' data (when we first saw
242    * him, how did we get his ID, how many pushes (in a timeinterval),
243    * ...)
244    */
245 };
246
247 /**
248  * @brief Closure to #valid_peer_iterator
249  */
250 struct PeersIteratorCls
251 {
252   /**
253    * Iterator function
254    */
255   PeersIterator iterator;
256
257   /**
258    * Closure to iterator
259    */
260   void *cls;
261 };
262
263 /**
264  * @brief Hashmap of valid peers.
265  */
266 static struct GNUNET_CONTAINER_MultiPeerMap *valid_peers;
267
268 /**
269  * @brief Maximum number of valid peers to keep.
270  * TODO read from config
271  */
272 static uint32_t num_valid_peers_max = UINT32_MAX;
273
274 /**
275  * @brief Filename of the file that stores the valid peers persistently.
276  */
277 static char *filename_valid_peers;
278
279 /**
280  * Set of all peers to keep track of them.
281  */
282 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
283
284 /**
285  * Cadet handle.
286  */
287 static struct GNUNET_CADET_Handle *cadet_handle;
288
289
290
291 /**
292  * @brief Get the #PeerContext associated with a peer
293  *
294  * @param peer the peer id
295  *
296  * @return the #PeerContext
297  */
298 static struct PeerContext *
299 get_peer_ctx (const struct GNUNET_PeerIdentity *peer)
300 {
301   struct PeerContext *ctx;
302   int ret;
303
304   ret = GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
305   GNUNET_assert (GNUNET_YES == ret);
306   ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
307   GNUNET_assert (NULL != ctx);
308   return ctx;
309 }
310
311 int
312 Peers_check_peer_known (const struct GNUNET_PeerIdentity *peer);
313
314 /**
315  * @brief Create a new #PeerContext and insert it into the peer map
316  *
317  * @param peer the peer to create the #PeerContext for
318  *
319  * @return the #PeerContext
320  */
321 static struct PeerContext *
322 create_peer_ctx (const struct GNUNET_PeerIdentity *peer)
323 {
324   struct PeerContext *ctx;
325   int ret;
326
327   GNUNET_assert (GNUNET_NO == Peers_check_peer_known (peer));
328
329   ctx = GNUNET_new (struct PeerContext);
330   ctx->peer_id = *peer;
331   ctx->send_channel_flags = GNUNET_new (uint32_t);
332   ctx->recv_channel_flags = GNUNET_new (uint32_t);
333   ret = GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
334       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
335   GNUNET_assert (GNUNET_OK == ret);
336   return ctx;
337 }
338
339
340 /**
341  * @brief Create or get a #PeerContext
342  *
343  * @param peer the peer to get the associated context to
344  *
345  * @return the context
346  */
347 static struct PeerContext *
348 create_or_get_peer_ctx (const struct GNUNET_PeerIdentity *peer)
349 {
350   if (GNUNET_NO == Peers_check_peer_known (peer))
351   {
352     return create_peer_ctx (peer);
353   }
354   return get_peer_ctx (peer);
355 }
356
357 void
358 Peers_unset_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags);
359
360 void
361 Peers_set_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags);
362
363 /**
364  * @brief Check whether we have a connection to this @a peer
365  *
366  * Also sets the #Peers_ONLINE flag accordingly
367  *
368  * @param peer the peer in question
369  *
370  * @return #GNUNET_YES if we are connected
371  *         #GNUNET_NO  otherwise
372  */
373 int
374 Peers_check_connected (const struct GNUNET_PeerIdentity *peer)
375 {
376   const struct PeerContext *peer_ctx;
377
378   /* If we don't know about this peer we don't know whether it's online */
379   if (GNUNET_NO == Peers_check_peer_known (peer))
380   {
381     return GNUNET_NO;
382   }
383   /* Get the context */
384   peer_ctx = get_peer_ctx (peer);
385   /* If we have no channel to this peer we don't know whether it's online */
386   if ( (NULL == peer_ctx->send_channel) &&
387        (NULL == peer_ctx->recv_channel) )
388   {
389     Peers_unset_peer_flag (peer, Peers_ONLINE);
390     return GNUNET_NO;
391   }
392   /* Otherwise (if we have a channel, we know that it's online */
393   Peers_set_peer_flag (peer, Peers_ONLINE);
394   return GNUNET_YES;
395 }
396
397
398 /**
399  * @brief The closure to #get_rand_peer_iterator.
400  */
401 struct GetRandPeerIteratorCls
402 {
403   /**
404    * @brief The index of the peer to return.
405    * Will be decreased until 0.
406    * Then current peer is returned.
407    */
408   uint32_t index;
409
410   /**
411    * @brief Pointer to peer to return.
412    */
413   const struct GNUNET_PeerIdentity *peer;
414 };
415
416
417 /**
418  * @brief Iterator function for #get_random_peer_from_peermap.
419  *
420  * Implements #GNUNET_CONTAINER_PeerMapIterator.
421  * Decreases the index until the index is null.
422  * Then returns the current peer.
423  *
424  * @param cls the #GetRandPeerIteratorCls containing index and peer
425  * @param peer current peer
426  * @param value unused
427  *
428  * @return  #GNUNET_YES if we should continue to
429  *          iterate,
430  *          #GNUNET_NO if not.
431  */
432 static int
433 get_rand_peer_iterator (void *cls,
434                         const struct GNUNET_PeerIdentity *peer,
435                         void *value)
436 {
437   struct GetRandPeerIteratorCls *iterator_cls = cls;
438   if (0 >= iterator_cls->index)
439   {
440     iterator_cls->peer = peer;
441     return GNUNET_NO;
442   }
443   iterator_cls->index--;
444   return GNUNET_YES;
445 }
446
447
448 /**
449  * @brief Get a random peer from @a peer_map
450  *
451  * @param peer_map the peer_map to get the peer from
452  *
453  * @return a random peer
454  */
455 static const struct GNUNET_PeerIdentity *
456 get_random_peer_from_peermap (const struct
457                               GNUNET_CONTAINER_MultiPeerMap *peer_map)
458 {
459   struct GetRandPeerIteratorCls *iterator_cls;
460   const struct GNUNET_PeerIdentity *ret;
461
462   iterator_cls = GNUNET_new (struct GetRandPeerIteratorCls);
463   iterator_cls->index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
464       GNUNET_CONTAINER_multipeermap_size (peer_map));
465   (void) GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
466                                                 get_rand_peer_iterator,
467                                                 iterator_cls);
468   ret = iterator_cls->peer;
469   GNUNET_free (iterator_cls);
470   return ret;
471 }
472
473
474 /**
475  * @brief Add a given @a peer to valid peers.
476  *
477  * If valid peers are already #num_valid_peers_max, delete a peer previously.
478  *
479  * @param peer the peer that is added to the valid peers.
480  *
481  * @return #GNUNET_YES if no other peer had to be removed
482  *         #GNUNET_NO  otherwise
483  */
484 static int
485 add_valid_peer (const struct GNUNET_PeerIdentity *peer)
486 {
487   const struct GNUNET_PeerIdentity *rand_peer;
488   int ret;
489
490   ret = GNUNET_YES;
491   while (GNUNET_CONTAINER_multipeermap_size (valid_peers) >= num_valid_peers_max)
492   {
493     rand_peer = get_random_peer_from_peermap (valid_peers);
494     GNUNET_CONTAINER_multipeermap_remove_all (valid_peers, rand_peer);
495     ret = GNUNET_NO;
496   }
497   (void) GNUNET_CONTAINER_multipeermap_put (valid_peers, peer, NULL,
498       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
499   return ret;
500 }
501
502
503 /**
504  * @brief Set the peer flag to living and
505  *        call the pending operations on this peer.
506  *
507  * Also adds peer to #valid_peers.
508  *
509  * @param peer_ctx the #PeerContext of the peer to set live
510  */
511 static void
512 set_peer_live (struct PeerContext *peer_ctx)
513 {
514   struct GNUNET_PeerIdentity *peer;
515   unsigned int i;
516
517   peer = &peer_ctx->peer_id;
518   LOG (GNUNET_ERROR_TYPE_DEBUG,
519       "Peer %s is live and valid, calling %i pending operations on it\n",
520       GNUNET_i2s (peer),
521       peer_ctx->num_pending_ops);
522
523   if (NULL != peer_ctx->liveliness_check_pending)
524   {
525     LOG (GNUNET_ERROR_TYPE_DEBUG,
526          "Removing pending liveliness check for peer %s\n",
527          GNUNET_i2s (&peer_ctx->peer_id));
528     // TODO wait until cadet sets mq->cancel_impl
529     //GNUNET_MQ_send_cancel (peer_ctx->liveliness_check_pending->ev);
530     GNUNET_free (peer_ctx->liveliness_check_pending);
531     peer_ctx->liveliness_check_pending = NULL;
532   }
533
534   (void) add_valid_peer (peer);
535   set_peer_flag (peer_ctx, Peers_ONLINE);
536
537   /* Call pending operations */
538   for (i = 0; i < peer_ctx->num_pending_ops; i++)
539   {
540     peer_ctx->pending_ops[i].op (peer_ctx->pending_ops[i].op_cls, peer);
541   }
542   GNUNET_array_grow (peer_ctx->pending_ops, peer_ctx->num_pending_ops, 0);
543 }
544
545 static void
546 cleanup_destroyed_channel (void *cls,
547                            const struct GNUNET_CADET_Channel *channel);
548
549 /* Declaration of handlers */
550 static void
551 handle_peer_check (void *cls,
552                    const struct GNUNET_MessageHeader *msg);
553
554 static void
555 handle_peer_push (void *cls,
556                   const struct GNUNET_MessageHeader *msg);
557
558 static void
559 handle_peer_pull_request (void *cls,
560                           const struct GNUNET_MessageHeader *msg);
561
562 static int
563 check_peer_pull_reply (void *cls,
564                        const struct GNUNET_RPS_P2P_PullReplyMessage *msg);
565
566 static void
567 handle_peer_pull_reply (void *cls,
568                         const struct GNUNET_RPS_P2P_PullReplyMessage *msg);
569
570 /* End declaration of handlers */
571
572
573 /**
574  * @brief Get the channel of a peer. If not existing, create.
575  *
576  * @param peer the peer id
577  * @return the #GNUNET_CADET_Channel used to send data to @a peer
578  */
579 struct GNUNET_CADET_Channel *
580 get_channel (const struct GNUNET_PeerIdentity *peer)
581 {
582   struct PeerContext *peer_ctx;
583   struct GNUNET_HashCode port;
584   /* There exists a copy-paste-clone in run() */
585   struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
586     GNUNET_MQ_hd_fixed_size (peer_check,
587                              GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE,
588                              struct GNUNET_MessageHeader,
589                              NULL),
590     GNUNET_MQ_hd_fixed_size (peer_push,
591                              GNUNET_MESSAGE_TYPE_RPS_PP_PUSH,
592                              struct GNUNET_MessageHeader,
593                              NULL),
594     GNUNET_MQ_hd_fixed_size (peer_pull_request,
595                              GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
596                              struct GNUNET_MessageHeader,
597                              NULL),
598     GNUNET_MQ_hd_var_size (peer_pull_reply,
599                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY,
600                            struct GNUNET_RPS_P2P_PullReplyMessage,
601                            NULL),
602     GNUNET_MQ_handler_end ()
603   };
604
605
606   peer_ctx = get_peer_ctx (peer);
607   if (NULL == peer_ctx->send_channel)
608   {
609     LOG (GNUNET_ERROR_TYPE_DEBUG,
610          "Trying to establish channel to peer %s\n",
611          GNUNET_i2s (peer));
612     GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_RPS,
613                         strlen (GNUNET_APPLICATION_PORT_RPS),
614                         &port);
615     peer_ctx->send_channel =
616       GNUNET_CADET_channel_create (cadet_handle,
617                                    (struct GNUNET_PeerIdentity *) peer, /* context */
618                                    peer,
619                                    &port,
620                                    GNUNET_CADET_OPTION_RELIABLE,
621                                    NULL, /* WindowSize handler */
622                                    cleanup_destroyed_channel, /* Disconnect handler */
623                                    cadet_handlers);
624   }
625   GNUNET_assert (NULL != peer_ctx->send_channel);
626   return peer_ctx->send_channel;
627 }
628
629
630 /**
631  * Get the message queue (#GNUNET_MQ_Handle) of a specific peer.
632  *
633  * If we already have a message queue open to this client,
634  * simply return it, otherways create one.
635  *
636  * @param peer the peer to get the mq to
637  * @return the #GNUNET_MQ_Handle
638  */
639 static struct GNUNET_MQ_Handle *
640 get_mq (const struct GNUNET_PeerIdentity *peer)
641 {
642   struct PeerContext *peer_ctx;
643
644   peer_ctx = get_peer_ctx (peer);
645
646   if (NULL == peer_ctx->mq)
647   {
648     (void) get_channel (peer);
649     peer_ctx->mq = GNUNET_CADET_get_mq (peer_ctx->send_channel);
650   }
651   return peer_ctx->mq;
652 }
653
654
655 /**
656  * @brief This is called in response to the first message we sent as a
657  * liveliness check.
658  *
659  * @param cls #PeerContext of peer with pending liveliness check
660  */
661 static void
662 mq_liveliness_check_successful (void *cls)
663 {
664   struct PeerContext *peer_ctx = cls;
665
666   if (NULL != peer_ctx->liveliness_check_pending)
667   {
668     LOG (GNUNET_ERROR_TYPE_DEBUG,
669         "Liveliness check for peer %s was successfull\n",
670         GNUNET_i2s (&peer_ctx->peer_id));
671     GNUNET_free (peer_ctx->liveliness_check_pending);
672     peer_ctx->liveliness_check_pending = NULL;
673     set_peer_live (peer_ctx);
674   }
675 }
676
677 /**
678  * Issue a check whether peer is live
679  *
680  * @param peer_ctx the context of the peer
681  */
682 static void
683 check_peer_live (struct PeerContext *peer_ctx)
684 {
685   LOG (GNUNET_ERROR_TYPE_DEBUG,
686        "Get informed about peer %s getting live\n",
687        GNUNET_i2s (&peer_ctx->peer_id));
688
689   struct GNUNET_MQ_Handle *mq;
690   struct GNUNET_MQ_Envelope *ev;
691
692   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE);
693   peer_ctx->liveliness_check_pending = GNUNET_new (struct PendingMessage);
694   peer_ctx->liveliness_check_pending->ev = ev;
695   peer_ctx->liveliness_check_pending->peer_ctx = peer_ctx;
696   peer_ctx->liveliness_check_pending->type = "Check liveliness";
697   mq = get_mq (&peer_ctx->peer_id);
698   GNUNET_MQ_notify_sent (ev,
699                          mq_liveliness_check_successful,
700                          peer_ctx);
701   GNUNET_MQ_send (mq, ev);
702 }
703
704 /**
705  * @brief Add an envelope to a message passed to mq to list of pending messages
706  *
707  * @param peer peer the message was sent to
708  * @param ev envelope to the message
709  * @param type type of the message to be sent
710  * @return pointer to pending message
711  */
712 static struct PendingMessage *
713 insert_pending_message (const struct GNUNET_PeerIdentity *peer,
714                         struct GNUNET_MQ_Envelope *ev,
715                         const char *type)
716 {
717   struct PendingMessage *pending_msg;
718   struct PeerContext *peer_ctx;
719
720   peer_ctx = get_peer_ctx (peer);
721   pending_msg = GNUNET_new (struct PendingMessage);
722   pending_msg->ev = ev;
723   pending_msg->peer_ctx = peer_ctx;
724   pending_msg->type = type;
725   GNUNET_CONTAINER_DLL_insert (peer_ctx->pending_messages_head,
726                                peer_ctx->pending_messages_tail,
727                                pending_msg);
728   return pending_msg;
729 }
730
731
732 /**
733  * @brief Remove a pending message from the respective DLL
734  *
735  * @param pending_msg the pending message to remove
736  * @param cancel cancel the pending message, too
737  */
738 static void
739 remove_pending_message (struct PendingMessage *pending_msg, int cancel)
740 {
741   struct PeerContext *peer_ctx;
742
743   peer_ctx = pending_msg->peer_ctx;
744   GNUNET_assert (NULL != peer_ctx);
745   GNUNET_CONTAINER_DLL_remove (peer_ctx->pending_messages_head,
746                                peer_ctx->pending_messages_tail,
747                                pending_msg);
748   // TODO wait for the cadet implementation of message cancellation
749   //if (GNUNET_YES == cancel)
750   //{
751   //  GNUNET_MQ_send_cancel (pending_msg->ev);
752   //}
753   GNUNET_free (pending_msg);
754 }
755
756
757 /**
758  * @brief Check whether function of type #PeerOp was already scheduled
759  *
760  * The array with pending operations will probably never grow really big, so
761  * iterating over it should be ok.
762  *
763  * @param peer the peer to check
764  * @param peer_op the operation (#PeerOp) on the peer
765  *
766  * @return #GNUNET_YES if this operation is scheduled on that peer
767  *         #GNUNET_NO  otherwise
768  */
769 static int
770 check_operation_scheduled (const struct GNUNET_PeerIdentity *peer,
771                            const PeerOp peer_op)
772 {
773   const struct PeerContext *peer_ctx;
774   unsigned int i;
775
776   peer_ctx = get_peer_ctx (peer);
777   for (i = 0; i < peer_ctx->num_pending_ops; i++)
778     if (peer_op == peer_ctx->pending_ops[i].op)
779       return GNUNET_YES;
780   return GNUNET_NO;
781 }
782
783 int
784 Peers_remove_peer (const struct GNUNET_PeerIdentity *peer);
785
786 /**
787  * Iterator over hash map entries. Deletes all contexts of peers.
788  *
789  * @param cls closure
790  * @param key current public key
791  * @param value value in the hash map
792  * @return #GNUNET_YES if we should continue to iterate,
793  *         #GNUNET_NO if not.
794  */
795 static int
796 peermap_clear_iterator (void *cls,
797                         const struct GNUNET_PeerIdentity *key,
798                         void *value)
799 {
800   Peers_remove_peer (key);
801   return GNUNET_YES;
802 }
803
804
805 /**
806  * @brief This is called once a message is sent.
807  *
808  * Removes the pending message
809  *
810  * @param cls type of the message that was sent
811  */
812 static void
813 mq_notify_sent_cb (void *cls)
814 {
815   struct PendingMessage *pending_msg = (struct PendingMessage *) cls;
816   LOG (GNUNET_ERROR_TYPE_DEBUG,
817       "%s was sent.\n",
818       pending_msg->type);
819   if (0 == strncmp ("PULL REPLY", pending_msg->type, 10))
820     GNUNET_STATISTICS_update(stats, "# pull replys sent", 1, GNUNET_NO);
821   if (0 == strncmp ("PULL REQUEST", pending_msg->type, 12))
822     GNUNET_STATISTICS_update(stats, "# pull requests sent", 1, GNUNET_NO);
823   if (0 == strncmp ("PUSH", pending_msg->type, 4))
824     GNUNET_STATISTICS_update(stats, "# pushes sent", 1, GNUNET_NO);
825   /* Do not cancle message */
826   remove_pending_message (pending_msg, GNUNET_NO);
827 }
828
829
830 /**
831  * @brief Iterator function for #store_valid_peers.
832  *
833  * Implements #GNUNET_CONTAINER_PeerMapIterator.
834  * Writes single peer to disk.
835  *
836  * @param cls the file handle to write to.
837  * @param peer current peer
838  * @param value unused
839  *
840  * @return  #GNUNET_YES if we should continue to
841  *          iterate,
842  *          #GNUNET_NO if not.
843  */
844 static int
845 store_peer_presistently_iterator (void *cls,
846                                   const struct GNUNET_PeerIdentity *peer,
847                                   void *value)
848 {
849   const struct GNUNET_DISK_FileHandle *fh = cls;
850   char peer_string[128];
851   int size;
852   ssize_t ret;
853
854   if (NULL == peer)
855   {
856     return GNUNET_YES;
857   }
858   size = GNUNET_snprintf (peer_string,
859                           sizeof (peer_string),
860                           "%s\n",
861                           GNUNET_i2s_full (peer));
862   GNUNET_assert (53 == size);
863   ret = GNUNET_DISK_file_write (fh,
864                                 peer_string,
865                                 size);
866   GNUNET_assert (size == ret);
867   return GNUNET_YES;
868 }
869
870
871 /**
872  * @brief Store the peers currently in #valid_peers to disk.
873  */
874 static void
875 store_valid_peers ()
876 {
877   struct GNUNET_DISK_FileHandle *fh;
878   uint32_t number_written_peers;
879   int ret;
880
881   if (0 == strncmp ("DISABLE", filename_valid_peers, 7))
882   {
883     return;
884   }
885
886   ret = GNUNET_DISK_directory_create_for_file (filename_valid_peers);
887   if (GNUNET_SYSERR == ret)
888   {
889     LOG (GNUNET_ERROR_TYPE_WARNING,
890         "Not able to create directory for file `%s'\n",
891         filename_valid_peers);
892     GNUNET_break (0);
893   }
894   else if (GNUNET_NO == ret)
895   {
896     LOG (GNUNET_ERROR_TYPE_WARNING,
897         "Directory for file `%s' exists but is not writable for us\n",
898         filename_valid_peers);
899     GNUNET_break (0);
900   }
901   fh = GNUNET_DISK_file_open (filename_valid_peers,
902                               GNUNET_DISK_OPEN_WRITE |
903                                   GNUNET_DISK_OPEN_CREATE,
904                               GNUNET_DISK_PERM_USER_READ |
905                                   GNUNET_DISK_PERM_USER_WRITE);
906   if (NULL == fh)
907   {
908     LOG (GNUNET_ERROR_TYPE_WARNING,
909         "Not able to write valid peers to file `%s'\n",
910         filename_valid_peers);
911     return;
912   }
913   LOG (GNUNET_ERROR_TYPE_DEBUG,
914       "Writing %u valid peers to disk\n",
915       GNUNET_CONTAINER_multipeermap_size (valid_peers));
916   number_written_peers =
917     GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
918                                            store_peer_presistently_iterator,
919                                            fh);
920   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
921   GNUNET_assert (number_written_peers ==
922       GNUNET_CONTAINER_multipeermap_size (valid_peers));
923 }
924
925
926 /**
927  * @brief Convert string representation of peer id to peer id.
928  *
929  * Counterpart to #GNUNET_i2s_full.
930  *
931  * @param string_repr The string representation of the peer id
932  *
933  * @return The peer id
934  */
935 static const struct GNUNET_PeerIdentity *
936 s2i_full (const char *string_repr)
937 {
938   struct GNUNET_PeerIdentity *peer;
939   size_t len;
940   int ret;
941
942   peer = GNUNET_new (struct GNUNET_PeerIdentity);
943   len = strlen (string_repr);
944   if (52 > len)
945   {
946     LOG (GNUNET_ERROR_TYPE_WARNING,
947         "Not able to convert string representation of PeerID to PeerID\n"
948         "Sting representation: %s (len %lu) - too short\n",
949         string_repr,
950         len);
951     GNUNET_break (0);
952   }
953   else if (52 < len)
954   {
955     len = 52;
956   }
957   ret = GNUNET_CRYPTO_eddsa_public_key_from_string (string_repr,
958                                                     len,
959                                                     &peer->public_key);
960   if (GNUNET_OK != ret)
961   {
962     LOG (GNUNET_ERROR_TYPE_WARNING,
963         "Not able to convert string representation of PeerID to PeerID\n"
964         "Sting representation: %s\n",
965         string_repr);
966     GNUNET_break (0);
967   }
968   return peer;
969 }
970
971
972 /**
973  * @brief Restore the peers on disk to #valid_peers.
974  */
975 static void
976 restore_valid_peers ()
977 {
978   off_t file_size;
979   uint32_t num_peers;
980   struct GNUNET_DISK_FileHandle *fh;
981   char *buf;
982   ssize_t size_read;
983   char *iter_buf;
984   char *str_repr;
985   const struct GNUNET_PeerIdentity *peer;
986
987   if (0 == strncmp ("DISABLE", filename_valid_peers, 7))
988   {
989     return;
990   }
991
992   if (GNUNET_OK != GNUNET_DISK_file_test (filename_valid_peers))
993   {
994     return;
995   }
996   fh = GNUNET_DISK_file_open (filename_valid_peers,
997                               GNUNET_DISK_OPEN_READ,
998                               GNUNET_DISK_PERM_NONE);
999   GNUNET_assert (NULL != fh);
1000   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_handle_size (fh, &file_size));
1001   num_peers = file_size / 53;
1002   buf = GNUNET_malloc (file_size);
1003   size_read = GNUNET_DISK_file_read (fh, buf, file_size);
1004   GNUNET_assert (size_read == file_size);
1005   LOG (GNUNET_ERROR_TYPE_DEBUG,
1006       "Restoring %" PRIu32 " peers from file `%s'\n",
1007       num_peers,
1008       filename_valid_peers);
1009   for (iter_buf = buf; iter_buf < buf + file_size - 1; iter_buf += 53)
1010   {
1011     str_repr = GNUNET_strndup (iter_buf, 53);
1012     peer = s2i_full (str_repr);
1013     GNUNET_free (str_repr);
1014     add_valid_peer (peer);
1015     LOG (GNUNET_ERROR_TYPE_DEBUG,
1016         "Restored valid peer %s from disk\n",
1017         GNUNET_i2s_full (peer));
1018   }
1019   iter_buf = NULL;
1020   GNUNET_free (buf);
1021   LOG (GNUNET_ERROR_TYPE_DEBUG,
1022       "num_peers: %" PRIu32 ", _size (valid_peers): %u\n",
1023       num_peers,
1024       GNUNET_CONTAINER_multipeermap_size (valid_peers));
1025   if (num_peers != GNUNET_CONTAINER_multipeermap_size (valid_peers))
1026   {
1027     LOG (GNUNET_ERROR_TYPE_WARNING,
1028         "Number of restored peers does not match file size. Have probably duplicates.\n");
1029   }
1030   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
1031   LOG (GNUNET_ERROR_TYPE_DEBUG,
1032       "Restored %u valid peers from disk\n",
1033       GNUNET_CONTAINER_multipeermap_size (valid_peers));
1034 }
1035
1036
1037 /**
1038  * @brief Initialise storage of peers
1039  *
1040  * @param fn_valid_peers filename of the file used to store valid peer ids
1041  * @param cadet_h cadet handle
1042  * @param disconnect_handler Disconnect handler
1043  * @param own_id own peer identity
1044  */
1045 void
1046 Peers_initialise (char* fn_valid_peers,
1047                   struct GNUNET_CADET_Handle *cadet_h,
1048                   GNUNET_CADET_DisconnectEventHandler disconnect_handler,
1049                   const struct GNUNET_PeerIdentity *own_id)
1050 {
1051   filename_valid_peers = GNUNET_strdup (fn_valid_peers);
1052   cadet_handle = cadet_h;
1053   own_identity = *own_id;
1054   peer_map = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
1055   valid_peers = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
1056   restore_valid_peers ();
1057 }
1058
1059
1060 /**
1061  * @brief Delete storage of peers that was created with #Peers_initialise ()
1062  */
1063 void
1064 Peers_terminate ()
1065 {
1066   if (GNUNET_SYSERR ==
1067       GNUNET_CONTAINER_multipeermap_iterate (peer_map,
1068                                              peermap_clear_iterator,
1069                                              NULL))
1070   {
1071     LOG (GNUNET_ERROR_TYPE_WARNING,
1072         "Iteration destroying peers was aborted.\n");
1073   }
1074   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1075   store_valid_peers ();
1076   GNUNET_free (filename_valid_peers);
1077   GNUNET_CONTAINER_multipeermap_destroy (valid_peers);
1078 }
1079
1080
1081 /**
1082  * Iterator over #valid_peers hash map entries.
1083  *
1084  * @param cls closure - unused
1085  * @param peer current peer id
1086  * @param value value in the hash map - unused
1087  * @return #GNUNET_YES if we should continue to
1088  *         iterate,
1089  *         #GNUNET_NO if not.
1090  */
1091 static int
1092 valid_peer_iterator (void *cls,
1093                      const struct GNUNET_PeerIdentity *peer,
1094                      void *value)
1095 {
1096   struct PeersIteratorCls *it_cls = cls;
1097
1098   return it_cls->iterator (it_cls->cls,
1099                            peer);
1100 }
1101
1102
1103 /**
1104  * @brief Get all currently known, valid peer ids.
1105  *
1106  * @param it function to call on each peer id
1107  * @param it_cls extra argument to @a it
1108  * @return the number of key value pairs processed,
1109  *         #GNUNET_SYSERR if it aborted iteration
1110  */
1111 int
1112 Peers_get_valid_peers (PeersIterator iterator,
1113                        void *it_cls)
1114 {
1115   struct PeersIteratorCls *cls;
1116   int ret;
1117
1118   cls = GNUNET_new (struct PeersIteratorCls);
1119   cls->iterator = iterator;
1120   cls->cls = it_cls;
1121   ret = GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
1122                                                valid_peer_iterator,
1123                                                cls);
1124   GNUNET_free (cls);
1125   return ret;
1126 }
1127
1128
1129 /**
1130  * @brief Add peer to known peers.
1131  *
1132  * This function is called on new peer_ids from 'external' sources
1133  * (client seed, cadet get_peers(), ...)
1134  *
1135  * @param peer the new #GNUNET_PeerIdentity
1136  *
1137  * @return #GNUNET_YES if peer was inserted
1138  *         #GNUNET_NO  otherwise (if peer was already known or
1139  *                     peer was #own_identity)
1140  */
1141 int
1142 Peers_insert_peer (const struct GNUNET_PeerIdentity *peer)
1143 {
1144   if ( (GNUNET_YES == Peers_check_peer_known (peer)) ||
1145        (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, &own_identity)) )
1146   {
1147     return GNUNET_NO; /* We already know this peer - nothing to do */
1148   }
1149   (void) create_peer_ctx (peer);
1150   return GNUNET_YES;
1151 }
1152
1153 int
1154 Peers_check_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags);
1155
1156 /**
1157  * @brief Try connecting to a peer to see whether it is online
1158  *
1159  * If not known yet, insert into known peers
1160  *
1161  * @param peer the peer whose liveliness is to be checked
1162  * @return #GNUNET_YES if peer had to be inserted
1163  *         #GNUNET_NO  otherwise (if peer was already known or
1164  *                     peer was #own_identity)
1165  */
1166 int
1167 Peers_issue_peer_liveliness_check (const struct GNUNET_PeerIdentity *peer)
1168 {
1169   struct PeerContext *peer_ctx;
1170   int ret;
1171
1172   if (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, &own_identity))
1173   {
1174     return GNUNET_NO;
1175   }
1176   ret = Peers_insert_peer (peer);
1177   peer_ctx = get_peer_ctx (peer);
1178   if (GNUNET_NO == Peers_check_peer_flag (peer, Peers_ONLINE))
1179   {
1180     check_peer_live (peer_ctx);
1181   }
1182   return ret;
1183 }
1184
1185
1186 /**
1187  * @brief Check if peer is removable.
1188  *
1189  * Check if
1190  *  - a recv channel exists
1191  *  - there are pending messages
1192  *  - there is no pending pull reply
1193  *
1194  * @param peer the peer in question
1195  * @return #GNUNET_YES    if peer is removable
1196  *         #GNUNET_NO     if peer is NOT removable
1197  *         #GNUNET_SYSERR if peer is not known
1198  */
1199 int
1200 Peers_check_removable (const struct GNUNET_PeerIdentity *peer)
1201 {
1202   struct PeerContext *peer_ctx;
1203
1204   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1205   {
1206     return GNUNET_SYSERR;
1207   }
1208
1209   peer_ctx = get_peer_ctx (peer);
1210   if ( (NULL != peer_ctx->recv_channel) ||
1211        (NULL != peer_ctx->pending_messages_head) ||
1212        (GNUNET_NO == check_peer_flag_set (peer_ctx, Peers_PULL_REPLY_PENDING)) )
1213   {
1214     return GNUNET_NO;
1215   }
1216   return GNUNET_YES;
1217 }
1218
1219 uint32_t *
1220 Peers_get_channel_flag (const struct GNUNET_PeerIdentity *peer,
1221                         enum Peers_ChannelRole role);
1222
1223 int
1224 Peers_check_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags);
1225
1226 /**
1227  * @brief Remove peer
1228  *
1229  * @param peer the peer to clean
1230  * @return #GNUNET_YES if peer was removed
1231  *         #GNUNET_NO  otherwise
1232  */
1233 int
1234 Peers_remove_peer (const struct GNUNET_PeerIdentity *peer)
1235 {
1236   struct PeerContext *peer_ctx;
1237   uint32_t *channel_flag;
1238
1239   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1240   {
1241     return GNUNET_NO;
1242   }
1243
1244   peer_ctx = get_peer_ctx (peer);
1245   set_peer_flag (peer_ctx, Peers_TO_DESTROY);
1246   LOG (GNUNET_ERROR_TYPE_DEBUG,
1247        "Going to remove peer %s\n",
1248        GNUNET_i2s (&peer_ctx->peer_id));
1249   Peers_unset_peer_flag (peer, Peers_ONLINE);
1250
1251   GNUNET_array_grow (peer_ctx->pending_ops, peer_ctx->num_pending_ops, 0);
1252   while (NULL != peer_ctx->pending_messages_head)
1253   {
1254     LOG (GNUNET_ERROR_TYPE_DEBUG,
1255         "Removing unsent %s\n",
1256         peer_ctx->pending_messages_head->type);
1257     /* Cancle pending message, too */
1258     remove_pending_message (peer_ctx->pending_messages_head, GNUNET_YES);
1259   }
1260   /* If we are still waiting for notification whether this peer is live
1261    * cancel the according task */
1262   if (NULL != peer_ctx->liveliness_check_pending)
1263   {
1264     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1265          "Removing pending liveliness check for peer %s\n",
1266          GNUNET_i2s (&peer_ctx->peer_id));
1267     // TODO wait until cadet sets mq->cancel_impl
1268     //GNUNET_MQ_send_cancel (peer_ctx->liveliness_check_pending->ev);
1269     GNUNET_free (peer_ctx->liveliness_check_pending);
1270     peer_ctx->liveliness_check_pending = NULL;
1271   }
1272   channel_flag = Peers_get_channel_flag (peer, Peers_CHANNEL_ROLE_SENDING);
1273   if (NULL != peer_ctx->send_channel &&
1274       GNUNET_YES != Peers_check_channel_flag (channel_flag, Peers_CHANNEL_DESTROING))
1275   {
1276     LOG (GNUNET_ERROR_TYPE_DEBUG,
1277         "Destroying send channel\n");
1278     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
1279     peer_ctx->send_channel = NULL;
1280   }
1281   channel_flag = Peers_get_channel_flag (peer, Peers_CHANNEL_ROLE_RECEIVING);
1282   if (NULL != peer_ctx->recv_channel &&
1283       GNUNET_YES != Peers_check_channel_flag (channel_flag, Peers_CHANNEL_DESTROING))
1284   {
1285     LOG (GNUNET_ERROR_TYPE_DEBUG,
1286         "Destroying recv channel\n");
1287     GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
1288     peer_ctx->recv_channel = NULL;
1289   }
1290
1291   GNUNET_free (peer_ctx->send_channel_flags);
1292   GNUNET_free (peer_ctx->recv_channel_flags);
1293
1294   if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, &peer_ctx->peer_id))
1295   {
1296     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1297   }
1298   GNUNET_free (peer_ctx);
1299   return GNUNET_YES;
1300 }
1301
1302
1303 /**
1304  * @brief set flags on a given peer.
1305  *
1306  * @param peer the peer to set flags on
1307  * @param flags the flags
1308  */
1309 void
1310 Peers_set_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags)
1311 {
1312   struct PeerContext *peer_ctx;
1313
1314   peer_ctx = get_peer_ctx (peer);
1315   set_peer_flag (peer_ctx, flags);
1316 }
1317
1318
1319 /**
1320  * @brief unset flags on a given peer.
1321  *
1322  * @param peer the peer to unset flags on
1323  * @param flags the flags
1324  */
1325 void
1326 Peers_unset_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags)
1327 {
1328   struct PeerContext *peer_ctx;
1329
1330   peer_ctx = get_peer_ctx (peer);
1331   unset_peer_flag (peer_ctx, flags);
1332 }
1333
1334
1335 /**
1336  * @brief Check whether flags on a peer are set.
1337  *
1338  * @param peer the peer to check the flag of
1339  * @param flags the flags to check
1340  *
1341  * @return #GNUNET_SYSERR if peer is not known
1342  *         #GNUNET_YES    if all given flags are set
1343  *         #GNUNET_NO     otherwise
1344  */
1345 int
1346 Peers_check_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags)
1347 {
1348   struct PeerContext *peer_ctx;
1349
1350   if (GNUNET_NO == Peers_check_peer_known (peer))
1351   {
1352     return GNUNET_SYSERR;
1353   }
1354   peer_ctx = get_peer_ctx (peer);
1355   return check_peer_flag_set (peer_ctx, flags);
1356 }
1357
1358
1359 /**
1360  * @brief set flags on a given channel.
1361  *
1362  * @param channel the channel to set flags on
1363  * @param flags the flags
1364  */
1365 void
1366 Peers_set_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags)
1367 {
1368   set_channel_flag (channel_flags, flags);
1369 }
1370
1371
1372 /**
1373  * @brief unset flags on a given channel.
1374  *
1375  * @param channel the channel to unset flags on
1376  * @param flags the flags
1377  */
1378 void
1379 Peers_unset_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags)
1380 {
1381   unset_channel_flag (channel_flags, flags);
1382 }
1383
1384
1385 /**
1386  * @brief Check whether flags on a channel are set.
1387  *
1388  * @param channel the channel to check the flag of
1389  * @param flags the flags to check
1390  *
1391  * @return #GNUNET_YES if all given flags are set
1392  *         #GNUNET_NO  otherwise
1393  */
1394 int
1395 Peers_check_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags)
1396 {
1397   return check_channel_flag_set (channel_flags, flags);
1398 }
1399
1400 /**
1401  * @brief Get the flags for the channel in @a role for @a peer.
1402  *
1403  * @param peer Peer to get the channel flags for.
1404  * @param role Role of channel to get flags for
1405  *
1406  * @return The flags.
1407  */
1408 uint32_t *
1409 Peers_get_channel_flag (const struct GNUNET_PeerIdentity *peer,
1410                         enum Peers_ChannelRole role)
1411 {
1412   const struct PeerContext *peer_ctx;
1413
1414   peer_ctx = get_peer_ctx (peer);
1415   if (Peers_CHANNEL_ROLE_SENDING == role)
1416   {
1417     return peer_ctx->send_channel_flags;
1418   }
1419   else if (Peers_CHANNEL_ROLE_RECEIVING == role)
1420   {
1421     return peer_ctx->recv_channel_flags;
1422   }
1423   else
1424   {
1425     GNUNET_assert (0);
1426   }
1427 }
1428
1429 /**
1430  * @brief Check whether we have information about the given peer.
1431  *
1432  * FIXME probably deprecated. Make this the new _online.
1433  *
1434  * @param peer peer in question
1435  *
1436  * @return #GNUNET_YES if peer is known
1437  *         #GNUNET_NO  if peer is not knwon
1438  */
1439 int
1440 Peers_check_peer_known (const struct GNUNET_PeerIdentity *peer)
1441 {
1442   return GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
1443 }
1444
1445
1446 /**
1447  * @brief Check whether @a peer is actually a peer.
1448  *
1449  * A valid peer is a peer that we know exists eg. we were connected to once.
1450  *
1451  * @param peer peer in question
1452  *
1453  * @return #GNUNET_YES if peer is valid
1454  *         #GNUNET_NO  if peer is not valid
1455  */
1456 int
1457 Peers_check_peer_valid (const struct GNUNET_PeerIdentity *peer)
1458 {
1459   return GNUNET_CONTAINER_multipeermap_contains (valid_peers, peer);
1460 }
1461
1462
1463 /**
1464  * @brief Indicate that we want to send to the other peer
1465  *
1466  * This establishes a sending channel
1467  *
1468  * @param peer the peer to establish channel to
1469  */
1470 void
1471 Peers_indicate_sending_intention (const struct GNUNET_PeerIdentity *peer)
1472 {
1473   GNUNET_assert (GNUNET_YES == Peers_check_peer_known (peer));
1474   (void) get_channel (peer);
1475 }
1476
1477
1478 /**
1479  * @brief Check whether other peer has the intention to send/opened channel
1480  *        towars us
1481  *
1482  * @param peer the peer in question
1483  *
1484  * @return #GNUNET_YES if peer has the intention to send
1485  *         #GNUNET_NO  otherwise
1486  */
1487 int
1488 Peers_check_peer_send_intention (const struct GNUNET_PeerIdentity *peer)
1489 {
1490   const struct PeerContext *peer_ctx;
1491
1492   peer_ctx = get_peer_ctx (peer);
1493   if (NULL != peer_ctx->recv_channel)
1494   {
1495     return GNUNET_YES;
1496   }
1497   return GNUNET_NO;
1498 }
1499
1500
1501 /**
1502  * Handle the channel a peer opens to us.
1503  *
1504  * @param cls The closure
1505  * @param channel The channel the peer wants to establish
1506  * @param initiator The peer's peer ID
1507  *
1508  * @return initial channel context for the channel
1509  *         (can be NULL -- that's not an error)
1510  */
1511 void *
1512 Peers_handle_inbound_channel (void *cls,
1513                               struct GNUNET_CADET_Channel *channel,
1514                               const struct GNUNET_PeerIdentity *initiator)
1515 {
1516   struct PeerContext *peer_ctx;
1517
1518   LOG (GNUNET_ERROR_TYPE_DEBUG,
1519       "New channel was established to us (Peer %s).\n",
1520       GNUNET_i2s (initiator));
1521   GNUNET_assert (NULL != channel); /* according to cadet API */
1522   /* Make sure we 'know' about this peer */
1523   peer_ctx = create_or_get_peer_ctx (initiator);
1524   set_peer_live (peer_ctx);
1525   /* We only accept one incoming channel per peer */
1526   if (GNUNET_YES == Peers_check_peer_send_intention (initiator))
1527   {
1528     set_channel_flag (peer_ctx->recv_channel_flags,
1529                       Peers_CHANNEL_ESTABLISHED_TWICE);
1530     //GNUNET_CADET_channel_destroy (channel);
1531     GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
1532     peer_ctx->recv_channel = channel;
1533     /* return the channel context */
1534     return &peer_ctx->peer_id;
1535   }
1536   peer_ctx->recv_channel = channel;
1537   return &peer_ctx->peer_id;
1538 }
1539
1540
1541 /**
1542  * @brief Check whether a sending channel towards the given peer exists
1543  *
1544  * @param peer the peer to check for
1545  *
1546  * @return #GNUNET_YES if a sending channel towards that peer exists
1547  *         #GNUNET_NO  otherwise
1548  */
1549 int
1550 Peers_check_sending_channel_exists (const struct GNUNET_PeerIdentity *peer)
1551 {
1552   struct PeerContext *peer_ctx;
1553
1554   if (GNUNET_NO == Peers_check_peer_known (peer))
1555   { /* If no such peer exists, there is no channel */
1556     return GNUNET_NO;
1557   }
1558   peer_ctx = get_peer_ctx (peer);
1559   if (NULL == peer_ctx->send_channel)
1560   {
1561     return GNUNET_NO;
1562   }
1563   return GNUNET_YES;
1564 }
1565
1566
1567 /**
1568  * @brief check whether the given channel is the sending channel of the given
1569  *        peer
1570  *
1571  * @param peer the peer in question
1572  * @param channel the channel to check for
1573  * @param role either #Peers_CHANNEL_ROLE_SENDING, or
1574  *                    #Peers_CHANNEL_ROLE_RECEIVING
1575  *
1576  * @return #GNUNET_YES if the given chennel is the sending channel of the peer
1577  *         #GNUNET_NO  otherwise
1578  */
1579 int
1580 Peers_check_channel_role (const struct GNUNET_PeerIdentity *peer,
1581                           const struct GNUNET_CADET_Channel *channel,
1582                           enum Peers_ChannelRole role)
1583 {
1584   const struct PeerContext *peer_ctx;
1585
1586   if (GNUNET_NO == Peers_check_peer_known (peer))
1587   {
1588     return GNUNET_NO;
1589   }
1590   peer_ctx = get_peer_ctx (peer);
1591   if ( (Peers_CHANNEL_ROLE_SENDING == role) &&
1592        (channel == peer_ctx->send_channel) )
1593   {
1594     return GNUNET_YES;
1595   }
1596   if ( (Peers_CHANNEL_ROLE_RECEIVING == role) &&
1597        (channel == peer_ctx->recv_channel) )
1598   {
1599     return GNUNET_YES;
1600   }
1601   return GNUNET_NO;
1602 }
1603
1604
1605 /**
1606  * @brief Destroy the send channel of a peer e.g. stop indicating a sending
1607  *        intention to another peer
1608  *
1609  * If there is also no channel to receive messages from that peer, remove it
1610  * from the peermap.
1611  * TODO really?
1612  *
1613  * @peer the peer identity of the peer whose sending channel to destroy
1614  * @return #GNUNET_YES if channel was destroyed
1615  *         #GNUNET_NO  otherwise
1616  */
1617 int
1618 Peers_destroy_sending_channel (const struct GNUNET_PeerIdentity *peer)
1619 {
1620   struct PeerContext *peer_ctx;
1621
1622   if (GNUNET_NO == Peers_check_peer_known (peer))
1623   {
1624     return GNUNET_NO;
1625   }
1626   peer_ctx = get_peer_ctx (peer);
1627   if (NULL != peer_ctx->send_channel)
1628   {
1629     set_channel_flag (peer_ctx->send_channel_flags, Peers_CHANNEL_CLEAN);
1630     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
1631     peer_ctx->send_channel = NULL;
1632     (void) Peers_check_connected (peer);
1633     return GNUNET_YES;
1634   }
1635   return GNUNET_NO;
1636 }
1637
1638 /**
1639  * This is called when a channel is destroyed.
1640  *
1641  * @param cls The closure
1642  * @param channel The channel being closed
1643  */
1644 void
1645 Peers_cleanup_destroyed_channel (void *cls,
1646                                  const struct GNUNET_CADET_Channel *channel)
1647 {
1648   struct GNUNET_PeerIdentity *peer = cls;
1649   struct PeerContext *peer_ctx;
1650
1651   if (GNUNET_NO == Peers_check_peer_known (peer))
1652   {/* We don't want to implicitly create a context that we're about to kill */
1653   LOG (GNUNET_ERROR_TYPE_DEBUG,
1654        "channel (%s) without associated context was destroyed\n",
1655        GNUNET_i2s (peer));
1656     return;
1657   }
1658   peer_ctx = get_peer_ctx (peer);
1659
1660   /* If our peer issued the destruction of the channel, the #Peers_TO_DESTROY
1661    * flag will be set. In this case simply make sure that the channels are
1662    * cleaned. */
1663   /* FIXME This distinction seems to be redundant */
1664   if (Peers_check_peer_flag (peer, Peers_TO_DESTROY))
1665   {/* We initiatad the destruction of this particular peer */
1666     if (channel == peer_ctx->send_channel)
1667       peer_ctx->send_channel = NULL;
1668     else if (channel == peer_ctx->recv_channel)
1669       peer_ctx->recv_channel = NULL;
1670
1671     if (NULL != peer_ctx->send_channel)
1672     {
1673       GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
1674       peer_ctx->send_channel = NULL;
1675     }
1676     if (NULL != peer_ctx->recv_channel)
1677     {
1678       GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
1679       peer_ctx->recv_channel = NULL;
1680     }
1681     /* Set the #Peers_ONLINE flag accordingly */
1682     (void) Peers_check_connected (peer);
1683     return;
1684   }
1685
1686   else
1687   { /* We did not initiate the destruction of this peer */
1688     if (channel == peer_ctx->send_channel)
1689     { /* Something (but us) killd the channel - clean up peer */
1690       LOG (GNUNET_ERROR_TYPE_DEBUG,
1691           "send channel (%s) was destroyed - cleaning up\n",
1692           GNUNET_i2s (peer));
1693       peer_ctx->send_channel = NULL;
1694     }
1695     else if (channel == peer_ctx->recv_channel)
1696     { /* Other peer doesn't want to send us messages anymore */
1697       LOG (GNUNET_ERROR_TYPE_DEBUG,
1698            "Peer %s destroyed recv channel - cleaning up channel\n",
1699            GNUNET_i2s (peer));
1700       peer_ctx->recv_channel = NULL;
1701     }
1702     else
1703     {
1704       LOG (GNUNET_ERROR_TYPE_WARNING,
1705            "unknown channel (%s) was destroyed\n",
1706            GNUNET_i2s (peer));
1707     }
1708   }
1709   (void) Peers_check_connected (peer);
1710 }
1711
1712 /**
1713  * @brief Send a message to another peer.
1714  *
1715  * Keeps track about pending messages so they can be properly removed when the
1716  * peer is destroyed.
1717  *
1718  * @param peer receeiver of the message
1719  * @param ev envelope of the message
1720  * @param type type of the message
1721  */
1722 void
1723 Peers_send_message (const struct GNUNET_PeerIdentity *peer,
1724                     struct GNUNET_MQ_Envelope *ev,
1725                     const char *type)
1726 {
1727   struct PendingMessage *pending_msg;
1728   struct GNUNET_MQ_Handle *mq;
1729
1730   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1731               "Sending message to %s of type %s\n",
1732               GNUNET_i2s (peer),
1733               type);
1734   pending_msg = insert_pending_message (peer, ev, type);
1735   mq = get_mq (peer);
1736   GNUNET_MQ_notify_sent (ev,
1737                          mq_notify_sent_cb,
1738                          pending_msg);
1739   GNUNET_MQ_send (mq, ev);
1740 }
1741
1742 /**
1743  * @brief Schedule a operation on given peer
1744  *
1745  * Avoids scheduling an operation twice.
1746  *
1747  * @param peer the peer we want to schedule the operation for once it gets live
1748  *
1749  * @return #GNUNET_YES if the operation was scheduled
1750  *         #GNUNET_NO  otherwise
1751  */
1752 int
1753 Peers_schedule_operation (const struct GNUNET_PeerIdentity *peer,
1754                           const PeerOp peer_op)
1755 {
1756   struct PeerPendingOp pending_op;
1757   struct PeerContext *peer_ctx;
1758
1759   if (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, &own_identity))
1760   {
1761     return GNUNET_NO;
1762   }
1763   GNUNET_assert (GNUNET_YES == Peers_check_peer_known (peer));
1764
1765   //TODO if LIVE/ONLINE execute immediately
1766
1767   if (GNUNET_NO == check_operation_scheduled (peer, peer_op))
1768   {
1769     peer_ctx = get_peer_ctx (peer);
1770     pending_op.op = peer_op;
1771     pending_op.op_cls = NULL;
1772     GNUNET_array_append (peer_ctx->pending_ops,
1773                          peer_ctx->num_pending_ops,
1774                          pending_op);
1775     return GNUNET_YES;
1776   }
1777   return GNUNET_NO;
1778 }
1779
1780 /**
1781  * @brief Get the recv_channel of @a peer.
1782  * Needed to correctly handle (call #GNUNET_CADET_receive_done()) incoming
1783  * messages.
1784  *
1785  * @param peer The peer to get the recv_channel from.
1786  *
1787  * @return The recv_channel.
1788  */
1789 struct GNUNET_CADET_Channel *
1790 Peers_get_recv_channel (const struct GNUNET_PeerIdentity *peer)
1791 {
1792   struct PeerContext *peer_ctx;
1793
1794   GNUNET_assert (GNUNET_YES == Peers_check_peer_known (peer));
1795   peer_ctx = get_peer_ctx (peer);
1796   return peer_ctx->recv_channel;
1797 }
1798 /***********************************************************************
1799  * /Old gnunet-service-rps_peers.c
1800 ***********************************************************************/
1801
1802
1803 /***********************************************************************
1804  * Housekeeping with clients
1805 ***********************************************************************/
1806
1807 /**
1808  * Closure used to pass the client and the id to the callback
1809  * that replies to a client's request
1810  */
1811 struct ReplyCls
1812 {
1813   /**
1814    * DLL
1815    */
1816   struct ReplyCls *next;
1817   struct ReplyCls *prev;
1818
1819   /**
1820    * The identifier of the request
1821    */
1822   uint32_t id;
1823
1824   /**
1825    * The handle to the request
1826    */
1827   struct RPS_SamplerRequestHandle *req_handle;
1828
1829   /**
1830    * The client handle to send the reply to
1831    */
1832   struct ClientContext *cli_ctx;
1833 };
1834
1835
1836 /**
1837  * Struct used to store the context of a connected client.
1838  */
1839 struct ClientContext
1840 {
1841   /**
1842    * DLL
1843    */
1844   struct ClientContext *next;
1845   struct ClientContext *prev;
1846
1847   /**
1848    * The message queue to communicate with the client.
1849    */
1850   struct GNUNET_MQ_Handle *mq;
1851
1852   /**
1853    * DLL with handles to single requests from the client
1854    */
1855   struct ReplyCls *rep_cls_head;
1856   struct ReplyCls *rep_cls_tail;
1857
1858   /**
1859    * The client handle to send the reply to
1860    */
1861   struct GNUNET_SERVICE_Client *client;
1862 };
1863
1864 /**
1865  * DLL with all clients currently connected to us
1866  */
1867 struct ClientContext *cli_ctx_head;
1868 struct ClientContext *cli_ctx_tail;
1869
1870 /***********************************************************************
1871  * /Housekeeping with clients
1872 ***********************************************************************/
1873
1874
1875
1876
1877
1878 /***********************************************************************
1879  * Globals
1880 ***********************************************************************/
1881
1882 /**
1883  * Sampler used for the Brahms protocol itself.
1884  */
1885 static struct RPS_Sampler *prot_sampler;
1886
1887 /**
1888  * Sampler used for the clients.
1889  */
1890 static struct RPS_Sampler *client_sampler;
1891
1892 /**
1893  * Name to log view to
1894  */
1895 static char *file_name_view_log;
1896
1897 /**
1898  * The size of sampler we need to be able to satisfy the client's need
1899  * of random peers.
1900  */
1901 static unsigned int sampler_size_client_need;
1902
1903 /**
1904  * The size of sampler we need to be able to satisfy the Brahms protocol's
1905  * need of random peers.
1906  *
1907  * This is one minimum size the sampler grows to.
1908  */
1909 static unsigned int sampler_size_est_need;
1910
1911 /**
1912  * Percentage of total peer number in the view
1913  * to send random PUSHes to
1914  */
1915 static float alpha;
1916
1917 /**
1918  * Percentage of total peer number in the view
1919  * to send random PULLs to
1920  */
1921 static float beta;
1922
1923 /**
1924  * Identifier for the main task that runs periodically.
1925  */
1926 static struct GNUNET_SCHEDULER_Task *do_round_task;
1927
1928 /**
1929  * Time inverval the do_round task runs in.
1930  */
1931 static struct GNUNET_TIME_Relative round_interval;
1932
1933 /**
1934  * List to store peers received through pushes temporary.
1935  */
1936 static struct CustomPeerMap *push_map;
1937
1938 /**
1939  * List to store peers received through pulls temporary.
1940  */
1941 static struct CustomPeerMap *pull_map;
1942
1943 /**
1944  * Handler to NSE.
1945  */
1946 static struct GNUNET_NSE_Handle *nse;
1947
1948 /**
1949  * Handler to CADET.
1950  */
1951 static struct GNUNET_CADET_Handle *cadet_handle;
1952
1953 /**
1954  * @brief Port to communicate to other peers.
1955  */
1956 static struct GNUNET_CADET_Port *cadet_port;
1957
1958 /**
1959  * Handler to PEERINFO.
1960  */
1961 static struct GNUNET_PEERINFO_Handle *peerinfo_handle;
1962
1963 /**
1964  * Handle for cancellation of iteration over peers.
1965  */
1966 static struct GNUNET_PEERINFO_NotifyContext *peerinfo_notify_handle;
1967
1968 /**
1969  * Request counter.
1970  *
1971  * Counts how many requets clients already issued.
1972  * Only needed in the beginning to check how many of the 64 deltas
1973  * we already have
1974  */
1975 static unsigned int req_counter;
1976
1977 /**
1978  * Time of the last request we received.
1979  *
1980  * Used to compute the expected request rate.
1981  */
1982 static struct GNUNET_TIME_Absolute last_request;
1983
1984 /**
1985  * Size of #request_deltas.
1986  */
1987 #define REQUEST_DELTAS_SIZE 64
1988 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
1989
1990 /**
1991  * Last 64 deltas between requests
1992  */
1993 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
1994
1995 /**
1996  * The prediction of the rate of requests
1997  */
1998 static struct GNUNET_TIME_Relative request_rate;
1999
2000
2001 #ifdef ENABLE_MALICIOUS
2002 /**
2003  * Type of malicious peer
2004  *
2005  * 0 Don't act malicious at all - Default
2006  * 1 Try to maximise representation
2007  * 2 Try to partition the network
2008  * 3 Combined attack
2009  */
2010 static uint32_t mal_type;
2011
2012 /**
2013  * Other malicious peers
2014  */
2015 static struct GNUNET_PeerIdentity *mal_peers;
2016
2017 /**
2018  * Hashmap of malicious peers used as set.
2019  * Used to more efficiently check whether we know that peer.
2020  */
2021 static struct GNUNET_CONTAINER_MultiPeerMap *mal_peer_set;
2022
2023 /**
2024  * Number of other malicious peers
2025  */
2026 static uint32_t num_mal_peers;
2027
2028
2029 /**
2030  * If type is 2 This struct is used to store the attacked peers in a DLL
2031  */
2032 struct AttackedPeer
2033 {
2034   /**
2035    * DLL
2036    */
2037   struct AttackedPeer *next;
2038   struct AttackedPeer *prev;
2039
2040   /**
2041    * PeerID
2042    */
2043   struct GNUNET_PeerIdentity peer_id;
2044 };
2045
2046 /**
2047  * If type is 2 this is the DLL of attacked peers
2048  */
2049 static struct AttackedPeer *att_peers_head;
2050 static struct AttackedPeer *att_peers_tail;
2051
2052 /**
2053  * This index is used to point to an attacked peer to
2054  * implement the round-robin-ish way to select attacked peers.
2055  */
2056 static struct AttackedPeer *att_peer_index;
2057
2058 /**
2059  * Hashmap of attacked peers used as set.
2060  * Used to more efficiently check whether we know that peer.
2061  */
2062 static struct GNUNET_CONTAINER_MultiPeerMap *att_peer_set;
2063
2064 /**
2065  * Number of attacked peers
2066  */
2067 static uint32_t num_attacked_peers;
2068
2069 /**
2070  * If type is 1 this is the attacked peer
2071  */
2072 static struct GNUNET_PeerIdentity attacked_peer;
2073
2074 /**
2075  * The limit of PUSHes we can send in one round.
2076  * This is an assumption of the Brahms protocol and either implemented
2077  * via proof of work
2078  * or
2079  * assumend to be the bandwidth limitation.
2080  */
2081 static uint32_t push_limit = 10000;
2082 #endif /* ENABLE_MALICIOUS */
2083
2084
2085 /***********************************************************************
2086  * /Globals
2087 ***********************************************************************/
2088
2089
2090 /***********************************************************************
2091  * Util functions
2092 ***********************************************************************/
2093
2094
2095 /**
2096  * Print peerlist to log.
2097  */
2098 static void
2099 print_peer_list (struct GNUNET_PeerIdentity *list,
2100                  unsigned int len)
2101 {
2102   unsigned int i;
2103
2104   LOG (GNUNET_ERROR_TYPE_DEBUG,
2105        "Printing peer list of length %u at %p:\n",
2106        len,
2107        list);
2108   for (i = 0 ; i < len ; i++)
2109   {
2110     LOG (GNUNET_ERROR_TYPE_DEBUG,
2111          "%u. peer: %s\n",
2112          i, GNUNET_i2s (&list[i]));
2113   }
2114 }
2115
2116
2117 /**
2118  * Remove peer from list.
2119  */
2120 static void
2121 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
2122                unsigned int *list_size,
2123                const struct GNUNET_PeerIdentity *peer)
2124 {
2125   unsigned int i;
2126   struct GNUNET_PeerIdentity *tmp;
2127
2128   tmp = *peer_list;
2129
2130   LOG (GNUNET_ERROR_TYPE_DEBUG,
2131        "Removing peer %s from list at %p\n",
2132        GNUNET_i2s (peer),
2133        tmp);
2134
2135   for ( i = 0 ; i < *list_size ; i++ )
2136   {
2137     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
2138     {
2139       if (i < *list_size -1)
2140       { /* Not at the last entry -- shift peers left */
2141         memmove (&tmp[i], &tmp[i +1],
2142                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
2143       }
2144       /* Remove last entry (should be now useless PeerID) */
2145       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
2146     }
2147   }
2148   *peer_list = tmp;
2149 }
2150
2151
2152 /**
2153  * Sum all time relatives of an array.
2154  */
2155 static struct GNUNET_TIME_Relative
2156 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array,
2157                 uint32_t arr_size)
2158 {
2159   struct GNUNET_TIME_Relative sum;
2160   uint32_t i;
2161
2162   sum = GNUNET_TIME_UNIT_ZERO;
2163   for ( i = 0 ; i < arr_size ; i++ )
2164   {
2165     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
2166   }
2167   return sum;
2168 }
2169
2170
2171 /**
2172  * Compute the average of given time relatives.
2173  */
2174 static struct GNUNET_TIME_Relative
2175 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array,
2176                 uint32_t arr_size)
2177 {
2178   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array,
2179                                                       arr_size),
2180                                       arr_size);
2181 }
2182
2183
2184 /**
2185  * Insert PeerID in #view
2186  *
2187  * Called once we know a peer is live.
2188  * Implements #PeerOp
2189  *
2190  * @return GNUNET_OK if peer was actually inserted
2191  *         GNUNET_NO if peer was not inserted
2192  */
2193 static void
2194 insert_in_view_op (void *cls,
2195                 const struct GNUNET_PeerIdentity *peer);
2196
2197 /**
2198  * Insert PeerID in #view
2199  *
2200  * Called once we know a peer is live.
2201  *
2202  * @return GNUNET_OK if peer was actually inserted
2203  *         GNUNET_NO if peer was not inserted
2204  */
2205 static int
2206 insert_in_view (const struct GNUNET_PeerIdentity *peer)
2207 {
2208   int online;
2209
2210   online = Peers_check_peer_flag (peer, Peers_ONLINE);
2211   if ( (GNUNET_NO == online) ||
2212        (GNUNET_SYSERR == online) ) /* peer is not even known */
2213   {
2214     (void) Peers_issue_peer_liveliness_check (peer);
2215     (void) Peers_schedule_operation (peer, insert_in_view_op);
2216     return GNUNET_NO;
2217   }
2218   /* Open channel towards peer to keep connection open */
2219   Peers_indicate_sending_intention (peer);
2220   return View_put (peer);
2221 }
2222
2223 /**
2224  * Put random peer from sampler into the view as history update.
2225  */
2226 static void
2227 hist_update (void *cls,
2228              struct GNUNET_PeerIdentity *ids,
2229              uint32_t num_peers)
2230 {
2231   unsigned int i;
2232
2233   for (i = 0; i < num_peers; i++)
2234   {
2235     (void) insert_in_view (&ids[i]);
2236     to_file (file_name_view_log,
2237              "+%s\t(hist)",
2238              GNUNET_i2s_full (ids));
2239   }
2240 }
2241
2242
2243 /**
2244  * Wrapper around #RPS_sampler_resize()
2245  *
2246  * If we do not have enough sampler elements, double current sampler size
2247  * If we have more than enough sampler elements, halv current sampler size
2248  */
2249 static void
2250 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
2251 {
2252   unsigned int sampler_size;
2253
2254   // TODO statistics
2255   // TODO respect the min, max
2256   sampler_size = RPS_sampler_get_size (sampler);
2257   if (sampler_size > new_size * 4)
2258   { /* Shrinking */
2259     RPS_sampler_resize (sampler, sampler_size / 2);
2260   }
2261   else if (sampler_size < new_size)
2262   { /* Growing */
2263     RPS_sampler_resize (sampler, sampler_size * 2);
2264   }
2265   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
2266 }
2267
2268
2269 /**
2270  * Wrapper around #RPS_sampler_resize() resizing the client sampler
2271  */
2272 static void
2273 client_resize_wrapper ()
2274 {
2275   uint32_t bigger_size;
2276
2277   // TODO statistics
2278
2279   bigger_size = GNUNET_MAX (sampler_size_est_need, sampler_size_client_need);
2280
2281   // TODO respect the min, max
2282   resize_wrapper (client_sampler, bigger_size);
2283   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size_client is now %" PRIu32 "\n",
2284       bigger_size);
2285 }
2286
2287
2288 /**
2289  * Estimate request rate
2290  *
2291  * Called every time we receive a request from the client.
2292  */
2293 static void
2294 est_request_rate()
2295 {
2296   struct GNUNET_TIME_Relative max_round_duration;
2297
2298   if (request_deltas_size > req_counter)
2299     req_counter++;
2300   if ( 1 < req_counter)
2301   {
2302     /* Shift last request deltas to the right */
2303     memmove (&request_deltas[1],
2304         request_deltas,
2305         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
2306
2307     /* Add current delta to beginning */
2308     request_deltas[0] =
2309         GNUNET_TIME_absolute_get_difference (last_request,
2310                                              GNUNET_TIME_absolute_get ());
2311     request_rate = T_relative_avg (request_deltas, req_counter);
2312     request_rate = (request_rate.rel_value_us < 1) ?
2313       GNUNET_TIME_relative_get_unit_ () : request_rate;
2314
2315     /* Compute the duration a round will maximally take */
2316     max_round_duration =
2317         GNUNET_TIME_relative_add (round_interval,
2318                                   GNUNET_TIME_relative_divide (round_interval, 2));
2319
2320     /* Set the estimated size the sampler has to have to
2321      * satisfy the current client request rate */
2322     sampler_size_client_need =
2323         max_round_duration.rel_value_us / request_rate.rel_value_us;
2324
2325     /* Resize the sampler */
2326     client_resize_wrapper ();
2327   }
2328   last_request = GNUNET_TIME_absolute_get ();
2329 }
2330
2331
2332 /**
2333  * Add all peers in @a peer_array to @a peer_map used as set.
2334  *
2335  * @param peer_array array containing the peers
2336  * @param num_peers number of peers in @peer_array
2337  * @param peer_map the peermap to use as set
2338  */
2339 static void
2340 add_peer_array_to_set (const struct GNUNET_PeerIdentity *peer_array,
2341                        unsigned int num_peers,
2342                        struct GNUNET_CONTAINER_MultiPeerMap *peer_map)
2343 {
2344   unsigned int i;
2345   if (NULL == peer_map)
2346   {
2347     LOG (GNUNET_ERROR_TYPE_WARNING,
2348          "Trying to add peers to non-existing peermap.\n");
2349     return;
2350   }
2351
2352   for (i = 0; i < num_peers; i++)
2353   {
2354     GNUNET_CONTAINER_multipeermap_put (peer_map,
2355                                        &peer_array[i],
2356                                        NULL,
2357                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2358   }
2359 }
2360
2361
2362 /**
2363  * Send a PULL REPLY to @a peer_id
2364  *
2365  * @param peer_id the peer to send the reply to.
2366  * @param peer_ids the peers to send to @a peer_id
2367  * @param num_peer_ids the number of peers to send to @a peer_id
2368  */
2369 static void
2370 send_pull_reply (const struct GNUNET_PeerIdentity *peer_id,
2371                  const struct GNUNET_PeerIdentity *peer_ids,
2372                  unsigned int num_peer_ids)
2373 {
2374   uint32_t send_size;
2375   struct GNUNET_MQ_Envelope *ev;
2376   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
2377
2378   /* Compute actual size */
2379   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
2380               num_peer_ids * sizeof (struct GNUNET_PeerIdentity);
2381
2382   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
2383     /* Compute number of peers to send
2384      * If too long, simply truncate */
2385     // TODO select random ones via permutation
2386     //      or even better: do good protocol design
2387     send_size =
2388       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
2389        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
2390        sizeof (struct GNUNET_PeerIdentity);
2391   else
2392     send_size = num_peer_ids;
2393
2394   LOG (GNUNET_ERROR_TYPE_DEBUG,
2395       "Going to send PULL REPLY with %u peers to %s\n",
2396       send_size, GNUNET_i2s (peer_id));
2397
2398   ev = GNUNET_MQ_msg_extra (out_msg,
2399                             send_size * sizeof (struct GNUNET_PeerIdentity),
2400                             GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
2401   out_msg->num_peers = htonl (send_size);
2402   GNUNET_memcpy (&out_msg[1], peer_ids,
2403          send_size * sizeof (struct GNUNET_PeerIdentity));
2404
2405   Peers_send_message (peer_id, ev, "PULL REPLY");
2406   GNUNET_STATISTICS_update(stats, "# pull reply send issued", 1, GNUNET_NO);
2407 }
2408
2409
2410 /**
2411  * Insert PeerID in #pull_map
2412  *
2413  * Called once we know a peer is live.
2414  */
2415 static void
2416 insert_in_pull_map (void *cls,
2417                     const struct GNUNET_PeerIdentity *peer)
2418 {
2419   CustomPeerMap_put (pull_map, peer);
2420 }
2421
2422
2423 /**
2424  * Insert PeerID in #view
2425  *
2426  * Called once we know a peer is live.
2427  * Implements #PeerOp
2428  */
2429 static void
2430 insert_in_view_op (void *cls,
2431                 const struct GNUNET_PeerIdentity *peer)
2432 {
2433   (void) insert_in_view (peer);
2434 }
2435
2436
2437 /**
2438  * Update sampler with given PeerID.
2439  * Implements #PeerOp
2440  */
2441 static void
2442 insert_in_sampler (void *cls,
2443                    const struct GNUNET_PeerIdentity *peer)
2444 {
2445   LOG (GNUNET_ERROR_TYPE_DEBUG,
2446        "Updating samplers with peer %s from insert_in_sampler()\n",
2447        GNUNET_i2s (peer));
2448   RPS_sampler_update (prot_sampler,   peer);
2449   RPS_sampler_update (client_sampler, peer);
2450   if (0 < RPS_sampler_count_id (prot_sampler, peer))
2451   {
2452     /* Make sure we 'know' about this peer */
2453     (void) Peers_issue_peer_liveliness_check (peer);
2454     /* Establish a channel towards that peer to indicate we are going to send
2455      * messages to it */
2456     //Peers_indicate_sending_intention (peer);
2457   }
2458 }
2459
2460 /**
2461  * @brief This is called on peers from external sources (cadet, peerinfo, ...)
2462  *        If the peer is not known, liveliness check is issued and it is
2463  *        scheduled to be inserted in sampler and view.
2464  *
2465  * "External sources" refer to every source except the gossip.
2466  *
2467  * @param peer peer to insert
2468  */
2469 static void
2470 got_peer (const struct GNUNET_PeerIdentity *peer)
2471 {
2472   /* If we did not know this peer already, insert it into sampler and view */
2473   if (GNUNET_YES == Peers_issue_peer_liveliness_check (peer))
2474   {
2475     Peers_schedule_operation (peer, insert_in_sampler);
2476     Peers_schedule_operation (peer, insert_in_view_op);
2477   }
2478 }
2479
2480 /**
2481  * @brief Checks if there is a sending channel and if it is needed
2482  *
2483  * @param peer the peer whose sending channel is checked
2484  * @return GNUNET_YES if sending channel exists and is still needed
2485  *         GNUNET_NO  otherwise
2486  */
2487 static int
2488 check_sending_channel_needed (const struct GNUNET_PeerIdentity *peer)
2489 {
2490   /* struct GNUNET_CADET_Channel *channel; */
2491   if (GNUNET_NO == Peers_check_peer_known (peer))
2492   {
2493     return GNUNET_NO;
2494   }
2495   if (GNUNET_YES == Peers_check_sending_channel_exists (peer))
2496   {
2497     if ( (0 < RPS_sampler_count_id (prot_sampler, peer)) ||
2498          (GNUNET_YES == View_contains_peer (peer)) ||
2499          (GNUNET_YES == CustomPeerMap_contains_peer (push_map, peer)) ||
2500          (GNUNET_YES == CustomPeerMap_contains_peer (pull_map, peer)) ||
2501          (GNUNET_YES == Peers_check_peer_flag (peer, Peers_PULL_REPLY_PENDING)))
2502     { /* If we want to keep the connection to peer open */
2503       return GNUNET_YES;
2504     }
2505     return GNUNET_NO;
2506   }
2507   return GNUNET_NO;
2508 }
2509
2510 /**
2511  * @brief remove peer from our knowledge, the view, push and pull maps and
2512  * samplers.
2513  *
2514  * @param peer the peer to remove
2515  */
2516 static void
2517 remove_peer (const struct GNUNET_PeerIdentity *peer)
2518 {
2519   (void) View_remove_peer (peer);
2520   CustomPeerMap_remove_peer (pull_map, peer);
2521   CustomPeerMap_remove_peer (push_map, peer);
2522   RPS_sampler_reinitialise_by_value (prot_sampler, peer);
2523   RPS_sampler_reinitialise_by_value (client_sampler, peer);
2524   Peers_remove_peer (peer);
2525 }
2526
2527
2528 /**
2529  * @brief Remove data that is not needed anymore.
2530  *
2531  * If the sending channel is no longer needed it is destroyed.
2532  *
2533  * @param peer the peer whose data is about to be cleaned
2534  */
2535 static void
2536 clean_peer (const struct GNUNET_PeerIdentity *peer)
2537 {
2538   if (GNUNET_NO == check_sending_channel_needed (peer))
2539   {
2540     LOG (GNUNET_ERROR_TYPE_DEBUG,
2541         "Going to remove send channel to peer %s\n",
2542         GNUNET_i2s (peer));
2543     #ifdef ENABLE_MALICIOUS
2544     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
2545       (void) Peers_destroy_sending_channel (peer);
2546     #else /* ENABLE_MALICIOUS */
2547     (void) Peers_destroy_sending_channel (peer);
2548     #endif /* ENABLE_MALICIOUS */
2549   }
2550
2551   if ( (GNUNET_NO == Peers_check_peer_send_intention (peer)) &&
2552        (GNUNET_NO == View_contains_peer (peer)) &&
2553        (GNUNET_NO == CustomPeerMap_contains_peer (push_map, peer)) &&
2554        (GNUNET_NO == CustomPeerMap_contains_peer (push_map, peer)) &&
2555        (0 == RPS_sampler_count_id (prot_sampler,   peer)) &&
2556        (0 == RPS_sampler_count_id (client_sampler, peer)) &&
2557        (GNUNET_NO != Peers_check_removable (peer)) )
2558   { /* We can safely remove this peer */
2559     LOG (GNUNET_ERROR_TYPE_DEBUG,
2560         "Going to remove peer %s\n",
2561         GNUNET_i2s (peer));
2562     remove_peer (peer);
2563     return;
2564   }
2565 }
2566
2567 /**
2568  * @brief This is called when a channel is destroyed.
2569  *
2570  * Removes peer completely from our knowledge if the send_channel was destroyed
2571  * Otherwise simply delete the recv_channel
2572  * Also check if the knowledge about this peer is still needed.
2573  * If not, remove this peer from our knowledge.
2574  *
2575  * @param cls The closure
2576  * @param channel The channel being closed
2577  * @param channel_ctx The context associated with this channel
2578  */
2579 static void
2580 cleanup_destroyed_channel (void *cls,
2581                            const struct GNUNET_CADET_Channel *channel)
2582 {
2583   struct GNUNET_PeerIdentity *peer = cls;
2584   uint32_t *channel_flag;
2585   struct PeerContext *peer_ctx;
2586
2587   GNUNET_assert (NULL != peer);
2588
2589   if (GNUNET_NO == Peers_check_peer_known (peer))
2590   { /* We don't know a context to that peer */
2591     LOG (GNUNET_ERROR_TYPE_WARNING,
2592          "channel (%s) without associated context was destroyed\n",
2593          GNUNET_i2s (peer));
2594     return;
2595   }
2596
2597   peer_ctx = get_peer_ctx (peer);
2598   if (GNUNET_YES == Peers_check_channel_role (peer, channel, Peers_CHANNEL_ROLE_RECEIVING))
2599   {
2600     set_channel_flag (peer_ctx->recv_channel_flags, Peers_CHANNEL_DESTROING);
2601   } else if (GNUNET_YES == Peers_check_channel_role (peer, channel, Peers_CHANNEL_ROLE_SENDING))
2602   {
2603     set_channel_flag (peer_ctx->send_channel_flags, Peers_CHANNEL_DESTROING);
2604   }
2605
2606   if (GNUNET_YES == Peers_check_peer_flag (peer, Peers_TO_DESTROY))
2607   { /* We are in the middle of removing that peer from our knowledge. In this
2608        case simply make sure that the channels are cleaned. */
2609     Peers_cleanup_destroyed_channel (cls, channel);
2610     to_file (file_name_view_log,
2611              "-%s\t(cleanup channel, ourself)",
2612              GNUNET_i2s_full (peer));
2613     return;
2614   }
2615
2616   if (GNUNET_YES ==
2617       Peers_check_channel_role (peer, channel, Peers_CHANNEL_ROLE_SENDING))
2618   { /* Channel used for sending was destroyed */
2619     /* Possible causes of channel destruction:
2620      *  - ourselves  -> cleaning send channel -> clean context
2621      *  - other peer -> peer probably went down -> remove
2622      */
2623     channel_flag = Peers_get_channel_flag (peer, Peers_CHANNEL_ROLE_SENDING);
2624     if (GNUNET_YES == Peers_check_channel_flag (channel_flag, Peers_CHANNEL_CLEAN))
2625     { /* We are about to clean the sending channel. Clean the respective
2626        * context */
2627       Peers_cleanup_destroyed_channel (cls, channel);
2628       return;
2629     }
2630     else
2631     { /* Other peer destroyed our sending channel that he is supposed to keep
2632        * open. It probably went down. Remove it from our knowledge. */
2633       Peers_cleanup_destroyed_channel (cls, channel);
2634       remove_peer (peer);
2635       return;
2636     }
2637   }
2638   else if (GNUNET_YES ==
2639       Peers_check_channel_role (peer, channel, Peers_CHANNEL_ROLE_RECEIVING))
2640   { /* Channel used for receiving was destroyed */
2641     /* Possible causes of channel destruction:
2642      *  - ourselves  -> peer tried to establish channel twice -> clean context
2643      *  - other peer -> peer doesn't want to send us data -> clean
2644      */
2645     channel_flag = Peers_get_channel_flag (peer, Peers_CHANNEL_ROLE_RECEIVING);
2646     if (GNUNET_YES ==
2647         Peers_check_channel_flag (channel_flag, Peers_CHANNEL_ESTABLISHED_TWICE))
2648     { /* Other peer tried to establish a channel to us twice. We do not accept
2649        * that. Clean the context. */
2650       Peers_cleanup_destroyed_channel (cls, channel);
2651       return;
2652     }
2653     else
2654     { /* Other peer doesn't want to send us data anymore. We are free to clean
2655        * it. */
2656       Peers_cleanup_destroyed_channel (cls, channel);
2657       clean_peer (peer);
2658       return;
2659     }
2660   }
2661   else
2662   {
2663     LOG (GNUNET_ERROR_TYPE_WARNING,
2664         "Destroyed channel is neither sending nor receiving channel\n");
2665   }
2666 }
2667
2668 /***********************************************************************
2669  * /Util functions
2670 ***********************************************************************/
2671
2672 static void
2673 destroy_reply_cls (struct ReplyCls *rep_cls)
2674 {
2675   struct ClientContext *cli_ctx;
2676
2677   cli_ctx = rep_cls->cli_ctx;
2678   GNUNET_assert (NULL != cli_ctx);
2679   if (NULL != rep_cls->req_handle)
2680   {
2681     RPS_sampler_request_cancel (rep_cls->req_handle);
2682   }
2683   GNUNET_CONTAINER_DLL_remove (cli_ctx->rep_cls_head,
2684                                cli_ctx->rep_cls_tail,
2685                                rep_cls);
2686   GNUNET_free (rep_cls);
2687 }
2688
2689
2690 static void
2691 destroy_cli_ctx (struct ClientContext *cli_ctx)
2692 {
2693   GNUNET_assert (NULL != cli_ctx);
2694   if (NULL != cli_ctx->rep_cls_head)
2695   {
2696     LOG (GNUNET_ERROR_TYPE_WARNING,
2697          "Trying to destroy the context of a client that still has pending requests. Going to clean those\n");
2698     while (NULL != cli_ctx->rep_cls_head)
2699       destroy_reply_cls (cli_ctx->rep_cls_head);
2700   }
2701   GNUNET_CONTAINER_DLL_remove (cli_ctx_head,
2702                                cli_ctx_tail,
2703                                cli_ctx);
2704   GNUNET_free (cli_ctx);
2705 }
2706
2707
2708 /**
2709  * Function called by NSE.
2710  *
2711  * Updates sizes of sampler list and view and adapt those lists
2712  * accordingly.
2713  */
2714 static void
2715 nse_callback (void *cls,
2716               struct GNUNET_TIME_Absolute timestamp,
2717               double logestimate, double std_dev)
2718 {
2719   double estimate;
2720   //double scale; // TODO this might go gloabal/config
2721
2722   LOG (GNUNET_ERROR_TYPE_DEBUG,
2723        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
2724        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
2725   //scale = .01;
2726   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
2727   // GNUNET_NSE_log_estimate_to_n (logestimate);
2728   estimate = pow (estimate, 1.0 / 3);
2729   // TODO add if std_dev is a number
2730   // estimate += (std_dev * scale);
2731   if (2 < ceil (estimate))
2732   {
2733     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
2734     sampler_size_est_need = estimate;
2735   } else
2736     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
2737
2738   /* If the NSE has changed adapt the lists accordingly */
2739   resize_wrapper (prot_sampler, sampler_size_est_need);
2740   client_resize_wrapper ();
2741 }
2742
2743
2744 /**
2745  * Callback called once the requested PeerIDs are ready.
2746  *
2747  * Sends those to the requesting client.
2748  */
2749 static void
2750 client_respond (void *cls,
2751                 struct GNUNET_PeerIdentity *peer_ids,
2752                 uint32_t num_peers)
2753 {
2754   struct ReplyCls *reply_cls = cls;
2755   uint32_t i;
2756   struct GNUNET_MQ_Envelope *ev;
2757   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
2758   uint32_t size_needed;
2759   struct ClientContext *cli_ctx;
2760
2761   GNUNET_assert (NULL != reply_cls);
2762   LOG (GNUNET_ERROR_TYPE_DEBUG,
2763        "sampler returned %" PRIu32 " peers:\n",
2764        num_peers);
2765   for (i = 0; i < num_peers; i++)
2766   {
2767     LOG (GNUNET_ERROR_TYPE_DEBUG,
2768          "  %" PRIu32 ": %s\n",
2769          i,
2770          GNUNET_i2s (&peer_ids[i]));
2771   }
2772
2773   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
2774                 num_peers * sizeof (struct GNUNET_PeerIdentity);
2775
2776   GNUNET_assert (GNUNET_MAX_MESSAGE_SIZE >= size_needed);
2777
2778   ev = GNUNET_MQ_msg_extra (out_msg,
2779                             num_peers * sizeof (struct GNUNET_PeerIdentity),
2780                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
2781   out_msg->num_peers = htonl (num_peers);
2782   out_msg->id = htonl (reply_cls->id);
2783
2784   GNUNET_memcpy (&out_msg[1],
2785           peer_ids,
2786           num_peers * sizeof (struct GNUNET_PeerIdentity));
2787   GNUNET_free (peer_ids);
2788
2789   cli_ctx = reply_cls->cli_ctx;
2790   GNUNET_assert (NULL != cli_ctx);
2791   reply_cls->req_handle = NULL;
2792   destroy_reply_cls (reply_cls);
2793   GNUNET_MQ_send (cli_ctx->mq, ev);
2794 }
2795
2796
2797 /**
2798  * Handle RPS request from the client.
2799  *
2800  * @param cls closure
2801  * @param message the actual message
2802  */
2803 static void
2804 handle_client_request (void *cls,
2805                        const struct GNUNET_RPS_CS_RequestMessage *msg)
2806 {
2807   struct ClientContext *cli_ctx = cls;
2808   uint32_t num_peers;
2809   uint32_t size_needed;
2810   struct ReplyCls *reply_cls;
2811   uint32_t i;
2812
2813   num_peers = ntohl (msg->num_peers);
2814   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
2815                 num_peers * sizeof (struct GNUNET_PeerIdentity);
2816
2817   if (GNUNET_MAX_MESSAGE_SIZE < size_needed)
2818   {
2819     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2820                 "Message received from client has size larger than expected\n");
2821     GNUNET_SERVICE_client_drop (cli_ctx->client);
2822     return;
2823   }
2824
2825   for (i = 0 ; i < num_peers ; i++)
2826     est_request_rate();
2827
2828   LOG (GNUNET_ERROR_TYPE_DEBUG,
2829        "Client requested %" PRIu32 " random peer(s).\n",
2830        num_peers);
2831
2832   reply_cls = GNUNET_new (struct ReplyCls);
2833   reply_cls->id = ntohl (msg->id);
2834   reply_cls->cli_ctx = cli_ctx;
2835   reply_cls->req_handle = RPS_sampler_get_n_rand_peers (client_sampler,
2836                                                         client_respond,
2837                                                         reply_cls,
2838                                                         num_peers);
2839
2840   GNUNET_assert (NULL != cli_ctx);
2841   GNUNET_CONTAINER_DLL_insert (cli_ctx->rep_cls_head,
2842                                cli_ctx->rep_cls_tail,
2843                                reply_cls);
2844   GNUNET_SERVICE_client_continue (cli_ctx->client);
2845 }
2846
2847
2848 /**
2849  * @brief Handle a message that requests the cancellation of a request
2850  *
2851  * @param cls unused
2852  * @param message the message containing the id of the request
2853  */
2854 static void
2855 handle_client_request_cancel (void *cls,
2856                               const struct GNUNET_RPS_CS_RequestCancelMessage *msg)
2857 {
2858   struct ClientContext *cli_ctx = cls;
2859   struct ReplyCls *rep_cls;
2860
2861   GNUNET_assert (NULL != cli_ctx);
2862   GNUNET_assert (NULL != cli_ctx->rep_cls_head);
2863   rep_cls = cli_ctx->rep_cls_head;
2864   LOG (GNUNET_ERROR_TYPE_DEBUG,
2865       "Client cancels request with id %" PRIu32 "\n",
2866       ntohl (msg->id));
2867   while ( (NULL != rep_cls->next) &&
2868           (rep_cls->id != ntohl (msg->id)) )
2869     rep_cls = rep_cls->next;
2870   GNUNET_assert (rep_cls->id == ntohl (msg->id));
2871   destroy_reply_cls (rep_cls);
2872   GNUNET_SERVICE_client_continue (cli_ctx->client);
2873 }
2874
2875
2876 /**
2877  * @brief This function is called, when the client seeds peers.
2878  * It verifies that @a msg is well-formed.
2879  *
2880  * @param cls the closure (#ClientContext)
2881  * @param msg the message
2882  * @return #GNUNET_OK if @a msg is well-formed
2883  */
2884 static int
2885 check_client_seed (void *cls, const struct GNUNET_RPS_CS_SeedMessage *msg)
2886 {
2887   struct ClientContext *cli_ctx = cls;
2888   uint16_t msize = ntohs (msg->header.size);
2889   uint32_t num_peers = ntohl (msg->num_peers);
2890
2891   msize -= sizeof (struct GNUNET_RPS_CS_SeedMessage);
2892   if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
2893        (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
2894   {
2895     GNUNET_break (0);
2896     GNUNET_SERVICE_client_drop (cli_ctx->client);
2897     return GNUNET_SYSERR;
2898   }
2899   return GNUNET_OK;
2900 }
2901
2902
2903 /**
2904  * Handle seed from the client.
2905  *
2906  * @param cls closure
2907  * @param message the actual message
2908  */
2909 static void
2910 handle_client_seed (void *cls,
2911                     const struct GNUNET_RPS_CS_SeedMessage *msg)
2912 {
2913   struct ClientContext *cli_ctx = cls;
2914   struct GNUNET_PeerIdentity *peers;
2915   uint32_t num_peers;
2916   uint32_t i;
2917
2918   num_peers = ntohl (msg->num_peers);
2919   peers = (struct GNUNET_PeerIdentity *) &msg[1];
2920   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
2921   //GNUNET_memcpy (peers, &msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
2922
2923   LOG (GNUNET_ERROR_TYPE_DEBUG,
2924        "Client seeded peers:\n");
2925   print_peer_list (peers, num_peers);
2926
2927   for (i = 0; i < num_peers; i++)
2928   {
2929     LOG (GNUNET_ERROR_TYPE_DEBUG,
2930          "Updating samplers with seed %" PRIu32 ": %s\n",
2931          i,
2932          GNUNET_i2s (&peers[i]));
2933
2934     got_peer (&peers[i]);
2935   }
2936
2937   ////GNUNET_free (peers);
2938
2939   GNUNET_SERVICE_client_continue (cli_ctx->client);
2940 }
2941
2942 /**
2943  * Handle a CHECK_LIVE message from another peer.
2944  *
2945  * This does nothing. But without calling #GNUNET_CADET_receive_done()
2946  * the channel is blocked for all other communication.
2947  *
2948  * @param cls Closure
2949  * @param msg The message header
2950  */
2951 static void
2952 handle_peer_check (void *cls,
2953                    const struct GNUNET_MessageHeader *msg)
2954 {
2955   const struct GNUNET_PeerIdentity *peer = cls;
2956
2957   GNUNET_CADET_receive_done (Peers_get_recv_channel (peer));
2958 }
2959
2960 /**
2961  * Handle a PUSH message from another peer.
2962  *
2963  * Check the proof of work and store the PeerID
2964  * in the temporary list for pushed PeerIDs.
2965  *
2966  * @param cls Closure
2967  * @param msg The message header
2968  */
2969 static void
2970 handle_peer_push (void *cls,
2971                   const struct GNUNET_MessageHeader *msg)
2972 {
2973   const struct GNUNET_PeerIdentity *peer = cls;
2974
2975   // (check the proof of work (?))
2976
2977   LOG (GNUNET_ERROR_TYPE_DEBUG,
2978        "Received PUSH (%s)\n",
2979        GNUNET_i2s (peer));
2980   GNUNET_STATISTICS_update(stats, "# push message received", 1, GNUNET_NO);
2981
2982   #ifdef ENABLE_MALICIOUS
2983   struct AttackedPeer *tmp_att_peer;
2984
2985   if ( (1 == mal_type) ||
2986        (3 == mal_type) )
2987   { /* Try to maximise representation */
2988     tmp_att_peer = GNUNET_new (struct AttackedPeer);
2989     tmp_att_peer->peer_id = *peer;
2990     if (NULL == att_peer_set)
2991       att_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
2992     if (GNUNET_NO ==
2993         GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
2994                                                 peer))
2995     {
2996       GNUNET_CONTAINER_DLL_insert (att_peers_head,
2997                                    att_peers_tail,
2998                                    tmp_att_peer);
2999       add_peer_array_to_set (peer, 1, att_peer_set);
3000     }
3001   }
3002
3003
3004   else if (2 == mal_type)
3005   {
3006     /* We attack one single well-known peer - simply ignore */
3007   }
3008   #endif /* ENABLE_MALICIOUS */
3009
3010   /* Add the sending peer to the push_map */
3011   CustomPeerMap_put (push_map, peer);
3012
3013   GNUNET_CADET_receive_done (Peers_get_recv_channel (peer));
3014 }
3015
3016
3017 /**
3018  * Handle PULL REQUEST request message from another peer.
3019  *
3020  * Reply with the view of PeerIDs.
3021  *
3022  * @param cls Closure
3023  * @param msg The message header
3024  */
3025 static void
3026 handle_peer_pull_request (void *cls,
3027                           const struct GNUNET_MessageHeader *msg)
3028 {
3029   struct GNUNET_PeerIdentity *peer = cls;
3030   const struct GNUNET_PeerIdentity *view_array;
3031
3032   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REQUEST (%s)\n", GNUNET_i2s (peer));
3033   GNUNET_STATISTICS_update(stats, "# pull request message received", 1, GNUNET_NO);
3034
3035   #ifdef ENABLE_MALICIOUS
3036   if (1 == mal_type
3037       || 3 == mal_type)
3038   { /* Try to maximise representation */
3039     send_pull_reply (peer, mal_peers, num_mal_peers);
3040   }
3041
3042   else if (2 == mal_type)
3043   { /* Try to partition network */
3044     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
3045     {
3046       send_pull_reply (peer, mal_peers, num_mal_peers);
3047     }
3048   }
3049   #endif /* ENABLE_MALICIOUS */
3050
3051   view_array = View_get_as_array ();
3052   send_pull_reply (peer, view_array, View_size ());
3053
3054   GNUNET_CADET_receive_done (Peers_get_recv_channel (peer));
3055 }
3056
3057
3058 /**
3059  * Check whether we sent a corresponding request and
3060  * whether this reply is the first one.
3061  *
3062  * @param cls Closure
3063  * @param msg The message header
3064  */
3065 static int
3066 check_peer_pull_reply (void *cls,
3067                        const struct GNUNET_RPS_P2P_PullReplyMessage *msg)
3068 {
3069   struct GNUNET_PeerIdentity *sender = cls;
3070
3071   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->header.size))
3072   {
3073     GNUNET_break_op (0);
3074     return GNUNET_SYSERR;
3075   }
3076
3077   if ((ntohs (msg->header.size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
3078       sizeof (struct GNUNET_PeerIdentity) != ntohl (msg->num_peers))
3079   {
3080     LOG (GNUNET_ERROR_TYPE_ERROR,
3081         "message says it sends %" PRIu32 " peers, have space for %lu peers\n",
3082         ntohl (msg->num_peers),
3083         (ntohs (msg->header.size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
3084             sizeof (struct GNUNET_PeerIdentity));
3085     GNUNET_break_op (0);
3086     return GNUNET_SYSERR;
3087   }
3088
3089   if (GNUNET_YES != Peers_check_peer_flag (sender, Peers_PULL_REPLY_PENDING))
3090   {
3091     LOG (GNUNET_ERROR_TYPE_WARNING,
3092         "Received a pull reply from a peer we didn't request one from!\n");
3093     GNUNET_break_op (0);
3094     return GNUNET_SYSERR;
3095   }
3096   return GNUNET_OK;
3097 }
3098
3099 /**
3100  * Handle PULL REPLY message from another peer.
3101  *
3102  * @param cls Closure
3103  * @param msg The message header
3104  */
3105 static void
3106 handle_peer_pull_reply (void *cls,
3107                         const struct GNUNET_RPS_P2P_PullReplyMessage *msg)
3108 {
3109   const struct GNUNET_PeerIdentity *peers;
3110   struct GNUNET_PeerIdentity *sender = cls;
3111   uint32_t i;
3112 #ifdef ENABLE_MALICIOUS
3113   struct AttackedPeer *tmp_att_peer;
3114 #endif /* ENABLE_MALICIOUS */
3115
3116   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received PULL REPLY (%s)\n", GNUNET_i2s (sender));
3117   GNUNET_STATISTICS_update(stats, "# pull reply messages received", 1, GNUNET_NO);
3118
3119   #ifdef ENABLE_MALICIOUS
3120   // We shouldn't even receive pull replies as we're not sending
3121   if (2 == mal_type)
3122   {
3123   }
3124   #endif /* ENABLE_MALICIOUS */
3125
3126   /* Do actual logic */
3127   peers = (const struct GNUNET_PeerIdentity *) &msg[1];
3128
3129   LOG (GNUNET_ERROR_TYPE_DEBUG,
3130        "PULL REPLY received, got following %u peers:\n",
3131        ntohl (msg->num_peers));
3132
3133   for (i = 0; i < ntohl (msg->num_peers); i++)
3134   {
3135     LOG (GNUNET_ERROR_TYPE_DEBUG,
3136          "%u. %s\n",
3137          i,
3138          GNUNET_i2s (&peers[i]));
3139
3140     #ifdef ENABLE_MALICIOUS
3141     if ((NULL != att_peer_set) &&
3142         (1 == mal_type || 3 == mal_type))
3143     { /* Add attacked peer to local list */
3144       // TODO check if we sent a request and this was the first reply
3145       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
3146                                                                &peers[i])
3147           && GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mal_peer_set,
3148                                                                   &peers[i])
3149           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&peers[i],
3150                                                    &own_identity))
3151       {
3152         tmp_att_peer = GNUNET_new (struct AttackedPeer);
3153         tmp_att_peer->peer_id = peers[i];
3154         GNUNET_CONTAINER_DLL_insert (att_peers_head,
3155                                      att_peers_tail,
3156                                      tmp_att_peer);
3157         add_peer_array_to_set (&peers[i], 1, att_peer_set);
3158       }
3159       continue;
3160     }
3161     #endif /* ENABLE_MALICIOUS */
3162     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity,
3163                                               &peers[i]))
3164     {
3165       /* Make sure we 'know' about this peer */
3166       (void) Peers_insert_peer (&peers[i]);
3167
3168       if (GNUNET_YES == Peers_check_peer_valid (&peers[i]))
3169       {
3170         CustomPeerMap_put (pull_map, &peers[i]);
3171       }
3172       else
3173       {
3174         Peers_schedule_operation (&peers[i], insert_in_pull_map);
3175         (void) Peers_issue_peer_liveliness_check (&peers[i]);
3176       }
3177     }
3178   }
3179
3180   Peers_unset_peer_flag (sender, Peers_PULL_REPLY_PENDING);
3181   clean_peer (sender);
3182
3183   GNUNET_CADET_receive_done (Peers_get_recv_channel (sender));
3184 }
3185
3186
3187 /**
3188  * Compute a random delay.
3189  * A uniformly distributed value between mean + spread and mean - spread.
3190  *
3191  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
3192  * It would return a random value between 2 and 6 min.
3193  *
3194  * @param mean the mean
3195  * @param spread the inverse amount of deviation from the mean
3196  */
3197 static struct GNUNET_TIME_Relative
3198 compute_rand_delay (struct GNUNET_TIME_Relative mean,
3199                     unsigned int spread)
3200 {
3201   struct GNUNET_TIME_Relative half_interval;
3202   struct GNUNET_TIME_Relative ret;
3203   unsigned int rand_delay;
3204   unsigned int max_rand_delay;
3205
3206   if (0 == spread)
3207   {
3208     LOG (GNUNET_ERROR_TYPE_WARNING,
3209          "Not accepting spread of 0\n");
3210     GNUNET_break (0);
3211     GNUNET_assert (0);
3212   }
3213   GNUNET_assert (0 != mean.rel_value_us);
3214
3215   /* Compute random time value between spread * mean and spread * mean */
3216   half_interval = GNUNET_TIME_relative_divide (mean, spread);
3217
3218   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
3219   /**
3220    * Compute random value between (0 and 1) * round_interval
3221    * via multiplying round_interval with a 'fraction' (0 to value)/value
3222    */
3223   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
3224   ret = GNUNET_TIME_relative_saturating_multiply (mean,  rand_delay);
3225   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
3226   ret = GNUNET_TIME_relative_add      (ret, half_interval);
3227
3228   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
3229     LOG (GNUNET_ERROR_TYPE_WARNING,
3230          "Returning FOREVER_REL\n");
3231
3232   return ret;
3233 }
3234
3235
3236 /**
3237  * Send single pull request
3238  *
3239  * @param peer_id the peer to send the pull request to.
3240  */
3241 static void
3242 send_pull_request (const struct GNUNET_PeerIdentity *peer)
3243 {
3244   struct GNUNET_MQ_Envelope *ev;
3245
3246   GNUNET_assert (GNUNET_NO == Peers_check_peer_flag (peer,
3247                                                      Peers_PULL_REPLY_PENDING));
3248   Peers_set_peer_flag (peer, Peers_PULL_REPLY_PENDING);
3249
3250   LOG (GNUNET_ERROR_TYPE_DEBUG,
3251        "Going to send PULL REQUEST to peer %s.\n",
3252        GNUNET_i2s (peer));
3253
3254   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
3255   Peers_send_message (peer, ev, "PULL REQUEST");
3256   GNUNET_STATISTICS_update(stats, "# pull request send issued", 1, GNUNET_NO);
3257 }
3258
3259
3260 /**
3261  * Send single push
3262  *
3263  * @param peer_id the peer to send the push to.
3264  */
3265 static void
3266 send_push (const struct GNUNET_PeerIdentity *peer_id)
3267 {
3268   struct GNUNET_MQ_Envelope *ev;
3269
3270   LOG (GNUNET_ERROR_TYPE_DEBUG,
3271        "Going to send PUSH to peer %s.\n",
3272        GNUNET_i2s (peer_id));
3273
3274   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
3275   Peers_send_message (peer_id, ev, "PUSH");
3276   GNUNET_STATISTICS_update(stats, "# push send issued", 1, GNUNET_NO);
3277 }
3278
3279
3280 static void
3281 do_round (void *cls);
3282
3283 static void
3284 do_mal_round (void *cls);
3285
3286 #ifdef ENABLE_MALICIOUS
3287
3288
3289 /**
3290  * @brief This function is called, when the client tells us to act malicious.
3291  * It verifies that @a msg is well-formed.
3292  *
3293  * @param cls the closure (#ClientContext)
3294  * @param msg the message
3295  * @return #GNUNET_OK if @a msg is well-formed
3296  */
3297 static int
3298 check_client_act_malicious (void *cls,
3299                             const struct GNUNET_RPS_CS_ActMaliciousMessage *msg)
3300 {
3301   struct ClientContext *cli_ctx = cls;
3302   uint16_t msize = ntohs (msg->header.size);
3303   uint32_t num_peers = ntohl (msg->num_peers);
3304
3305   msize -= sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage);
3306   if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
3307        (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
3308   {
3309     LOG (GNUNET_ERROR_TYPE_ERROR,
3310         "message says it sends %" PRIu32 " peers, have space for %lu peers\n",
3311         ntohl (msg->num_peers),
3312         (msize / sizeof (struct GNUNET_PeerIdentity)));
3313     GNUNET_break (0);
3314     GNUNET_SERVICE_client_drop (cli_ctx->client);
3315     return GNUNET_SYSERR;
3316   }
3317   return GNUNET_OK;
3318 }
3319
3320 /**
3321  * Turn RPS service to act malicious.
3322  *
3323  * @param cls Closure
3324  * @param client The client that sent the message
3325  * @param msg The message header
3326  */
3327 static void
3328 handle_client_act_malicious (void *cls,
3329                              const struct GNUNET_RPS_CS_ActMaliciousMessage *msg)
3330 {
3331   struct ClientContext *cli_ctx = cls;
3332   struct GNUNET_PeerIdentity *peers;
3333   uint32_t num_mal_peers_sent;
3334   uint32_t num_mal_peers_old;
3335
3336   /* Do actual logic */
3337   peers = (struct GNUNET_PeerIdentity *) &msg[1];
3338   mal_type = ntohl (msg->type);
3339   if (NULL == mal_peer_set)
3340     mal_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
3341
3342   LOG (GNUNET_ERROR_TYPE_DEBUG,
3343        "Now acting malicious type %" PRIu32 ", got %" PRIu32 " peers.\n",
3344        mal_type,
3345        ntohl (msg->num_peers));
3346
3347   if (1 == mal_type)
3348   { /* Try to maximise representation */
3349     /* Add other malicious peers to those we already know */
3350
3351     num_mal_peers_sent = ntohl (msg->num_peers);
3352     num_mal_peers_old = num_mal_peers;
3353     GNUNET_array_grow (mal_peers,
3354                        num_mal_peers,
3355                        num_mal_peers + num_mal_peers_sent);
3356     GNUNET_memcpy (&mal_peers[num_mal_peers_old],
3357             peers,
3358             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
3359
3360     /* Add all mal peers to mal_peer_set */
3361     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
3362                            num_mal_peers_sent,
3363                            mal_peer_set);
3364
3365     /* Substitute do_round () with do_mal_round () */
3366     GNUNET_SCHEDULER_cancel (do_round_task);
3367     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
3368   }
3369
3370   else if ( (2 == mal_type) ||
3371             (3 == mal_type) )
3372   { /* Try to partition the network */
3373     /* Add other malicious peers to those we already know */
3374
3375     num_mal_peers_sent = ntohl (msg->num_peers) - 1;
3376     num_mal_peers_old = num_mal_peers;
3377     GNUNET_array_grow (mal_peers,
3378                        num_mal_peers,
3379                        num_mal_peers + num_mal_peers_sent);
3380     if (NULL != mal_peers &&
3381         0 != num_mal_peers)
3382     {
3383       GNUNET_memcpy (&mal_peers[num_mal_peers_old],
3384               peers,
3385               num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
3386
3387       /* Add all mal peers to mal_peer_set */
3388       add_peer_array_to_set (&mal_peers[num_mal_peers_old],
3389                              num_mal_peers_sent,
3390                              mal_peer_set);
3391     }
3392
3393     /* Store the one attacked peer */
3394     GNUNET_memcpy (&attacked_peer,
3395             &msg->attacked_peer,
3396             sizeof (struct GNUNET_PeerIdentity));
3397     /* Set the flag of the attacked peer to valid to avoid problems */
3398     if (GNUNET_NO == Peers_check_peer_known (&attacked_peer))
3399     {
3400       (void) Peers_issue_peer_liveliness_check (&attacked_peer);
3401     }
3402
3403     LOG (GNUNET_ERROR_TYPE_DEBUG,
3404          "Attacked peer is %s\n",
3405          GNUNET_i2s (&attacked_peer));
3406
3407     /* Substitute do_round () with do_mal_round () */
3408     GNUNET_SCHEDULER_cancel (do_round_task);
3409     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
3410   }
3411   else if (0 == mal_type)
3412   { /* Stop acting malicious */
3413     GNUNET_array_grow (mal_peers, num_mal_peers, 0);
3414
3415     /* Substitute do_mal_round () with do_round () */
3416     GNUNET_SCHEDULER_cancel (do_round_task);
3417     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
3418   }
3419   else
3420   {
3421     GNUNET_break (0);
3422     GNUNET_SERVICE_client_continue (cli_ctx->client);
3423   }
3424   GNUNET_SERVICE_client_continue (cli_ctx->client);
3425 }
3426
3427
3428 /**
3429  * Send out PUSHes and PULLs maliciously.
3430  *
3431  * This is executed regylary.
3432  */
3433 static void
3434 do_mal_round (void *cls)
3435 {
3436   uint32_t num_pushes;
3437   uint32_t i;
3438   struct GNUNET_TIME_Relative time_next_round;
3439   struct AttackedPeer *tmp_att_peer;
3440
3441   LOG (GNUNET_ERROR_TYPE_DEBUG,
3442        "Going to execute next round maliciously type %" PRIu32 ".\n",
3443       mal_type);
3444   do_round_task = NULL;
3445   GNUNET_assert (mal_type <= 3);
3446   /* Do malicious actions */
3447   if (1 == mal_type)
3448   { /* Try to maximise representation */
3449
3450     /* The maximum of pushes we're going to send this round */
3451     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit,
3452                                          num_attacked_peers),
3453                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
3454
3455     LOG (GNUNET_ERROR_TYPE_DEBUG,
3456          "Going to send %" PRIu32 " pushes\n",
3457          num_pushes);
3458
3459     /* Send PUSHes to attacked peers */
3460     for (i = 0 ; i < num_pushes ; i++)
3461     {
3462       if (att_peers_tail == att_peer_index)
3463         att_peer_index = att_peers_head;
3464       else
3465         att_peer_index = att_peer_index->next;
3466
3467       send_push (&att_peer_index->peer_id);
3468     }
3469
3470     /* Send PULLs to some peers to learn about additional peers to attack */
3471     tmp_att_peer = att_peer_index;
3472     for (i = 0 ; i < num_pushes * alpha ; i++)
3473     {
3474       if (att_peers_tail == tmp_att_peer)
3475         tmp_att_peer = att_peers_head;
3476       else
3477         att_peer_index = tmp_att_peer->next;
3478
3479       send_pull_request (&tmp_att_peer->peer_id);
3480     }
3481   }
3482
3483
3484   else if (2 == mal_type)
3485   { /**
3486      * Try to partition the network
3487      * Send as many pushes to the attacked peer as possible
3488      * That is one push per round as it will ignore more.
3489      */
3490     (void) Peers_issue_peer_liveliness_check (&attacked_peer);
3491     if (GNUNET_YES == Peers_check_peer_flag (&attacked_peer, Peers_ONLINE))
3492       send_push (&attacked_peer);
3493   }
3494
3495
3496   if (3 == mal_type)
3497   { /* Combined attack */
3498
3499     /* Send PUSH to attacked peers */
3500     if (GNUNET_YES == Peers_check_peer_known (&attacked_peer))
3501     {
3502       (void) Peers_issue_peer_liveliness_check (&attacked_peer);
3503       if (GNUNET_YES == Peers_check_peer_flag (&attacked_peer, Peers_ONLINE))
3504       {
3505         LOG (GNUNET_ERROR_TYPE_DEBUG,
3506             "Goding to send push to attacked peer (%s)\n",
3507             GNUNET_i2s (&attacked_peer));
3508         send_push (&attacked_peer);
3509       }
3510     }
3511     (void) Peers_issue_peer_liveliness_check (&attacked_peer);
3512
3513     /* The maximum of pushes we're going to send this round */
3514     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit - 1,
3515                                          num_attacked_peers),
3516                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
3517
3518     LOG (GNUNET_ERROR_TYPE_DEBUG,
3519          "Going to send %" PRIu32 " pushes\n",
3520          num_pushes);
3521
3522     for (i = 0; i < num_pushes; i++)
3523     {
3524       if (att_peers_tail == att_peer_index)
3525         att_peer_index = att_peers_head;
3526       else
3527         att_peer_index = att_peer_index->next;
3528
3529       send_push (&att_peer_index->peer_id);
3530     }
3531
3532     /* Send PULLs to some peers to learn about additional peers to attack */
3533     tmp_att_peer = att_peer_index;
3534     for (i = 0; i < num_pushes * alpha; i++)
3535     {
3536       if (att_peers_tail == tmp_att_peer)
3537         tmp_att_peer = att_peers_head;
3538       else
3539         att_peer_index = tmp_att_peer->next;
3540
3541       send_pull_request (&tmp_att_peer->peer_id);
3542     }
3543   }
3544
3545   /* Schedule next round */
3546   time_next_round = compute_rand_delay (round_interval, 2);
3547
3548   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round,
3549   //NULL);
3550   GNUNET_assert (NULL == do_round_task);
3551   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round,
3552                                                 &do_mal_round, NULL);
3553   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
3554 }
3555 #endif /* ENABLE_MALICIOUS */
3556
3557
3558 /**
3559  * Send out PUSHes and PULLs, possibly update #view, samplers.
3560  *
3561  * This is executed regylary.
3562  */
3563 static void
3564 do_round (void *cls)
3565 {
3566   uint32_t i;
3567   const struct GNUNET_PeerIdentity *view_array;
3568   unsigned int *permut;
3569   unsigned int a_peers; /* Number of peers we send pushes to */
3570   unsigned int b_peers; /* Number of peers we send pull requests to */
3571   uint32_t first_border;
3572   uint32_t second_border;
3573   struct GNUNET_PeerIdentity peer;
3574   struct GNUNET_PeerIdentity *update_peer;
3575
3576   LOG (GNUNET_ERROR_TYPE_DEBUG,
3577        "Going to execute next round.\n");
3578   GNUNET_STATISTICS_update(stats, "# rounds", 1, GNUNET_NO);
3579   do_round_task = NULL;
3580   LOG (GNUNET_ERROR_TYPE_DEBUG,
3581        "Printing view:\n");
3582   to_file (file_name_view_log,
3583            "___ new round ___");
3584   view_array = View_get_as_array ();
3585   for (i = 0; i < View_size (); i++)
3586   {
3587     LOG (GNUNET_ERROR_TYPE_DEBUG,
3588          "\t%s\n", GNUNET_i2s (&view_array[i]));
3589     to_file (file_name_view_log,
3590              "=%s\t(do round)",
3591              GNUNET_i2s_full (&view_array[i]));
3592   }
3593
3594
3595   /* Send pushes and pull requests */
3596   if (0 < View_size ())
3597   {
3598     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
3599                                            View_size ());
3600
3601     /* Send PUSHes */
3602     a_peers = ceil (alpha * View_size ());
3603
3604     LOG (GNUNET_ERROR_TYPE_DEBUG,
3605          "Going to send pushes to %u (ceil (%f * %u)) peers.\n",
3606          a_peers, alpha, View_size ());
3607     for (i = 0; i < a_peers; i++)
3608     {
3609       peer = view_array[permut[i]];
3610       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
3611       { // FIXME if this fails schedule/loop this for later
3612         send_push (&peer);
3613       }
3614     }
3615
3616     /* Send PULL requests */
3617     b_peers = ceil (beta * View_size ());
3618     first_border = a_peers;
3619     second_border = a_peers + b_peers;
3620     if (second_border > View_size ())
3621     {
3622       first_border = View_size () - b_peers;
3623       second_border = View_size ();
3624     }
3625     LOG (GNUNET_ERROR_TYPE_DEBUG,
3626         "Going to send pulls to %u (ceil (%f * %u)) peers.\n",
3627         b_peers, beta, View_size ());
3628     for (i = first_border; i < second_border; i++)
3629     {
3630       peer = view_array[permut[i]];
3631       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer) &&
3632           GNUNET_NO == Peers_check_peer_flag (&peer, Peers_PULL_REPLY_PENDING)) // TODO
3633       { // FIXME if this fails schedule/loop this for later
3634         send_pull_request (&peer);
3635       }
3636     }
3637
3638     GNUNET_free (permut);
3639     permut = NULL;
3640   }
3641
3642
3643   /* Update view */
3644   /* TODO see how many peers are in push-/pull- list! */
3645
3646   if ((CustomPeerMap_size (push_map) <= alpha * View_size ()) &&
3647       (0 < CustomPeerMap_size (push_map)) &&
3648       (0 < CustomPeerMap_size (pull_map)))
3649   { /* If conditions for update are fulfilled, update */
3650     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the view.\n");
3651
3652     uint32_t final_size;
3653     uint32_t peers_to_clean_size;
3654     struct GNUNET_PeerIdentity *peers_to_clean;
3655
3656     peers_to_clean = NULL;
3657     peers_to_clean_size = 0;
3658     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, View_size ());
3659     GNUNET_memcpy (peers_to_clean,
3660             view_array,
3661             View_size () * sizeof (struct GNUNET_PeerIdentity));
3662
3663     /* Seems like recreating is the easiest way of emptying the peermap */
3664     View_clear ();
3665     to_file (file_name_view_log,
3666              "--- emptied ---");
3667
3668     first_border  = GNUNET_MIN (ceil (alpha * sampler_size_est_need),
3669                                 CustomPeerMap_size (push_map));
3670     second_border = first_border +
3671                     GNUNET_MIN (floor (beta  * sampler_size_est_need),
3672                                 CustomPeerMap_size (pull_map));
3673     final_size    = second_border +
3674       ceil ((1 - (alpha + beta)) * sampler_size_est_need);
3675
3676     /* Update view with peers received through PUSHes */
3677     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
3678                                            CustomPeerMap_size (push_map));
3679     for (i = 0; i < first_border; i++)
3680     {
3681       (void) insert_in_view (CustomPeerMap_get_peer_by_index (push_map,
3682                                                               permut[i]));
3683       to_file (file_name_view_log,
3684                "+%s\t(push list)",
3685                GNUNET_i2s_full (&view_array[i]));
3686       // TODO change the peer_flags accordingly
3687     }
3688     GNUNET_free (permut);
3689     permut = NULL;
3690
3691     /* Update view with peers received through PULLs */
3692     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
3693                                            CustomPeerMap_size (pull_map));
3694     for (i = first_border; i < second_border; i++)
3695     {
3696       (void) insert_in_view (CustomPeerMap_get_peer_by_index (pull_map,
3697             permut[i - first_border]));
3698       to_file (file_name_view_log,
3699                "+%s\t(pull list)",
3700                GNUNET_i2s_full (&view_array[i]));
3701       // TODO change the peer_flags accordingly
3702     }
3703     GNUNET_free (permut);
3704     permut = NULL;
3705
3706     /* Update view with peers from history */
3707     RPS_sampler_get_n_rand_peers (prot_sampler,
3708                                   hist_update,
3709                                   NULL,
3710                                   final_size - second_border);
3711     // TODO change the peer_flags accordingly
3712
3713     for (i = 0; i < View_size (); i++)
3714       rem_from_list (&peers_to_clean, &peers_to_clean_size, &view_array[i]);
3715
3716     /* Clean peers that were removed from the view */
3717     for (i = 0; i < peers_to_clean_size; i++)
3718     {
3719       to_file (file_name_view_log,
3720                "-%s",
3721                GNUNET_i2s_full (&peers_to_clean[i]));
3722       clean_peer (&peers_to_clean[i]);
3723       //peer_destroy_channel_send (sender);
3724     }
3725
3726     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, 0);
3727   } else {
3728     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the view.\n");
3729     GNUNET_STATISTICS_update(stats, "# rounds blocked", 1, GNUNET_NO);
3730     if (CustomPeerMap_size (push_map) > alpha * View_size () &&
3731         !(0 >= CustomPeerMap_size (pull_map)))
3732       GNUNET_STATISTICS_update(stats, "# rounds blocked - too many pushes", 1, GNUNET_NO);
3733     if (CustomPeerMap_size (push_map) > alpha * View_size () &&
3734         (0 >= CustomPeerMap_size (pull_map)))
3735       GNUNET_STATISTICS_update(stats, "# rounds blocked - too many pushes, no pull replies", 1, GNUNET_NO);
3736     if (0 >= CustomPeerMap_size (push_map) &&
3737         !(0 >= CustomPeerMap_size (pull_map)))
3738       GNUNET_STATISTICS_update(stats, "# rounds blocked - no pushes", 1, GNUNET_NO);
3739     if (0 >= CustomPeerMap_size (push_map) &&
3740         (0 >= CustomPeerMap_size (pull_map)))
3741       GNUNET_STATISTICS_update(stats, "# rounds blocked - no pushes, no pull replies", 1, GNUNET_NO);
3742     if (0 >= CustomPeerMap_size (pull_map) &&
3743         CustomPeerMap_size (push_map) > alpha * View_size () &&
3744         0 >= CustomPeerMap_size (push_map))
3745       GNUNET_STATISTICS_update(stats, "# rounds blocked - no pull replies", 1, GNUNET_NO);
3746   }
3747   // TODO independent of that also get some peers from CADET_get_peers()?
3748   GNUNET_STATISTICS_set (stats,
3749       "# peers in push map at end of round",
3750       CustomPeerMap_size (push_map),
3751       GNUNET_NO);
3752   GNUNET_STATISTICS_set (stats,
3753       "# peers in pull map at end of round",
3754       CustomPeerMap_size (pull_map),
3755       GNUNET_NO);
3756   GNUNET_STATISTICS_set (stats,
3757       "# peers in view at end of round",
3758       View_size (),
3759       GNUNET_NO);
3760
3761   LOG (GNUNET_ERROR_TYPE_DEBUG,
3762        "Received %u pushes and %u pulls last round (alpha (%.2f) * view_size (%u) = %.2f)\n",
3763        CustomPeerMap_size (push_map),
3764        CustomPeerMap_size (pull_map),
3765        alpha,
3766        View_size (),
3767        alpha * View_size ());
3768
3769   /* Update samplers */
3770   for (i = 0; i < CustomPeerMap_size (push_map); i++)
3771   {
3772     update_peer = CustomPeerMap_get_peer_by_index (push_map, i);
3773     LOG (GNUNET_ERROR_TYPE_DEBUG,
3774          "Updating with peer %s from push list\n",
3775          GNUNET_i2s (update_peer));
3776     insert_in_sampler (NULL, update_peer);
3777     clean_peer (update_peer); /* This cleans only if it is not in the view */
3778     //peer_destroy_channel_send (sender);
3779   }
3780
3781   for (i = 0; i < CustomPeerMap_size (pull_map); i++)
3782   {
3783     LOG (GNUNET_ERROR_TYPE_DEBUG,
3784          "Updating with peer %s from pull list\n",
3785          GNUNET_i2s (CustomPeerMap_get_peer_by_index (pull_map, i)));
3786     insert_in_sampler (NULL, CustomPeerMap_get_peer_by_index (pull_map, i));
3787     /* This cleans only if it is not in the view */
3788     clean_peer (CustomPeerMap_get_peer_by_index (pull_map, i));
3789     //peer_destroy_channel_send (sender);
3790   }
3791
3792
3793   /* Empty push/pull lists */
3794   CustomPeerMap_clear (push_map);
3795   CustomPeerMap_clear (pull_map);
3796
3797   struct GNUNET_TIME_Relative time_next_round;
3798
3799   time_next_round = compute_rand_delay (round_interval, 2);
3800
3801   /* Schedule next round */
3802   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round,
3803                                                 &do_round, NULL);
3804   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
3805 }
3806
3807
3808 /**
3809  * This is called from GNUNET_CADET_get_peers().
3810  *
3811  * It is called on every peer(ID) that cadet somehow has contact with.
3812  * We use those to initialise the sampler.
3813  */
3814 void
3815 init_peer_cb (void *cls,
3816               const struct GNUNET_PeerIdentity *peer,
3817               int tunnel, // "Do we have a tunnel towards this peer?"
3818               unsigned int n_paths, // "Number of known paths towards this peer"
3819               unsigned int best_path) // "How long is the best path?
3820                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
3821 {
3822   if (NULL != peer)
3823   {
3824     LOG (GNUNET_ERROR_TYPE_DEBUG,
3825          "Got peer_id %s from cadet\n",
3826          GNUNET_i2s (peer));
3827     got_peer (peer);
3828   }
3829 }
3830
3831 /**
3832  * @brief Iterator function over stored, valid peers.
3833  *
3834  * We initialise the sampler with those.
3835  *
3836  * @param cls the closure
3837  * @param peer the peer id
3838  * @return #GNUNET_YES if we should continue to
3839  *         iterate,
3840  *         #GNUNET_NO if not.
3841  */
3842 static int
3843 valid_peers_iterator (void *cls,
3844                       const struct GNUNET_PeerIdentity *peer)
3845 {
3846   if (NULL != peer)
3847   {
3848     LOG (GNUNET_ERROR_TYPE_DEBUG,
3849          "Got stored, valid peer %s\n",
3850          GNUNET_i2s (peer));
3851     got_peer (peer);
3852   }
3853   return GNUNET_YES;
3854 }
3855
3856
3857 /**
3858  * Iterator over peers from peerinfo.
3859  *
3860  * @param cls closure
3861  * @param peer id of the peer, NULL for last call
3862  * @param hello hello message for the peer (can be NULL)
3863  * @param error message
3864  */
3865 void
3866 process_peerinfo_peers (void *cls,
3867                         const struct GNUNET_PeerIdentity *peer,
3868                         const struct GNUNET_HELLO_Message *hello,
3869                         const char *err_msg)
3870 {
3871   if (NULL != peer)
3872   {
3873     LOG (GNUNET_ERROR_TYPE_DEBUG,
3874          "Got peer_id %s from peerinfo\n",
3875          GNUNET_i2s (peer));
3876     got_peer (peer);
3877   }
3878 }
3879
3880
3881 /**
3882  * Task run during shutdown.
3883  *
3884  * @param cls unused
3885  */
3886 static void
3887 shutdown_task (void *cls)
3888 {
3889   struct ClientContext *client_ctx;
3890   struct ReplyCls *reply_cls;
3891
3892   LOG (GNUNET_ERROR_TYPE_DEBUG,
3893        "RPS is going down\n");
3894
3895   /* Clean all clients */
3896   for (client_ctx = cli_ctx_head;
3897        NULL != cli_ctx_head;
3898        client_ctx = cli_ctx_head)
3899   {
3900     /* Clean pending requests to the sampler */
3901     for (reply_cls = client_ctx->rep_cls_head;
3902          NULL != client_ctx->rep_cls_head;
3903          reply_cls = client_ctx->rep_cls_head)
3904     {
3905       RPS_sampler_request_cancel (reply_cls->req_handle);
3906       GNUNET_CONTAINER_DLL_remove (client_ctx->rep_cls_head,
3907                                    client_ctx->rep_cls_tail,
3908                                    reply_cls);
3909       GNUNET_free (reply_cls);
3910     }
3911     GNUNET_CONTAINER_DLL_remove (cli_ctx_head, cli_ctx_tail, client_ctx);
3912     GNUNET_free (client_ctx);
3913   }
3914   GNUNET_PEERINFO_notify_cancel (peerinfo_notify_handle);
3915   GNUNET_PEERINFO_disconnect (peerinfo_handle);
3916
3917   if (NULL != do_round_task)
3918   {
3919     GNUNET_SCHEDULER_cancel (do_round_task);
3920     do_round_task = NULL;
3921   }
3922
3923   Peers_terminate ();
3924
3925   GNUNET_NSE_disconnect (nse);
3926   RPS_sampler_destroy (prot_sampler);
3927   RPS_sampler_destroy (client_sampler);
3928   GNUNET_CADET_close_port (cadet_port);
3929   GNUNET_CADET_disconnect (cadet_handle);
3930   View_destroy ();
3931   CustomPeerMap_destroy (push_map);
3932   CustomPeerMap_destroy (pull_map);
3933   if (NULL != stats)
3934   {
3935     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3936     stats = NULL;
3937   }
3938   #ifdef ENABLE_MALICIOUS
3939   struct AttackedPeer *tmp_att_peer;
3940   GNUNET_free (file_name_view_log);
3941   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
3942   if (NULL != mal_peer_set)
3943     GNUNET_CONTAINER_multipeermap_destroy (mal_peer_set);
3944   if (NULL != att_peer_set)
3945     GNUNET_CONTAINER_multipeermap_destroy (att_peer_set);
3946   while (NULL != att_peers_head)
3947   {
3948     tmp_att_peer = att_peers_head;
3949     GNUNET_CONTAINER_DLL_remove (att_peers_head, att_peers_tail, tmp_att_peer);
3950   }
3951   #endif /* ENABLE_MALICIOUS */
3952 }
3953
3954
3955 /**
3956  * Handle client connecting to the service.
3957  *
3958  * @param cls NULL
3959  * @param client the new client
3960  * @param mq the message queue of @a client
3961  * @return @a client
3962  */
3963 static void *
3964 client_connect_cb (void *cls,
3965                    struct GNUNET_SERVICE_Client *client,
3966                    struct GNUNET_MQ_Handle *mq)
3967 {
3968   struct ClientContext *cli_ctx;
3969
3970   LOG (GNUNET_ERROR_TYPE_DEBUG,
3971        "Client connected\n");
3972   if (NULL == client)
3973     return client; /* Server was destroyed before a client connected. Shutting down */
3974   cli_ctx = GNUNET_new (struct ClientContext);
3975   cli_ctx->mq = GNUNET_SERVICE_client_get_mq (client);
3976   cli_ctx->client = client;
3977   GNUNET_CONTAINER_DLL_insert (cli_ctx_head,
3978                                cli_ctx_tail,
3979                                cli_ctx);
3980   return cli_ctx;
3981 }
3982
3983 /**
3984  * Callback called when a client disconnected from the service
3985  *
3986  * @param cls closure for the service
3987  * @param c the client that disconnected
3988  * @param internal_cls should be equal to @a c
3989  */
3990 static void
3991 client_disconnect_cb (void *cls,
3992                       struct GNUNET_SERVICE_Client *client,
3993                       void *internal_cls)
3994 {
3995   struct ClientContext *cli_ctx = internal_cls;
3996
3997   GNUNET_assert (client == cli_ctx->client);
3998   if (NULL == client)
3999   {/* shutdown task - destroy all clients */
4000     while (NULL != cli_ctx_head)
4001       destroy_cli_ctx (cli_ctx_head);
4002   }
4003   else
4004   { /* destroy this client */
4005     LOG (GNUNET_ERROR_TYPE_DEBUG,
4006         "Client disconnected. Destroy its context.\n");
4007     destroy_cli_ctx (cli_ctx);
4008   }
4009 }
4010
4011
4012 /**
4013  * Handle random peer sampling clients.
4014  *
4015  * @param cls closure
4016  * @param c configuration to use
4017  * @param service the initialized service
4018  */
4019 static void
4020 run (void *cls,
4021      const struct GNUNET_CONFIGURATION_Handle *c,
4022      struct GNUNET_SERVICE_Handle *service)
4023 {
4024   int size;
4025   int out_size;
4026   char* fn_valid_peers;
4027   struct GNUNET_HashCode port;
4028
4029   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
4030   cfg = c;
4031
4032
4033   /* Get own ID */
4034   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
4035   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4036               "STARTING SERVICE (rps) for peer [%s]\n",
4037               GNUNET_i2s (&own_identity));
4038   #ifdef ENABLE_MALICIOUS
4039   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4040               "Malicious execution compiled in.\n");
4041   #endif /* ENABLE_MALICIOUS */
4042
4043
4044
4045   /* Get time interval from the configuration */
4046   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
4047                                                         "ROUNDINTERVAL",
4048                                                         &round_interval))
4049   {
4050     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
4051                                "RPS", "ROUNDINTERVAL");
4052     GNUNET_SCHEDULER_shutdown ();
4053     return;
4054   }
4055
4056   /* Get initial size of sampler/view from the configuration */
4057   if (GNUNET_OK !=
4058       GNUNET_CONFIGURATION_get_value_number (cfg, "RPS", "INITSIZE",
4059         (long long unsigned int *) &sampler_size_est_need))
4060   {
4061     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
4062                                "RPS", "INITSIZE");
4063     GNUNET_SCHEDULER_shutdown ();
4064     return;
4065   }
4066   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %u\n", sampler_size_est_need);
4067
4068   if (GNUNET_OK !=
4069       GNUNET_CONFIGURATION_get_value_filename (cfg,
4070                                                "rps",
4071                                                "FILENAME_VALID_PEERS",
4072                                                &fn_valid_peers))
4073   {
4074     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
4075                                "rps", "FILENAME_VALID_PEERS");
4076   }
4077
4078
4079   View_create (4);
4080
4081   /* file_name_view_log */
4082   if (GNUNET_OK != GNUNET_DISK_directory_create ("/tmp/rps/"))
4083   {
4084     LOG (GNUNET_ERROR_TYPE_WARNING,
4085          "Failed to create directory /tmp/rps/\n");
4086   }
4087
4088   size = (14 + strlen (GNUNET_i2s_full (&own_identity)) + 1) * sizeof (char);
4089   file_name_view_log = GNUNET_malloc (size);
4090   out_size = GNUNET_snprintf (file_name_view_log,
4091                               size,
4092                               "/tmp/rps/view-%s",
4093                               GNUNET_i2s_full (&own_identity));
4094   if (size < out_size ||
4095       0 > out_size)
4096   {
4097     LOG (GNUNET_ERROR_TYPE_WARNING,
4098          "Failed to write string to buffer (size: %i, out_size: %i)\n",
4099          size,
4100          out_size);
4101   }
4102
4103
4104   /* connect to NSE */
4105   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
4106
4107
4108   alpha = 0.45;
4109   beta  = 0.45;
4110
4111
4112   /* Initialise cadet */
4113   /* There exists a copy-paste-clone in get_channel() */
4114   struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
4115     GNUNET_MQ_hd_fixed_size (peer_check,
4116                              GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE,
4117                              struct GNUNET_MessageHeader,
4118                              NULL),
4119     GNUNET_MQ_hd_fixed_size (peer_push,
4120                              GNUNET_MESSAGE_TYPE_RPS_PP_PUSH,
4121                              struct GNUNET_MessageHeader,
4122                              NULL),
4123     GNUNET_MQ_hd_fixed_size (peer_pull_request,
4124                              GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
4125                              struct GNUNET_MessageHeader,
4126                              NULL),
4127     GNUNET_MQ_hd_var_size (peer_pull_reply,
4128                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY,
4129                            struct GNUNET_RPS_P2P_PullReplyMessage,
4130                            NULL),
4131     GNUNET_MQ_handler_end ()
4132   };
4133
4134   cadet_handle = GNUNET_CADET_connect (cfg);
4135   GNUNET_assert (NULL != cadet_handle);
4136   GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_RPS,
4137                       strlen (GNUNET_APPLICATION_PORT_RPS),
4138                       &port);
4139   cadet_port = GNUNET_CADET_open_port (cadet_handle,
4140                                        &port,
4141                                        &Peers_handle_inbound_channel, /* Connect handler */
4142                                        NULL, /* cls */
4143                                        NULL, /* WindowSize handler */
4144                                        cleanup_destroyed_channel, /* Disconnect handler */
4145                                        cadet_handlers);
4146
4147
4148   peerinfo_handle = GNUNET_PEERINFO_connect (cfg);
4149   Peers_initialise (fn_valid_peers, cadet_handle, cleanup_destroyed_channel,
4150                     &own_identity);
4151   GNUNET_free (fn_valid_peers);
4152
4153   /* Initialise sampler */
4154   struct GNUNET_TIME_Relative half_round_interval;
4155   struct GNUNET_TIME_Relative  max_round_interval;
4156
4157   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
4158   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
4159
4160   prot_sampler =   RPS_sampler_init     (sampler_size_est_need, max_round_interval);
4161   client_sampler = RPS_sampler_mod_init (sampler_size_est_need, max_round_interval);
4162
4163   /* Initialise push and pull maps */
4164   push_map = CustomPeerMap_create (4);
4165   pull_map = CustomPeerMap_create (4);
4166
4167
4168   //LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
4169   //GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
4170   // TODO send push/pull to each of those peers?
4171   // TODO read stored valid peers from last run
4172   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting stored valid peers\n");
4173   Peers_get_valid_peers (valid_peers_iterator, NULL);
4174
4175   peerinfo_notify_handle = GNUNET_PEERINFO_notify (cfg,
4176                                                    GNUNET_NO,
4177                                                    process_peerinfo_peers,
4178                                                    NULL);
4179
4180   LOG (GNUNET_ERROR_TYPE_INFO, "Ready to receive requests from clients\n");
4181
4182   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
4183   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
4184
4185   GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
4186   stats = GNUNET_STATISTICS_create ("rps", cfg);
4187
4188 }
4189
4190
4191 /**
4192  * Define "main" method using service macro.
4193  */
4194 GNUNET_SERVICE_MAIN
4195 ("rps",
4196  GNUNET_SERVICE_OPTION_NONE,
4197  &run,
4198  &client_connect_cb,
4199  &client_disconnect_cb,
4200  NULL,
4201  GNUNET_MQ_hd_fixed_size (client_request,
4202    GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
4203    struct GNUNET_RPS_CS_RequestMessage,
4204    NULL),
4205  GNUNET_MQ_hd_fixed_size (client_request_cancel,
4206    GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST_CANCEL,
4207    struct GNUNET_RPS_CS_RequestCancelMessage,
4208    NULL),
4209  GNUNET_MQ_hd_var_size (client_seed,
4210    GNUNET_MESSAGE_TYPE_RPS_CS_SEED,
4211    struct GNUNET_RPS_CS_SeedMessage,
4212    NULL),
4213 #ifdef ENABLE_MALICIOUS
4214  GNUNET_MQ_hd_var_size (client_act_malicious,
4215    GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS,
4216    struct GNUNET_RPS_CS_ActMaliciousMessage,
4217    NULL),
4218 #endif /* ENABLE_MALICIOUS */
4219  GNUNET_MQ_handler_end());
4220
4221 /* end of gnunet-service-rps.c */