Merge remote-tracking branch 'origin/master' into identity_abe
[oweals/gnunet.git] / src / rps / gnunet-service-rps_peers.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file rps/gnunet-service-rps_peers.c
23  * @brief utilities for managing (information about) peers
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 <inttypes.h>
31 #include "rps.h"
32 #include "gnunet-service-rps_peers.h"
33
34
35
36 #define LOG(kind, ...) GNUNET_log_from(kind,"rps-peers",__VA_ARGS__)
37
38
39 /**
40  * Set a peer flag of given peer context.
41  */
42 #define set_peer_flag(peer_ctx, mask) ((peer_ctx->peer_flags) |= (mask))
43
44 /**
45  * Get peer flag of given peer context.
46  */
47 #define check_peer_flag_set(peer_ctx, mask)\
48   ((peer_ctx->peer_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
49
50 /**
51  * Unset flag of given peer context.
52  */
53 #define unset_peer_flag(peer_ctx, mask) ((peer_ctx->peer_flags) &= ~(mask))
54
55 /**
56  * Set a channel flag of given channel context.
57  */
58 #define set_channel_flag(channel_flags, mask) ((*channel_flags) |= (mask))
59
60 /**
61  * Get channel flag of given channel context.
62  */
63 #define check_channel_flag_set(channel_flags, mask)\
64   ((*channel_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
65
66 /**
67  * Unset flag of given channel context.
68  */
69 #define unset_channel_flag(channel_flags, mask) ((*channel_flags) &= ~(mask))
70
71
72
73 /**
74  * Pending operation on peer consisting of callback and closure
75  *
76  * When an operation cannot be executed right now this struct is used to store
77  * the callback and closure for later execution.
78  */
79 struct PeerPendingOp
80 {
81   /**
82    * Callback
83    */
84   PeerOp op;
85
86   /**
87    * Closure
88    */
89   void *op_cls;
90 };
91
92 /**
93  * List containing all messages that are yet to be send
94  *
95  * This is used to keep track of all messages that have not been sent yet. When
96  * a peer is to be removed the pending messages can be removed properly.
97  */
98 struct PendingMessage
99 {
100   /**
101    * DLL next, prev
102    */
103   struct PendingMessage *next;
104   struct PendingMessage *prev;
105
106   /**
107    * The envelope to the corresponding message
108    */
109   struct GNUNET_MQ_Envelope *ev;
110
111   /**
112    * The corresponding context
113    */
114   struct PeerContext *peer_ctx;
115
116   /**
117    * The message type
118    */
119   const char *type;
120 };
121
122 /**
123  * Struct used to keep track of other peer's status
124  *
125  * This is stored in a multipeermap.
126  * It contains information such as cadet channels, a message queue for sending,
127  * status about the channels, the pending operations on this peer and some flags
128  * about the status of the peer itself. (live, valid, ...)
129  */
130 struct PeerContext
131 {
132   /**
133    * Message queue open to client
134    */
135   struct GNUNET_MQ_Handle *mq;
136
137   /**
138    * Channel open to client.
139    */
140   struct GNUNET_CADET_Channel *send_channel;
141
142   /**
143    * Flags to the sending channel
144    */
145   uint32_t *send_channel_flags;
146
147   /**
148    * Channel open from client.
149    */
150   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
151
152   /**
153    * Flags to the receiving channel
154    */
155   uint32_t *recv_channel_flags;
156
157   /**
158    * Array of pending operations on this peer.
159    */
160   struct PeerPendingOp *pending_ops;
161
162   /**
163    * Handle to the callback given to cadet_ntfy_tmt_rdy()
164    *
165    * To be canceled on shutdown.
166    */
167   struct PendingMessage *liveliness_check_pending;
168
169   /**
170    * Number of pending operations.
171    */
172   unsigned int num_pending_ops;
173
174   /**
175    * Identity of the peer
176    */
177   struct GNUNET_PeerIdentity peer_id;
178
179   /**
180    * Flags indicating status of peer
181    */
182   uint32_t peer_flags;
183
184   /**
185    * Last time we received something from that peer.
186    */
187   struct GNUNET_TIME_Absolute last_message_recv;
188
189   /**
190    * Last time we received a keepalive message.
191    */
192   struct GNUNET_TIME_Absolute last_keepalive;
193
194   /**
195    * DLL with all messages that are yet to be sent
196    */
197   struct PendingMessage *pending_messages_head;
198   struct PendingMessage *pending_messages_tail;
199
200   /**
201    * This is pobably followed by 'statistical' data (when we first saw
202    * him, how did we get his ID, how many pushes (in a timeinterval),
203    * ...)
204    */
205 };
206
207 /**
208  * @brief Closure to #valid_peer_iterator
209  */
210 struct PeersIteratorCls
211 {
212   /**
213    * Iterator function
214    */
215   PeersIterator iterator;
216
217   /**
218    * Closure to iterator
219    */
220   void *cls;
221 };
222
223 /**
224  * @brief Hashmap of valid peers.
225  */
226 static struct GNUNET_CONTAINER_MultiPeerMap *valid_peers;
227
228 /**
229  * @brief Maximum number of valid peers to keep.
230  * TODO read from config
231  */
232 static uint32_t num_valid_peers_max = UINT32_MAX;
233
234 /**
235  * @brief Filename of the file that stores the valid peers persistently.
236  */
237 static char *filename_valid_peers;
238
239 /**
240  * Set of all peers to keep track of them.
241  */
242 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
243
244 /**
245  * Own #GNUNET_PeerIdentity.
246  */
247 static const struct GNUNET_PeerIdentity *own_identity;
248
249 /**
250  * Cadet handle.
251  */
252 static struct GNUNET_CADET_Handle *cadet_handle;
253
254 /**
255  * @brief Disconnect handler
256  */
257 static GNUNET_CADET_DisconnectEventHandler cleanup_destroyed_channel;
258
259 /**
260  * @brief cadet handlers
261  */
262 static const struct GNUNET_MQ_MessageHandler *cadet_handlers;
263
264
265
266 /**
267  * @brief Get the #PeerContext associated with a peer
268  *
269  * @param peer the peer id
270  *
271  * @return the #PeerContext
272  */
273 static struct PeerContext *
274 get_peer_ctx (const struct GNUNET_PeerIdentity *peer)
275 {
276   struct PeerContext *ctx;
277   int ret;
278
279   ret = GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
280   GNUNET_assert (GNUNET_YES == ret);
281   ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
282   GNUNET_assert (NULL != ctx);
283   return ctx;
284 }
285
286
287 /**
288  * @brief Create a new #PeerContext and insert it into the peer map
289  *
290  * @param peer the peer to create the #PeerContext for
291  *
292  * @return the #PeerContext
293  */
294 static struct PeerContext *
295 create_peer_ctx (const struct GNUNET_PeerIdentity *peer)
296 {
297   struct PeerContext *ctx;
298   int ret;
299
300   GNUNET_assert (GNUNET_NO == Peers_check_peer_known (peer));
301
302   ctx = GNUNET_new (struct PeerContext);
303   ctx->peer_id = *peer;
304   ctx->send_channel_flags = GNUNET_new (uint32_t);
305   ctx->recv_channel_flags = GNUNET_new (uint32_t);
306   ret = GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
307       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
308   GNUNET_assert (GNUNET_OK == ret);
309   return ctx;
310 }
311
312
313 /**
314  * @brief Create or get a #PeerContext
315  *
316  * @param peer the peer to get the associated context to
317  *
318  * @return the context
319  */
320 static struct PeerContext *
321 create_or_get_peer_ctx (const struct GNUNET_PeerIdentity *peer)
322 {
323   if (GNUNET_NO == Peers_check_peer_known (peer))
324   {
325     return create_peer_ctx (peer);
326   }
327   return get_peer_ctx (peer);
328 }
329
330
331 /**
332  * @brief Check whether we have a connection to this @a peer
333  *
334  * Also sets the #Peers_ONLINE flag accordingly
335  *
336  * @param peer the peer in question
337  *
338  * @return #GNUNET_YES if we are connected
339  *         #GNUNET_NO  otherwise
340  */
341 int
342 Peers_check_connected (const struct GNUNET_PeerIdentity *peer)
343 {
344   const struct PeerContext *peer_ctx;
345
346   /* If we don't know about this peer we don't know whether it's online */
347   if (GNUNET_NO == Peers_check_peer_known (peer))
348   {
349     return GNUNET_NO;
350   }
351   /* Get the context */
352   peer_ctx = get_peer_ctx (peer);
353   /* If we have no channel to this peer we don't know whether it's online */
354   if ( (NULL == peer_ctx->send_channel) &&
355        (NULL == peer_ctx->recv_channel) )
356   {
357     Peers_unset_peer_flag (peer, Peers_ONLINE);
358     return GNUNET_NO;
359   }
360   /* Otherwise (if we have a channel, we know that it's online */
361   Peers_set_peer_flag (peer, Peers_ONLINE);
362   return GNUNET_YES;
363 }
364
365
366 /**
367  * @brief The closure to #get_rand_peer_iterator.
368  */
369 struct GetRandPeerIteratorCls
370 {
371   /**
372    * @brief The index of the peer to return.
373    * Will be decreased until 0.
374    * Then current peer is returned.
375    */
376   uint32_t index;
377
378   /**
379    * @brief Pointer to peer to return.
380    */
381   const struct GNUNET_PeerIdentity *peer;
382 };
383
384
385 /**
386  * @brief Iterator function for #get_random_peer_from_peermap.
387  *
388  * Implements #GNUNET_CONTAINER_PeerMapIterator.
389  * Decreases the index until the index is null.
390  * Then returns the current peer.
391  *
392  * @param cls the #GetRandPeerIteratorCls containing index and peer
393  * @param peer current peer
394  * @param value unused
395  *
396  * @return  #GNUNET_YES if we should continue to
397  *          iterate,
398  *          #GNUNET_NO if not.
399  */
400 static int
401 get_rand_peer_iterator (void *cls,
402                         const struct GNUNET_PeerIdentity *peer,
403                         void *value)
404 {
405   struct GetRandPeerIteratorCls *iterator_cls = cls;
406   if (0 >= iterator_cls->index)
407   {
408     iterator_cls->peer = peer;
409     return GNUNET_NO;
410   }
411   iterator_cls->index--;
412   return GNUNET_YES;
413 }
414
415
416 /**
417  * @brief Get a random peer from @a peer_map
418  *
419  * @param peer_map the peer_map to get the peer from
420  *
421  * @return a random peer
422  */
423 static const struct GNUNET_PeerIdentity *
424 get_random_peer_from_peermap (const struct
425                               GNUNET_CONTAINER_MultiPeerMap *peer_map)
426 {
427   struct GetRandPeerIteratorCls *iterator_cls;
428   const struct GNUNET_PeerIdentity *ret;
429
430   iterator_cls = GNUNET_new (struct GetRandPeerIteratorCls);
431   iterator_cls->index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
432       GNUNET_CONTAINER_multipeermap_size (peer_map));
433   (void) GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
434                                                 get_rand_peer_iterator,
435                                                 iterator_cls);
436   ret = iterator_cls->peer;
437   GNUNET_free (iterator_cls);
438   return ret;
439 }
440
441
442 /**
443  * @brief Add a given @a peer to valid peers.
444  *
445  * If valid peers are already #num_valid_peers_max, delete a peer previously.
446  *
447  * @param peer the peer that is added to the valid peers.
448  *
449  * @return #GNUNET_YES if no other peer had to be removed
450  *         #GNUNET_NO  otherwise
451  */
452 static int
453 add_valid_peer (const struct GNUNET_PeerIdentity *peer)
454 {
455   const struct GNUNET_PeerIdentity *rand_peer;
456   int ret;
457
458   ret = GNUNET_YES;
459   while (GNUNET_CONTAINER_multipeermap_size (valid_peers) >= num_valid_peers_max)
460   {
461     rand_peer = get_random_peer_from_peermap (valid_peers);
462     GNUNET_CONTAINER_multipeermap_remove_all (valid_peers, rand_peer);
463     ret = GNUNET_NO;
464   }
465   (void) GNUNET_CONTAINER_multipeermap_put (valid_peers, peer, NULL,
466       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
467   return ret;
468 }
469
470
471 /**
472  * @brief Set the peer flag to living and
473  *        call the pending operations on this peer.
474  *
475  * Also adds peer to #valid_peers.
476  *
477  * @param peer_ctx the #PeerContext of the peer to set live
478  */
479 static void
480 set_peer_live (struct PeerContext *peer_ctx)
481 {
482   struct GNUNET_PeerIdentity *peer;
483   unsigned int i;
484
485   peer = &peer_ctx->peer_id;
486   LOG (GNUNET_ERROR_TYPE_DEBUG,
487       "Peer %s is live and valid, calling %i pending operations on it\n",
488       GNUNET_i2s (peer),
489       peer_ctx->num_pending_ops);
490
491   if (NULL != peer_ctx->liveliness_check_pending)
492   {
493     LOG (GNUNET_ERROR_TYPE_DEBUG,
494          "Removing pending liveliness check for peer %s\n",
495          GNUNET_i2s (&peer_ctx->peer_id));
496     // TODO wait until cadet sets mq->cancel_impl
497     //GNUNET_MQ_send_cancel (peer_ctx->liveliness_check_pending->ev);
498     GNUNET_free (peer_ctx->liveliness_check_pending);
499     peer_ctx->liveliness_check_pending = NULL;
500   }
501
502   (void) add_valid_peer (peer);
503   set_peer_flag (peer_ctx, Peers_ONLINE);
504
505   /* Call pending operations */
506   for (i = 0; i < peer_ctx->num_pending_ops; i++)
507   {
508     peer_ctx->pending_ops[i].op (peer_ctx->pending_ops[i].op_cls, peer);
509   }
510   GNUNET_array_grow (peer_ctx->pending_ops, peer_ctx->num_pending_ops, 0);
511 }
512
513
514 /**
515  * @brief Get the channel of a peer. If not existing, create.
516  *
517  * @param peer the peer id
518  * @return the #GNUNET_CADET_Channel used to send data to @a peer
519  */
520 struct GNUNET_CADET_Channel *
521 get_channel (const struct GNUNET_PeerIdentity *peer)
522 {
523   struct PeerContext *peer_ctx;
524   struct GNUNET_HashCode port;
525
526   peer_ctx = get_peer_ctx (peer);
527   if (NULL == peer_ctx->send_channel)
528   {
529     LOG (GNUNET_ERROR_TYPE_DEBUG,
530          "Trying to establish channel to peer %s\n",
531          GNUNET_i2s (peer));
532     GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_RPS,
533                         strlen (GNUNET_APPLICATION_PORT_RPS),
534                         &port);
535     peer_ctx->send_channel =
536       GNUNET_CADET_channel_create (cadet_handle,
537                                    (struct GNUNET_PeerIdentity *) peer, /* context */
538                                    peer,
539                                    &port,
540                                    GNUNET_CADET_OPTION_RELIABLE,
541                                    NULL, /* WindowSize handler */
542                                    cleanup_destroyed_channel, /* Disconnect handler */
543                                    cadet_handlers);
544   }
545   GNUNET_assert (NULL != peer_ctx->send_channel);
546   return peer_ctx->send_channel;
547 }
548
549
550 /**
551  * Get the message queue (#GNUNET_MQ_Handle) of a specific peer.
552  *
553  * If we already have a message queue open to this client,
554  * simply return it, otherways create one.
555  *
556  * @param peer the peer to get the mq to
557  * @return the #GNUNET_MQ_Handle
558  */
559 static struct GNUNET_MQ_Handle *
560 get_mq (const struct GNUNET_PeerIdentity *peer)
561 {
562   struct PeerContext *peer_ctx;
563
564   peer_ctx = get_peer_ctx (peer);
565
566   if (NULL == peer_ctx->mq)
567   {
568     (void) get_channel (peer);
569     peer_ctx->mq = GNUNET_CADET_get_mq (peer_ctx->send_channel);
570   }
571   return peer_ctx->mq;
572 }
573
574
575 /**
576  * @brief This is called in response to the first message we sent as a
577  * liveliness check.
578  *
579  * @param cls #PeerContext of peer with pending liveliness check
580  */
581 static void
582 mq_liveliness_check_successful (void *cls)
583 {
584   struct PeerContext *peer_ctx = cls;
585
586   if (NULL != peer_ctx->liveliness_check_pending)
587   {
588     LOG (GNUNET_ERROR_TYPE_DEBUG,
589         "Liveliness check for peer %s was successfull\n",
590         GNUNET_i2s (&peer_ctx->peer_id));
591     GNUNET_free (peer_ctx->liveliness_check_pending);
592     peer_ctx->liveliness_check_pending = NULL;
593     set_peer_live (peer_ctx);
594   }
595 }
596
597 /**
598  * Issue a check whether peer is live
599  *
600  * @param peer_ctx the context of the peer
601  */
602 static void
603 check_peer_live (struct PeerContext *peer_ctx)
604 {
605   LOG (GNUNET_ERROR_TYPE_DEBUG,
606        "Get informed about peer %s getting live\n",
607        GNUNET_i2s (&peer_ctx->peer_id));
608
609   struct GNUNET_MQ_Handle *mq;
610   struct GNUNET_MQ_Envelope *ev;
611
612   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE);
613   peer_ctx->liveliness_check_pending = GNUNET_new (struct PendingMessage);
614   peer_ctx->liveliness_check_pending->ev = ev;
615   peer_ctx->liveliness_check_pending->peer_ctx = peer_ctx;
616   peer_ctx->liveliness_check_pending->type = "Check liveliness";
617   mq = get_mq (&peer_ctx->peer_id);
618   GNUNET_MQ_notify_sent (ev,
619                          mq_liveliness_check_successful,
620                          peer_ctx);
621   GNUNET_MQ_send (mq, ev);
622 }
623
624 /**
625  * @brief Add an envelope to a message passed to mq to list of pending messages
626  *
627  * @param peer peer the message was sent to
628  * @param ev envelope to the message
629  * @param type type of the message to be sent
630  * @return pointer to pending message
631  */
632 static struct PendingMessage *
633 insert_pending_message (const struct GNUNET_PeerIdentity *peer,
634                         struct GNUNET_MQ_Envelope *ev,
635                         const char *type)
636 {
637   struct PendingMessage *pending_msg;
638   struct PeerContext *peer_ctx;
639
640   peer_ctx = get_peer_ctx (peer);
641   pending_msg = GNUNET_new (struct PendingMessage);
642   pending_msg->ev = ev;
643   pending_msg->peer_ctx = peer_ctx;
644   pending_msg->type = type;
645   GNUNET_CONTAINER_DLL_insert (peer_ctx->pending_messages_head,
646                                peer_ctx->pending_messages_tail,
647                                pending_msg);
648   return pending_msg;
649 }
650
651
652 /**
653  * @brief Remove a pending message from the respective DLL
654  *
655  * @param pending_msg the pending message to remove
656  */
657 static void
658 remove_pending_message (struct PendingMessage *pending_msg)
659 {
660   struct PeerContext *peer_ctx;
661
662   peer_ctx = pending_msg->peer_ctx;
663   GNUNET_CONTAINER_DLL_remove (peer_ctx->pending_messages_head,
664                                peer_ctx->pending_messages_tail,
665                                pending_msg);
666   GNUNET_MQ_send_cancel (peer_ctx->pending_messages_head->ev);
667   GNUNET_free (pending_msg);
668 }
669
670
671 /**
672  * @brief Check whether function of type #PeerOp was already scheduled
673  *
674  * The array with pending operations will probably never grow really big, so
675  * iterating over it should be ok.
676  *
677  * @param peer the peer to check
678  * @param peer_op the operation (#PeerOp) on the peer
679  *
680  * @return #GNUNET_YES if this operation is scheduled on that peer
681  *         #GNUNET_NO  otherwise
682  */
683 static int
684 check_operation_scheduled (const struct GNUNET_PeerIdentity *peer,
685                            const PeerOp peer_op)
686 {
687   const struct PeerContext *peer_ctx;
688   unsigned int i;
689
690   peer_ctx = get_peer_ctx (peer);
691   for (i = 0; i < peer_ctx->num_pending_ops; i++)
692     if (peer_op == peer_ctx->pending_ops[i].op)
693       return GNUNET_YES;
694   return GNUNET_NO;
695 }
696
697
698 /**
699  * Iterator over hash map entries. Deletes all contexts of peers.
700  *
701  * @param cls closure
702  * @param key current public key
703  * @param value value in the hash map
704  * @return #GNUNET_YES if we should continue to iterate,
705  *         #GNUNET_NO if not.
706  */
707 static int
708 peermap_clear_iterator (void *cls,
709                         const struct GNUNET_PeerIdentity *key,
710                         void *value)
711 {
712   Peers_remove_peer (key);
713   return GNUNET_YES;
714 }
715
716
717 /**
718  * @brief This is called once a message is sent.
719  *
720  * Removes the pending message
721  *
722  * @param cls type of the message that was sent
723  */
724 static void
725 mq_notify_sent_cb (void *cls)
726 {
727   struct PendingMessage *pending_msg = (struct PendingMessage *) cls;
728   LOG (GNUNET_ERROR_TYPE_DEBUG,
729       "%s was sent.\n",
730       pending_msg->type);
731   remove_pending_message (pending_msg);
732 }
733
734
735 /**
736  * @brief Iterator function for #store_valid_peers.
737  *
738  * Implements #GNUNET_CONTAINER_PeerMapIterator.
739  * Writes single peer to disk.
740  *
741  * @param cls the file handle to write to.
742  * @param peer current peer
743  * @param value unused
744  *
745  * @return  #GNUNET_YES if we should continue to
746  *          iterate,
747  *          #GNUNET_NO if not.
748  */
749 static int
750 store_peer_presistently_iterator (void *cls,
751                                   const struct GNUNET_PeerIdentity *peer,
752                                   void *value)
753 {
754   const struct GNUNET_DISK_FileHandle *fh = cls;
755   char peer_string[128];
756   int size;
757   ssize_t ret;
758
759   if (NULL == peer)
760   {
761     return GNUNET_YES;
762   }
763   size = GNUNET_snprintf (peer_string,
764                           sizeof (peer_string),
765                           "%s\n",
766                           GNUNET_i2s_full (peer));
767   GNUNET_assert (53 == size);
768   ret = GNUNET_DISK_file_write (fh,
769                                 peer_string,
770                                 size);
771   GNUNET_assert (size == ret);
772   return GNUNET_YES;
773 }
774
775
776 /**
777  * @brief Store the peers currently in #valid_peers to disk.
778  */
779 static void
780 store_valid_peers ()
781 {
782   struct GNUNET_DISK_FileHandle *fh;
783   uint32_t number_written_peers;
784   int ret;
785
786   if (0 == strncmp ("DISABLE", filename_valid_peers, 7))
787   {
788     return;
789   }
790
791   ret = GNUNET_DISK_directory_create_for_file (filename_valid_peers);
792   if (GNUNET_SYSERR == ret)
793   {
794     LOG (GNUNET_ERROR_TYPE_WARNING,
795         "Not able to create directory for file `%s'\n",
796         filename_valid_peers);
797     GNUNET_break (0);
798   }
799   else if (GNUNET_NO == ret)
800   {
801     LOG (GNUNET_ERROR_TYPE_WARNING,
802         "Directory for file `%s' exists but is not writable for us\n",
803         filename_valid_peers);
804     GNUNET_break (0);
805   }
806   fh = GNUNET_DISK_file_open (filename_valid_peers,
807                               GNUNET_DISK_OPEN_WRITE |
808                                   GNUNET_DISK_OPEN_CREATE,
809                               GNUNET_DISK_PERM_USER_READ |
810                                   GNUNET_DISK_PERM_USER_WRITE);
811   if (NULL == fh)
812   {
813     LOG (GNUNET_ERROR_TYPE_WARNING,
814         "Not able to write valid peers to file `%s'\n",
815         filename_valid_peers);
816     return;
817   }
818   LOG (GNUNET_ERROR_TYPE_DEBUG,
819       "Writing %u valid peers to disk\n",
820       GNUNET_CONTAINER_multipeermap_size (valid_peers));
821   number_written_peers =
822     GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
823                                            store_peer_presistently_iterator,
824                                            fh);
825   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
826   GNUNET_assert (number_written_peers ==
827       GNUNET_CONTAINER_multipeermap_size (valid_peers));
828 }
829
830
831 /**
832  * @brief Convert string representation of peer id to peer id.
833  *
834  * Counterpart to #GNUNET_i2s_full.
835  *
836  * @param string_repr The string representation of the peer id
837  *
838  * @return The peer id
839  */
840 static const struct GNUNET_PeerIdentity *
841 s2i_full (const char *string_repr)
842 {
843   struct GNUNET_PeerIdentity *peer;
844   size_t len;
845   int ret;
846
847   peer = GNUNET_new (struct GNUNET_PeerIdentity);
848   len = strlen (string_repr);
849   if (52 > len)
850   {
851     LOG (GNUNET_ERROR_TYPE_WARNING,
852         "Not able to convert string representation of PeerID to PeerID\n"
853         "Sting representation: %s (len %u) - too short\n",
854         string_repr,
855         len);
856     GNUNET_break (0);
857   }
858   else if (52 < len)
859   {
860     len = 52;
861   }
862   ret = GNUNET_CRYPTO_eddsa_public_key_from_string (string_repr,
863                                                     len,
864                                                     &peer->public_key);
865   if (GNUNET_OK != ret)
866   {
867     LOG (GNUNET_ERROR_TYPE_WARNING,
868         "Not able to convert string representation of PeerID to PeerID\n"
869         "Sting representation: %s\n",
870         string_repr);
871     GNUNET_break (0);
872   }
873   return peer;
874 }
875
876
877 /**
878  * @brief Restore the peers on disk to #valid_peers.
879  */
880 static void
881 restore_valid_peers ()
882 {
883   off_t file_size;
884   uint32_t num_peers;
885   struct GNUNET_DISK_FileHandle *fh;
886   char *buf;
887   ssize_t size_read;
888   char *iter_buf;
889   char *str_repr;
890   const struct GNUNET_PeerIdentity *peer;
891
892   if (0 == strncmp ("DISABLE", filename_valid_peers, 7))
893   {
894     return;
895   }
896
897   if (GNUNET_OK != GNUNET_DISK_file_test (filename_valid_peers))
898   {
899     return;
900   }
901   fh = GNUNET_DISK_file_open (filename_valid_peers,
902                               GNUNET_DISK_OPEN_READ,
903                               GNUNET_DISK_PERM_NONE);
904   GNUNET_assert (NULL != fh);
905   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_handle_size (fh, &file_size));
906   num_peers = file_size / 53;
907   buf = GNUNET_malloc (file_size);
908   size_read = GNUNET_DISK_file_read (fh, buf, file_size);
909   GNUNET_assert (size_read == file_size);
910   LOG (GNUNET_ERROR_TYPE_DEBUG,
911       "Restoring %" PRIu32 " peers from file `%s'\n",
912       num_peers,
913       filename_valid_peers);
914   for (iter_buf = buf; iter_buf < buf + file_size - 1; iter_buf += 53)
915   {
916     str_repr = GNUNET_strndup (iter_buf, 53);
917     peer = s2i_full (str_repr);
918     GNUNET_free (str_repr);
919     add_valid_peer (peer);
920     LOG (GNUNET_ERROR_TYPE_DEBUG,
921         "Restored valid peer %s from disk\n",
922         GNUNET_i2s_full (peer));
923   }
924   iter_buf = NULL;
925   GNUNET_free (buf);
926   LOG (GNUNET_ERROR_TYPE_DEBUG,
927       "num_peers: %" PRIu32 ", _size (valid_peers): %u\n",
928       num_peers,
929       GNUNET_CONTAINER_multipeermap_size (valid_peers));
930   if (num_peers != GNUNET_CONTAINER_multipeermap_size (valid_peers))
931   {
932     LOG (GNUNET_ERROR_TYPE_WARNING,
933         "Number of restored peers does not match file size. Have probably duplicates.\n");
934   }
935   GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
936   LOG (GNUNET_ERROR_TYPE_DEBUG,
937       "Restored %u valid peers from disk\n",
938       GNUNET_CONTAINER_multipeermap_size (valid_peers));
939 }
940
941
942 /**
943  * @brief Initialise storage of peers
944  *
945  * @param fn_valid_peers filename of the file used to store valid peer ids
946  * @param cadet_h cadet handle
947  * @param disconnect_handler Disconnect handler
948  * @param c_handlers cadet handlers
949  * @param own_id own peer identity
950  */
951 void
952 Peers_initialise (char* fn_valid_peers,
953                   struct GNUNET_CADET_Handle *cadet_h,
954                   GNUNET_CADET_DisconnectEventHandler disconnect_handler,
955                   const struct GNUNET_MQ_MessageHandler *c_handlers,
956                   const struct GNUNET_PeerIdentity *own_id)
957 {
958   filename_valid_peers = GNUNET_strdup (fn_valid_peers);
959   cadet_handle = cadet_h;
960   cleanup_destroyed_channel = disconnect_handler;
961   cadet_handlers = c_handlers;
962   own_identity = own_id;
963   peer_map = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
964   valid_peers = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
965   restore_valid_peers ();
966 }
967
968
969 /**
970  * @brief Delete storage of peers that was created with #Peers_initialise ()
971  */
972 void
973 Peers_terminate ()
974 {
975   if (GNUNET_SYSERR ==
976       GNUNET_CONTAINER_multipeermap_iterate (peer_map,
977                                              peermap_clear_iterator,
978                                              NULL))
979   {
980     LOG (GNUNET_ERROR_TYPE_WARNING,
981         "Iteration destroying peers was aborted.\n");
982   }
983   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
984   store_valid_peers ();
985   GNUNET_free (filename_valid_peers);
986   GNUNET_CONTAINER_multipeermap_destroy (valid_peers);
987 }
988
989
990 /**
991  * Iterator over #valid_peers hash map entries.
992  *
993  * @param cls closure - unused
994  * @param peer current peer id
995  * @param value value in the hash map - unused
996  * @return #GNUNET_YES if we should continue to
997  *         iterate,
998  *         #GNUNET_NO if not.
999  */
1000 static int
1001 valid_peer_iterator (void *cls,
1002                      const struct GNUNET_PeerIdentity *peer,
1003                      void *value)
1004 {
1005   struct PeersIteratorCls *it_cls = cls;
1006
1007   return it_cls->iterator (it_cls->cls,
1008                            peer);
1009 }
1010
1011
1012 /**
1013  * @brief Get all currently known, valid peer ids.
1014  *
1015  * @param it function to call on each peer id
1016  * @param it_cls extra argument to @a it
1017  * @return the number of key value pairs processed,
1018  *         #GNUNET_SYSERR if it aborted iteration
1019  */
1020 int
1021 Peers_get_valid_peers (PeersIterator iterator,
1022                        void *it_cls)
1023 {
1024   struct PeersIteratorCls *cls;
1025   int ret;
1026
1027   cls = GNUNET_new (struct PeersIteratorCls);
1028   cls->iterator = iterator;
1029   cls->cls = it_cls;
1030   ret = GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
1031                                                valid_peer_iterator,
1032                                                cls);
1033   GNUNET_free (cls);
1034   return ret;
1035 }
1036
1037
1038 /**
1039  * @brief Add peer to known peers.
1040  *
1041  * This function is called on new peer_ids from 'external' sources
1042  * (client seed, cadet get_peers(), ...)
1043  *
1044  * @param peer the new #GNUNET_PeerIdentity
1045  *
1046  * @return #GNUNET_YES if peer was inserted
1047  *         #GNUNET_NO  otherwise (if peer was already known or
1048  *                     peer was #own_identity)
1049  */
1050 int
1051 Peers_insert_peer (const struct GNUNET_PeerIdentity *peer)
1052 {
1053   if ( (GNUNET_YES == Peers_check_peer_known (peer)) ||
1054        (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, own_identity)) )
1055   {
1056     return GNUNET_NO; /* We already know this peer - nothing to do */
1057   }
1058   (void) create_peer_ctx (peer);
1059   return GNUNET_YES;
1060 }
1061
1062
1063 /**
1064  * @brief Try connecting to a peer to see whether it is online
1065  *
1066  * If not known yet, insert into known peers
1067  *
1068  * @param peer the peer whose liveliness is to be checked
1069  * @return #GNUNET_YES if peer had to be inserted
1070  *         #GNUNET_NO  otherwise (if peer was already known or
1071  *                     peer was #own_identity)
1072  */
1073 int
1074 Peers_issue_peer_liveliness_check (const struct GNUNET_PeerIdentity *peer)
1075 {
1076   struct PeerContext *peer_ctx;
1077   int ret;
1078
1079   if (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, own_identity))
1080   {
1081     return GNUNET_NO;
1082   }
1083   ret = Peers_insert_peer (peer);
1084   peer_ctx = get_peer_ctx (peer);
1085   if (GNUNET_NO == Peers_check_peer_flag (peer, Peers_ONLINE))
1086   {
1087     check_peer_live (peer_ctx);
1088   }
1089   return ret;
1090 }
1091
1092
1093 /**
1094  * @brief Check if peer is removable.
1095  *
1096  * Check if
1097  *  - a recv channel exists
1098  *  - there are pending messages
1099  *  - there is no pending pull reply
1100  *
1101  * @param peer the peer in question
1102  * @return #GNUNET_YES    if peer is removable
1103  *         #GNUNET_NO     if peer is NOT removable
1104  *         #GNUNET_SYSERR if peer is not known
1105  */
1106 int
1107 Peers_check_removable (const struct GNUNET_PeerIdentity *peer)
1108 {
1109   struct PeerContext *peer_ctx;
1110
1111   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1112   {
1113     return GNUNET_SYSERR;
1114   }
1115
1116   peer_ctx = get_peer_ctx (peer);
1117   if ( (NULL != peer_ctx->recv_channel) ||
1118        (NULL != peer_ctx->pending_messages_head) ||
1119        (GNUNET_NO == check_peer_flag_set (peer_ctx, Peers_PULL_REPLY_PENDING)) )
1120   {
1121     return GNUNET_NO;
1122   }
1123   return GNUNET_YES;
1124 }
1125
1126
1127 /**
1128  * @brief Remove peer
1129  *
1130  * @param peer the peer to clean
1131  * @return #GNUNET_YES if peer was removed
1132  *         #GNUNET_NO  otherwise
1133  */
1134 int
1135 Peers_remove_peer (const struct GNUNET_PeerIdentity *peer)
1136 {
1137   struct PeerContext *peer_ctx;
1138
1139   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1140   {
1141     return GNUNET_NO;
1142   }
1143
1144   peer_ctx = get_peer_ctx (peer);
1145   set_peer_flag (peer_ctx, Peers_TO_DESTROY);
1146   LOG (GNUNET_ERROR_TYPE_DEBUG,
1147        "Going to remove peer %s\n",
1148        GNUNET_i2s (&peer_ctx->peer_id));
1149   Peers_unset_peer_flag (peer, Peers_ONLINE);
1150
1151   GNUNET_array_grow (peer_ctx->pending_ops, peer_ctx->num_pending_ops, 0);
1152   while (NULL != peer_ctx->pending_messages_head)
1153   {
1154     LOG (GNUNET_ERROR_TYPE_DEBUG,
1155         "Removing unsent %s\n",
1156         peer_ctx->pending_messages_head->type);
1157     remove_pending_message (peer_ctx->pending_messages_head);
1158   }
1159   /* If we are still waiting for notification whether this peer is live
1160    * cancel the according task */
1161   if (NULL != peer_ctx->liveliness_check_pending)
1162   {
1163     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1164          "Removing pending liveliness check for peer %s\n",
1165          GNUNET_i2s (&peer_ctx->peer_id));
1166     // TODO wait until cadet sets mq->cancel_impl
1167     //GNUNET_MQ_send_cancel (peer_ctx->liveliness_check_pending->ev);
1168     GNUNET_free (peer_ctx->liveliness_check_pending);
1169     peer_ctx->liveliness_check_pending = NULL;
1170   }
1171   if (NULL != peer_ctx->send_channel)
1172   {
1173     LOG (GNUNET_ERROR_TYPE_DEBUG,
1174         "Destroying send channel\n");
1175     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
1176     peer_ctx->send_channel = NULL;
1177   }
1178   if (NULL != peer_ctx->recv_channel)
1179   {
1180     LOG (GNUNET_ERROR_TYPE_DEBUG,
1181         "Destroying recv channel\n");
1182     GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
1183     peer_ctx->recv_channel = NULL;
1184   }
1185   if (NULL != peer_ctx->mq)
1186   {
1187     GNUNET_MQ_destroy (peer_ctx->mq);
1188     peer_ctx->mq = NULL;
1189   }
1190
1191   GNUNET_free (peer_ctx->send_channel_flags);
1192   GNUNET_free (peer_ctx->recv_channel_flags);
1193
1194   if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, &peer_ctx->peer_id))
1195   {
1196     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1197   }
1198   GNUNET_free (peer_ctx);
1199   return GNUNET_YES;
1200 }
1201
1202
1203 /**
1204  * @brief set flags on a given peer.
1205  *
1206  * @param peer the peer to set flags on
1207  * @param flags the flags
1208  */
1209 void
1210 Peers_set_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags)
1211 {
1212   struct PeerContext *peer_ctx;
1213
1214   peer_ctx = get_peer_ctx (peer);
1215   set_peer_flag (peer_ctx, flags);
1216 }
1217
1218
1219 /**
1220  * @brief unset flags on a given peer.
1221  *
1222  * @param peer the peer to unset flags on
1223  * @param flags the flags
1224  */
1225 void
1226 Peers_unset_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags)
1227 {
1228   struct PeerContext *peer_ctx;
1229
1230   peer_ctx = get_peer_ctx (peer);
1231   unset_peer_flag (peer_ctx, flags);
1232 }
1233
1234
1235 /**
1236  * @brief Check whether flags on a peer are set.
1237  *
1238  * @param peer the peer to check the flag of
1239  * @param flags the flags to check
1240  *
1241  * @return #GNUNET_SYSERR if peer is not known
1242  *         #GNUNET_YES    if all given flags are set
1243  *         #GNUNET_NO     otherwise
1244  */
1245 int
1246 Peers_check_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags)
1247 {
1248   struct PeerContext *peer_ctx;
1249
1250   if (GNUNET_NO == Peers_check_peer_known (peer))
1251   {
1252     return GNUNET_SYSERR;
1253   }
1254   peer_ctx = get_peer_ctx (peer);
1255   return check_peer_flag_set (peer_ctx, flags);
1256 }
1257
1258
1259 /**
1260  * @brief set flags on a given channel.
1261  *
1262  * @param channel the channel to set flags on
1263  * @param flags the flags
1264  */
1265 void
1266 Peers_set_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags)
1267 {
1268   set_channel_flag (channel_flags, flags);
1269 }
1270
1271
1272 /**
1273  * @brief unset flags on a given channel.
1274  *
1275  * @param channel the channel to unset flags on
1276  * @param flags the flags
1277  */
1278 void
1279 Peers_unset_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags)
1280 {
1281   unset_channel_flag (channel_flags, flags);
1282 }
1283
1284
1285 /**
1286  * @brief Check whether flags on a channel are set.
1287  *
1288  * @param channel the channel to check the flag of
1289  * @param flags the flags to check
1290  *
1291  * @return #GNUNET_YES if all given flags are set
1292  *         #GNUNET_NO  otherwise
1293  */
1294 int
1295 Peers_check_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags)
1296 {
1297   return check_channel_flag_set (channel_flags, flags);
1298 }
1299
1300 /**
1301  * @brief Get the flags for the channel in @a role for @a peer.
1302  *
1303  * @param peer Peer to get the channel flags for.
1304  * @param role Role of channel to get flags for
1305  *
1306  * @return The flags.
1307  */
1308 uint32_t *
1309 Peers_get_channel_flag (const struct GNUNET_PeerIdentity *peer,
1310                         enum Peers_ChannelRole role)
1311 {
1312   const struct PeerContext *peer_ctx;
1313
1314   peer_ctx = get_peer_ctx (peer);
1315   if (Peers_CHANNEL_ROLE_SENDING == role)
1316   {
1317     return peer_ctx->send_channel_flags;
1318   }
1319   else if (Peers_CHANNEL_ROLE_RECEIVING == role)
1320   {
1321     return peer_ctx->recv_channel_flags;
1322   }
1323   else
1324   {
1325     GNUNET_assert (0);
1326   }
1327 }
1328
1329 /**
1330  * @brief Check whether we have information about the given peer.
1331  *
1332  * FIXME probably deprecated. Make this the new _online.
1333  *
1334  * @param peer peer in question
1335  *
1336  * @return #GNUNET_YES if peer is known
1337  *         #GNUNET_NO  if peer is not knwon
1338  */
1339 int
1340 Peers_check_peer_known (const struct GNUNET_PeerIdentity *peer)
1341 {
1342   return GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
1343 }
1344
1345
1346 /**
1347  * @brief Check whether @a peer is actually a peer.
1348  *
1349  * A valid peer is a peer that we know exists eg. we were connected to once.
1350  *
1351  * @param peer peer in question
1352  *
1353  * @return #GNUNET_YES if peer is valid
1354  *         #GNUNET_NO  if peer is not valid
1355  */
1356 int
1357 Peers_check_peer_valid (const struct GNUNET_PeerIdentity *peer)
1358 {
1359   return GNUNET_CONTAINER_multipeermap_contains (valid_peers, peer);
1360 }
1361
1362
1363 /**
1364  * @brief Indicate that we want to send to the other peer
1365  *
1366  * This establishes a sending channel
1367  *
1368  * @param peer the peer to establish channel to
1369  */
1370 void
1371 Peers_indicate_sending_intention (const struct GNUNET_PeerIdentity *peer)
1372 {
1373   GNUNET_assert (GNUNET_YES == Peers_check_peer_known (peer));
1374   (void) get_channel (peer);
1375 }
1376
1377
1378 /**
1379  * @brief Check whether other peer has the intention to send/opened channel
1380  *        towars us
1381  *
1382  * @param peer the peer in question
1383  *
1384  * @return #GNUNET_YES if peer has the intention to send
1385  *         #GNUNET_NO  otherwise
1386  */
1387 int
1388 Peers_check_peer_send_intention (const struct GNUNET_PeerIdentity *peer)
1389 {
1390   const struct PeerContext *peer_ctx;
1391
1392   peer_ctx = get_peer_ctx (peer);
1393   if (NULL != peer_ctx->recv_channel)
1394   {
1395     return GNUNET_YES;
1396   }
1397   return GNUNET_NO;
1398 }
1399
1400
1401 /**
1402  * Handle the channel a peer opens to us.
1403  *
1404  * @param cls The closure
1405  * @param channel The channel the peer wants to establish
1406  * @param initiator The peer's peer ID
1407  *
1408  * @return initial channel context for the channel
1409  *         (can be NULL -- that's not an error)
1410  */
1411 void *
1412 Peers_handle_inbound_channel (void *cls,
1413                               struct GNUNET_CADET_Channel *channel,
1414                               const struct GNUNET_PeerIdentity *initiator)
1415 {
1416   struct PeerContext *peer_ctx;
1417
1418   LOG (GNUNET_ERROR_TYPE_DEBUG,
1419       "New channel was established to us (Peer %s).\n",
1420       GNUNET_i2s (initiator));
1421   GNUNET_assert (NULL != channel); /* according to cadet API */
1422   /* Make sure we 'know' about this peer */
1423   peer_ctx = create_or_get_peer_ctx (initiator);
1424   set_peer_live (peer_ctx);
1425   /* We only accept one incoming channel per peer */
1426   if (GNUNET_YES == Peers_check_peer_send_intention (initiator))
1427   {
1428     set_channel_flag (peer_ctx->recv_channel_flags,
1429                       Peers_CHANNEL_ESTABLISHED_TWICE);
1430     GNUNET_CADET_channel_destroy (channel);
1431     /* return the channel context */
1432     return &peer_ctx->peer_id;
1433   }
1434   peer_ctx->recv_channel = channel;
1435   return &peer_ctx->peer_id;
1436 }
1437
1438
1439 /**
1440  * @brief Check whether a sending channel towards the given peer exists
1441  *
1442  * @param peer the peer to check for
1443  *
1444  * @return #GNUNET_YES if a sending channel towards that peer exists
1445  *         #GNUNET_NO  otherwise
1446  */
1447 int
1448 Peers_check_sending_channel_exists (const struct GNUNET_PeerIdentity *peer)
1449 {
1450   struct PeerContext *peer_ctx;
1451
1452   if (GNUNET_NO == Peers_check_peer_known (peer))
1453   { /* If no such peer exists, there is no channel */
1454     return GNUNET_NO;
1455   }
1456   peer_ctx = get_peer_ctx (peer);
1457   if (NULL == peer_ctx->send_channel)
1458   {
1459     return GNUNET_NO;
1460   }
1461   return GNUNET_YES;
1462 }
1463
1464
1465 /**
1466  * @brief check whether the given channel is the sending channel of the given
1467  *        peer
1468  *
1469  * @param peer the peer in question
1470  * @param channel the channel to check for
1471  * @param role either #Peers_CHANNEL_ROLE_SENDING, or
1472  *                    #Peers_CHANNEL_ROLE_RECEIVING
1473  *
1474  * @return #GNUNET_YES if the given chennel is the sending channel of the peer
1475  *         #GNUNET_NO  otherwise
1476  */
1477 int
1478 Peers_check_channel_role (const struct GNUNET_PeerIdentity *peer,
1479                           const struct GNUNET_CADET_Channel *channel,
1480                           enum Peers_ChannelRole role)
1481 {
1482   const struct PeerContext *peer_ctx;
1483
1484   if (GNUNET_NO == Peers_check_peer_known (peer))
1485   {
1486     return GNUNET_NO;
1487   }
1488   peer_ctx = get_peer_ctx (peer);
1489   if ( (Peers_CHANNEL_ROLE_SENDING == role) &&
1490        (channel == peer_ctx->send_channel) )
1491   {
1492     return GNUNET_YES;
1493   }
1494   if ( (Peers_CHANNEL_ROLE_RECEIVING == role) &&
1495        (channel == peer_ctx->recv_channel) )
1496   {
1497     return GNUNET_YES;
1498   }
1499   return GNUNET_NO;
1500 }
1501
1502
1503 /**
1504  * @brief Destroy the send channel of a peer e.g. stop indicating a sending
1505  *        intention to another peer
1506  *
1507  * If there is also no channel to receive messages from that peer, remove it
1508  * from the peermap.
1509  * TODO really?
1510  *
1511  * @peer the peer identity of the peer whose sending channel to destroy
1512  * @return #GNUNET_YES if channel was destroyed
1513  *         #GNUNET_NO  otherwise
1514  */
1515 int
1516 Peers_destroy_sending_channel (const struct GNUNET_PeerIdentity *peer)
1517 {
1518   struct PeerContext *peer_ctx;
1519
1520   if (GNUNET_NO == Peers_check_peer_known (peer))
1521   {
1522     return GNUNET_NO;
1523   }
1524   peer_ctx = get_peer_ctx (peer);
1525   if (NULL != peer_ctx->send_channel)
1526   {
1527     set_channel_flag (peer_ctx->send_channel_flags, Peers_CHANNEL_CLEAN);
1528     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
1529     peer_ctx->send_channel = NULL;
1530     (void) Peers_check_connected (peer);
1531     return GNUNET_YES;
1532   }
1533   return GNUNET_NO;
1534 }
1535
1536 /**
1537  * This is called when a channel is destroyed.
1538  *
1539  * @param cls The closure
1540  * @param channel The channel being closed
1541  * @param channel_ctx The context associated with this channel
1542  */
1543 void
1544 Peers_cleanup_destroyed_channel (void *cls,
1545                                  const struct GNUNET_CADET_Channel *channel)
1546 {
1547   struct GNUNET_PeerIdentity *peer = cls;
1548   struct PeerContext *peer_ctx;
1549
1550   if (GNUNET_NO == Peers_check_peer_known (peer))
1551   {/* We don't want to implicitly create a context that we're about to kill */
1552   LOG (GNUNET_ERROR_TYPE_DEBUG,
1553        "channel (%s) without associated context was destroyed\n",
1554        GNUNET_i2s (peer));
1555     return;
1556   }
1557   peer_ctx = get_peer_ctx (peer);
1558
1559   /* If our peer issued the destruction of the channel, the #Peers_TO_DESTROY
1560    * flag will be set. In this case simply make sure that the channels are
1561    * cleaned. */
1562   /* FIXME This distinction seems to be redundant */
1563   if (Peers_check_peer_flag (peer, Peers_TO_DESTROY))
1564   {/* We initiatad the destruction of this particular peer */
1565     if (channel == peer_ctx->send_channel)
1566       peer_ctx->send_channel = NULL;
1567     else if (channel == peer_ctx->recv_channel)
1568       peer_ctx->recv_channel = NULL;
1569
1570     if (NULL != peer_ctx->send_channel)
1571     {
1572       GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
1573       peer_ctx->send_channel = NULL;
1574     }
1575     if (NULL != peer_ctx->recv_channel)
1576     {
1577       GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
1578       peer_ctx->recv_channel = NULL;
1579     }
1580     /* Set the #Peers_ONLINE flag accordingly */
1581     (void) Peers_check_connected (peer);
1582     return;
1583   }
1584
1585   else
1586   { /* We did not initiate the destruction of this peer */
1587     if (channel == peer_ctx->send_channel)
1588     { /* Something (but us) killd the channel - clean up peer */
1589       LOG (GNUNET_ERROR_TYPE_DEBUG,
1590           "send channel (%s) was destroyed - cleaning up\n",
1591           GNUNET_i2s (peer));
1592       peer_ctx->send_channel = NULL;
1593     }
1594     else if (channel == peer_ctx->recv_channel)
1595     { /* Other peer doesn't want to send us messages anymore */
1596       LOG (GNUNET_ERROR_TYPE_DEBUG,
1597            "Peer %s destroyed recv channel - cleaning up channel\n",
1598            GNUNET_i2s (peer));
1599       peer_ctx->recv_channel = NULL;
1600     }
1601     else
1602     {
1603       LOG (GNUNET_ERROR_TYPE_WARNING,
1604            "unknown channel (%s) was destroyed\n",
1605            GNUNET_i2s (peer));
1606     }
1607   }
1608   (void) Peers_check_connected (peer);
1609 }
1610
1611 /**
1612  * @brief Send a message to another peer.
1613  *
1614  * Keeps track about pending messages so they can be properly removed when the
1615  * peer is destroyed.
1616  *
1617  * @param peer receeiver of the message
1618  * @param ev envelope of the message
1619  * @param type type of the message
1620  */
1621 void
1622 Peers_send_message (const struct GNUNET_PeerIdentity *peer,
1623                     struct GNUNET_MQ_Envelope *ev,
1624                     const char *type)
1625 {
1626   struct PendingMessage *pending_msg;
1627   struct GNUNET_MQ_Handle *mq;
1628
1629   pending_msg = insert_pending_message (peer, ev, type);
1630   mq = get_mq (peer);
1631   GNUNET_MQ_notify_sent (ev,
1632                          mq_notify_sent_cb,
1633                          pending_msg);
1634   GNUNET_MQ_send (mq, ev);
1635 }
1636
1637 /**
1638  * @brief Schedule a operation on given peer
1639  *
1640  * Avoids scheduling an operation twice.
1641  *
1642  * @param peer the peer we want to schedule the operation for once it gets live
1643  *
1644  * @return #GNUNET_YES if the operation was scheduled
1645  *         #GNUNET_NO  otherwise
1646  */
1647 int
1648 Peers_schedule_operation (const struct GNUNET_PeerIdentity *peer,
1649                           const PeerOp peer_op)
1650 {
1651   struct PeerPendingOp pending_op;
1652   struct PeerContext *peer_ctx;
1653
1654   if (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, own_identity))
1655   {
1656     return GNUNET_NO;
1657   }
1658   GNUNET_assert (GNUNET_YES == Peers_check_peer_known (peer));
1659
1660   //TODO if LIVE/ONLINE execute immediately
1661
1662   if (GNUNET_NO == check_operation_scheduled (peer, peer_op))
1663   {
1664     peer_ctx = get_peer_ctx (peer);
1665     pending_op.op = peer_op;
1666     pending_op.op_cls = NULL;
1667     GNUNET_array_append (peer_ctx->pending_ops,
1668                          peer_ctx->num_pending_ops,
1669                          pending_op);
1670     return GNUNET_YES;
1671   }
1672   return GNUNET_NO;
1673 }
1674
1675 /**
1676  * @brief Get the recv_channel of @a peer.
1677  * Needed to correctly handle (call #GNUNET_CADET_receive_done()) incoming
1678  * messages.
1679  *
1680  * @param peer The peer to get the recv_channel from.
1681  *
1682  * @return The recv_channel.
1683  */
1684 struct GNUNET_CADET_Channel *
1685 Peers_get_recv_channel (const struct GNUNET_PeerIdentity *peer)
1686 {
1687   struct PeerContext *peer_ctx;
1688
1689   GNUNET_assert (GNUNET_YES == Peers_check_peer_known (peer));
1690   peer_ctx = get_peer_ctx (peer);
1691   return peer_ctx->recv_channel;
1692 }
1693
1694 /* end of gnunet-service-rps_peers.c */