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